@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,501 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/runtime/isolation/shared.ts
3
+ import { existsSync as existsSync3, readFileSync, rmSync as rmSync2 } from "fs";
4
+ import { resolve as resolve3 } from "path";
5
+ import { randomUUID } from "crypto";
6
+
7
+ // packages/runtime/src/layout.ts
8
+ import { existsSync } from "fs";
9
+ import { basename, dirname, resolve } from "path";
10
+ function resolveMonorepoRoot(projectRoot) {
11
+ const normalizedProjectRoot = resolve(projectRoot);
12
+ const explicit = process.env.MONOREPO_ROOT?.trim();
13
+ if (explicit) {
14
+ const explicitRoot = resolve(explicit);
15
+ const explicitParent = dirname(explicitRoot);
16
+ if (basename(explicitParent) === ".worktrees") {
17
+ const owner = dirname(explicitParent);
18
+ const ownerHasGit = existsSync(resolve(owner, ".git"));
19
+ const ownerHasTaskConfig = existsSync(resolve(owner, ".rig", "task-config.json"));
20
+ const ownerHasRigConfig = existsSync(resolve(owner, "rig.config.ts"));
21
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
22
+ return owner;
23
+ }
24
+ throw new Error(`MONOREPO_ROOT points to worktree ${explicitRoot}, but the owner checkout is incomplete at ${owner}.`);
25
+ }
26
+ if (!existsSync(resolve(explicitRoot, ".git"))) {
27
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there.`);
28
+ }
29
+ const hasTaskConfig = existsSync(resolve(explicitRoot, ".rig", "task-config.json"));
30
+ const hasRigConfig = existsSync(resolve(explicitRoot, "rig.config.ts"));
31
+ if (!hasTaskConfig && !hasRigConfig) {
32
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but neither .rig/task-config.json nor rig.config.ts exists there.`);
33
+ }
34
+ return explicitRoot;
35
+ }
36
+ const projectParent = dirname(normalizedProjectRoot);
37
+ if (basename(projectParent) === ".worktrees") {
38
+ const worktreeOwner = dirname(projectParent);
39
+ const ownerHasGit = existsSync(resolve(worktreeOwner, ".git"));
40
+ const ownerHasTaskConfig = existsSync(resolve(worktreeOwner, ".rig", "task-config.json"));
41
+ const ownerHasRigConfig = existsSync(resolve(worktreeOwner, "rig.config.ts"));
42
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
43
+ return worktreeOwner;
44
+ }
45
+ }
46
+ return normalizedProjectRoot;
47
+ }
48
+
49
+ // packages/runtime/src/control-plane/native/runtime-native.ts
50
+ import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
51
+ import { copyFileSync, existsSync as existsSync2, mkdirSync, renameSync, rmSync, statSync } from "fs";
52
+ import { tmpdir } from "os";
53
+ import { dirname as dirname2, resolve as resolve2 } from "path";
54
+ var sharedNativeRuntimeOutputDir = resolve2(tmpdir(), "rig-native");
55
+ var sharedNativeRuntimeOutputPath = resolve2(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
56
+ var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
57
+ var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
58
+ async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
59
+ if (await buildNativeRuntimeLibrary(outputPath, options)) {
60
+ return outputPath;
61
+ }
62
+ return !options.force && existsSync2(outputPath) ? outputPath : null;
63
+ }
64
+ async function loadNativeRuntimeLibrary() {
65
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
66
+ return null;
67
+ }
68
+ for (const candidate of nativeRuntimeLibraryCandidates()) {
69
+ if (!candidate || !existsSync2(candidate)) {
70
+ continue;
71
+ }
72
+ const loaded = tryDlopenNativeRuntimeLibrary(candidate);
73
+ if (loaded) {
74
+ return loaded;
75
+ }
76
+ }
77
+ const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
78
+ if (!builtLibraryPath) {
79
+ return null;
80
+ }
81
+ return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
82
+ }
83
+ function nativePackageLibraryCandidates(fromDir, names) {
84
+ const candidates = [];
85
+ let cursor = resolve2(fromDir);
86
+ for (let index = 0;index < 8; index += 1) {
87
+ for (const name of names) {
88
+ 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));
89
+ }
90
+ const parent = dirname2(cursor);
91
+ if (parent === cursor)
92
+ break;
93
+ cursor = parent;
94
+ }
95
+ return candidates;
96
+ }
97
+ function nativeRuntimeLibraryCandidates() {
98
+ const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
99
+ const execDir = process.execPath?.trim() ? dirname2(process.execPath.trim()) : "";
100
+ const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
101
+ return [...new Set([
102
+ explicit,
103
+ ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
104
+ execDir ? resolve2(execDir, colocatedNativeRuntimeFileName) : "",
105
+ execDir ? resolve2(execDir, platformSpecific) : "",
106
+ execDir ? resolve2(execDir, "..", colocatedNativeRuntimeFileName) : "",
107
+ execDir ? resolve2(execDir, "..", platformSpecific) : "",
108
+ execDir ? resolve2(execDir, "lib", colocatedNativeRuntimeFileName) : "",
109
+ execDir ? resolve2(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
110
+ sharedNativeRuntimeOutputPath
111
+ ].filter(Boolean))];
112
+ }
113
+ function resolveNativeRuntimeSourcePath() {
114
+ const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
115
+ if (explicit && existsSync2(explicit)) {
116
+ return explicit;
117
+ }
118
+ const bundled = resolve2(import.meta.dir, "../../../native/snapshot.zig");
119
+ return existsSync2(bundled) ? bundled : null;
120
+ }
121
+ async function buildNativeRuntimeLibrary(outputPath, options = {}) {
122
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
123
+ return false;
124
+ }
125
+ const zigBinary = Bun.which("zig");
126
+ const sourcePath = resolveNativeRuntimeSourcePath();
127
+ if (!zigBinary || !sourcePath) {
128
+ return false;
129
+ }
130
+ const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
131
+ try {
132
+ mkdirSync(dirname2(outputPath), { recursive: true });
133
+ const needsBuild = options.force === true || !existsSync2(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
134
+ if (!needsBuild) {
135
+ return true;
136
+ }
137
+ const build = Bun.spawn([
138
+ zigBinary,
139
+ "build-lib",
140
+ sourcePath,
141
+ "-dynamic",
142
+ "-O",
143
+ "ReleaseFast",
144
+ `-femit-bin=${tempOutputPath}`
145
+ ], {
146
+ cwd: import.meta.dir,
147
+ stdout: "pipe",
148
+ stderr: "pipe"
149
+ });
150
+ const exitCode = await build.exited;
151
+ if (exitCode !== 0 || !existsSync2(tempOutputPath)) {
152
+ rmSync(tempOutputPath, { force: true });
153
+ return false;
154
+ }
155
+ renameSync(tempOutputPath, outputPath);
156
+ return true;
157
+ } catch {
158
+ rmSync(tempOutputPath, { force: true });
159
+ return false;
160
+ }
161
+ }
162
+ function tryDlopenNativeRuntimeLibrary(outputPath) {
163
+ try {
164
+ return dlopen(outputPath, {
165
+ rig_scope_match: {
166
+ args: ["ptr", "ptr"],
167
+ returns: "u8"
168
+ },
169
+ snapshot_capture: {
170
+ args: ["ptr", "u64", "ptr", "u64"],
171
+ returns: "ptr"
172
+ },
173
+ snapshot_delta: {
174
+ args: ["ptr", "ptr"],
175
+ returns: "ptr"
176
+ },
177
+ snapshot_store_delta: {
178
+ args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
179
+ returns: "ptr"
180
+ },
181
+ snapshot_inspect_delta: {
182
+ args: ["ptr", "u64"],
183
+ returns: "ptr"
184
+ },
185
+ snapshot_apply_delta: {
186
+ args: ["ptr", "u64", "ptr", "u64"],
187
+ returns: "ptr"
188
+ },
189
+ snapshot_release: {
190
+ args: ["ptr"],
191
+ returns: "void"
192
+ },
193
+ runtime_hash_file: {
194
+ args: ["ptr", "u64"],
195
+ returns: "ptr"
196
+ },
197
+ runtime_hash_tree: {
198
+ args: ["ptr", "u64"],
199
+ returns: "ptr"
200
+ },
201
+ runtime_prepare_paths: {
202
+ args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
203
+ returns: "ptr"
204
+ },
205
+ runtime_link_dependency_layer: {
206
+ args: ["ptr", "u64", "ptr", "u64"],
207
+ returns: "ptr"
208
+ },
209
+ runtime_scan_worktrees: {
210
+ args: ["ptr", "u64"],
211
+ returns: "ptr"
212
+ }
213
+ });
214
+ } catch {
215
+ return null;
216
+ }
217
+ }
218
+
219
+ // packages/runtime/src/control-plane/native/utils.ts
220
+ function resolveMonorepoRoot2(projectRoot) {
221
+ return resolveMonorepoRoot(projectRoot);
222
+ }
223
+ var scopeRegexCache = new Map;
224
+
225
+ // packages/runtime/src/control-plane/runtime/isolation/shared.ts
226
+ var generatedCredentialFiles = new Set;
227
+ var credentialCleanupRegistered = false;
228
+ function resolveMonorepoRoot3(projectRoot) {
229
+ return resolveMonorepoRoot2(projectRoot);
230
+ }
231
+ function isRuntimeGatewayGitPath(candidate) {
232
+ return /\/\.rig\/bin\/git$/.test(candidate.replace(/\\/g, "/"));
233
+ }
234
+ function resolveHostGitBinary() {
235
+ const candidates = [
236
+ process.env.RIG_GIT_BIN?.trim() || "",
237
+ "/usr/bin/git",
238
+ "/opt/homebrew/bin/git",
239
+ "/usr/local/bin/git"
240
+ ];
241
+ const bunResolved = Bun.which("git");
242
+ if (bunResolved && !isRuntimeGatewayGitPath(bunResolved)) {
243
+ candidates.push(bunResolved);
244
+ }
245
+ for (const candidate of candidates) {
246
+ if (!candidate || isRuntimeGatewayGitPath(candidate)) {
247
+ continue;
248
+ }
249
+ if (existsSync3(candidate)) {
250
+ return candidate;
251
+ }
252
+ }
253
+ return "git";
254
+ }
255
+ async function runGitCommand(repoRoot, args) {
256
+ const gitBinary = resolveHostGitBinary();
257
+ return Bun.$`${gitBinary} -C ${repoRoot} ${args}`.quiet().nothrow();
258
+ }
259
+ async function readGitConfigValue(repoRoot, key, global = false) {
260
+ const args = ["config", ...global ? ["--global"] : [], "--get", key];
261
+ const result = await runGitCommand(repoRoot, args);
262
+ if (result.exitCode !== 0) {
263
+ return "";
264
+ }
265
+ return String(result.stdout).trim();
266
+ }
267
+ async function readGitStdout(repoRoot, args) {
268
+ const result = await runGitCommand(repoRoot, args);
269
+ if (result.exitCode !== 0) {
270
+ throw new Error(`git -C ${repoRoot} ${args.join(" ")} failed: ${result.stderr || result.stdout}`);
271
+ }
272
+ return String(result.stdout).trim();
273
+ }
274
+ async function hasGitRemote(repoRoot, remote) {
275
+ const result = await runGitCommand(repoRoot, ["remote", "get-url", remote]);
276
+ return result.exitCode === 0;
277
+ }
278
+ async function ensureFullGitHistory(repoRoot) {
279
+ const shallow = await runGitCommand(repoRoot, ["rev-parse", "--is-shallow-repository"]);
280
+ if (shallow.exitCode !== 0 || String(shallow.stdout).trim() !== "true") {
281
+ return;
282
+ }
283
+ const unshallow = await runGitCommand(repoRoot, ["fetch", "--unshallow", "--tags", "origin"]);
284
+ if (unshallow.exitCode === 0) {
285
+ return;
286
+ }
287
+ const output = `${unshallow.stderr}
288
+ ${unshallow.stdout}`.trim();
289
+ if (/--unshallow on a complete repository|does not make sense/i.test(output)) {
290
+ return;
291
+ }
292
+ throw new Error(`Failed to expand git history for ${repoRoot}: ${output}`);
293
+ }
294
+ async function refreshOriginMain(repoRoot) {
295
+ await refreshRemoteBranch(repoRoot, "origin", "main");
296
+ }
297
+ async function refreshRemoteBranch(repoRoot, remote, branch) {
298
+ if (!await hasGitRemote(repoRoot, remote)) {
299
+ return;
300
+ }
301
+ try {
302
+ await ensureFullGitHistory(repoRoot);
303
+ const fetch = await runGitCommand(repoRoot, [
304
+ "fetch",
305
+ "--prune",
306
+ "--tags",
307
+ remote,
308
+ `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`
309
+ ]);
310
+ if (fetch.exitCode !== 0) {
311
+ return;
312
+ }
313
+ } catch {
314
+ return;
315
+ }
316
+ }
317
+ async function tryReadGitHead(repoRoot) {
318
+ if (!existsSync3(resolve3(repoRoot, ".git"))) {
319
+ return;
320
+ }
321
+ const result = await runGitCommand(repoRoot, ["rev-parse", "HEAD"]);
322
+ if (result.exitCode !== 0) {
323
+ return;
324
+ }
325
+ const value = String(result.stdout).trim();
326
+ return value || undefined;
327
+ }
328
+ async function captureRepoDirtyFiles(repoRoot) {
329
+ if (!existsSync3(resolve3(repoRoot, ".git"))) {
330
+ return [];
331
+ }
332
+ const files = new Set;
333
+ for (const args of [
334
+ ["diff", "--name-only"],
335
+ ["diff", "--cached", "--name-only"],
336
+ ["ls-files", "--others", "--exclude-standard"]
337
+ ]) {
338
+ const result = await runGitCommand(repoRoot, args);
339
+ if (result.exitCode !== 0) {
340
+ continue;
341
+ }
342
+ for (const line of String(result.stdout).split(/\r?\n/)) {
343
+ const trimmed = line.trim();
344
+ if (trimmed) {
345
+ files.add(trimmed);
346
+ }
347
+ }
348
+ }
349
+ return [...files].sort();
350
+ }
351
+ function sha256Hex(input) {
352
+ const hasher = new Bun.CryptoHasher("sha256");
353
+ hasher.update(input);
354
+ return hasher.digest("hex");
355
+ }
356
+ function registerCredentialCleanup(path) {
357
+ generatedCredentialFiles.add(path);
358
+ if (credentialCleanupRegistered) {
359
+ return;
360
+ }
361
+ credentialCleanupRegistered = true;
362
+ const cleanup = () => {
363
+ for (const filePath of generatedCredentialFiles) {
364
+ try {
365
+ rmSync2(filePath, { force: true });
366
+ } catch {}
367
+ }
368
+ generatedCredentialFiles.clear();
369
+ };
370
+ process.on("exit", cleanup);
371
+ process.on("beforeExit", cleanup);
372
+ }
373
+ async function captureStdout(fn) {
374
+ const chunks = [];
375
+ const originalWrite = process.stdout.write.bind(process.stdout);
376
+ const originalLog = console.log;
377
+ const originalError = console.error;
378
+ process.stdout.write = (chunk, encoding, cb) => {
379
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString(typeof encoding === "string" ? encoding : undefined));
380
+ const callback = typeof encoding === "function" ? encoding : cb;
381
+ callback?.(null);
382
+ return true;
383
+ };
384
+ console.log = (...args) => {
385
+ chunks.push(`${args.map((value) => String(value)).join(" ")}
386
+ `);
387
+ };
388
+ console.error = (...args) => {
389
+ chunks.push(`${args.map((value) => String(value)).join(" ")}
390
+ `);
391
+ };
392
+ try {
393
+ await fn();
394
+ return chunks.join("");
395
+ } finally {
396
+ process.stdout.write = originalWrite;
397
+ console.log = originalLog;
398
+ console.error = originalError;
399
+ }
400
+ }
401
+ function sanitizeRuntimeRefSegment(value) {
402
+ const sanitized = value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
403
+ return (sanitized || "runtime").slice(0, 64);
404
+ }
405
+ function runtimeBranchBackupName(branch) {
406
+ const branchId = branch.replace(/^rig\//, "");
407
+ return `rig-backup/${sanitizeRuntimeRefSegment(branchId)}-${Date.now()}`;
408
+ }
409
+ function agentId(prefix = "agent") {
410
+ return `${prefix}-${randomUUID().slice(0, 8)}`;
411
+ }
412
+ function taskRuntimeId(taskId) {
413
+ return `task-${taskId}`;
414
+ }
415
+ function hashProjectPath(workspaceDir) {
416
+ return sha256Hex(workspaceDir).slice(0, 16);
417
+ }
418
+ function resolveGithubCliBinaryPath() {
419
+ const explicit = process.env.RIG_GH_BIN?.trim();
420
+ if (explicit && existsSync3(explicit)) {
421
+ return explicit;
422
+ }
423
+ const bunResolved = Bun.which("gh");
424
+ if (bunResolved && existsSync3(bunResolved)) {
425
+ return bunResolved;
426
+ }
427
+ for (const candidate of ["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh"]) {
428
+ if (existsSync3(candidate)) {
429
+ return candidate;
430
+ }
431
+ }
432
+ return "";
433
+ }
434
+ async function resolveGithubCliAuthToken(ghBinary = "") {
435
+ const gh = ghBinary || resolveGithubCliBinaryPath();
436
+ if (!gh) {
437
+ return "";
438
+ }
439
+ const auth = Bun.spawn([gh, "auth", "token"], {
440
+ stdout: "pipe",
441
+ stderr: "pipe"
442
+ });
443
+ const [exitCode, stdout] = await Promise.all([
444
+ auth.exited,
445
+ new Response(auth.stdout).text()
446
+ ]);
447
+ if (exitCode !== 0) {
448
+ return "";
449
+ }
450
+ return stdout.trim();
451
+ }
452
+ function resolveSystemCertBundlePath() {
453
+ const candidates = [
454
+ process.env.SSL_CERT_FILE?.trim(),
455
+ "/etc/ssl/cert.pem",
456
+ "/private/etc/ssl/cert.pem",
457
+ "/opt/homebrew/etc/openssl@3/cert.pem"
458
+ ];
459
+ for (const candidate of candidates) {
460
+ if (candidate && existsSync3(candidate)) {
461
+ return resolve3(candidate);
462
+ }
463
+ }
464
+ return "";
465
+ }
466
+ var __testOnly = {
467
+ cleanupGeneratedCredentialFiles() {
468
+ generatedCredentialFiles.clear();
469
+ }
470
+ };
471
+ function readKnownHosts(path) {
472
+ if (!existsSync3(path)) {
473
+ return new Set;
474
+ }
475
+ return new Set(readFileSync(path, "utf-8").split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
476
+ }
477
+ export {
478
+ tryReadGitHead,
479
+ taskRuntimeId,
480
+ sha256Hex,
481
+ sanitizeRuntimeRefSegment,
482
+ runtimeBranchBackupName,
483
+ runGitCommand,
484
+ resolveSystemCertBundlePath,
485
+ resolveMonorepoRoot3 as resolveMonorepoRoot,
486
+ resolveGithubCliBinaryPath,
487
+ resolveGithubCliAuthToken,
488
+ registerCredentialCleanup,
489
+ refreshRemoteBranch,
490
+ refreshOriginMain,
491
+ readKnownHosts,
492
+ readGitStdout,
493
+ readGitConfigValue,
494
+ hashProjectPath,
495
+ hasGitRemote,
496
+ ensureFullGitHistory,
497
+ captureStdout,
498
+ captureRepoDirtyFiles,
499
+ agentId,
500
+ __testOnly
501
+ };