@h-rig/runtime 0.0.6-alpha.3 → 0.0.6-alpha.30

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 (59) hide show
  1. package/dist/bin/rig-agent-dispatch.js +1165 -785
  2. package/dist/bin/rig-agent.js +458 -389
  3. package/dist/src/control-plane/agent-wrapper.js +1191 -504
  4. package/dist/src/control-plane/authority-files.js +12 -6
  5. package/dist/src/control-plane/harness-main.js +2186 -1786
  6. package/dist/src/control-plane/hooks/completion-verification.js +2084 -1019
  7. package/dist/src/control-plane/hooks/inject-context.js +193 -139
  8. package/dist/src/control-plane/hooks/submodule-branch.js +603 -545
  9. package/dist/src/control-plane/hooks/task-runtime-start.js +603 -545
  10. package/dist/src/control-plane/materialize-task-config.js +64 -8
  11. package/dist/src/control-plane/native/git-ops.js +90 -64
  12. package/dist/src/control-plane/native/harness-cli.js +1989 -682
  13. package/dist/src/control-plane/native/pr-automation.js +1657 -54
  14. package/dist/src/control-plane/native/pr-review-gate.js +1455 -0
  15. package/dist/src/control-plane/native/repo-ops.js +3 -0
  16. package/dist/src/control-plane/native/run-ops.js +39 -13
  17. package/dist/src/control-plane/native/task-ops.js +1819 -527
  18. package/dist/src/control-plane/native/validator.js +163 -109
  19. package/dist/src/control-plane/native/verifier.js +1616 -323
  20. package/dist/src/control-plane/native/workspace-ops.js +12 -6
  21. package/dist/src/control-plane/pi-sessiond/bin.js +793 -0
  22. package/dist/src/control-plane/pi-sessiond/client.js +41 -0
  23. package/dist/src/control-plane/pi-sessiond/event-hub.js +59 -0
  24. package/dist/src/control-plane/pi-sessiond/extension-ui-context.js +198 -0
  25. package/dist/src/control-plane/pi-sessiond/launcher.js +173 -0
  26. package/dist/src/control-plane/pi-sessiond/server.js +802 -0
  27. package/dist/src/control-plane/pi-sessiond/session-service.js +540 -0
  28. package/dist/src/control-plane/pi-sessiond/types.js +1 -0
  29. package/dist/src/control-plane/plugin-host-context.js +54 -0
  30. package/dist/src/control-plane/runtime/image/fingerprint-sidecar.js +3 -0
  31. package/dist/src/control-plane/runtime/image/index.js +3 -0
  32. package/dist/src/control-plane/runtime/image-fingerprint-sidecar.js +3 -0
  33. package/dist/src/control-plane/runtime/image.js +3 -0
  34. package/dist/src/control-plane/runtime/index.js +517 -722
  35. package/dist/src/control-plane/runtime/isolation/home.js +28 -6
  36. package/dist/src/control-plane/runtime/isolation/index.js +541 -461
  37. package/dist/src/control-plane/runtime/isolation/runner.js +28 -6
  38. package/dist/src/control-plane/runtime/isolation/shared.js +9 -6
  39. package/dist/src/control-plane/runtime/isolation.js +541 -461
  40. package/dist/src/control-plane/runtime/plugin-mode.js +3 -27
  41. package/dist/src/control-plane/runtime/queue.js +458 -385
  42. package/dist/src/control-plane/runtime/snapshot/task-run.js +3 -0
  43. package/dist/src/control-plane/runtime/task-run-snapshot.js +3 -0
  44. package/dist/src/control-plane/skill-materializer.js +46 -0
  45. package/dist/src/control-plane/tasks/source-aware-task-config-source.js +14 -2
  46. package/dist/src/control-plane/tasks/source-lifecycle.js +86 -32
  47. package/dist/src/index.js +27 -298
  48. package/dist/src/layout.js +12 -7
  49. package/dist/src/local-server.js +20 -14
  50. package/native/darwin-arm64/rig-git +0 -0
  51. package/native/darwin-arm64/rig-git.build-manifest.json +1 -1
  52. package/native/darwin-arm64/rig-shell +0 -0
  53. package/native/darwin-arm64/rig-shell.build-manifest.json +1 -1
  54. package/native/darwin-arm64/rig-tools +0 -0
  55. package/native/darwin-arm64/rig-tools.build-manifest.json +1 -1
  56. package/native/darwin-arm64/runtime-native.dylib +0 -0
  57. package/package.json +8 -6
  58. package/dist/src/control-plane/runtime/plugins.js +0 -1131
  59. package/dist/src/plugins.js +0 -329
