@h-rig/runtime 0.0.6-alpha.0

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 (176) hide show
  1. package/README.md +27 -0
  2. package/dist/bin/rig-agent-dispatch.js +9615 -0
  3. package/dist/bin/rig-agent.js +9512 -0
  4. package/dist/bin/rig-browser-tool.js +269 -0
  5. package/dist/src/agent-mode.js +48 -0
  6. package/dist/src/baked-secrets.js +121 -0
  7. package/dist/src/binary-build-worker.js +312 -0
  8. package/dist/src/binary-run.js +540 -0
  9. package/dist/src/boundaries.js +1 -0
  10. package/dist/src/build-time-config.js +25 -0
  11. package/dist/src/control-plane/agent-roles.js +27 -0
  12. package/dist/src/control-plane/agent-wrapper.js +9621 -0
  13. package/dist/src/control-plane/authority-files.js +582 -0
  14. package/dist/src/control-plane/browser-contract.js +135 -0
  15. package/dist/src/control-plane/controlled-bash.js +1111 -0
  16. package/dist/src/control-plane/errors.js +13 -0
  17. package/dist/src/control-plane/harness-main.js +10828 -0
  18. package/dist/src/control-plane/hook-materializer.js +75 -0
  19. package/dist/src/control-plane/hooks/audit-trail.js +353 -0
  20. package/dist/src/control-plane/hooks/completion-verification.js +7552 -0
  21. package/dist/src/control-plane/hooks/import-guard.js +890 -0
  22. package/dist/src/control-plane/hooks/inject-context.js +4189 -0
  23. package/dist/src/control-plane/hooks/post-edit-lint.js +43 -0
  24. package/dist/src/control-plane/hooks/safety-guard.js +910 -0
  25. package/dist/src/control-plane/hooks/scope-guard.js +907 -0
  26. package/dist/src/control-plane/hooks/shared.js +44 -0
  27. package/dist/src/control-plane/hooks/submodule-branch.js +7797 -0
  28. package/dist/src/control-plane/hooks/task-runtime-start.js +7799 -0
  29. package/dist/src/control-plane/hooks/test-integrity-guard.js +891 -0
  30. package/dist/src/control-plane/materialize-task-config.js +453 -0
  31. package/dist/src/control-plane/memory-sync/cli.js +2019 -0
  32. package/dist/src/control-plane/memory-sync/db.js +753 -0
  33. package/dist/src/control-plane/memory-sync/embed.js +281 -0
  34. package/dist/src/control-plane/memory-sync/index.js +2049 -0
  35. package/dist/src/control-plane/memory-sync/query.js +294 -0
  36. package/dist/src/control-plane/memory-sync/read.js +784 -0
  37. package/dist/src/control-plane/memory-sync/types.js +6 -0
  38. package/dist/src/control-plane/memory-sync/write.js +1547 -0
  39. package/dist/src/control-plane/native/git-native.js +490 -0
  40. package/dist/src/control-plane/native/git-ops.js +2860 -0
  41. package/dist/src/control-plane/native/harness-cli.js +9721 -0
  42. package/dist/src/control-plane/native/pr-automation.js +373 -0
  43. package/dist/src/control-plane/native/profile-ops.js +481 -0
  44. package/dist/src/control-plane/native/repo-ops.js +2342 -0
  45. package/dist/src/control-plane/native/root-resolver.js +66 -0
  46. package/dist/src/control-plane/native/run-ops.js +3281 -0
  47. package/dist/src/control-plane/native/runtime-native-sidecar.js +299 -0
  48. package/dist/src/control-plane/native/runtime-native.js +392 -0
  49. package/dist/src/control-plane/native/scope-rules.js +17 -0
  50. package/dist/src/control-plane/native/task-ops.js +6320 -0
  51. package/dist/src/control-plane/native/task-state.js +1512 -0
  52. package/dist/src/control-plane/native/utils.js +535 -0
  53. package/dist/src/control-plane/native/validator-binaries.js +889 -0
  54. package/dist/src/control-plane/native/validator.js +2197 -0
  55. package/dist/src/control-plane/native/verifier.js +3249 -0
  56. package/dist/src/control-plane/native/workspace-ops.js +1635 -0
  57. package/dist/src/control-plane/plugin-host-context.js +334 -0
  58. package/dist/src/control-plane/project-main-pre-run-sync.js +630 -0
  59. package/dist/src/control-plane/provider/claude-stream-records.js +158 -0
  60. package/dist/src/control-plane/provider/codex-app-server.js +885 -0
  61. package/dist/src/control-plane/provider/codex-exec-records.js +203 -0
  62. package/dist/src/control-plane/provider/rig-task-run-skill.js +39 -0
  63. package/dist/src/control-plane/provider/runtime-instructions.js +96 -0
  64. package/dist/src/control-plane/remote.js +854 -0
  65. package/dist/src/control-plane/repos/index.js +473 -0
  66. package/dist/src/control-plane/repos/layout.js +124 -0
  67. package/dist/src/control-plane/repos/mirror/bootstrap.js +268 -0
  68. package/dist/src/control-plane/repos/mirror/refresh.js +398 -0
  69. package/dist/src/control-plane/repos/mirror/state.js +167 -0
  70. package/dist/src/control-plane/repos/registry.js +77 -0
  71. package/dist/src/control-plane/repos/types.js +1 -0
  72. package/dist/src/control-plane/runtime/agent-mode.js +48 -0
  73. package/dist/src/control-plane/runtime/baked-secrets.js +120 -0
  74. package/dist/src/control-plane/runtime/claude-tool-router-binary.js +343 -0
  75. package/dist/src/control-plane/runtime/claude-tool-router.js +520 -0
  76. package/dist/src/control-plane/runtime/context.js +216 -0
  77. package/dist/src/control-plane/runtime/events.js +218 -0
  78. package/dist/src/control-plane/runtime/guard-types.js +6 -0
  79. package/dist/src/control-plane/runtime/guard.js +880 -0
  80. package/dist/src/control-plane/runtime/image/fingerprint-sidecar.js +1194 -0
  81. package/dist/src/control-plane/runtime/image/index.js +2255 -0
  82. package/dist/src/control-plane/runtime/image-fingerprint-sidecar.js +1191 -0
  83. package/dist/src/control-plane/runtime/image.js +2255 -0
  84. package/dist/src/control-plane/runtime/index.js +8511 -0
  85. package/dist/src/control-plane/runtime/isolation/discovery.js +599 -0
  86. package/dist/src/control-plane/runtime/isolation/home.js +1217 -0
  87. package/dist/src/control-plane/runtime/isolation/index.js +8193 -0
  88. package/dist/src/control-plane/runtime/isolation/runner.js +2651 -0
  89. package/dist/src/control-plane/runtime/isolation/shared.js +501 -0
  90. package/dist/src/control-plane/runtime/isolation/toolchain.js +1892 -0
  91. package/dist/src/control-plane/runtime/isolation/types.js +1 -0
  92. package/dist/src/control-plane/runtime/isolation/worktree.js +509 -0
  93. package/dist/src/control-plane/runtime/isolation.js +8193 -0
  94. package/dist/src/control-plane/runtime/overlay.js +67 -0
  95. package/dist/src/control-plane/runtime/plugin-mode.js +41 -0
  96. package/dist/src/control-plane/runtime/plugins.js +1131 -0
  97. package/dist/src/control-plane/runtime/provisioning-env.js +220 -0
  98. package/dist/src/control-plane/runtime/queue.js +8358 -0
  99. package/dist/src/control-plane/runtime/rig-shell.js +205 -0
  100. package/dist/src/control-plane/runtime/rig-tools.js +182 -0
  101. package/dist/src/control-plane/runtime/runner-context.js +1 -0
  102. package/dist/src/control-plane/runtime/runtime-paths.js +184 -0
  103. package/dist/src/control-plane/runtime/sandbox/backend-bwrap.js +311 -0
  104. package/dist/src/control-plane/runtime/sandbox/backend-none.js +21 -0
  105. package/dist/src/control-plane/runtime/sandbox/backend-seatbelt.js +268 -0
  106. package/dist/src/control-plane/runtime/sandbox/backend.js +1718 -0
  107. package/dist/src/control-plane/runtime/sandbox/orchestrator.js +1745 -0
  108. package/dist/src/control-plane/runtime/sandbox/utils.js +137 -0
  109. package/dist/src/control-plane/runtime/sandbox-backend-bwrap.js +311 -0
  110. package/dist/src/control-plane/runtime/sandbox-backend-none.js +21 -0
  111. package/dist/src/control-plane/runtime/sandbox-backend-seatbelt.js +268 -0
  112. package/dist/src/control-plane/runtime/sandbox-backend.js +1718 -0
  113. package/dist/src/control-plane/runtime/sandbox-orchestrator.js +1745 -0
  114. package/dist/src/control-plane/runtime/sandbox-utils.js +137 -0
  115. package/dist/src/control-plane/runtime/snapshot/index.js +454 -0
  116. package/dist/src/control-plane/runtime/snapshot/sidecar.js +502 -0
  117. package/dist/src/control-plane/runtime/snapshot/task-run.js +1578 -0
  118. package/dist/src/control-plane/runtime/snapshot-sidecar.js +498 -0
  119. package/dist/src/control-plane/runtime/snapshot.js +454 -0
  120. package/dist/src/control-plane/runtime/task-run-snapshot.js +1578 -0
  121. package/dist/src/control-plane/runtime/tool-gateway.js +422 -0
  122. package/dist/src/control-plane/runtime/tooling/browser-tools.js +32 -0
  123. package/dist/src/control-plane/runtime/tooling/claude-router-binary.js +343 -0
  124. package/dist/src/control-plane/runtime/tooling/claude-router.js +524 -0
  125. package/dist/src/control-plane/runtime/tooling/file-tools.js +182 -0
  126. package/dist/src/control-plane/runtime/tooling/gateway.js +422 -0
  127. package/dist/src/control-plane/runtime/tooling/index.js +1290 -0
  128. package/dist/src/control-plane/runtime/tooling/shell.js +205 -0
  129. package/dist/src/control-plane/runtime/types.js +1 -0
  130. package/dist/src/control-plane/setup-version.js +14 -0
  131. package/dist/src/control-plane/state-sync/index.js +1509 -0
  132. package/dist/src/control-plane/state-sync/read.js +856 -0
  133. package/dist/src/control-plane/state-sync/reconcile.js +260 -0
  134. package/dist/src/control-plane/state-sync/repo.js +302 -0
  135. package/dist/src/control-plane/state-sync/types.js +111 -0
  136. package/dist/src/control-plane/state-sync/write.js +1469 -0
  137. package/dist/src/control-plane/task-fields.js +38 -0
  138. package/dist/src/control-plane/task-source-bootstrap.js +46 -0
  139. package/dist/src/control-plane/task-source.js +30 -0
  140. package/dist/src/control-plane/tasks/legacy-task-config-source.js +130 -0
  141. package/dist/src/control-plane/tasks/plugin-task-source.js +103 -0
  142. package/dist/src/control-plane/tasks/source-aware-task-config-source.js +611 -0
  143. package/dist/src/control-plane/tasks/source-lifecycle.js +1093 -0
  144. package/dist/src/control-plane/tasks/task-record-reader.js +9 -0
  145. package/dist/src/control-plane/validators/boundary/public-apis.js +107 -0
  146. package/dist/src/control-plane/validators/integration/_shared.js +51 -0
  147. package/dist/src/control-plane/validators/integration/adm-audit-http.js +85 -0
  148. package/dist/src/control-plane/validators/integration/adm-auth-http.js +78 -0
  149. package/dist/src/control-plane/validators/integration/adm-issuer-http.js +80 -0
  150. package/dist/src/control-plane/validators/integration/adm-migration.js +78 -0
  151. package/dist/src/control-plane/validators/integration/adm-scaffold.js +78 -0
  152. package/dist/src/control-plane/validators/runtime-registration.js +64 -0
  153. package/dist/src/control-plane/validators/shared.js +683 -0
  154. package/dist/src/events.js +218 -0
  155. package/dist/src/execution.js +35 -0
  156. package/dist/src/index.js +1633 -0
  157. package/dist/src/layout.js +145 -0
  158. package/dist/src/local-server.js +202 -0
  159. package/dist/src/plugins.js +329 -0
  160. package/dist/src/remote-http.js +83 -0
  161. package/dist/src/runtime-context.js +216 -0
  162. package/dist/src/types.js +1 -0
  163. package/native/darwin-arm64/bin/rig-git +0 -0
  164. package/native/darwin-arm64/bin/rig-shell +0 -0
  165. package/native/darwin-arm64/bin/rig-tools +0 -0
  166. package/native/darwin-arm64/lib/runtime-native-darwin-arm64.dylib +0 -0
  167. package/native/darwin-arm64/lib/runtime-native.dylib +0 -0
  168. package/native/darwin-arm64/manifest.json +1 -0
  169. package/native/linux-x64/bin/rig-git +0 -0
  170. package/native/linux-x64/bin/rig-shell +0 -0
  171. package/native/linux-x64/bin/rig-tools +0 -0
  172. package/native/linux-x64/lib/runtime-native-linux-x64.so +0 -0
  173. package/native/linux-x64/lib/runtime-native.so +0 -0
  174. package/native/linux-x64/manifest.json +1 -0
  175. package/package.json +74 -0
  176. package/skills/rig-task-run.md +71 -0
