@h-rig/core 0.0.6-alpha.17 → 0.0.6-alpha.170

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 (107) hide show
  1. package/dist/src/agent-role-registry.d.ts +4 -0
  2. package/dist/src/agent-role-registry.js +27 -0
  3. package/dist/src/authority-paths.d.ts +15 -0
  4. package/dist/src/authority-paths.js +80 -0
  5. package/dist/src/baked-secrets.d.ts +6 -0
  6. package/dist/src/baked-secrets.js +121 -0
  7. package/dist/src/build-time-config.d.ts +12 -0
  8. package/dist/src/build-time-config.js +25 -0
  9. package/dist/src/build-time-config.macro.d.ts +1 -0
  10. package/dist/src/capability-loaders.d.ts +51 -0
  11. package/dist/src/capability-loaders.js +758 -0
  12. package/dist/src/capability.d.ts +79 -0
  13. package/dist/src/capability.js +63 -0
  14. package/dist/src/checkout-root.d.ts +1 -0
  15. package/dist/src/checkout-root.js +30 -0
  16. package/dist/src/config-env.d.ts +4 -0
  17. package/dist/src/config-env.js +23 -0
  18. package/dist/src/config.d.ts +3 -0
  19. package/dist/src/config.js +44 -0
  20. package/dist/src/declarative-config.d.ts +14 -0
  21. package/dist/src/declarative-config.js +82 -0
  22. package/dist/src/default-kernel.d.ts +1 -0
  23. package/dist/src/default-kernel.js +12 -0
  24. package/dist/src/define-config.d.ts +20 -0
  25. package/dist/src/define-config.js +28 -15
  26. package/dist/src/define-plugin.d.ts +13 -0
  27. package/dist/src/define-plugin.js +4 -43
  28. package/dist/src/embedded-plugins.d.ts +59 -0
  29. package/dist/src/embedded-plugins.js +22 -0
  30. package/dist/src/exec.d.ts +13 -0
  31. package/dist/src/exec.js +101 -0
  32. package/dist/src/harness-paths.d.ts +18 -0
  33. package/dist/src/harness-paths.js +141 -0
  34. package/dist/src/hook-materializer.d.ts +72 -0
  35. package/dist/src/hook-materializer.js +281 -0
  36. package/dist/src/hook-protocol.d.ts +2 -0
  37. package/dist/src/hook-protocol.js +462 -0
  38. package/dist/src/hook-runner.d.ts +48 -0
  39. package/dist/src/hook-runner.js +756 -0
  40. package/dist/src/hook-runtime.d.ts +52 -0
  41. package/dist/src/hook-runtime.js +462 -0
  42. package/dist/src/index.d.ts +8 -0
  43. package/dist/src/index.js +210 -2499
  44. package/dist/src/json-files.d.ts +9 -0
  45. package/dist/src/json-files.js +125 -0
  46. package/dist/src/kernel-boot.d.ts +2 -0
  47. package/dist/src/kernel-boot.js +10 -0
  48. package/dist/src/kernel-entrypoint.d.ts +22 -0
  49. package/dist/src/kernel-entrypoint.js +548 -0
  50. package/dist/src/kernel-plugin-abi.d.ts +1 -0
  51. package/dist/src/kernel-plugin-abi.js +1 -0
  52. package/dist/src/kernel-resolver.d.ts +2 -0
  53. package/dist/src/kernel-resolver.js +6 -0
  54. package/dist/src/layout.d.ts +10 -0
  55. package/dist/src/layout.js +144 -0
  56. package/dist/src/load-config.d.ts +2 -0
  57. package/dist/src/load-config.js +423 -30
  58. package/dist/src/placement.d.ts +50 -0
  59. package/dist/src/placement.js +996 -0
  60. package/dist/src/plugin-host-context.d.ts +66 -0
  61. package/dist/src/plugin-host-context.js +1292 -0
  62. package/dist/src/plugin-host-registries.d.ts +31 -0
  63. package/dist/src/plugin-host-registries.js +79 -0
  64. package/dist/src/plugin-host.d.ts +77 -0
  65. package/dist/src/plugin-host.js +127 -63
  66. package/dist/src/plugin-runtime.d.ts +173 -0
  67. package/dist/src/profile-ops.d.ts +9 -0
  68. package/dist/src/profile-ops.js +252 -0
  69. package/dist/src/project-plugins.d.ts +63 -0
  70. package/dist/src/project-plugins.js +793 -0
  71. package/dist/src/remote-config.d.ts +183 -0
  72. package/dist/src/remote-config.js +574 -0
  73. package/dist/src/root-resolver.d.ts +5 -0
  74. package/dist/src/root-resolver.js +69 -0
  75. package/dist/src/run-provisioning.d.ts +58 -0
  76. package/dist/src/run-provisioning.js +128 -0
  77. package/dist/src/runtime-context.d.ts +20 -0
  78. package/dist/src/runtime-context.js +257 -0
  79. package/dist/src/runtime-events.d.ts +44 -0
  80. package/dist/src/runtime-events.js +212 -0
  81. package/dist/src/runtime-overlay.d.ts +11 -0
  82. package/dist/src/runtime-overlay.js +71 -0
  83. package/dist/src/runtime-paths.d.ts +21 -0
  84. package/dist/src/runtime-paths.js +181 -0
  85. package/dist/src/runtime-provisioning-env.d.ts +5 -0
  86. package/dist/src/runtime-provisioning-env.js +217 -0
  87. package/dist/src/runtime-runner-context.d.ts +12 -0
  88. package/dist/src/runtime-runner-context.js +1 -0
  89. package/dist/src/safe-identifiers.d.ts +44 -0
  90. package/dist/src/safe-identifiers.js +96 -0
  91. package/dist/src/scope-rules.d.ts +4 -0
  92. package/dist/src/scope-rules.js +21 -0
  93. package/dist/src/server-paths.d.ts +26 -0
  94. package/dist/src/server-paths.js +308 -0
  95. package/dist/src/setup-version.d.ts +3 -0
  96. package/dist/src/setup-version.js +14 -0
  97. package/dist/src/task-record-reader.d.ts +3 -0
  98. package/dist/src/task-record-reader.js +9 -0
  99. package/dist/src/validator-registry.d.ts +27 -0
  100. package/dist/src/validator-registry.js +64 -0
  101. package/package.json +166 -10
  102. package/dist/src/engineReadModelReducer.js +0 -1780
  103. package/dist/src/rig-init-builder.js +0 -57
  104. package/dist/src/rigSelectors.js +0 -293
  105. package/dist/src/taskGraph.js +0 -64
  106. package/dist/src/taskGraphCodes.js +0 -26
  107. package/dist/src/taskGraphLayout.js +0 -374