@@ -1,1131 +0,0 @@
1
- // @bun
2
- // packages/runtime/src/control-plane/runtime/plugins.ts
3
- import { existsSync as existsSync3, readdirSync } from "fs";
4
- import { resolve as resolve3, basename } from "path";
5
-
6
- // packages/runtime/src/control-plane/runtime/guard.ts
7
- import { optimizeNextInvocation } from "bun:jsc";
8
- import { existsSync as existsSync2, readFileSync, statSync as statSync2 } from "fs";
9
- import { resolve as resolve2 } from "path";
10
-
11
- // packages/runtime/src/control-plane/native/utils.ts
12
- import { ptr as ptr2 } from "bun:ffi";
13
-
14
- // packages/runtime/src/control-plane/native/runtime-native.ts
15
- import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
16
- import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, statSync } from "fs";
17
- import { tmpdir } from "os";
18
- import { dirname, resolve } from "path";
19
- var sharedNativeRuntimeOutputDir = resolve(tmpdir(), "rig-native");
20
- var sharedNativeRuntimeOutputPath = resolve(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
21
- var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
22
- var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
23
- function requireNativeRuntimeLibrary(feature) {
24
- if (!nativeRuntimeLibrary) {
25
- throw new Error(`Native Zig runtime is required for ${feature}`);
26
- }
27
- return nativeRuntimeLibrary;
28
- }
29
- async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
30
- if (await buildNativeRuntimeLibrary(outputPath, options)) {
31
- return outputPath;
32
- }
33
- return !options.force && existsSync(outputPath) ? outputPath : null;
34
- }
35
- async function loadNativeRuntimeLibrary() {
36
- if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
37
- return null;
38
- }
39
- for (const candidate of nativeRuntimeLibraryCandidates()) {
40
- if (!candidate || !existsSync(candidate)) {
41
- continue;
42
- }
43
- const loaded = tryDlopenNativeRuntimeLibrary(candidate);
44
- if (loaded) {
45
- return loaded;
46
- }
47
- }
48
- const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
49
- if (!builtLibraryPath) {
50
- return null;
51
- }
52
- return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
53
- }
54
- function nativePackageLibraryCandidates(fromDir, names) {
55
- const candidates = [];
56
- let cursor = resolve(fromDir);
57
- for (let index = 0;index < 8; index += 1) {
58
- for (const name of names) {
59
- candidates.push(resolve(cursor, "native", `${process.platform}-${process.arch}`, name), resolve(cursor, "native", `${process.platform}-${process.arch}`, "lib", name), resolve(cursor, "native", name), resolve(cursor, "native", "lib", name));
60
- }
61
- const parent = dirname(cursor);
62
- if (parent === cursor)
63
- break;
64
- cursor = parent;
65
- }
66
- return candidates;
67
- }
68
- function nativeRuntimeLibraryCandidates() {
69
- const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
70
- const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
71
- const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
72
- return [...new Set([
73
- explicit,
74
- ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
75
- execDir ? resolve(execDir, colocatedNativeRuntimeFileName) : "",
76
- execDir ? resolve(execDir, platformSpecific) : "",
77
- execDir ? resolve(execDir, "..", colocatedNativeRuntimeFileName) : "",
78
- execDir ? resolve(execDir, "..", platformSpecific) : "",
79
- execDir ? resolve(execDir, "lib", colocatedNativeRuntimeFileName) : "",
80
- execDir ? resolve(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
81
- sharedNativeRuntimeOutputPath
82
- ].filter(Boolean))];
83
- }
84
- function resolveNativeRuntimeSourcePath() {
85
- const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
86
- if (explicit && existsSync(explicit)) {
87
- return explicit;
88
- }
89
- const bundled = resolve(import.meta.dir, "../../../native/snapshot.zig");
90
- return existsSync(bundled) ? bundled : null;
91
- }
92
- async function buildNativeRuntimeLibrary(outputPath, options = {}) {
93
- if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
94
- return false;
95
- }
96
- const zigBinary = Bun.which("zig");
97
- const sourcePath = resolveNativeRuntimeSourcePath();
98
- if (!zigBinary || !sourcePath) {
99
- return false;
100
- }
101
- const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
102
- try {
103
- mkdirSync(dirname(outputPath), { recursive: true });
104
- const needsBuild = options.force === true || !existsSync(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
105
- if (!needsBuild) {
106
- return true;
107
- }
108
- const build = Bun.spawn([
109
- zigBinary,
110
- "build-lib",
111
- sourcePath,
112
- "-dynamic",
113
- "-O",
114
- "ReleaseFast",
115
- `-femit-bin=${tempOutputPath}`
116
- ], {
117
- cwd: import.meta.dir,
118
- stdout: "pipe",
119
- stderr: "pipe"
120
- });
121
- const exitCode = await build.exited;
122
- if (exitCode !== 0 || !existsSync(tempOutputPath)) {
123
- rmSync(tempOutputPath, { force: true });
124
- return false;
125
- }
126
- renameSync(tempOutputPath, outputPath);
127
- return true;
128
- } catch {
129
- rmSync(tempOutputPath, { force: true });
130
- return false;
131
- }
132
- }
133
- function tryDlopenNativeRuntimeLibrary(outputPath) {
134
- try {
135
- return dlopen(outputPath, {
136
- rig_scope_match: {
137
- args: ["ptr", "ptr"],
138
- returns: "u8"
139
- },
140
- snapshot_capture: {
141
- args: ["ptr", "u64", "ptr", "u64"],
142
- returns: "ptr"
143
- },
144
- snapshot_delta: {
145
- args: ["ptr", "ptr"],
146
- returns: "ptr"
147
- },
148
- snapshot_store_delta: {
149
- args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
150
- returns: "ptr"
151
- },
152
- snapshot_inspect_delta: {
153
- args: ["ptr", "u64"],
154
- returns: "ptr"
155
- },
156
- snapshot_apply_delta: {
157
- args: ["ptr", "u64", "ptr", "u64"],
158
- returns: "ptr"
159
- },
160
- snapshot_release: {
161
- args: ["ptr"],
162
- returns: "void"
163
- },
164
- runtime_hash_file: {
165
- args: ["ptr", "u64"],
166
- returns: "ptr"
167
- },
168
- runtime_hash_tree: {
169
- args: ["ptr", "u64"],
170
- returns: "ptr"
171
- },
172
- runtime_prepare_paths: {
173
- args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
174
- returns: "ptr"
175
- },
176
- runtime_link_dependency_layer: {
177
- args: ["ptr", "u64", "ptr", "u64"],
178
- returns: "ptr"
179
- },
180
- runtime_scan_worktrees: {
181
- args: ["ptr", "u64"],
182
- returns: "ptr"
183
- }
184
- });
185
- } catch {
186
- return null;
187
- }
188
- }
189
-
190
- // packages/runtime/src/control-plane/native/scope-rules.ts
191
- var activeRules = null;
192
- function getScopeRules() {
193
- return activeRules;
194
- }
195
-
196
- // packages/runtime/src/control-plane/native/utils.ts
197
- var nativeScopeMatcher = null;
198
- var scopeRegexCache = new Map;
199
- function unique(values) {
200
- return [...new Set(values)];
201
- }
202
- function normalizeRelativeScopePath(inputPath) {
203
- let normalized = inputPath.replace(/^\.\//, "");
204
- const rules = getScopeRules();
205
- if (rules?.stripPrefixes) {
206
- for (const prefix of rules.stripPrefixes) {
207
- if (normalized.startsWith(prefix)) {
208
- normalized = normalized.slice(prefix.length);
209
- }
210
- }
211
- }
212
- return normalized;
213
- }
214
- function normalizePathToScope(projectRoot, monorepoRoot, inputPath) {
215
- let normalized = inputPath.replace(/^\.\//, "");
216
- if (normalized.startsWith(projectRoot + "/")) {
217
- normalized = normalized.slice(projectRoot.length + 1);
218
- }
219
- if (normalized.startsWith(monorepoRoot + "/")) {
220
- normalized = normalized.slice(monorepoRoot.length + 1);
221
- }
222
- return normalizeRelativeScopePath(normalized);
223
- }
224
- function scopeMatches(path, scopes) {
225
- const matcher = getNativeScopeMatcher();
226
- const pathVariants = unique([path, normalizeRelativeScopePath(path)]);
227
- for (const scope of scopes) {
228
- const scopeVariants = unique([scope, normalizeRelativeScopePath(scope)]);
229
- for (const candidatePath of pathVariants) {
230
- for (const candidateScope of scopeVariants) {
231
- if (candidatePath === candidateScope) {
232
- return true;
233
- }
234
- if (matcher.match(candidateScope, candidatePath)) {
235
- return true;
236
- }
237
- }
238
- }
239
- }
240
- return false;
241
- }
242
- function getNativeScopeMatcher() {
243
- if (nativeScopeMatcher) {
244
- return nativeScopeMatcher;
245
- }
246
- nativeScopeMatcher = createNativeScopeMatcher();
247
- return nativeScopeMatcher;
248
- }
249
- function createNativeScopeMatcher() {
250
- const library = requireNativeRuntimeLibrary("scope matching");
251
- return {
252
- match: (pattern, path) => {
253
- const patternBuffer = Buffer.from(`${pattern}\x00`);
254
- const pathBuffer = Buffer.from(`${path}\x00`);
255
- return library.symbols.rig_scope_match(Number(ptr2(patternBuffer)), Number(ptr2(pathBuffer))) !== 0;
256
- }
257
- };
258
- }
259
-
260
- // packages/runtime/src/control-plane/runtime/guard-types.ts
261
- var POLICY_VERSION = 1;
262
-
263
- // packages/runtime/src/control-plane/runtime/guard.ts
264
- var DEFAULT_SCOPE = {
265
- fail_closed: true,
266
- harness_paths_exempt: true,
267
- runtime_paths_exempt: true
268
- };
269
- var DEFAULT_SANDBOX = {
270
- mode: "enforce",
271
- network: true,
272
- read_deny: [],
273
- write_allow_from_runtime: true
274
- };
275
- var DEFAULT_ISOLATION = {
276
- default_mode: "worktree",
277
- repo_symlink_fallback: false,
278
- strict_provisioning: true,
279
- fail_closed_on_provision_error: true
280
- };
281
- var DEFAULT_COMPLETION = {
282
- derive_checks_from_scope: true,
283
- checks: [],
284
- typescript_config_probe: ["tsconfig.json"],
285
- eslint_config_probe: [".eslintrc.js", ".eslintrc.json", "eslint.config.js"]
286
- };
287
- var DEFAULT_RUNTIME_IMAGE = {
288
- deps: {
289
- monorepo_install: false,
290
- hp_next_install: false
291
- },
292
- plugins_require_binaries: true
293
- };
294
- var DEFAULT_RUNTIME_SNAPSHOT = {
295
- enabled: true
296
- };
297
- function defaultPolicy() {
298
- return {
299
- version: POLICY_VERSION,
300
- mode: "enforce",
301
- scope: { ...DEFAULT_SCOPE },
302
- rules: [],
303
- sandbox: { ...DEFAULT_SANDBOX },
304
- isolation: { ...DEFAULT_ISOLATION },
305
- completion: { ...DEFAULT_COMPLETION },
306
- runtime_image: {
307
- deps: { ...DEFAULT_RUNTIME_IMAGE.deps },
308
- plugins_require_binaries: DEFAULT_RUNTIME_IMAGE.plugins_require_binaries
309
- },
310
- runtime_snapshot: { ...DEFAULT_RUNTIME_SNAPSHOT }
311
- };
312
- }
313
- var policyCache = null;
314
- var policyCachePath = null;
315
- var seededPolicyConfig = null;
316
- var compiledRegexCache = new Map;
317
- function loadPolicy(projectRoot) {
318
- if (seededPolicyConfig) {
319
- return seededPolicyConfig;
320
- }
321
- const configPath = resolve2(projectRoot, "rig/policy/policy.json");
322
- if (!existsSync2(configPath)) {
323
- return defaultPolicy();
324
- }
325
- let mtimeMs;
326
- try {
327
- mtimeMs = statSync2(configPath).mtimeMs;
328
- } catch {
329
- return defaultPolicy();
330
- }
331
- if (policyCache && policyCachePath === configPath && policyCache.mtimeMs === mtimeMs) {
332
- return policyCache.config;
333
- }
334
- let parsed;
335
- try {
336
- parsed = JSON.parse(readFileSync(configPath, "utf-8"));
337
- } catch {
338
- return defaultPolicy();
339
- }
340
- const config = mergeWithDefaults(parsed);
341
- policyCache = { mtimeMs, config };
342
- policyCachePath = configPath;
343
- return config;
344
- }
345
- function mergeWithDefaults(parsed) {
346
- const base = defaultPolicy();
347
- if (typeof parsed.mode === "string" && isValidMode(parsed.mode)) {
348
- base.mode = parsed.mode;
349
- }
350
- if (parsed.scope && typeof parsed.scope === "object" && !Array.isArray(parsed.scope)) {
351
- const s = parsed.scope;
352
- if (typeof s.fail_closed === "boolean")
353
- base.scope.fail_closed = s.fail_closed;
354
- if (typeof s.harness_paths_exempt === "boolean")
355
- base.scope.harness_paths_exempt = s.harness_paths_exempt;
356
- if (typeof s.runtime_paths_exempt === "boolean")
357
- base.scope.runtime_paths_exempt = s.runtime_paths_exempt;
358
- }
359
- if (Array.isArray(parsed.rules)) {
360
- base.rules = precompilePolicyRuleRegexes(parsed.rules.filter(isValidRule));
361
- }
362
- if (Array.isArray(parsed.deny) && base.rules.length === 0) {
363
- base.rules = precompilePolicyRuleRegexes(migrateLegacyDeny(parsed.deny));
364
- }
365
- if (parsed.sandbox && typeof parsed.sandbox === "object" && !Array.isArray(parsed.sandbox)) {
366
- const sb = parsed.sandbox;
367
- if (typeof sb.mode === "string" && isValidMode(sb.mode))
368
- base.sandbox.mode = sb.mode;
369
- if (typeof sb.network === "boolean")
370
- base.sandbox.network = sb.network;
371
- if (Array.isArray(sb.read_deny))
372
- base.sandbox.read_deny = sb.read_deny.filter((v) => typeof v === "string");
373
- if (typeof sb.write_allow_from_runtime === "boolean")
374
- base.sandbox.write_allow_from_runtime = sb.write_allow_from_runtime;
375
- }
376
- if (parsed.isolation && typeof parsed.isolation === "object" && !Array.isArray(parsed.isolation)) {
377
- const iso = parsed.isolation;
378
- if (iso.default_mode === "worktree")
379
- base.isolation.default_mode = iso.default_mode;
380
- if (typeof iso.repo_symlink_fallback === "boolean")
381
- base.isolation.repo_symlink_fallback = iso.repo_symlink_fallback;
382
- if (typeof iso.strict_provisioning === "boolean")
383
- base.isolation.strict_provisioning = iso.strict_provisioning;
384
- if (typeof iso.fail_closed_on_provision_error === "boolean")
385
- base.isolation.fail_closed_on_provision_error = iso.fail_closed_on_provision_error;
386
- }
387
- if (parsed.completion && typeof parsed.completion === "object" && !Array.isArray(parsed.completion)) {
388
- const comp = parsed.completion;
389
- if (typeof comp.derive_checks_from_scope === "boolean")
390
- base.completion.derive_checks_from_scope = comp.derive_checks_from_scope;
391
- if (Array.isArray(comp.checks))
392
- base.completion.checks = comp.checks.filter((v) => typeof v === "string");
393
- if (Array.isArray(comp.typescript_config_probe))
394
- base.completion.typescript_config_probe = comp.typescript_config_probe.filter((v) => typeof v === "string");
395
- if (Array.isArray(comp.eslint_config_probe))
396
- base.completion.eslint_config_probe = comp.eslint_config_probe.filter((v) => typeof v === "string");
397
- }
398
- if (parsed.runtime_image && typeof parsed.runtime_image === "object" && !Array.isArray(parsed.runtime_image)) {
399
- const runtimeImage = parsed.runtime_image;
400
- if (runtimeImage.deps && typeof runtimeImage.deps === "object" && !Array.isArray(runtimeImage.deps)) {
401
- const deps = runtimeImage.deps;
402
- if (typeof deps.monorepo_install === "boolean") {
403
- base.runtime_image.deps.monorepo_install = deps.monorepo_install;
404
- }
405
- if (typeof deps.hp_next_install === "boolean") {
406
- base.runtime_image.deps.hp_next_install = deps.hp_next_install;
407
- }
408
- }
409
- if (typeof runtimeImage.plugins_require_binaries === "boolean") {
410
- base.runtime_image.plugins_require_binaries = runtimeImage.plugins_require_binaries;
411
- }
412
- }
413
- if (parsed.runtime_snapshot && typeof parsed.runtime_snapshot === "object" && !Array.isArray(parsed.runtime_snapshot)) {
414
- const runtimeSnapshot = parsed.runtime_snapshot;
415
- if (typeof runtimeSnapshot.enabled === "boolean") {
416
- base.runtime_snapshot.enabled = runtimeSnapshot.enabled;
417
- }
418
- }
419
- return base;
420
- }
421
- function isValidMode(value) {
422
- return value === "off" || value === "observe" || value === "enforce";
423
- }
424
- function isValidRule(value) {
425
- if (!value || typeof value !== "object" || Array.isArray(value))
426
- return false;
427
- const r = value;
428
- return typeof r.id === "string" && typeof r.category === "string" && r.match != null && typeof r.match === "object";
429
- }
430
- function migrateLegacyDeny(deny) {
431
- const rules = [];
432
- for (const entry of deny) {
433
- if (typeof entry.id !== "string")
434
- continue;
435
- const match = {};
436
- if (typeof entry.pattern === "string")
437
- match.pattern = entry.pattern;
438
- if (typeof entry.regex === "string")
439
- match.regex = entry.regex;
440
- if (!match.pattern && !match.regex)
441
- continue;
442
- rules.push({
443
- id: entry.id,
444
- category: "command",
445
- match,
446
- action: "block",
447
- ...typeof entry.description === "string" ? { description: entry.description } : {}
448
- });
449
- }
450
- return rules;
451
- }
452
- function precompilePolicyRuleRegexes(rules) {
453
- return rules.map((rule) => {
454
- const compiledRegex = rule.match.regex ? compileSafeRegex(rule.match.regex, `rules.${rule.id}.match.regex`, true) : undefined;
455
- const compiledUnlessRegex = rule.unless?.regex ? compileSafeRegex(rule.unless.regex, `rules.${rule.id}.unless.regex`, true) : undefined;
456
- return {
457
- ...rule,
458
- ...compiledRegex ? { compiledRegex } : {},
459
- ...compiledUnlessRegex ? { compiledUnlessRegex } : {}
460
- };
461
- });
462
- }
463
- function getRegexUnsafeReason(pattern) {
464
- if (pattern.length > 512) {
465
- return "pattern exceeds max safe length (512 chars)";
466
- }
467
- if (/\\[1-9]/.test(pattern)) {
468
- return "pattern uses backreferences";
469
- }
470
- if (/\((?:[^()\\]|\\.)*[+*](?:[^()\\]|\\.)*\)\s*[*+{]/.test(pattern)) {
471
- return "pattern contains nested quantifiers";
472
- }
473
- if (/\((?:[^()\\]|\\.)*\.\\?[+*](?:[^()\\]|\\.)*\)\s*[*+{]/.test(pattern)) {
474
- return "pattern contains nested broad quantifiers";
475
- }
476
- return null;
477
- }
478
- function compileSafeRegex(pattern, sourceLabel, logOnFailure) {
479
- const cached = compiledRegexCache.get(pattern);
480
- if (cached !== undefined) {
481
- return cached ?? undefined;
482
- }
483
- const unsafeReason = getRegexUnsafeReason(pattern);
484
- if (unsafeReason) {
485
- if (logOnFailure) {
486
- console.warn(`[policy] Skipping unsafe regex in ${sourceLabel}: ${unsafeReason}`);
487
- }
488
- compiledRegexCache.set(pattern, null);
489
- return;
490
- }
491
- try {
492
- const compiled = new RegExp(pattern);
493
- compiledRegexCache.set(pattern, compiled);
494
- return compiled;
495
- } catch (error) {
496
- if (logOnFailure) {
497
- const message = error instanceof Error ? error.message : String(error);
498
- console.warn(`[policy] Skipping invalid regex in ${sourceLabel}: ${message}`);
499
- }
500
- compiledRegexCache.set(pattern, null);
501
- return;
502
- }
503
- }
504
- function matchRule(rule, input) {
505
- const { match } = rule;
506
- if (match.pattern && input.includes(match.pattern)) {
507
- return true;
508
- }
509
- if (match.regex) {
510
- const compiled = rule.compiledRegex || compileSafeRegex(match.regex, `rules.${rule.id}.match.regex`, false);
511
- if (!compiled) {
512
- return false;
513
- }
514
- try {
515
- return compiled.test(input);
516
- } catch {
517
- return false;
518
- }
519
- }
520
- return false;
521
- }
522
- function matchRuleUnless(rule, command, taskId) {
523
- if (!rule.unless)
524
- return false;
525
- if (rule.unless.regex) {
526
- const compiled = rule.compiledUnlessRegex || compileSafeRegex(rule.unless.regex, `rules.${rule.id}.unless.regex`, false);
527
- if (!compiled) {
528
- return false;
529
- }
530
- try {
531
- if (compiled.test(command))
532
- return true;
533
- } catch {}
534
- }
535
- if (rule.unless.task_in && taskId) {
536
- if (rule.unless.task_in.includes(taskId))
537
- return true;
538
- }
539
- return false;
540
- }
541
- function resolveAction(mode, matched) {
542
- if (matched.length === 0)
543
- return "allow";
544
- if (mode === "off")
545
- return "allow";
546
- if (mode === "observe")
547
- return "warn";
548
- return "block";
549
- }
550
- function resolveAbsolutePath(projectRoot, rawPath) {
551
- if (rawPath.startsWith("/"))
552
- return resolve2(rawPath);
553
- return resolve2(projectRoot, rawPath);
554
- }
555
- function isHarnessPath(projectRoot, rawPath) {
556
- const absPath = resolveAbsolutePath(projectRoot, rawPath);
557
- const managedRoots = [
558
- resolve2(projectRoot, "rig"),
559
- resolve2(projectRoot, ".rig"),
560
- resolve2(projectRoot, "artifacts")
561
- ];
562
- return managedRoots.some((root) => absPath === root || absPath.startsWith(root + "/"));
563
- }
564
- function isRuntimePath(projectRoot, rawPath, taskWorkspace) {
565
- const absPath = resolveAbsolutePath(projectRoot, rawPath);
566
- if (taskWorkspace) {
567
- const workspaceRigRoot = resolve2(taskWorkspace, ".rig");
568
- const workspaceArtifactsRoot = resolve2(taskWorkspace, "artifacts");
569
- if (absPath === workspaceRigRoot || absPath.startsWith(workspaceRigRoot + "/") || absPath === workspaceArtifactsRoot || absPath.startsWith(workspaceArtifactsRoot + "/")) {
570
- return true;
571
- }
572
- }
573
- const runtimeRoot = resolve2(projectRoot, ".rig/runtime/agents");
574
- return absPath === runtimeRoot || absPath.startsWith(runtimeRoot + "/");
575
- }
576
- function isTestFile(path) {
577
- return /\.(test|spec)\.(ts|tsx|js|jsx)$/.test(path) || /\/(__tests__|tests|test)\//.test(path);
578
- }
579
- function evaluate(context) {
580
- const policy = loadPolicy(context.projectRoot);
581
- switch (context.evaluation.type) {
582
- case "tool-call":
583
- return evaluateToolCall(policy, context);
584
- case "command":
585
- return evaluateCommand(policy, context);
586
- case "content-write":
587
- return evaluateContent(policy, context);
588
- case "file-access":
589
- return evaluateScope(policy, context, context.evaluation.file_path, context.evaluation.access);
590
- }
591
- }
592
- function evaluateScope(policy, context, filePath, access) {
593
- const allowed = () => ({
594
- allowed: true,
595
- matchedRules: [],
596
- action: "allow",
597
- failClosed: false
598
- });
599
- if (policy.scope.harness_paths_exempt && isHarnessPath(context.projectRoot, filePath)) {
600
- return allowed();
601
- }
602
- if (policy.scope.runtime_paths_exempt && isRuntimePath(context.projectRoot, filePath, context.taskWorkspace)) {
603
- return allowed();
604
- }
605
- if (!context.taskId) {
606
- if (access === "write" && policy.scope.fail_closed) {
607
- return {
608
- allowed: false,
609
- matchedRules: [],
610
- action: resolveAction(policy.mode, [{ id: "scope:no-task", category: "command", reason: "No active task; fail-closed for write operations" }]),
611
- failClosed: true
612
- };
613
- }
614
- return allowed();
615
- }
616
- const scopes = context.taskScopes || [];
617
- if (scopes.length === 0) {
618
- return allowed();
619
- }
620
- if (context.taskWorkspace && context.taskWorkspace !== context.projectRoot && filePath.startsWith("/")) {
621
- const absPath = resolve2(filePath);
622
- if (!absPath.startsWith(context.taskWorkspace + "/") && !isHarnessPath(context.projectRoot, filePath)) {
623
- const reason2 = `Absolute path '${filePath}' is outside task runtime boundary. Allowed root: ${context.taskWorkspace}`;
624
- const matched2 = [{ id: "scope:workspace-boundary", category: "command", reason: reason2 }];
625
- return {
626
- allowed: policy.mode !== "enforce",
627
- matchedRules: matched2,
628
- action: resolveAction(policy.mode, matched2),
629
- failClosed: false
630
- };
631
- }
632
- }
633
- const monorepoRoot = context.monorepoRoot || process.env.MONOREPO_ROOT?.trim() || context.taskWorkspace || context.projectRoot;
634
- let normalizedPath = filePath;
635
- if (context.taskWorkspace && context.taskWorkspace !== context.projectRoot && filePath.startsWith(context.taskWorkspace + "/")) {
636
- normalizedPath = filePath.slice(context.taskWorkspace.length + 1);
637
- }
638
- normalizedPath = normalizePathToScope(context.projectRoot, monorepoRoot, normalizedPath);
639
- if (scopeMatches(filePath, scopes) || scopeMatches(normalizedPath, scopes)) {
640
- return allowed();
641
- }
642
- const reason = `File '${filePath}' (normalized: '${normalizedPath}') is outside scope of task ${context.taskId}`;
643
- const matched = [{ id: "scope:out-of-scope", category: "command", reason }];
644
- return {
645
- allowed: policy.mode !== "enforce",
646
- matchedRules: matched,
647
- action: resolveAction(policy.mode, matched),
648
- failClosed: false
649
- };
650
- }
651
- function evaluateCommand(policy, context) {
652
- const evaluation = context.evaluation;
653
- if (evaluation.type !== "command") {
654
- return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
655
- }
656
- const command = evaluation.command;
657
- const matchedRules = [];
658
- for (const rule of policy.rules) {
659
- if (rule.category !== "command")
660
- continue;
661
- if (!matchRule(rule, command))
662
- continue;
663
- if (matchRuleUnless(rule, command, context.taskId))
664
- continue;
665
- matchedRules.push({
666
- id: rule.id,
667
- category: rule.category,
668
- description: rule.description,
669
- reason: rule.description || `Matched rule ${rule.id}`
670
- });
671
- }
672
- const writeTarget = extractWriteTarget(command);
673
- if (writeTarget && !/^\/dev\//.test(writeTarget) && !/^\/proc\//.test(writeTarget)) {
674
- const scopeResult = evaluateScope(policy, context, writeTarget, "write");
675
- if (!scopeResult.allowed || scopeResult.matchedRules.length > 0) {
676
- matchedRules.push(...scopeResult.matchedRules);
677
- }
678
- }
679
- const action = resolveAction(policy.mode, matchedRules);
680
- return {
681
- allowed: action !== "block",
682
- matchedRules,
683
- action,
684
- failClosed: false
685
- };
686
- }
687
- function extractWriteTarget(command) {
688
- const redirect = command.match(/>>?\s+([^\s;|&]+)/);
689
- if (redirect?.[1])
690
- return redirect[1];
691
- const tee = command.match(/tee\s+(-a\s+)?([^\s;|&]+)/);
692
- if (tee?.[2])
693
- return tee[2];
694
- return "";
695
- }
696
- function evaluateContent(policy, context) {
697
- const evaluation = context.evaluation;
698
- if (evaluation.type !== "content-write") {
699
- return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
700
- }
701
- const { content, file_path } = evaluation;
702
- const matchedRules = [];
703
- const scopeResult = evaluateScope(policy, context, file_path, "write");
704
- if (scopeResult.matchedRules.length > 0) {
705
- matchedRules.push(...scopeResult.matchedRules);
706
- }
707
- for (const rule of policy.rules) {
708
- if (rule.category !== "content" && rule.category !== "import" && rule.category !== "test-integrity")
709
- continue;
710
- if (rule.applies_to === "test-files" && !isTestFile(file_path))
711
- continue;
712
- if (!matchRule(rule, content))
713
- continue;
714
- if (matchRuleUnless(rule, content, context.taskId))
715
- continue;
716
- matchedRules.push({
717
- id: rule.id,
718
- category: rule.category,
719
- description: rule.description,
720
- reason: rule.description || `Matched rule ${rule.id}`
721
- });
722
- }
723
- const action = resolveAction(policy.mode, matchedRules);
724
- return {
725
- allowed: action !== "block",
726
- matchedRules,
727
- action,
728
- failClosed: false
729
- };
730
- }
731
- function evaluateToolCall(policy, context) {
732
- const evaluation = context.evaluation;
733
- if (evaluation.type !== "tool-call") {
734
- return { allowed: true, matchedRules: [], action: "allow", failClosed: false };
735
- }
736
- const { tool_name, tool_input } = evaluation;
737
- const allMatched = [];
738
- const filePaths = extractFilePathsFromToolInput(tool_name, tool_input);
739
- for (const fp of filePaths) {
740
- const access = isWriteTool(tool_name) ? "write" : "read";
741
- const scopeResult = evaluateScope(policy, context, fp, access);
742
- if (scopeResult.matchedRules.length > 0) {
743
- allMatched.push(...scopeResult.matchedRules);
744
- }
745
- }
746
- const content = extractContentFromToolInput(tool_input);
747
- if (content) {
748
- const filePath = filePaths[0] || "";
749
- const contentContext = {
750
- ...context,
751
- evaluation: { type: "content-write", file_path: filePath, content }
752
- };
753
- const contentPolicy = loadPolicy(context.projectRoot);
754
- for (const rule of contentPolicy.rules) {
755
- if (rule.category !== "content" && rule.category !== "import" && rule.category !== "test-integrity")
756
- continue;
757
- if (rule.applies_to === "test-files" && !isTestFile(filePath))
758
- continue;
759
- if (!matchRule(rule, content))
760
- continue;
761
- if (matchRuleUnless(rule, content, context.taskId))
762
- continue;
763
- allMatched.push({
764
- id: rule.id,
765
- category: rule.category,
766
- description: rule.description,
767
- reason: rule.description || `Matched rule ${rule.id}`
768
- });
769
- }
770
- }
771
- if (tool_name === "Bash") {
772
- const command = String(tool_input.command || tool_input.cmd || "");
773
- if (command) {
774
- const cmdContext = {
775
- ...context,
776
- evaluation: { type: "command", command }
777
- };
778
- const cmdResult = evaluateCommand(policy, cmdContext);
779
- if (cmdResult.matchedRules.length > 0) {
780
- allMatched.push(...cmdResult.matchedRules);
781
- }
782
- }
783
- }
784
- const seen = new Set;
785
- const deduplicated = [];
786
- for (const rule of allMatched) {
787
- if (!seen.has(rule.id)) {
788
- seen.add(rule.id);
789
- deduplicated.push(rule);
790
- }
791
- }
792
- const action = resolveAction(policy.mode, deduplicated);
793
- return {
794
- allowed: action !== "block",
795
- matchedRules: deduplicated,
796
- action,
797
- failClosed: false
798
- };
799
- }
800
- function isWriteTool(toolName) {
801
- return toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit";
802
- }
803
- function extractFilePathsFromToolInput(toolName, input) {
804
- const paths = [];
805
- const add = (value) => {
806
- if (typeof value === "string" && value.trim()) {
807
- paths.push(value.trim());
808
- }
809
- };
810
- if (toolName === "Read" || toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
811
- add(input.file_path);
812
- add(input.path);
813
- } else if (toolName === "Glob") {
814
- add(input.path);
815
- } else if (toolName === "Grep") {
816
- add(input.path);
817
- } else {
818
- add(input.file_path);
819
- add(input.path);
820
- }
821
- return paths;
822
- }
823
- function extractContentFromToolInput(input) {
824
- if (typeof input.content === "string")
825
- return input.content;
826
- if (typeof input.new_string === "string")
827
- return input.new_string;
828
- return "";
829
- }
830
- function loadRuntimeImageConfig(projectRoot) {
831
- return loadPolicy(projectRoot).runtime_image ?? {
832
- deps: { ...DEFAULT_RUNTIME_IMAGE.deps },
833
- plugins_require_binaries: DEFAULT_RUNTIME_IMAGE.plugins_require_binaries
834
- };
835
- }
836
- var guardHotPathPrimed = false;
837
- function primeGuardHotPaths() {
838
- if (guardHotPathPrimed) {
839
- return;
840
- }
841
- guardHotPathPrimed = true;
842
- try {
843
- optimizeNextInvocation(matchRule);
844
- optimizeNextInvocation(evaluate);
845
- } catch {}
846
- }
847
- primeGuardHotPaths();
848
-
849
- // packages/runtime/src/control-plane/runtime/plugin-mode.ts
850
- var LEGACY_PLUGIN_SCAN_ENV = "RIG_LEGACY_PLUGIN_SCAN";
851
- function isLegacyPluginScanEnabled(env = process.env) {
852
- const value = env[LEGACY_PLUGIN_SCAN_ENV]?.trim().toLowerCase();
853
- return value === "1" || value === "true" || value === "yes" || value === "on";
854
- }
855
-
856
- // packages/runtime/src/control-plane/runtime/plugins.ts
857
- class PluginManager {
858
- eventBus;
859
- context;
860
- pluginDir;
861
- pluginFiles;
862
- pluginNames;
863
- localBinDir;
864
- pluginsRequireBinaries;
865
- plugins;
866
- loadPromise;
867
- constructor(options) {
868
- this.eventBus = options.eventBus;
869
- this.context = options.context;
870
- this.pluginDir = options.pluginDir;
871
- this.pluginFiles = options.pluginFiles;
872
- this.pluginNames = options.pluginNames;
873
- this.localBinDir = options.localBinDir;
874
- this.pluginsRequireBinaries = options.pluginsRequireBinaries;
875
- this.plugins = options.preloadedPlugins ?? null;
876
- this.loadPromise = null;
877
- }
878
- static disabled(options) {
879
- const validatorProjectRoot = options.runtimeContext?.workspaceDir || options.projectRoot;
880
- return new PluginManager({
881
- eventBus: options.eventBus,
882
- context: {
883
- projectRoot: validatorProjectRoot,
884
- runId: options.runId,
885
- eventBus: options.eventBus
886
- },
887
- pluginDir: resolve3(options.projectRoot, "rig/plugins"),
888
- pluginFiles: [],
889
- pluginNames: [],
890
- localBinDir: options.runtimeContext ? resolve3(options.runtimeContext.binDir, "plugins") : resolve3(options.projectRoot, "rig/plugins"),
891
- pluginsRequireBinaries: false,
892
- preloadedPlugins: []
893
- });
894
- }
895
- static async load(options) {
896
- const pluginDir = resolve3(options.projectRoot, "rig/plugins");
897
- const runtimeImageConfig = loadRuntimeImageConfig(options.projectRoot);
898
- const localBinDir = options.runtimeContext ? resolve3(options.runtimeContext.binDir, "plugins") : resolve3(options.projectRoot, "rig/plugins");
899
- const legacyPluginScan = options.legacyPluginScan ?? isLegacyPluginScanEnabled(options.env);
900
- const files = legacyPluginScan ? safeReadDir(pluginDir).filter((entry) => /\.(ts|js|mjs|cjs)$/.test(entry)) : [];
901
- const pluginNames = files.map((file) => basename(file).replace(/\.plugin\.(ts|js|mjs|cjs)$/, ""));
902
- const validatorProjectRoot = options.runtimeContext?.workspaceDir || options.projectRoot;
903
- const context = {
904
- projectRoot: validatorProjectRoot,
905
- runId: options.runId,
906
- eventBus: options.eventBus
907
- };
908
- return new PluginManager({
909
- eventBus: options.eventBus,
910
- context,
911
- pluginDir,
912
- pluginFiles: files,
913
- pluginNames,
914
- localBinDir,
915
- pluginsRequireBinaries: options.pluginsRequireBinaries ?? (runtimeImageConfig.plugins_require_binaries && Boolean(options.runtimeContext))
916
- });
917
- }
918
- list() {
919
- if (this.plugins) {
920
- return this.plugins.map((plugin) => ({
921
- name: plugin.name,
922
- validators: plugin.validators?.map((validator) => validator.id) ?? []
923
- }));
924
- }
925
- return this.pluginNames.map((name) => ({
926
- name,
927
- validators: []
928
- }));
929
- }
930
- async beforeCommand(ctx) {
931
- const plugins = await this.ensureLoaded();
932
- for (const plugin of plugins) {
933
- if (!plugin.beforeCommand) {
934
- continue;
935
- }
936
- await this.safeInvoke(plugin.name, "beforeCommand", () => plugin.beforeCommand?.(ctx, this.context));
937
- }
938
- }
939
- async afterCommand(result) {
940
- const plugins = await this.ensureLoaded();
941
- for (const plugin of plugins) {
942
- if (!plugin.afterCommand) {
943
- continue;
944
- }
945
- await this.safeInvoke(plugin.name, "afterCommand", () => plugin.afterCommand?.(result, this.context));
946
- }
947
- }
948
- async onEvent(event) {
949
- const plugins = this.plugins;
950
- if (!plugins) {
951
- return;
952
- }
953
- for (const plugin of plugins) {
954
- if (!plugin.onEvent) {
955
- continue;
956
- }
957
- await this.safeInvoke(plugin.name, "onEvent", () => plugin.onEvent?.(event, this.context));
958
- }
959
- }
960
- async runValidators(taskId) {
961
- const plugins = await this.ensureLoaded();
962
- const results = [];
963
- for (const plugin of plugins) {
964
- for (const validator of plugin.validators ?? []) {
965
- await this.eventBus.emit("validator.started", {
966
- plugin: plugin.name,
967
- validator: validator.id,
968
- taskId
969
- });
970
- try {
971
- const result = await validator.run({ taskId, projectRoot: this.context.projectRoot }, this.context);
972
- results.push(result);
973
- await this.eventBus.emit("validator.finished", {
974
- plugin: plugin.name,
975
- validator: validator.id,
976
- taskId,
977
- passed: result.passed,
978
- summary: result.summary
979
- });
980
- } catch (error) {
981
- const failed = {
982
- id: validator.id,
983
- passed: false,
984
- summary: `${plugin.name}/${validator.id} failed unexpectedly`,
985
- details: `${error}`
986
- };
987
- results.push(failed);
988
- await this.eventBus.emit("validator.finished", {
989
- plugin: plugin.name,
990
- validator: validator.id,
991
- taskId,
992
- passed: false,
993
- summary: failed.summary,
994
- details: failed.details
995
- });
996
- }
997
- }
998
- }
999
- return results;
1000
- }
1001
- async safeInvoke(pluginName, hook, call) {
1002
- try {
1003
- await call();
1004
- } catch (error) {
1005
- await this.eventBus.emit("plugin.error", {
1006
- plugin: pluginName,
1007
- phase: hook,
1008
- error: `${error}`
1009
- });
1010
- }
1011
- }
1012
- async ensureLoaded() {
1013
- if (this.plugins) {
1014
- return this.plugins;
1015
- }
1016
- if (this.loadPromise) {
1017
- return this.loadPromise;
1018
- }
1019
- this.loadPromise = this.loadCompiledPlugins();
1020
- try {
1021
- this.plugins = await this.loadPromise;
1022
- return this.plugins;
1023
- } finally {
1024
- this.loadPromise = null;
1025
- }
1026
- }
1027
- resolveBinPath(binName) {
1028
- const candidates = [this.localBinDir].filter(Boolean).map((dir) => resolve3(dir, binName));
1029
- return candidates.find((candidate) => existsSync3(candidate));
1030
- }
1031
- async loadCompiledPlugins() {
1032
- const plugins = [];
1033
- for (const file of this.pluginFiles) {
1034
- const binName = basename(file).replace(/\.plugin\.(ts|js|mjs|cjs)$/, "");
1035
- let binPath = this.resolveBinPath(binName);
1036
- if (!binPath) {
1037
- const triedPaths = [this.localBinDir].filter(Boolean).map((dir) => resolve3(dir, binName));
1038
- const missingError = `Compiled plugin binary not found for '${binName}'. Tried: ${triedPaths.join(", ")}`;
1039
- await this.eventBus.emit("plugin.error", {
1040
- file: resolve3(this.pluginDir, file),
1041
- phase: "load",
1042
- error: missingError
1043
- });
1044
- if (this.pluginsRequireBinaries) {
1045
- throw new Error(missingError);
1046
- }
1047
- plugins.push({
1048
- name: binName,
1049
- validators: []
1050
- });
1051
- await this.eventBus.emit("plugin.loaded", {
1052
- plugin: binName,
1053
- file: resolve3(this.pluginDir, file),
1054
- source: "metadata-only"
1055
- });
1056
- continue;
1057
- }
1058
- const wrapper = createBinaryPluginWrapper(binName, binPath, this.context.projectRoot);
1059
- plugins.push(wrapper);
1060
- await this.eventBus.emit("plugin.loaded", {
1061
- plugin: wrapper.name,
1062
- file: binPath,
1063
- source: "compiled-binary"
1064
- });
1065
- }
1066
- return plugins;
1067
- }
1068
- }
1069
- function createBinaryPluginWrapper(name, binPath, projectRoot) {
1070
- return {
1071
- name,
1072
- validators: [
1073
- {
1074
- id: `${name}:compiled`,
1075
- async run(ctx) {
1076
- const proc = Bun.spawn([binPath, "--validate", ctx.taskId, ctx.projectRoot], {
1077
- cwd: projectRoot,
1078
- stdout: "pipe",
1079
- stderr: "pipe"
1080
- });
1081
- const exitCode = await proc.exited;
1082
- const stdout = await new Response(proc.stdout).text();
1083
- const stderr = await new Response(proc.stderr).text();
1084
- if (exitCode !== 0) {
1085
- return {
1086
- id: `${name}:compiled`,
1087
- passed: false,
1088
- summary: `Plugin binary ${name} exited with code ${exitCode}`,
1089
- details: stderr || stdout
1090
- };
1091
- }
1092
- try {
1093
- const results = JSON.parse(stdout.trim());
1094
- const failed = results.filter((r) => !r.passed);
1095
- if (failed.length > 0) {
1096
- return {
1097
- id: `${name}:compiled`,
1098
- passed: false,
1099
- summary: `${failed.length} of ${results.length} validator(s) failed`,
1100
- details: failed.map((f) => `${f.id}: ${f.summary}`).join(`
1101
- `)
1102
- };
1103
- }
1104
- return {
1105
- id: `${name}:compiled`,
1106
- passed: true,
1107
- summary: `All ${results.length} validator(s) passed`
1108
- };
1109
- } catch {
1110
- return {
1111
- id: `${name}:compiled`,
1112
- passed: false,
1113
- summary: `Failed to parse output from compiled plugin ${name}`,
1114
- details: stdout.slice(0, 500)
1115
- };
1116
- }
1117
- }
1118
- }
1119
- ]
1120
- };
1121
- }
1122
- function safeReadDir(path) {
1123
- try {
1124
- return readdirSync(path, { withFileTypes: true }).filter((entry) => entry.isFile()).map((entry) => entry.name).sort();
1125
- } catch {
1126
- return [];
1127
- }
1128
- }
1129
- export {
1130
- PluginManager
1131
- };