@@ -0,0 +1,630 @@
1
+ // @bun
2
+ // packages/runtime/src/layout.ts
3
+ import { existsSync } from "fs";
4
+ import { basename, dirname, resolve } from "path";
5
+ function resolveMonorepoRoot(projectRoot) {
6
+ const normalizedProjectRoot = resolve(projectRoot);
7
+ const explicit = process.env.MONOREPO_ROOT?.trim();
8
+ if (explicit) {
9
+ const explicitRoot = resolve(explicit);
10
+ const explicitParent = dirname(explicitRoot);
11
+ if (basename(explicitParent) === ".worktrees") {
12
+ const owner = dirname(explicitParent);
13
+ const ownerHasGit = existsSync(resolve(owner, ".git"));
14
+ const ownerHasTaskConfig = existsSync(resolve(owner, ".rig", "task-config.json"));
15
+ const ownerHasRigConfig = existsSync(resolve(owner, "rig.config.ts"));
16
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
17
+ return owner;
18
+ }
19
+ throw new Error(`MONOREPO_ROOT points to worktree ${explicitRoot}, but the owner checkout is incomplete at ${owner}.`);
20
+ }
21
+ if (!existsSync(resolve(explicitRoot, ".git"))) {
22
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there.`);
23
+ }
24
+ const hasTaskConfig = existsSync(resolve(explicitRoot, ".rig", "task-config.json"));
25
+ const hasRigConfig = existsSync(resolve(explicitRoot, "rig.config.ts"));
26
+ if (!hasTaskConfig && !hasRigConfig) {
27
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but neither .rig/task-config.json nor rig.config.ts exists there.`);
28
+ }
29
+ return explicitRoot;
30
+ }
31
+ const projectParent = dirname(normalizedProjectRoot);
32
+ if (basename(projectParent) === ".worktrees") {
33
+ const worktreeOwner = dirname(projectParent);
34
+ const ownerHasGit = existsSync(resolve(worktreeOwner, ".git"));
35
+ const ownerHasTaskConfig = existsSync(resolve(worktreeOwner, ".rig", "task-config.json"));
36
+ const ownerHasRigConfig = existsSync(resolve(worktreeOwner, "rig.config.ts"));
37
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
38
+ return worktreeOwner;
39
+ }
40
+ }
41
+ return normalizedProjectRoot;
42
+ }
43
+
44
+ // packages/runtime/src/control-plane/native/runtime-native.ts
45
+ import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
46
+ import { copyFileSync, existsSync as existsSync2, mkdirSync, renameSync, rmSync, statSync } from "fs";
47
+ import { tmpdir } from "os";
48
+ import { dirname as dirname2, resolve as resolve2 } from "path";
49
+ var sharedNativeRuntimeOutputDir = resolve2(tmpdir(), "rig-native");
50
+ var sharedNativeRuntimeOutputPath = resolve2(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
51
+ var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
52
+ var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
53
+ async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
54
+ if (await buildNativeRuntimeLibrary(outputPath, options)) {
55
+ return outputPath;
56
+ }
57
+ return !options.force && existsSync2(outputPath) ? outputPath : null;
58
+ }
59
+ async function loadNativeRuntimeLibrary() {
60
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
61
+ return null;
62
+ }
63
+ for (const candidate of nativeRuntimeLibraryCandidates()) {
64
+ if (!candidate || !existsSync2(candidate)) {
65
+ continue;
66
+ }
67
+ const loaded = tryDlopenNativeRuntimeLibrary(candidate);
68
+ if (loaded) {
69
+ return loaded;
70
+ }
71
+ }
72
+ const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
73
+ if (!builtLibraryPath) {
74
+ return null;
75
+ }
76
+ return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
77
+ }
78
+ function nativePackageLibraryCandidates(fromDir, names) {
79
+ const candidates = [];
80
+ let cursor = resolve2(fromDir);
81
+ for (let index = 0;index < 8; index += 1) {
82
+ for (const name of names) {
83
+ candidates.push(resolve2(cursor, "native", `${process.platform}-${process.arch}`, name), resolve2(cursor, "native", `${process.platform}-${process.arch}`, "lib", name), resolve2(cursor, "native", name), resolve2(cursor, "native", "lib", name));
84
+ }
85
+ const parent = dirname2(cursor);
86
+ if (parent === cursor)
87
+ break;
88
+ cursor = parent;
89
+ }
90
+ return candidates;
91
+ }
92
+ function nativeRuntimeLibraryCandidates() {
93
+ const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
94
+ const execDir = process.execPath?.trim() ? dirname2(process.execPath.trim()) : "";
95
+ const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
96
+ return [...new Set([
97
+ explicit,
98
+ ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
99
+ execDir ? resolve2(execDir, colocatedNativeRuntimeFileName) : "",
100
+ execDir ? resolve2(execDir, platformSpecific) : "",
101
+ execDir ? resolve2(execDir, "..", colocatedNativeRuntimeFileName) : "",
102
+ execDir ? resolve2(execDir, "..", platformSpecific) : "",
103
+ execDir ? resolve2(execDir, "lib", colocatedNativeRuntimeFileName) : "",
104
+ execDir ? resolve2(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
105
+ sharedNativeRuntimeOutputPath
106
+ ].filter(Boolean))];
107
+ }
108
+ function resolveNativeRuntimeSourcePath() {
109
+ const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
110
+ if (explicit && existsSync2(explicit)) {
111
+ return explicit;
112
+ }
113
+ const bundled = resolve2(import.meta.dir, "../../../native/snapshot.zig");
114
+ return existsSync2(bundled) ? bundled : null;
115
+ }
116
+ async function buildNativeRuntimeLibrary(outputPath, options = {}) {
117
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
118
+ return false;
119
+ }
120
+ const zigBinary = Bun.which("zig");
121
+ const sourcePath = resolveNativeRuntimeSourcePath();
122
+ if (!zigBinary || !sourcePath) {
123
+ return false;
124
+ }
125
+ const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
126
+ try {
127
+ mkdirSync(dirname2(outputPath), { recursive: true });
128
+ const needsBuild = options.force === true || !existsSync2(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
129
+ if (!needsBuild) {
130
+ return true;
131
+ }
132
+ const build = Bun.spawn([
133
+ zigBinary,
134
+ "build-lib",
135
+ sourcePath,
136
+ "-dynamic",
137
+ "-O",
138
+ "ReleaseFast",
139
+ `-femit-bin=${tempOutputPath}`
140
+ ], {
141
+ cwd: import.meta.dir,
142
+ stdout: "pipe",
143
+ stderr: "pipe"
144
+ });
145
+ const exitCode = await build.exited;
146
+ if (exitCode !== 0 || !existsSync2(tempOutputPath)) {
147
+ rmSync(tempOutputPath, { force: true });
148
+ return false;
149
+ }
150
+ renameSync(tempOutputPath, outputPath);
151
+ return true;
152
+ } catch {
153
+ rmSync(tempOutputPath, { force: true });
154
+ return false;
155
+ }
156
+ }
157
+ function tryDlopenNativeRuntimeLibrary(outputPath) {
158
+ try {
159
+ return dlopen(outputPath, {
160
+ rig_scope_match: {
161
+ args: ["ptr", "ptr"],
162
+ returns: "u8"
163
+ },
164
+ snapshot_capture: {
165
+ args: ["ptr", "u64", "ptr", "u64"],
166
+ returns: "ptr"
167
+ },
168
+ snapshot_delta: {
169
+ args: ["ptr", "ptr"],
170
+ returns: "ptr"
171
+ },
172
+ snapshot_store_delta: {
173
+ args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
174
+ returns: "ptr"
175
+ },
176
+ snapshot_inspect_delta: {
177
+ args: ["ptr", "u64"],
178
+ returns: "ptr"
179
+ },
180
+ snapshot_apply_delta: {
181
+ args: ["ptr", "u64", "ptr", "u64"],
182
+ returns: "ptr"
183
+ },
184
+ snapshot_release: {
185
+ args: ["ptr"],
186
+ returns: "void"
187
+ },
188
+ runtime_hash_file: {
189
+ args: ["ptr", "u64"],
190
+ returns: "ptr"
191
+ },
192
+ runtime_hash_tree: {
193
+ args: ["ptr", "u64"],
194
+ returns: "ptr"
195
+ },
196
+ runtime_prepare_paths: {
197
+ args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
198
+ returns: "ptr"
199
+ },
200
+ runtime_link_dependency_layer: {
201
+ args: ["ptr", "u64", "ptr", "u64"],
202
+ returns: "ptr"
203
+ },
204
+ runtime_scan_worktrees: {
205
+ args: ["ptr", "u64"],
206
+ returns: "ptr"
207
+ }
208
+ });
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+
214
+ // packages/runtime/src/control-plane/native/utils.ts
215
+ var scopeRegexCache = new Map;
216
+ function runCapture(command, cwd, env) {
217
+ const result = Bun.spawnSync(command, {
218
+ cwd,
219
+ env: env ? { ...process.env, ...env } : process.env,
220
+ stdout: "pipe",
221
+ stderr: "pipe"
222
+ });
223
+ return {
224
+ exitCode: result.exitCode,
225
+ stdout: result.stdout.toString(),
226
+ stderr: result.stderr.toString()
227
+ };
228
+ }
229
+
230
+ // packages/runtime/src/control-plane/repos/registry.ts
231
+ var MANAGED_REPOS = new Map;
232
+ function getManagedRepoEntry(repoId) {
233
+ const entry = MANAGED_REPOS.get(repoId);
234
+ if (!entry) {
235
+ throw new Error(`managed repo not registered: ${repoId}. Plugins contribute repos via RigPlugin.contributes.repoSources; ` + `make sure a plugin declares this id and the plugin host has been initialized.`);
236
+ }
237
+ return entry;
238
+ }
239
+ function listManagedRepoEntries() {
240
+ return Array.from(MANAGED_REPOS.values());
241
+ }
242
+ // packages/runtime/src/control-plane/repos/layout.ts
243
+ import { existsSync as existsSync3 } from "fs";
244
+ import { basename as basename2, dirname as dirname3, join, resolve as resolve3 } from "path";
245
+ function resolveRepoStateDir(projectRoot) {
246
+ const normalizedProjectRoot = resolve3(projectRoot);
247
+ const projectParent = dirname3(normalizedProjectRoot);
248
+ if (basename2(projectParent) === ".worktrees") {
249
+ const ownerRoot = dirname3(projectParent);
250
+ const ownerHasRepoMarkers = existsSync3(resolve3(ownerRoot, ".git")) || existsSync3(resolve3(ownerRoot, ".rig", "state"));
251
+ if (ownerHasRepoMarkers) {
252
+ return resolve3(ownerRoot, ".rig", "state");
253
+ }
254
+ }
255
+ return resolve3(projectRoot, ".rig", "state");
256
+ }
257
+ function resolveManagedRepoLayout(projectRoot, repoId) {
258
+ const normalizedProjectRoot = resolve3(projectRoot);
259
+ const entry = getManagedRepoEntry(repoId);
260
+ const stateDir = resolveRepoStateDir(normalizedProjectRoot);
261
+ const metadataRelativePath = join("repos", entry.id);
262
+ const metadataRoot = resolve3(stateDir, metadataRelativePath);
263
+ const runtimeWorkspace = process.env.RIG_TASK_WORKSPACE?.trim();
264
+ const runsInsideTaskWorktree = runtimeWorkspace && resolve3(runtimeWorkspace) === normalizedProjectRoot || basename2(dirname3(normalizedProjectRoot)) === ".worktrees";
265
+ const isPrimaryManagedRepo = listManagedRepoEntries()[0]?.id === repoId;
266
+ const checkoutRoot = isPrimaryManagedRepo && runsInsideTaskWorktree ? resolveMonorepoRoot(normalizedProjectRoot) : entry.checkoutEnvVar && process.env[entry.checkoutEnvVar]?.trim() ? resolve3(process.env[entry.checkoutEnvVar].trim()) : resolve3(normalizedProjectRoot, entry.alias);
267
+ return {
268
+ projectRoot: normalizedProjectRoot,
269
+ repoId: entry.id,
270
+ alias: entry.alias,
271
+ defaultBranch: entry.defaultBranch,
272
+ remoteUrl: entry.remoteEnvVar && process.env[entry.remoteEnvVar]?.trim() ? process.env[entry.remoteEnvVar].trim() : entry.defaultRemoteUrl,
273
+ checkoutRoot,
274
+ worktreesRoot: resolve3(checkoutRoot, ".worktrees"),
275
+ stateDir,
276
+ metadataRoot,
277
+ metadataRelativePath,
278
+ mirrorRoot: resolve3(metadataRoot, "mirror.git"),
279
+ mirrorStatePath: resolve3(metadataRoot, "mirror-state.json"),
280
+ mirrorStateRelativePath: join(metadataRelativePath, "mirror-state.json")
281
+ };
282
+ }
283
+ // packages/runtime/src/control-plane/repos/mirror/bootstrap.ts
284
+ import { existsSync as existsSync5, mkdirSync as mkdirSync3, realpathSync } from "fs";
285
+ import { resolve as resolve5 } from "path";
286
+
287
+ // packages/runtime/src/control-plane/authority-files.ts
288
+ import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync, writeFileSync, appendFileSync, copyFileSync as copyFileSync2, statSync as statSync2, readdirSync, chmodSync } from "fs";
289
+ import { dirname as dirname4, join as join2, relative, resolve as resolve4 } from "path";
290
+ import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
291
+ function resolveAuthorityProjectStateDir(projectRoot) {
292
+ const explicit = process.env.RIG_STATE_DIR?.trim();
293
+ if (explicit) {
294
+ return resolve4(explicit);
295
+ }
296
+ return resolve4(resolve4(projectRoot), ".rig", "state");
297
+ }
298
+ function readJsonAtPath(path, fallback) {
299
+ if (!existsSync4(path)) {
300
+ return fallback;
301
+ }
302
+ try {
303
+ return JSON.parse(readFileSync(path, "utf-8"));
304
+ } catch {
305
+ return fallback;
306
+ }
307
+ }
308
+ function writeJsonAtPath(path, value) {
309
+ mkdirSync2(dirname4(path), { recursive: true });
310
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
311
+ `, "utf8");
312
+ return path;
313
+ }
314
+ function readAuthorityProjectStateJson(projectRoot, relativePath, fallback) {
315
+ return readJsonAtPath(resolve4(resolveAuthorityProjectStateDir(projectRoot), relativePath), fallback);
316
+ }
317
+ function writeAuthorityProjectStateJson(projectRoot, relativePath, value) {
318
+ return writeJsonAtPath(resolve4(resolveAuthorityProjectStateDir(projectRoot), relativePath), value);
319
+ }
320
+
321
+ // packages/runtime/src/control-plane/repos/mirror/state.ts
322
+ var STATE_VERSION = 1;
323
+ function defaultMirrorState(projectRoot, repoId) {
324
+ const layout = resolveManagedRepoLayout(projectRoot, repoId);
325
+ return {
326
+ version: STATE_VERSION,
327
+ repoId,
328
+ remoteUrl: layout.remoteUrl,
329
+ defaultBranch: layout.defaultBranch
330
+ };
331
+ }
332
+ function readManagedRepoMirrorState(projectRoot, repoId) {
333
+ const layout = resolveManagedRepoLayout(projectRoot, repoId);
334
+ return readAuthorityProjectStateJson(projectRoot, layout.mirrorStateRelativePath, null);
335
+ }
336
+ function writeManagedRepoMirrorState(projectRoot, repoId, patch) {
337
+ const current = readManagedRepoMirrorState(projectRoot, repoId) || defaultMirrorState(projectRoot, repoId);
338
+ const next = {
339
+ ...current,
340
+ ...patch,
341
+ version: STATE_VERSION,
342
+ repoId
343
+ };
344
+ const layout = resolveManagedRepoLayout(projectRoot, repoId);
345
+ writeAuthorityProjectStateJson(projectRoot, layout.mirrorStateRelativePath, next);
346
+ return next;
347
+ }
348
+
349
+ // packages/runtime/src/control-plane/repos/mirror/bootstrap.ts
350
+ function nowIso() {
351
+ return new Date().toISOString();
352
+ }
353
+ function runGit(command, cwd) {
354
+ const result = Bun.spawnSync(command, {
355
+ cwd,
356
+ stdout: "pipe",
357
+ stderr: "pipe",
358
+ env: process.env
359
+ });
360
+ return {
361
+ exitCode: result.exitCode,
362
+ stdout: result.stdout.toString(),
363
+ stderr: result.stderr.toString()
364
+ };
365
+ }
366
+ function ensureGitSuccess(result, command) {
367
+ if (result.exitCode !== 0) {
368
+ throw new Error(result.stderr || result.stdout || `git command failed: ${command.join(" ")}`);
369
+ }
370
+ }
371
+ function isUsableRemoteUrl(candidate, layout) {
372
+ return candidate.length > 0 && candidate !== layout.mirrorRoot && candidate !== layout.checkoutRoot;
373
+ }
374
+ function sameExistingPath(left, right) {
375
+ try {
376
+ return realpathSync(left) === realpathSync(right);
377
+ } catch {
378
+ return resolve5(left) === resolve5(right);
379
+ }
380
+ }
381
+ function repoLooksUsable(repoRoot, projectRoot) {
382
+ const probe = runGit(["git", "-C", repoRoot, "rev-parse", "--show-toplevel"], projectRoot);
383
+ return probe.exitCode === 0 && sameExistingPath(probe.stdout.trim(), repoRoot);
384
+ }
385
+ function checkoutLooksUsable(layout) {
386
+ return repoLooksUsable(layout.checkoutRoot, layout.projectRoot);
387
+ }
388
+ function resolveMirrorRemoteUrl(layout) {
389
+ const entry = getManagedRepoEntry(layout.repoId);
390
+ const explicit = entry.remoteEnvVar ? process.env[entry.remoteEnvVar]?.trim() : "";
391
+ if (explicit) {
392
+ return explicit;
393
+ }
394
+ const persisted = readManagedRepoMirrorState(layout.projectRoot, layout.repoId)?.remoteUrl?.trim();
395
+ if (persisted && isUsableRemoteUrl(persisted, layout)) {
396
+ return persisted;
397
+ }
398
+ const mirrorOrigin = runGit(["git", "--git-dir", layout.mirrorRoot, "remote", "get-url", "origin"], layout.projectRoot);
399
+ if (mirrorOrigin.exitCode === 0) {
400
+ const currentOrigin = mirrorOrigin.stdout.trim();
401
+ if (isUsableRemoteUrl(currentOrigin, layout)) {
402
+ return currentOrigin;
403
+ }
404
+ }
405
+ if (repoLooksUsable(layout.projectRoot, layout.projectRoot)) {
406
+ const projectOrigin = runGit(["git", "-C", layout.projectRoot, "remote", "get-url", "origin"], layout.projectRoot);
407
+ if (projectOrigin.exitCode === 0) {
408
+ const currentOrigin = projectOrigin.stdout.trim();
409
+ if (isUsableRemoteUrl(currentOrigin, layout)) {
410
+ return currentOrigin;
411
+ }
412
+ }
413
+ }
414
+ if (existsSync5(resolve5(layout.checkoutRoot, ".git")) && checkoutLooksUsable(layout)) {
415
+ const checkoutOrigin = runGit(["git", "-C", layout.checkoutRoot, "remote", "get-url", "origin"], layout.projectRoot);
416
+ if (checkoutOrigin.exitCode === 0) {
417
+ const currentOrigin = checkoutOrigin.stdout.trim();
418
+ if (isUsableRemoteUrl(currentOrigin, layout)) {
419
+ return currentOrigin;
420
+ }
421
+ }
422
+ }
423
+ return layout.remoteUrl;
424
+ }
425
+ function ensureManagedRepoMirror(projectRoot, repoId) {
426
+ const layout = resolveManagedRepoLayout(projectRoot, repoId);
427
+ mkdirSync3(layout.metadataRoot, { recursive: true });
428
+ const remoteUrl = resolveMirrorRemoteUrl(layout);
429
+ if (!existsSync5(resolve5(layout.mirrorRoot, "HEAD"))) {
430
+ ensureGitSuccess(runGit(["git", "init", "--bare", layout.mirrorRoot], layout.projectRoot), ["git", "init", "--bare", layout.mirrorRoot]);
431
+ }
432
+ const getOrigin = runGit(["git", "--git-dir", layout.mirrorRoot, "remote", "get-url", "origin"], layout.projectRoot);
433
+ if (getOrigin.exitCode === 0) {
434
+ const currentOrigin = getOrigin.stdout.trim();
435
+ if (currentOrigin !== remoteUrl) {
436
+ ensureGitSuccess(runGit(["git", "--git-dir", layout.mirrorRoot, "remote", "set-url", "origin", remoteUrl], layout.projectRoot), ["git", "--git-dir", layout.mirrorRoot, "remote", "set-url", "origin", remoteUrl]);
437
+ }
438
+ } else {
439
+ ensureGitSuccess(runGit(["git", "--git-dir", layout.mirrorRoot, "remote", "add", "origin", remoteUrl], layout.projectRoot), ["git", "--git-dir", layout.mirrorRoot, "remote", "add", "origin", remoteUrl]);
440
+ }
441
+ writeManagedRepoMirrorState(projectRoot, repoId, {
442
+ remoteUrl,
443
+ defaultBranch: layout.defaultBranch,
444
+ initializedAt: nowIso()
445
+ });
446
+ return layout;
447
+ }
448
+ // packages/runtime/src/control-plane/repos/mirror/refresh.ts
449
+ import { existsSync as existsSync6, mkdirSync as mkdirSync4, realpathSync as realpathSync2, rmSync as rmSync2 } from "fs";
450
+ import { resolve as resolve6 } from "path";
451
+ function nowIso2() {
452
+ return new Date().toISOString();
453
+ }
454
+ function runGit2(command, cwd) {
455
+ const result = Bun.spawnSync(command, {
456
+ cwd,
457
+ stdout: "pipe",
458
+ stderr: "pipe",
459
+ env: process.env
460
+ });
461
+ return {
462
+ exitCode: result.exitCode,
463
+ stdout: result.stdout.toString(),
464
+ stderr: result.stderr.toString()
465
+ };
466
+ }
467
+ function ensureGitSuccess2(result, command) {
468
+ if (result.exitCode !== 0) {
469
+ throw new Error(result.stderr || result.stdout || `git command failed: ${command.join(" ")}`);
470
+ }
471
+ return result.stdout.trim();
472
+ }
473
+ function sameExistingPath2(left, right) {
474
+ try {
475
+ return realpathSync2(left) === realpathSync2(right);
476
+ } catch {
477
+ return resolve6(left) === resolve6(right);
478
+ }
479
+ }
480
+ function ensureMirrorHead(layout) {
481
+ ensureGitSuccess2(runGit2([
482
+ "git",
483
+ "--git-dir",
484
+ layout.mirrorRoot,
485
+ "fetch",
486
+ "--prune",
487
+ "origin",
488
+ "+refs/heads/*:refs/heads/*",
489
+ "+refs/tags/*:refs/tags/*"
490
+ ], layout.projectRoot), [
491
+ "git",
492
+ "--git-dir",
493
+ layout.mirrorRoot,
494
+ "fetch",
495
+ "--prune",
496
+ "origin",
497
+ "+refs/heads/*:refs/heads/*",
498
+ "+refs/tags/*:refs/tags/*"
499
+ ]);
500
+ const headRef = `refs/heads/${layout.defaultBranch}`;
501
+ const headCommit = ensureGitSuccess2(runGit2(["git", "--git-dir", layout.mirrorRoot, "rev-parse", headRef], layout.projectRoot), ["git", "--git-dir", layout.mirrorRoot, "rev-parse", headRef]);
502
+ const remoteUrl = ensureGitSuccess2(runGit2(["git", "--git-dir", layout.mirrorRoot, "remote", "get-url", "origin"], layout.projectRoot), ["git", "--git-dir", layout.mirrorRoot, "remote", "get-url", "origin"]);
503
+ ensureGitSuccess2(runGit2(["git", "--git-dir", layout.mirrorRoot, "symbolic-ref", "HEAD", headRef], layout.projectRoot), ["git", "--git-dir", layout.mirrorRoot, "symbolic-ref", "HEAD", headRef]);
504
+ writeManagedRepoMirrorState(layout.projectRoot, layout.repoId, {
505
+ remoteUrl,
506
+ defaultBranch: layout.defaultBranch,
507
+ lastSyncedAt: nowIso2(),
508
+ headRef,
509
+ headCommit
510
+ });
511
+ return headCommit;
512
+ }
513
+ function refreshManagedRepoMirror(projectRoot, repoId) {
514
+ const layout = ensureManagedRepoMirror(projectRoot, repoId);
515
+ const headCommit = ensureMirrorHead(layout);
516
+ return { layout, headCommit };
517
+ }
518
+ function checkoutLooksUsable2(layout) {
519
+ const probe = runGit2(["git", "-C", layout.checkoutRoot, "rev-parse", "--show-toplevel"], layout.projectRoot);
520
+ return probe.exitCode === 0 && sameExistingPath2(probe.stdout.trim(), layout.checkoutRoot);
521
+ }
522
+ function ensureCheckoutFromMirror(layout) {
523
+ mkdirSync4(resolve6(layout.checkoutRoot, ".."), { recursive: true });
524
+ const gitPath = resolve6(layout.checkoutRoot, ".git");
525
+ if (existsSync6(layout.checkoutRoot) && (!existsSync6(gitPath) || !checkoutLooksUsable2(layout))) {
526
+ rmSync2(layout.checkoutRoot, { recursive: true, force: true });
527
+ }
528
+ if (!existsSync6(gitPath)) {
529
+ ensureGitSuccess2(runGit2(["git", "clone", layout.mirrorRoot, layout.checkoutRoot], layout.projectRoot), ["git", "clone", layout.mirrorRoot, layout.checkoutRoot]);
530
+ }
531
+ const getOrigin = runGit2(["git", "-C", layout.checkoutRoot, "remote", "get-url", "origin"], layout.projectRoot);
532
+ if (getOrigin.exitCode === 0) {
533
+ const currentOrigin = getOrigin.stdout.trim();
534
+ if (currentOrigin !== layout.mirrorRoot) {
535
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "remote", "set-url", "origin", layout.mirrorRoot], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "remote", "set-url", "origin", layout.mirrorRoot]);
536
+ }
537
+ } else {
538
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "remote", "add", "origin", layout.mirrorRoot], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "remote", "add", "origin", layout.mirrorRoot]);
539
+ }
540
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "fetch", "origin", layout.defaultBranch], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "fetch", "origin", layout.defaultBranch]);
541
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "reset", "--hard"], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "reset", "--hard"]);
542
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "clean", "-fd"], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "clean", "-fd"]);
543
+ ensureGitSuccess2(runGit2([
544
+ "git",
545
+ "-C",
546
+ layout.checkoutRoot,
547
+ "checkout",
548
+ "--force",
549
+ "-B",
550
+ layout.defaultBranch,
551
+ `origin/${layout.defaultBranch}`
552
+ ], layout.projectRoot), [
553
+ "git",
554
+ "-C",
555
+ layout.checkoutRoot,
556
+ "checkout",
557
+ "--force",
558
+ "-B",
559
+ layout.defaultBranch,
560
+ `origin/${layout.defaultBranch}`
561
+ ]);
562
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "reset", "--hard", `origin/${layout.defaultBranch}`], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "reset", "--hard", `origin/${layout.defaultBranch}`]);
563
+ ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "clean", "-fd"], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "clean", "-fd"]);
564
+ return ensureGitSuccess2(runGit2(["git", "-C", layout.checkoutRoot, "rev-parse", "HEAD"], layout.projectRoot), ["git", "-C", layout.checkoutRoot, "rev-parse", "HEAD"]);
565
+ }
566
+ function syncManagedRepo(projectRoot, repoId) {
567
+ const { layout, headCommit } = refreshManagedRepoMirror(projectRoot, repoId);
568
+ const checkoutCommit = ensureCheckoutFromMirror(layout);
569
+ if (checkoutCommit !== headCommit) {
570
+ throw new Error(`Managed repo checkout ${layout.alias} is out of sync with mirror: expected ${headCommit}, got ${checkoutCommit}.`);
571
+ }
572
+ return { layout, headCommit };
573
+ }
574
+ // packages/runtime/src/control-plane/errors.ts
575
+ class CliError extends Error {
576
+ exitCode;
577
+ constructor(message, exitCode = 1) {
578
+ super(message);
579
+ this.name = "CliError";
580
+ this.exitCode = exitCode;
581
+ }
582
+ }
583
+
584
+ // packages/runtime/src/control-plane/project-main-pre-run-sync.ts
585
+ function runGit3(projectRoot, args, failureSummary) {
586
+ const result = runCapture(["git", ...args], projectRoot);
587
+ if (result.exitCode !== 0) {
588
+ const details = result.stderr.trim() || result.stdout.trim() || "unknown git failure";
589
+ throw new CliError(`${failureSummary}: ${details}`, 2);
590
+ }
591
+ return result.stdout.trim();
592
+ }
593
+ async function ensureProjectMainFreshBeforeRun(options) {
594
+ if (options.disabled) {
595
+ return { status: "disabled" };
596
+ }
597
+ const defaultSync = (projectRoot) => {
598
+ for (const entry of listManagedRepoEntries()) {
599
+ syncManagedRepo(projectRoot, entry.id);
600
+ }
601
+ };
602
+ await (options.syncMonorepo ?? defaultSync)(options.projectRoot);
603
+ runGit3(options.projectRoot, ["fetch", "origin", "main"], "Failed to fetch origin/main");
604
+ const branch = runGit3(options.projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"], "Failed to read current branch");
605
+ if (branch !== "main") {
606
+ return { status: "skipped_not_main", branch };
607
+ }
608
+ const countsText = runGit3(options.projectRoot, ["rev-list", "--left-right", "--count", "main...origin/main"], "Failed to compare local main to origin/main");
609
+ const [localAheadRaw, remoteAheadRaw] = countsText.split(/\s+/);
610
+ const localAhead = Number.parseInt(localAheadRaw || "0", 10);
611
+ const remoteAhead = Number.parseInt(remoteAheadRaw || "0", 10);
612
+ if (!Number.isFinite(localAhead) || !Number.isFinite(remoteAhead)) {
613
+ throw new CliError(`Failed to compare local main to origin/main: unexpected rev-list output "${countsText}"`, 2);
614
+ }
615
+ if (remoteAhead === 0) {
616
+ if (localAhead > 0) {
617
+ return { status: "local_ahead", localAhead };
618
+ }
619
+ return { status: "up_to_date" };
620
+ }
621
+ if (localAhead > 0) {
622
+ throw new CliError("Local main has diverged from origin/main. Resolve the branch state manually or rerun with --skip-project-sync.", 2);
623
+ }
624
+ runGit3(options.projectRoot, ["merge", "--ff-only", "origin/main"], "Failed to fast-forward local main to origin/main");
625
+ await options.runBootstrap();
626
+ return { status: "updated", remoteAhead };
627
+ }
628
+ export {
629
+ ensureProjectMainFreshBeforeRun
630
+ };