@@ -0,0 +1,756 @@
1
+ // @bun
2
+ // packages/core/src/load-config.ts
3
+ import { existsSync as existsSync2, mkdirSync, mkdtempSync, readFileSync as readFileSync2, readdirSync, rmSync, statSync } from "fs";
4
+ import { isBuiltin } from "module";
5
+ import { dirname, isAbsolute, join as join2, relative, resolve } from "path";
6
+ import { pathToFileURL } from "url";
7
+ import { Schema as Schema3 } from "effect";
8
+ import { RigConfig as RigConfig3 } from "@rig/contracts";
9
+
10
+ // packages/core/src/define-config.ts
11
+ import { Schema } from "effect";
12
+ import { RigConfig } from "@rig/contracts";
13
+ function normalizeWorkspaceConfig(raw) {
14
+ const workspace = raw && typeof raw === "object" && !Array.isArray(raw) ? { ...raw } : {};
15
+ if (workspace.mainRepo === undefined)
16
+ workspace.mainRepo = ".";
17
+ if (workspace.checkout === undefined && workspace.isolation !== undefined)
18
+ workspace.checkout = workspace.isolation;
19
+ if (workspace.isolation === undefined && workspace.checkout !== undefined)
20
+ workspace.isolation = workspace.checkout;
21
+ return workspace;
22
+ }
23
+ function applyConfigDefaults(raw) {
24
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
25
+ return raw;
26
+ const record = raw;
27
+ return {
28
+ ...record,
29
+ plugins: Array.isArray(record.plugins) ? record.plugins.flat() : [],
30
+ workspace: normalizeWorkspaceConfig(record.workspace)
31
+ };
32
+ }
33
+
34
+ // packages/core/src/declarative-config.ts
35
+ import { existsSync, readFileSync } from "fs";
36
+ import { join } from "path";
37
+ import { parse as parseToml } from "smol-toml";
38
+ import { Schema as Schema2 } from "effect";
39
+ import { RigConfig as RigConfig2 } from "@rig/contracts";
40
+
41
+ // packages/core/src/embedded-plugins.ts
42
+ var registered = null;
43
+ function getStandardPluginsResolver() {
44
+ return registered;
45
+ }
46
+ var bakedProjectConfig = null;
47
+ function getEmbeddedProjectConfig() {
48
+ return bakedProjectConfig;
49
+ }
50
+
51
+ // packages/core/src/declarative-config.ts
52
+ var DECLARATIVE_CONFIG_NAMES = ["rigfig.toml", "rigfig.json"];
53
+ function findDeclarativeConfigPath(cwd) {
54
+ const dir = join(cwd, ".rig");
55
+ for (const name of DECLARATIVE_CONFIG_NAMES) {
56
+ const candidate = join(dir, name);
57
+ if (existsSync(candidate))
58
+ return candidate;
59
+ }
60
+ return null;
61
+ }
62
+ function parseDeclarativeFile(path) {
63
+ const raw = readFileSync(path, "utf8");
64
+ const parsed = path.endsWith(".json") ? JSON.parse(raw) : parseToml(raw);
65
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
66
+ throw new Error(`Declarative config ${path} must parse to an object.`);
67
+ }
68
+ return parsed;
69
+ }
70
+ function loadDeclarativeConfig(path) {
71
+ const data = parseDeclarativeFile(path);
72
+ const standardSection = data.standard && typeof data.standard === "object" && !Array.isArray(data.standard) ? data.standard : {};
73
+ const useStandard = standardSection.enabled !== false;
74
+ let plugins = [];
75
+ if (useStandard) {
76
+ const resolver = getStandardPluginsResolver();
77
+ if (!resolver) {
78
+ throw new Error(`Declarative config ${path} needs the embedded standard plugins, but none were registered. ` + `This is a seed/boot wiring error (the binary entrypoint must import the standard-plugin registration).`);
79
+ }
80
+ plugins = resolver(data);
81
+ }
82
+ const { standard: _standardDirective, ...configFields } = data;
83
+ const withDefaults = applyConfigDefaults({ ...configFields, plugins });
84
+ const explicitPlugins = Array.isArray(withDefaults.plugins) ? [...withDefaults.plugins] : [];
85
+ const decoded = Schema2.decodeUnknownSync(RigConfig2)({
86
+ ...withDefaults,
87
+ plugins: explicitPlugins
88
+ });
89
+ return { ...decoded, plugins: explicitPlugins };
90
+ }
91
+
92
+ // packages/core/src/load-config.ts
93
+ var TS_NAMES = [".rig/rig.config.ts", ".rig/rig.config.mts"];
94
+ var JSON_NAMES = [".rig/rig.config.json"];
95
+ function isModuleResolutionError(error) {
96
+ const message = error instanceof Error ? error.message : String(error);
97
+ return message.includes("Cannot find module") || message.includes("Could not resolve");
98
+ }
99
+ function runningFromCompiledBinary() {
100
+ return import.meta.url.includes("$bunfs");
101
+ }
102
+ function packageNameAndSubpath(specifier) {
103
+ if (specifier.startsWith(".") || specifier.startsWith("/") || /^[a-zA-Z]+:/.test(specifier))
104
+ return null;
105
+ const parts = specifier.split("/");
106
+ const packageName = specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
107
+ if (!packageName)
108
+ return null;
109
+ const rest = parts.slice(specifier.startsWith("@") ? 2 : 1).join("/");
110
+ return { packageName, subpath: rest ? `./${rest}` : "." };
111
+ }
112
+ function exportTargetFromEntry(entry) {
113
+ if (typeof entry === "string")
114
+ return entry;
115
+ if (entry && typeof entry === "object" && !Array.isArray(entry)) {
116
+ const conditions = entry;
117
+ for (const key of ["bun", "import", "default", "require"]) {
118
+ if (typeof conditions[key] === "string")
119
+ return conditions[key];
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+ function patternExportTarget(record, subpath) {
125
+ for (const [pattern, entry] of Object.entries(record)) {
126
+ if (!pattern.includes("*"))
127
+ continue;
128
+ const [prefix = "", suffix = ""] = pattern.split("*");
129
+ if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix))
130
+ continue;
131
+ const replacement = subpath.slice(prefix.length, subpath.length - suffix.length);
132
+ const target = exportTargetFromEntry(entry);
133
+ if (target)
134
+ return target.replace("*", replacement);
135
+ }
136
+ return null;
137
+ }
138
+ function exportTargetFromPackageJson(pkg, subpath) {
139
+ const exportsField = pkg.exports;
140
+ const target = (() => {
141
+ if (typeof exportsField === "string" && subpath === ".")
142
+ return exportsField;
143
+ if (!exportsField || typeof exportsField !== "object" || Array.isArray(exportsField))
144
+ return null;
145
+ const record = exportsField;
146
+ return exportTargetFromEntry(record[subpath] ?? (subpath === "." ? record["."] : undefined)) ?? patternExportTarget(record, subpath);
147
+ })();
148
+ if (target)
149
+ return target;
150
+ return subpath === "." && typeof pkg.module === "string" ? pkg.module : subpath === "." && typeof pkg.main === "string" ? pkg.main : null;
151
+ }
152
+ function resolvePackageDirFromBunStore(packageName, nodeModulesDir) {
153
+ const storeDir = join2(nodeModulesDir, ".bun");
154
+ if (!existsSync2(storeDir))
155
+ return null;
156
+ const encoded = packageName.replace("/", "+");
157
+ try {
158
+ const candidates = readdirSync(storeDir).filter((entry) => entry.startsWith(`${encoded}@`)).map((entry) => {
159
+ const candidateDir = join2(storeDir, entry, "node_modules", packageName);
160
+ const packageJsonPath = join2(candidateDir, "package.json");
161
+ if (!existsSync2(packageJsonPath))
162
+ return null;
163
+ try {
164
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
165
+ return {
166
+ dir: candidateDir,
167
+ sortKey: pkg.version?.trim() || entry
168
+ };
169
+ } catch {
170
+ return {
171
+ dir: candidateDir,
172
+ sortKey: entry
173
+ };
174
+ }
175
+ }).filter((candidate) => candidate !== null).sort((a, b) => b.sortKey.localeCompare(a.sortKey, undefined, { numeric: true, sensitivity: "base" }));
176
+ return candidates[0]?.dir ?? null;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+ function resolveDirectoryModulePath(directoryPath) {
182
+ const packageJsonPath = join2(directoryPath, "package.json");
183
+ if (existsSync2(packageJsonPath)) {
184
+ try {
185
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
186
+ const target = exportTargetFromPackageJson(pkg, ".");
187
+ if (target) {
188
+ const resolved = resolveModulePath(join2(directoryPath, target));
189
+ if (resolved)
190
+ return resolved;
191
+ }
192
+ } catch {}
193
+ }
194
+ for (const candidate of ["index.js", "index.mjs", "index.cjs", "index.ts", "index.json"]) {
195
+ const resolved = resolveModulePath(join2(directoryPath, candidate));
196
+ if (resolved)
197
+ return resolved;
198
+ }
199
+ return null;
200
+ }
201
+ function resolveModulePath(candidatePath) {
202
+ if (!existsSync2(candidatePath)) {
203
+ for (const extension of [".ts", ".mts", ".tsx", ".js", ".mjs", ".cjs", ".json"]) {
204
+ const withExtension = `${candidatePath}${extension}`;
205
+ if (existsSync2(withExtension))
206
+ return resolveModulePath(withExtension);
207
+ }
208
+ return null;
209
+ }
210
+ try {
211
+ const stat = statSync(candidatePath);
212
+ if (stat.isFile())
213
+ return candidatePath;
214
+ if (stat.isDirectory())
215
+ return resolveDirectoryModulePath(candidatePath);
216
+ } catch {
217
+ return null;
218
+ }
219
+ return null;
220
+ }
221
+ function resolvePackageExportFromDir(packageDir, subpath) {
222
+ const packageJsonPath = join2(packageDir, "package.json");
223
+ if (existsSync2(packageJsonPath)) {
224
+ try {
225
+ const pkg = JSON.parse(readFileSync2(packageJsonPath, "utf8"));
226
+ const target = exportTargetFromPackageJson(pkg, subpath);
227
+ if (target) {
228
+ const resolved = resolveModulePath(join2(packageDir, target));
229
+ if (resolved)
230
+ return resolved;
231
+ }
232
+ } catch {
233
+ return null;
234
+ }
235
+ }
236
+ if (subpath !== ".") {
237
+ const legacySubpath = subpath.replace(/^\.\//, "");
238
+ for (const candidate of [
239
+ join2(packageDir, legacySubpath),
240
+ join2(packageDir, `${legacySubpath}.js`),
241
+ join2(packageDir, `${legacySubpath}.mjs`),
242
+ join2(packageDir, `${legacySubpath}.cjs`),
243
+ join2(packageDir, `${legacySubpath}.ts`),
244
+ join2(packageDir, `${legacySubpath}.json`)
245
+ ]) {
246
+ const resolved = resolveModulePath(candidate);
247
+ if (resolved)
248
+ return resolved;
249
+ }
250
+ }
251
+ return subpath === "." ? resolveDirectoryModulePath(packageDir) : null;
252
+ }
253
+ var runtimeBundleQueue = Promise.resolve();
254
+ function enqueueRuntimeBundle(operation) {
255
+ const next = runtimeBundleQueue.then(operation, operation);
256
+ runtimeBundleQueue = next.then(() => {
257
+ return;
258
+ }, () => {
259
+ return;
260
+ });
261
+ return next;
262
+ }
263
+ function isWithinDir(candidatePath, rootPath) {
264
+ const rel = relative(resolve(rootPath), resolve(candidatePath));
265
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
266
+ }
267
+ function resolvedFilePath(path, rootPath) {
268
+ if (!path || !isAbsolute(path))
269
+ return null;
270
+ const resolved = resolveModulePath(path);
271
+ if (!resolved)
272
+ return null;
273
+ return rootPath && !isWithinDir(resolved, rootPath) ? null : resolved;
274
+ }
275
+ function resolveProjectPackageImport(specifier, configDir) {
276
+ const parsed = packageNameAndSubpath(specifier);
277
+ if (!parsed)
278
+ return null;
279
+ const nodeModulesDir = join2(configDir, "node_modules");
280
+ const directPackageDir = join2(nodeModulesDir, parsed.packageName);
281
+ const packageDir = existsSync2(join2(directPackageDir, "package.json")) ? directPackageDir : resolvePackageDirFromBunStore(parsed.packageName, nodeModulesDir);
282
+ return packageDir ? resolvePackageExportFromDir(packageDir, parsed.subpath) : null;
283
+ }
284
+ function canImportRigWorkspacePackagesDirectly(source, configDir) {
285
+ const packageNames = new Set;
286
+ for (const match of source.matchAll(/(?:from\s*|import\s*\(\s*|import\s*)["'](@rig\/[^"']+)["']/g)) {
287
+ const parsed = packageNameAndSubpath(match[1] ?? "");
288
+ if (parsed?.packageName)
289
+ packageNames.add(parsed.packageName);
290
+ }
291
+ if (packageNames.size === 0)
292
+ return false;
293
+ for (const packageName of packageNames) {
294
+ const shortName = packageName.replace(/^@rig\//, "");
295
+ const manifestPath = join2(configDir, "packages", shortName, "package.json");
296
+ if (!existsSync2(manifestPath))
297
+ return false;
298
+ try {
299
+ const parsed = JSON.parse(readFileSync2(manifestPath, "utf8"));
300
+ if (parsed.name !== packageName)
301
+ return false;
302
+ } catch {
303
+ return false;
304
+ }
305
+ }
306
+ return true;
307
+ }
308
+ async function importConfigViaRuntimeBundleUnserialized(configPath) {
309
+ const bun = globalThis.Bun;
310
+ if (!bun?.build) {
311
+ throw new Error(`Failed to import ${configPath}: bare imports could not be resolved and no Bun.build runtime bundler is available.`);
312
+ }
313
+ const RUNTIME_ONLY_EXTERNAL_PACKAGES = new Set(["effect", "mupdf", "fastembed", "onnxruntime-node", "markit-ai"]);
314
+ const configDir = dirname(configPath);
315
+ const UNRESOLVED_NAMESPACE = "rig-config-unresolved";
316
+ const unresolvedLocalPlugin = {
317
+ name: "rig-config-unresolved-local",
318
+ setup(build) {
319
+ build.onLoad({ filter: /\.(?:html|txt)$/ }, (args) => ({
320
+ loader: "js",
321
+ contents: `export default ${JSON.stringify(readFileSync2(args.path, "utf8"))};
322
+ `
323
+ }));
324
+ build.onResolve({ filter: /.*/ }, (args) => {
325
+ const directFilePath = resolvedFilePath(args.path, configDir);
326
+ if (directFilePath)
327
+ return { path: directFilePath };
328
+ const packageImport = packageNameAndSubpath(args.path);
329
+ if (packageImport && (packageImport.packageName.startsWith("@rig/") || RUNTIME_ONLY_EXTERNAL_PACKAGES.has(packageImport.packageName))) {
330
+ return { path: args.path, external: true };
331
+ }
332
+ const projectPackagePath = resolveProjectPackageImport(args.path, configDir);
333
+ if (projectPackagePath)
334
+ return { path: projectPackagePath };
335
+ if (/^(?:node|bun):/.test(args.path) || isBuiltin(args.path))
336
+ return;
337
+ if (packageImport)
338
+ return { path: args.path, external: true };
339
+ const parentCandidates = args.path.startsWith(".") ? [args.importer && isAbsolute(args.importer) ? dirname(args.importer) : null, configDir].filter((value) => Boolean(value)) : [args.importer && isAbsolute(args.importer) ? dirname(args.importer) : configDir];
340
+ for (const parent2 of parentCandidates) {
341
+ const filePath = resolvedFilePath(resolve(parent2, args.path), configDir);
342
+ if (filePath)
343
+ return { path: filePath };
344
+ }
345
+ const parent = parentCandidates[0] ?? configDir;
346
+ try {
347
+ const resolved = bun.resolveSync?.(args.path, parent) ?? resolve(parent, args.path);
348
+ const filePath = resolvedFilePath(resolved, configDir);
349
+ if (filePath)
350
+ return { path: filePath };
351
+ } catch {}
352
+ return { path: args.path, namespace: UNRESOLVED_NAMESPACE };
353
+ });
354
+ build.onLoad({ filter: /.*/, namespace: UNRESOLVED_NAMESPACE }, (args) => ({
355
+ loader: "js",
356
+ contents: `module.exports = {};
357
+ throw new Error(${JSON.stringify(`Failed to bundle ${configPath}: Could not resolve local import "${args.path}". Maybe you need to fix a relative import in rig.config.ts or install project deps.`)});
358
+ `
359
+ }));
360
+ }
361
+ };
362
+ const result = await bun.build({
363
+ entrypoints: [configPath],
364
+ target: "bun",
365
+ external: ["effect", "mupdf", "fastembed", "onnxruntime-node", "markit-ai"],
366
+ format: "esm",
367
+ throw: false,
368
+ packages: "bundle",
369
+ plugins: [unresolvedLocalPlugin]
370
+ });
371
+ if (!result.success || !result.outputs[0]) {
372
+ const detail = result.logs.map((log) => String(log)).join(`
373
+ `);
374
+ throw new Error(`Failed to bundle ${configPath}: ${detail || "unknown bundler error"}`);
375
+ }
376
+ const bundleParentDir = join2(configDir, ".rig", "tmp");
377
+ mkdirSync(bundleParentDir, { recursive: true });
378
+ const dir = mkdtempSync(join2(bundleParentDir, "rig-config-bundle-"));
379
+ try {
380
+ const bundledPath = join2(dir, "rig.config.bundled.js");
381
+ await bun.write(bundledPath, await result.outputs[0].text());
382
+ return await import(pathToFileURL(bundledPath).href);
383
+ } finally {
384
+ try {
385
+ rmSync(dir, { recursive: true, force: true });
386
+ } catch {}
387
+ }
388
+ }
389
+ async function loadConfig(cwd) {
390
+ const baked = getEmbeddedProjectConfig();
391
+ if (baked && resolve(baked.projectRoot) === resolve(cwd)) {
392
+ return decodeExplicitPluginConfig(baked.raw);
393
+ }
394
+ for (const name of TS_NAMES) {
395
+ const p = join2(cwd, name);
396
+ if (existsSync2(p)) {
397
+ const mod = await enqueueRuntimeBundle(async () => {
398
+ if (runningFromCompiledBinary()) {
399
+ return importConfigViaRuntimeBundleUnserialized(p);
400
+ }
401
+ const source = readFileSync2(p, "utf8");
402
+ const importsRigHostPackages = /(?:import\s+[^;]*?from\s*|import\s*\()\s*["']@rig\//.test(source);
403
+ if (importsRigHostPackages && !canImportRigWorkspacePackagesDirectly(source, cwd)) {
404
+ return importConfigViaRuntimeBundleUnserialized(p);
405
+ }
406
+ try {
407
+ return await import(pathToFileURL(p).href);
408
+ } catch (error) {
409
+ if (!isModuleResolutionError(error))
410
+ throw error;
411
+ return importConfigViaRuntimeBundleUnserialized(p);
412
+ }
413
+ });
414
+ const raw = mod.default ?? mod.config;
415
+ return decodeExplicitPluginConfig(raw);
416
+ }
417
+ }
418
+ const declarativePath = findDeclarativeConfigPath(cwd);
419
+ if (declarativePath) {
420
+ return loadDeclarativeConfig(declarativePath);
421
+ }
422
+ for (const name of JSON_NAMES) {
423
+ const p = join2(cwd, name);
424
+ if (existsSync2(p)) {
425
+ const raw = JSON.parse(readFileSync2(p, "utf-8"));
426
+ return decodeExplicitPluginConfig(raw);
427
+ }
428
+ }
429
+ throw new Error(`no .rig/rig.config.{ts,mts,json} or .rig/rigfig.{toml,json} found in ${cwd}`);
430
+ }
431
+ function decodeExplicitPluginConfig(raw) {
432
+ const withDefaults = applyConfigDefaults(raw);
433
+ const explicitPlugins = Array.isArray(withDefaults.plugins) ? [...withDefaults.plugins] : [];
434
+ const decoded = Schema3.decodeUnknownSync(RigConfig3)({
435
+ ...withDefaults,
436
+ plugins: explicitPlugins
437
+ });
438
+ return { ...decoded, plugins: explicitPlugins };
439
+ }
440
+
441
+ // packages/core/src/hook-runtime.ts
442
+ import { appendFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, realpathSync, writeSync } from "fs";
443
+ import { resolve as resolve2 } from "path";
444
+ import { RIG_DEFINITION_DIRNAME, RIG_STATE_DIRNAME } from "@rig/contracts";
445
+ function normalizeBuildConfig(value) {
446
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
447
+ return {};
448
+ }
449
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string"));
450
+ }
451
+ function readBuildConfigForCoreHooks() {
452
+ if (typeof __RIG_BUILD_CONFIG__ !== "undefined") {
453
+ return normalizeBuildConfig(__RIG_BUILD_CONFIG__);
454
+ }
455
+ const raw = process.env.RIG_BUILD_CONFIG_JSON?.trim();
456
+ if (!raw) {
457
+ return {};
458
+ }
459
+ try {
460
+ return normalizeBuildConfig(JSON.parse(raw));
461
+ } catch {
462
+ return {};
463
+ }
464
+ }
465
+ var BUILD_CONFIG = readBuildConfigForCoreHooks();
466
+ var BAKED_PROJECT_ROOT = BUILD_CONFIG.AGENT_PROJECT_ROOT ?? "";
467
+ var BAKED_TASK_ID = BUILD_CONFIG.AGENT_TASK_ID ?? "";
468
+ var BAKED_STATE_DIR = BUILD_CONFIG.AGENT_STATE_DIR ?? "";
469
+ var BAKED_BUN_PATH = BUILD_CONFIG.AGENT_BUN_PATH ?? "";
470
+ var BAKED_TASK_CONFIG = BUILD_CONFIG.AGENT_TASK_CONFIG ?? "";
471
+ var BAKED_POLICY_CONTENT = BUILD_CONFIG.AGENT_POLICY_CONTENT ?? "";
472
+ var BAKED_TASK_SCOPES = BUILD_CONFIG.AGENT_TASK_SCOPES ?? "";
473
+ var RUNTIME_CONTEXT_ENV = "RIG_RUNTIME_CONTEXT_FILE";
474
+ function isPlainObject(value) {
475
+ return typeof value === "object" && value !== null && !Array.isArray(value);
476
+ }
477
+ function isStringArray(value) {
478
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
479
+ }
480
+ function loadHookContextFromEnv() {
481
+ const contextFile = process.env[RUNTIME_CONTEXT_ENV]?.trim();
482
+ let filePath = contextFile || "";
483
+ if (!filePath) {
484
+ let current = resolve2(process.cwd());
485
+ while (true) {
486
+ const candidate = resolve2(current, "runtime-context.json");
487
+ if (existsSync3(candidate)) {
488
+ filePath = candidate;
489
+ break;
490
+ }
491
+ const parent = resolve2(current, "..");
492
+ if (parent === current) {
493
+ break;
494
+ }
495
+ current = parent;
496
+ }
497
+ }
498
+ if (!filePath || !existsSync3(filePath)) {
499
+ return null;
500
+ }
501
+ try {
502
+ const raw = JSON.parse(readFileSync3(filePath, "utf-8"));
503
+ if (!isPlainObject(raw)) {
504
+ return null;
505
+ }
506
+ const taskId = typeof raw.taskId === "string" ? raw.taskId : "";
507
+ const role = typeof raw.role === "string" ? raw.role : "";
508
+ const scopes = isStringArray(raw.scopes) ? raw.scopes : [];
509
+ const validation = isStringArray(raw.validation) ? raw.validation : [];
510
+ const hostProjectRoot = typeof raw.hostProjectRoot === "string" ? raw.hostProjectRoot : undefined;
511
+ const monorepoMainRoot = typeof raw.monorepoMainRoot === "string" ? raw.monorepoMainRoot : undefined;
512
+ const stateDir = typeof raw.stateDir === "string" ? raw.stateDir : "";
513
+ const policyFile = typeof raw.policyFile === "string" ? raw.policyFile : "";
514
+ if (!taskId || !stateDir) {
515
+ return null;
516
+ }
517
+ return {
518
+ taskId,
519
+ role,
520
+ scopes,
521
+ validation,
522
+ hostProjectRoot,
523
+ monorepoMainRoot,
524
+ stateDir,
525
+ policyFile
526
+ };
527
+ } catch {
528
+ return null;
529
+ }
530
+ }
531
+ var cachedContext;
532
+ function getContext() {
533
+ if (cachedContext !== undefined) {
534
+ return cachedContext;
535
+ }
536
+ cachedContext = loadHookContextFromEnv();
537
+ return cachedContext;
538
+ }
539
+ function resolveProjectRoot() {
540
+ const ctx = getContext();
541
+ if (ctx?.hostProjectRoot)
542
+ return ctx.hostProjectRoot;
543
+ if (BAKED_PROJECT_ROOT) {
544
+ return BAKED_PROJECT_ROOT;
545
+ }
546
+ if (process.env.PROJECT_RIG_ROOT) {
547
+ return process.env.PROJECT_RIG_ROOT;
548
+ }
549
+ const candidates = [process.cwd(), resolve2(import.meta.dirname, "../..")];
550
+ for (const candidate of candidates) {
551
+ if (existsSync3(resolve2(candidate, RIG_DEFINITION_DIRNAME)) || existsSync3(resolve2(candidate, RIG_STATE_DIRNAME))) {
552
+ return candidate;
553
+ }
554
+ }
555
+ return resolve2(import.meta.dirname, "../..");
556
+ }
557
+ function resolveTaskIdForHook(_projectRoot) {
558
+ const ctx = getContext();
559
+ if (ctx)
560
+ return ctx.taskId;
561
+ if (BAKED_TASK_ID) {
562
+ return BAKED_TASK_ID;
563
+ }
564
+ const fromEnv = (process.env.RIG_TASK_ID || "").trim();
565
+ if (fromEnv) {
566
+ return fromEnv;
567
+ }
568
+ const runtimeId = (process.env.RIG_TASK_RUNTIME_ID || "").trim();
569
+ if (runtimeId.startsWith("task-") && runtimeId.length > "task-".length) {
570
+ return runtimeId.slice("task-".length);
571
+ }
572
+ return "";
573
+ }
574
+ async function readHookInput() {
575
+ let text = "";
576
+ const inputFile = process.env.RIG_HOOK_INPUT_FILE?.trim();
577
+ if (inputFile) {
578
+ text = readFileSync3(inputFile, "utf-8");
579
+ } else {
580
+ try {
581
+ text = readFileSync3("/dev/stdin", "utf-8");
582
+ } catch {
583
+ text = readFileSync3(0, "utf-8");
584
+ }
585
+ }
586
+ if (!text.trim()) {
587
+ return { input: {}, valid: true, hadPayload: false };
588
+ }
589
+ try {
590
+ return {
591
+ input: JSON.parse(text),
592
+ valid: true,
593
+ hadPayload: true
594
+ };
595
+ } catch {
596
+ return { input: {}, valid: false, hadPayload: true };
597
+ }
598
+ }
599
+ function extractToolFilePaths(toolName, input) {
600
+ const paths = [];
601
+ const add = (value) => {
602
+ if (typeof value === "string" && value.trim()) {
603
+ paths.push(value.trim());
604
+ }
605
+ };
606
+ if (toolName === "Read" || toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
607
+ add(input.file_path);
608
+ add(input.path);
609
+ } else if (toolName === "Glob") {
610
+ add(input.path);
611
+ } else if (toolName === "Grep") {
612
+ add(input.path);
613
+ } else {
614
+ add(input.file_path);
615
+ add(input.path);
616
+ }
617
+ return paths;
618
+ }
619
+ function buildPluginHookContext(parsed, opts) {
620
+ const toolName = parsed.input.tool_name;
621
+ const toolInput = parsed.input.tool_input ?? {};
622
+ return {
623
+ event: opts.event,
624
+ toolName,
625
+ toolInput,
626
+ filePaths: toolName ? extractToolFilePaths(toolName, toolInput) : [],
627
+ projectRoot: opts.projectRoot,
628
+ taskId: opts.taskId
629
+ };
630
+ }
631
+ function hookResultToProtocol(result) {
632
+ if (result.decision === "block") {
633
+ const lines = [`BLOCKED: ${result.reason ?? "blocked by plugin hook"}`];
634
+ if (result.systemMessage) {
635
+ lines.push(result.systemMessage);
636
+ }
637
+ return { exitCode: 1, stdout: `${lines.join(`
638
+ `)}
639
+ ` };
640
+ }
641
+ return {
642
+ exitCode: 0,
643
+ stdout: result.systemMessage ? `${result.systemMessage}
644
+ ` : ""
645
+ };
646
+ }
647
+ async function runTypedHook(fn, opts) {
648
+ const parsed = await readHookInput();
649
+ const projectRoot = opts.projectRoot ?? resolveProjectRoot();
650
+ const taskId = opts.taskId ?? resolveTaskIdForHook(projectRoot);
651
+ const ctx = buildPluginHookContext(parsed, {
652
+ event: opts.event,
653
+ projectRoot,
654
+ taskId
655
+ });
656
+ let result;
657
+ try {
658
+ result = await fn(ctx);
659
+ } catch (err) {
660
+ const message = err instanceof Error ? err.message : String(err);
661
+ writeSync(2, `[rig hook] typed hook threw: ${message}
662
+ `);
663
+ process.exit(0);
664
+ }
665
+ const { exitCode, stdout } = hookResultToProtocol(result);
666
+ if (stdout) {
667
+ writeSync(1, stdout);
668
+ }
669
+ process.exit(exitCode);
670
+ }
671
+
672
+ // packages/core/src/hook-runner.ts
673
+ function parseHookRunnerArgs(argv) {
674
+ const args = {};
675
+ for (let i = 0;i < argv.length; i += 1) {
676
+ const flag = argv[i];
677
+ const value = argv[i + 1];
678
+ if (value === undefined)
679
+ break;
680
+ switch (flag) {
681
+ case "--plugin":
682
+ args.plugin = value;
683
+ i += 1;
684
+ break;
685
+ case "--hook":
686
+ args.hook = value;
687
+ i += 1;
688
+ break;
689
+ case "--event":
690
+ args.event = value;
691
+ i += 1;
692
+ break;
693
+ case "--project-root":
694
+ args.projectRoot = value;
695
+ i += 1;
696
+ break;
697
+ default:
698
+ break;
699
+ }
700
+ }
701
+ return args;
702
+ }
703
+ function findTypedHook(plugins, pluginName, hookId) {
704
+ const plugin = plugins.find((p) => p.name === pluginName);
705
+ if (!plugin) {
706
+ return { hook: null, reason: `plugin "${pluginName}" not found in rig config` };
707
+ }
708
+ const registration = (plugin.contributes?.hooks ?? []).find((h) => h.id === hookId);
709
+ if (!registration) {
710
+ return {
711
+ hook: null,
712
+ reason: `plugin "${pluginName}" has no metadata entry for hook "${hookId}"`
713
+ };
714
+ }
715
+ const implementation = registration.handler;
716
+ if (!implementation) {
717
+ return {
718
+ hook: null,
719
+ reason: `plugin "${pluginName}" has no typed implementation for hook "${hookId}"`
720
+ };
721
+ }
722
+ return { hook: { implementation, registration } };
723
+ }
724
+ function warnAndAllow(message) {
725
+ process.stderr.write(`[rig hook-runner] ${message} \u2014 allowing
726
+ `);
727
+ process.exit(0);
728
+ }
729
+ async function main(argv) {
730
+ const args = parseHookRunnerArgs(argv);
731
+ if (!args.plugin || !args.hook) {
732
+ warnAndAllow("missing --plugin/--hook arguments");
733
+ }
734
+ const projectRoot = args.projectRoot?.trim() || process.env.CLAUDE_PROJECT_DIR?.trim() || process.cwd();
735
+ let plugins;
736
+ try {
737
+ const config = await loadConfig(projectRoot);
738
+ plugins = config.plugins;
739
+ } catch (err) {
740
+ warnAndAllow(`failed to load rig config from ${projectRoot}: ${err instanceof Error ? err.message : String(err)}`);
741
+ }
742
+ const { hook, reason } = findTypedHook(plugins, args.plugin, args.hook);
743
+ if (!hook) {
744
+ warnAndAllow(reason ?? "typed hook not found");
745
+ }
746
+ const event = hook.registration.event;
747
+ return runTypedHook(hook.implementation, { event, projectRoot });
748
+ }
749
+ if (import.meta.main) {
750
+ main(process.argv.slice(2));
751
+ }
752
+ export {
753
+ parseHookRunnerArgs,
754
+ main,
755
+ findTypedHook
756
+ };