@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,784 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/memory-sync/read.ts
3
+ import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
4
+ import { tmpdir as tmpdir3 } from "os";
5
+ import { join } from "path";
6
+
7
+ // packages/runtime/src/control-plane/native/git-native.ts
8
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
9
+ import { tmpdir } from "os";
10
+ import { dirname, isAbsolute, resolve } from "path";
11
+ import { createHash } from "crypto";
12
+ var sharedGitNativeOutputDir = resolve(tmpdir(), "rig-native");
13
+ var sharedGitNativeOutputPath = resolve(sharedGitNativeOutputDir, `rig-git-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`);
14
+ var trackerCommandUsageProbe = "usage: rig-git fetch-ref <repo-path> <remote> <branch>";
15
+ function temporaryGitBinaryOutputPath(outputPath) {
16
+ const suffix = process.platform === "win32" ? ".exe" : "";
17
+ return resolve(dirname(outputPath), `.rig-git-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}${suffix}`);
18
+ }
19
+ function publishGitBinary(tempOutputPath, outputPath) {
20
+ try {
21
+ renameSync(tempOutputPath, outputPath);
22
+ } catch (error) {
23
+ if (process.platform === "win32" && existsSync(outputPath)) {
24
+ rmSync(outputPath, { force: true });
25
+ renameSync(tempOutputPath, outputPath);
26
+ return;
27
+ }
28
+ throw error;
29
+ }
30
+ }
31
+ function runtimeRigGitFileName() {
32
+ return `rig-git${process.platform === "win32" ? ".exe" : ""}`;
33
+ }
34
+ function rigGitSourceCandidates() {
35
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
36
+ const cwd = process.cwd()?.trim() || "";
37
+ const projectRoot = process.env.PROJECT_RIG_ROOT?.trim() || "";
38
+ const hostProjectRoot = process.env.RIG_HOST_PROJECT_ROOT?.trim() || "";
39
+ const moduleRelativeSource = resolve(import.meta.dir, "../../../native/rig-git.zig");
40
+ return [...new Set([
41
+ process.env.RIG_NATIVE_GIT_SOURCE?.trim() || "",
42
+ moduleRelativeSource,
43
+ projectRoot ? resolve(projectRoot, "packages/runtime/native/rig-git.zig") : "",
44
+ hostProjectRoot ? resolve(hostProjectRoot, "packages/runtime/native/rig-git.zig") : "",
45
+ cwd ? resolve(cwd, "packages/runtime/native/rig-git.zig") : "",
46
+ execDir ? resolve(execDir, "..", "..", "packages/runtime/native/rig-git.zig") : "",
47
+ execDir ? resolve(execDir, "..", "native", "rig-git.zig") : ""
48
+ ].filter(Boolean))];
49
+ }
50
+ function nativePackageBinaryCandidates(fromDir, fileName) {
51
+ const candidates = [];
52
+ let cursor = resolve(fromDir);
53
+ for (let index = 0;index < 8; index += 1) {
54
+ candidates.push(resolve(cursor, "native", `${process.platform}-${process.arch}`, fileName), resolve(cursor, "native", `${process.platform}-${process.arch}`, "bin", fileName), resolve(cursor, "native", fileName), resolve(cursor, "native", "bin", fileName));
55
+ const parent = dirname(cursor);
56
+ if (parent === cursor)
57
+ break;
58
+ cursor = parent;
59
+ }
60
+ return candidates;
61
+ }
62
+ function rigGitBinaryCandidates() {
63
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
64
+ const fileName = runtimeRigGitFileName();
65
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
66
+ return [...new Set([
67
+ explicit,
68
+ ...nativePackageBinaryCandidates(import.meta.dir, fileName),
69
+ execDir ? resolve(execDir, fileName) : "",
70
+ execDir ? resolve(execDir, "..", fileName) : "",
71
+ execDir ? resolve(execDir, "..", "bin", fileName) : "",
72
+ sharedGitNativeOutputPath
73
+ ].filter(Boolean))];
74
+ }
75
+ function resolveGitSourcePath() {
76
+ for (const candidate of rigGitSourceCandidates()) {
77
+ if (candidate && existsSync(candidate)) {
78
+ return candidate;
79
+ }
80
+ }
81
+ return null;
82
+ }
83
+ function resolveGitBinaryPath() {
84
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
85
+ return null;
86
+ }
87
+ for (const candidate of rigGitBinaryCandidates()) {
88
+ if (candidate && existsSync(candidate)) {
89
+ return candidate;
90
+ }
91
+ }
92
+ return null;
93
+ }
94
+ function preferredGitBinaryOutputPath() {
95
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
96
+ return explicit || sharedGitNativeOutputPath;
97
+ }
98
+ function binarySupportsTrackerCommandsSync(binaryPath) {
99
+ try {
100
+ const probe = Bun.spawnSync([binaryPath, "fetch-ref", "."], {
101
+ stdout: "pipe",
102
+ stderr: "pipe"
103
+ });
104
+ const stdout = probe.stdout.toString().trim();
105
+ const stderr = probe.stderr.toString().trim();
106
+ if (stdout.includes('"error":"unknown command"')) {
107
+ return false;
108
+ }
109
+ return probe.exitCode === 2 && stderr.includes(trackerCommandUsageProbe);
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+ function nativeBuildManifestPath(outputPath) {
115
+ return `${outputPath}.build-manifest.json`;
116
+ }
117
+ function hasMatchingNativeBuildManifestSync(manifestPath, buildKey) {
118
+ if (!existsSync(manifestPath)) {
119
+ return false;
120
+ }
121
+ try {
122
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
123
+ return manifest.version === 1 && manifest.buildKey === buildKey;
124
+ } catch {
125
+ return false;
126
+ }
127
+ }
128
+ function sha256FileSync(path) {
129
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
130
+ }
131
+ function ensureRigGitBinaryPathSync(outputPath = preferredGitBinaryOutputPath()) {
132
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
133
+ throw new Error("Zig native git is disabled via RIG_DISABLE_ZIG_NATIVE=1");
134
+ }
135
+ const sourcePath = resolveGitSourcePath();
136
+ if (!sourcePath) {
137
+ const binaryPath = resolveGitBinaryPath();
138
+ if (binaryPath) {
139
+ return binaryPath;
140
+ }
141
+ throw new Error("rig-git.zig source file not found.");
142
+ }
143
+ const zigBinary = Bun.which("zig");
144
+ if (!zigBinary) {
145
+ throw new Error("zig is required to build native Rig git tools.");
146
+ }
147
+ mkdirSync(dirname(outputPath), { recursive: true });
148
+ const sourceDigest = sha256FileSync(sourcePath);
149
+ const buildKey = JSON.stringify({
150
+ version: 1,
151
+ zigBinary,
152
+ platform: process.platform,
153
+ arch: process.arch,
154
+ sourcePath,
155
+ sourceDigest
156
+ });
157
+ const manifestPath = nativeBuildManifestPath(outputPath);
158
+ const needsBuild = !existsSync(outputPath) || !hasMatchingNativeBuildManifestSync(manifestPath, buildKey) || !binarySupportsTrackerCommandsSync(outputPath);
159
+ if (!needsBuild) {
160
+ chmodSync(outputPath, 493);
161
+ return outputPath;
162
+ }
163
+ const tempOutputPath = temporaryGitBinaryOutputPath(outputPath);
164
+ const build = Bun.spawnSync([
165
+ zigBinary,
166
+ "build-exe",
167
+ sourcePath,
168
+ "-O",
169
+ "ReleaseFast",
170
+ `-femit-bin=${tempOutputPath}`
171
+ ], {
172
+ cwd: dirname(sourcePath),
173
+ stdout: "pipe",
174
+ stderr: "pipe"
175
+ });
176
+ if (build.exitCode !== 0 || !existsSync(tempOutputPath)) {
177
+ const stderr = build.stderr.toString().trim();
178
+ const stdout = build.stdout.toString().trim();
179
+ const details = [stderr, stdout].filter(Boolean).join(`
180
+ `);
181
+ throw new Error(`Failed to build native Rig git tools: ${details || `zig exited with code ${build.exitCode}`}`);
182
+ }
183
+ chmodSync(tempOutputPath, 493);
184
+ if (existsSync(outputPath) && hasMatchingNativeBuildManifestSync(manifestPath, buildKey)) {
185
+ rmSync(tempOutputPath, { force: true });
186
+ chmodSync(outputPath, 493);
187
+ return outputPath;
188
+ }
189
+ publishGitBinary(tempOutputPath, outputPath);
190
+ if (!binarySupportsTrackerCommandsSync(outputPath)) {
191
+ rmSync(outputPath, { force: true });
192
+ throw new Error("Failed to build native Rig git tools: tracker command probe failed");
193
+ }
194
+ writeFileSync(manifestPath, `${JSON.stringify({ version: 1, buildKey }, null, 2)}
195
+ `, "utf8");
196
+ return outputPath;
197
+ }
198
+ function runGitNative(command, args) {
199
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
200
+ return { ok: false, error: "rig-git native disabled" };
201
+ }
202
+ const trackerCommand = command === "fetch-ref" || command === "read-blob-at-ref" || command === "write-tree-commit" || command === "push-ref-with-lease";
203
+ let binaryPath = null;
204
+ if (trackerCommand) {
205
+ try {
206
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
207
+ } catch (error) {
208
+ const message = error instanceof Error ? error.message : String(error);
209
+ if (message.includes("rig-git.zig source file not found")) {
210
+ return { ok: false, error: "rig-git binary not found" };
211
+ }
212
+ return { ok: false, error: message };
213
+ }
214
+ } else {
215
+ const explicitBinaryPath = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
216
+ binaryPath = explicitBinaryPath && existsSync(explicitBinaryPath) ? explicitBinaryPath : !explicitBinaryPath ? resolveGitBinaryPath() : null;
217
+ if (!binaryPath) {
218
+ try {
219
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
220
+ } catch (error) {
221
+ const message = error instanceof Error ? error.message : String(error);
222
+ if (message.includes("rig-git.zig source file not found")) {
223
+ return { ok: false, error: "rig-git binary not found" };
224
+ }
225
+ return { ok: false, error: message };
226
+ }
227
+ }
228
+ }
229
+ try {
230
+ const proc = Bun.spawnSync([binaryPath, command, ...args], {
231
+ stdout: "pipe",
232
+ stderr: "pipe",
233
+ env: process.env
234
+ });
235
+ if (proc.exitCode !== 0) {
236
+ const stdoutText = proc.stdout.toString().trim();
237
+ if (stdoutText) {
238
+ try {
239
+ const parsed = JSON.parse(stdoutText);
240
+ if (!parsed.ok) {
241
+ return parsed;
242
+ }
243
+ } catch {}
244
+ }
245
+ const errText = proc.stderr.toString().trim() || `exit code ${proc.exitCode}`;
246
+ return { ok: false, error: errText };
247
+ }
248
+ const output = proc.stdout.toString().trim();
249
+ return JSON.parse(output);
250
+ } catch (err) {
251
+ return { ok: false, error: String(err) };
252
+ }
253
+ }
254
+ function requireGitNative(command, args) {
255
+ const result = runGitNative(command, args);
256
+ if (!result.ok) {
257
+ throw new Error(`rig-git ${command} failed: ${result.error}`);
258
+ }
259
+ return result;
260
+ }
261
+ function requireGitNativeString(command, args) {
262
+ const result = requireGitNative(command, args);
263
+ if ("value" in result && typeof result.value === "string") {
264
+ return result.value;
265
+ }
266
+ throw new Error(`rig-git ${command} returned an unexpected result payload`);
267
+ }
268
+ function nativeFetchRef(repoPath, remote, branch) {
269
+ return requireGitNativeString("fetch-ref", [repoPath, remote, branch]);
270
+ }
271
+ function nativeReadBlobBytesAtRef(repoPath, ref, path) {
272
+ const requestDir = resolve(sharedGitNativeOutputDir, "reads", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
273
+ mkdirSync(requestDir, { recursive: true });
274
+ const outputPath = resolve(requestDir, "blob.bin");
275
+ try {
276
+ requireGitNative("read-blob-at-ref", [repoPath, ref, path, outputPath]);
277
+ return readFileSync(outputPath);
278
+ } finally {
279
+ rmSync(requestDir, { recursive: true, force: true });
280
+ }
281
+ }
282
+
283
+ // packages/runtime/src/layout.ts
284
+ import { existsSync as existsSync2 } from "fs";
285
+ import { basename, dirname as dirname2, resolve as resolve2 } from "path";
286
+ function resolveMonorepoRoot(projectRoot) {
287
+ const normalizedProjectRoot = resolve2(projectRoot);
288
+ const explicit = process.env.MONOREPO_ROOT?.trim();
289
+ if (explicit) {
290
+ const explicitRoot = resolve2(explicit);
291
+ const explicitParent = dirname2(explicitRoot);
292
+ if (basename(explicitParent) === ".worktrees") {
293
+ const owner = dirname2(explicitParent);
294
+ const ownerHasGit = existsSync2(resolve2(owner, ".git"));
295
+ const ownerHasTaskConfig = existsSync2(resolve2(owner, ".rig", "task-config.json"));
296
+ const ownerHasRigConfig = existsSync2(resolve2(owner, "rig.config.ts"));
297
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
298
+ return owner;
299
+ }
300
+ throw new Error(`MONOREPO_ROOT points to worktree ${explicitRoot}, but the owner checkout is incomplete at ${owner}.`);
301
+ }
302
+ if (!existsSync2(resolve2(explicitRoot, ".git"))) {
303
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there.`);
304
+ }
305
+ const hasTaskConfig = existsSync2(resolve2(explicitRoot, ".rig", "task-config.json"));
306
+ const hasRigConfig = existsSync2(resolve2(explicitRoot, "rig.config.ts"));
307
+ if (!hasTaskConfig && !hasRigConfig) {
308
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but neither .rig/task-config.json nor rig.config.ts exists there.`);
309
+ }
310
+ return explicitRoot;
311
+ }
312
+ const projectParent = dirname2(normalizedProjectRoot);
313
+ if (basename(projectParent) === ".worktrees") {
314
+ const worktreeOwner = dirname2(projectParent);
315
+ const ownerHasGit = existsSync2(resolve2(worktreeOwner, ".git"));
316
+ const ownerHasTaskConfig = existsSync2(resolve2(worktreeOwner, ".rig", "task-config.json"));
317
+ const ownerHasRigConfig = existsSync2(resolve2(worktreeOwner, "rig.config.ts"));
318
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
319
+ return worktreeOwner;
320
+ }
321
+ }
322
+ return normalizedProjectRoot;
323
+ }
324
+
325
+ // packages/runtime/src/control-plane/native/runtime-native.ts
326
+ import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
327
+ import { copyFileSync as copyFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync2, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
328
+ import { tmpdir as tmpdir2 } from "os";
329
+ import { dirname as dirname3, resolve as resolve3 } from "path";
330
+ var sharedNativeRuntimeOutputDir = resolve3(tmpdir2(), "rig-native");
331
+ var sharedNativeRuntimeOutputPath = resolve3(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
332
+ var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
333
+ var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
334
+ async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
335
+ if (await buildNativeRuntimeLibrary(outputPath, options)) {
336
+ return outputPath;
337
+ }
338
+ return !options.force && existsSync3(outputPath) ? outputPath : null;
339
+ }
340
+ async function loadNativeRuntimeLibrary() {
341
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
342
+ return null;
343
+ }
344
+ for (const candidate of nativeRuntimeLibraryCandidates()) {
345
+ if (!candidate || !existsSync3(candidate)) {
346
+ continue;
347
+ }
348
+ const loaded = tryDlopenNativeRuntimeLibrary(candidate);
349
+ if (loaded) {
350
+ return loaded;
351
+ }
352
+ }
353
+ const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
354
+ if (!builtLibraryPath) {
355
+ return null;
356
+ }
357
+ return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
358
+ }
359
+ function nativePackageLibraryCandidates(fromDir, names) {
360
+ const candidates = [];
361
+ let cursor = resolve3(fromDir);
362
+ for (let index = 0;index < 8; index += 1) {
363
+ for (const name of names) {
364
+ candidates.push(resolve3(cursor, "native", `${process.platform}-${process.arch}`, name), resolve3(cursor, "native", `${process.platform}-${process.arch}`, "lib", name), resolve3(cursor, "native", name), resolve3(cursor, "native", "lib", name));
365
+ }
366
+ const parent = dirname3(cursor);
367
+ if (parent === cursor)
368
+ break;
369
+ cursor = parent;
370
+ }
371
+ return candidates;
372
+ }
373
+ function nativeRuntimeLibraryCandidates() {
374
+ const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
375
+ const execDir = process.execPath?.trim() ? dirname3(process.execPath.trim()) : "";
376
+ const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
377
+ return [...new Set([
378
+ explicit,
379
+ ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
380
+ execDir ? resolve3(execDir, colocatedNativeRuntimeFileName) : "",
381
+ execDir ? resolve3(execDir, platformSpecific) : "",
382
+ execDir ? resolve3(execDir, "..", colocatedNativeRuntimeFileName) : "",
383
+ execDir ? resolve3(execDir, "..", platformSpecific) : "",
384
+ execDir ? resolve3(execDir, "lib", colocatedNativeRuntimeFileName) : "",
385
+ execDir ? resolve3(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
386
+ sharedNativeRuntimeOutputPath
387
+ ].filter(Boolean))];
388
+ }
389
+ function resolveNativeRuntimeSourcePath() {
390
+ const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
391
+ if (explicit && existsSync3(explicit)) {
392
+ return explicit;
393
+ }
394
+ const bundled = resolve3(import.meta.dir, "../../../native/snapshot.zig");
395
+ return existsSync3(bundled) ? bundled : null;
396
+ }
397
+ async function buildNativeRuntimeLibrary(outputPath, options = {}) {
398
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
399
+ return false;
400
+ }
401
+ const zigBinary = Bun.which("zig");
402
+ const sourcePath = resolveNativeRuntimeSourcePath();
403
+ if (!zigBinary || !sourcePath) {
404
+ return false;
405
+ }
406
+ const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
407
+ try {
408
+ mkdirSync2(dirname3(outputPath), { recursive: true });
409
+ const needsBuild = options.force === true || !existsSync3(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
410
+ if (!needsBuild) {
411
+ return true;
412
+ }
413
+ const build = Bun.spawn([
414
+ zigBinary,
415
+ "build-lib",
416
+ sourcePath,
417
+ "-dynamic",
418
+ "-O",
419
+ "ReleaseFast",
420
+ `-femit-bin=${tempOutputPath}`
421
+ ], {
422
+ cwd: import.meta.dir,
423
+ stdout: "pipe",
424
+ stderr: "pipe"
425
+ });
426
+ const exitCode = await build.exited;
427
+ if (exitCode !== 0 || !existsSync3(tempOutputPath)) {
428
+ rmSync2(tempOutputPath, { force: true });
429
+ return false;
430
+ }
431
+ renameSync2(tempOutputPath, outputPath);
432
+ return true;
433
+ } catch {
434
+ rmSync2(tempOutputPath, { force: true });
435
+ return false;
436
+ }
437
+ }
438
+ function tryDlopenNativeRuntimeLibrary(outputPath) {
439
+ try {
440
+ return dlopen(outputPath, {
441
+ rig_scope_match: {
442
+ args: ["ptr", "ptr"],
443
+ returns: "u8"
444
+ },
445
+ snapshot_capture: {
446
+ args: ["ptr", "u64", "ptr", "u64"],
447
+ returns: "ptr"
448
+ },
449
+ snapshot_delta: {
450
+ args: ["ptr", "ptr"],
451
+ returns: "ptr"
452
+ },
453
+ snapshot_store_delta: {
454
+ args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
455
+ returns: "ptr"
456
+ },
457
+ snapshot_inspect_delta: {
458
+ args: ["ptr", "u64"],
459
+ returns: "ptr"
460
+ },
461
+ snapshot_apply_delta: {
462
+ args: ["ptr", "u64", "ptr", "u64"],
463
+ returns: "ptr"
464
+ },
465
+ snapshot_release: {
466
+ args: ["ptr"],
467
+ returns: "void"
468
+ },
469
+ runtime_hash_file: {
470
+ args: ["ptr", "u64"],
471
+ returns: "ptr"
472
+ },
473
+ runtime_hash_tree: {
474
+ args: ["ptr", "u64"],
475
+ returns: "ptr"
476
+ },
477
+ runtime_prepare_paths: {
478
+ args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
479
+ returns: "ptr"
480
+ },
481
+ runtime_link_dependency_layer: {
482
+ args: ["ptr", "u64", "ptr", "u64"],
483
+ returns: "ptr"
484
+ },
485
+ runtime_scan_worktrees: {
486
+ args: ["ptr", "u64"],
487
+ returns: "ptr"
488
+ }
489
+ });
490
+ } catch {
491
+ return null;
492
+ }
493
+ }
494
+
495
+ // packages/runtime/src/control-plane/native/utils.ts
496
+ function resolveMonorepoRoot2(projectRoot) {
497
+ return resolveMonorepoRoot(projectRoot);
498
+ }
499
+ var scopeRegexCache = new Map;
500
+
501
+ // packages/runtime/src/control-plane/memory-sync/db.ts
502
+ import { Database } from "bun:sqlite";
503
+ import { mkdirSync as mkdirSync3 } from "fs";
504
+ import { dirname as dirname4 } from "path";
505
+ var SCHEMA_STATEMENTS = [
506
+ `CREATE TABLE IF NOT EXISTS memory_events (
507
+ event_id TEXT PRIMARY KEY,
508
+ event_type TEXT NOT NULL,
509
+ canonical_key TEXT NOT NULL,
510
+ summary TEXT,
511
+ kind TEXT,
512
+ category TEXT,
513
+ confidence REAL,
514
+ source_run_id TEXT,
515
+ source_task_id TEXT,
516
+ branch TEXT,
517
+ source_canonical_key TEXT,
518
+ replacement_canonical_key TEXT,
519
+ retrieval_query TEXT,
520
+ retrieval_rank INTEGER,
521
+ feedback_outcome TEXT,
522
+ details_json TEXT,
523
+ created_at TEXT NOT NULL
524
+ )`,
525
+ `CREATE TABLE IF NOT EXISTS memory_items (
526
+ canonical_key TEXT PRIMARY KEY,
527
+ summary TEXT NOT NULL,
528
+ kind TEXT,
529
+ category TEXT,
530
+ status TEXT NOT NULL,
531
+ confidence REAL NOT NULL,
532
+ source_run_id TEXT,
533
+ source_task_id TEXT,
534
+ branch TEXT,
535
+ details_json TEXT,
536
+ created_at TEXT NOT NULL,
537
+ updated_at TEXT NOT NULL,
538
+ last_event_id TEXT NOT NULL,
539
+ superseded_by TEXT,
540
+ embedding TEXT
541
+ )`,
542
+ `CREATE TABLE IF NOT EXISTS memory_links (
543
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
544
+ from_key TEXT NOT NULL,
545
+ to_key TEXT NOT NULL,
546
+ relation TEXT NOT NULL,
547
+ source_event_id TEXT NOT NULL,
548
+ created_at TEXT NOT NULL
549
+ )`,
550
+ `CREATE TABLE IF NOT EXISTS task_runs (
551
+ run_id TEXT PRIMARY KEY,
552
+ task_id TEXT,
553
+ branch TEXT,
554
+ first_event_id TEXT,
555
+ last_event_id TEXT,
556
+ created_at TEXT NOT NULL,
557
+ updated_at TEXT NOT NULL
558
+ )`,
559
+ `CREATE TABLE IF NOT EXISTS retrieval_feedback (
560
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
561
+ canonical_key TEXT NOT NULL,
562
+ outcome TEXT NOT NULL,
563
+ retrieval_rank INTEGER,
564
+ source_run_id TEXT,
565
+ source_task_id TEXT,
566
+ query_text TEXT,
567
+ source_event_id TEXT NOT NULL,
568
+ created_at TEXT NOT NULL
569
+ )`
570
+ ];
571
+ var MEMORY_EVENT_COLUMNS = [
572
+ ["summary", "TEXT"],
573
+ ["kind", "TEXT"],
574
+ ["category", "TEXT"],
575
+ ["confidence", "REAL"],
576
+ ["source_run_id", "TEXT"],
577
+ ["source_task_id", "TEXT"],
578
+ ["branch", "TEXT"],
579
+ ["source_canonical_key", "TEXT"],
580
+ ["replacement_canonical_key", "TEXT"],
581
+ ["retrieval_query", "TEXT"],
582
+ ["retrieval_rank", "INTEGER"],
583
+ ["feedback_outcome", "TEXT"],
584
+ ["details_json", "TEXT"]
585
+ ];
586
+ var MEMORY_ITEM_COLUMNS = [
587
+ ["kind", "TEXT"],
588
+ ["category", "TEXT"],
589
+ ["branch", "TEXT"],
590
+ ["details_json", "TEXT"],
591
+ ["superseded_by", "TEXT"],
592
+ ["embedding", "TEXT"]
593
+ ];
594
+ function normalizeStatement(statement, args) {
595
+ if (typeof statement === "string") {
596
+ return { sql: statement, args };
597
+ }
598
+ return {
599
+ sql: statement.sql,
600
+ args: statement.args ?? args
601
+ };
602
+ }
603
+ function normalizeBindings(bindings) {
604
+ return (bindings ?? []).map((binding) => binding === undefined ? null : binding);
605
+ }
606
+ function statementVerb(sql) {
607
+ const match = sql.trim().match(/^[A-Za-z]+/);
608
+ return match ? match[0].toUpperCase() : "";
609
+ }
610
+ function isMutationStatement(sql) {
611
+ return new Set([
612
+ "ALTER",
613
+ "ATTACH",
614
+ "BEGIN",
615
+ "COMMIT",
616
+ "CREATE",
617
+ "DELETE",
618
+ "DETACH",
619
+ "DROP",
620
+ "END",
621
+ "INSERT",
622
+ "REINDEX",
623
+ "RELEASE",
624
+ "REPLACE",
625
+ "ROLLBACK",
626
+ "SAVEPOINT",
627
+ "UPDATE",
628
+ "VACUUM"
629
+ ]).has(statementVerb(sql));
630
+ }
631
+ function executeSqlite(sqlite, statement, args) {
632
+ const normalized = normalizeStatement(statement, args);
633
+ const bindings = normalizeBindings(normalized.args);
634
+ if (isMutationStatement(normalized.sql)) {
635
+ const result = bindings.length > 0 ? sqlite.run(normalized.sql, ...bindings) : sqlite.run(normalized.sql);
636
+ return {
637
+ rows: [],
638
+ rowsAffected: Number(result.changes)
639
+ };
640
+ }
641
+ const query = sqlite.query(normalized.sql);
642
+ const rows = bindings.length > 0 ? query.all(...bindings) : query.all();
643
+ return {
644
+ rows,
645
+ rowsAffected: 0
646
+ };
647
+ }
648
+ function createTransaction(sqlite, mode) {
649
+ sqlite.run(mode === "write" ? "BEGIN IMMEDIATE" : "BEGIN");
650
+ let active = true;
651
+ return {
652
+ async execute(statement, args) {
653
+ if (!active) {
654
+ throw new Error("memory transaction is closed");
655
+ }
656
+ return executeSqlite(sqlite, statement, args);
657
+ },
658
+ async commit() {
659
+ if (!active) {
660
+ return;
661
+ }
662
+ sqlite.run("COMMIT");
663
+ active = false;
664
+ },
665
+ async rollback() {
666
+ if (!active) {
667
+ return;
668
+ }
669
+ sqlite.run("ROLLBACK");
670
+ active = false;
671
+ },
672
+ close() {
673
+ if (!active) {
674
+ return;
675
+ }
676
+ try {
677
+ sqlite.run("ROLLBACK");
678
+ } catch {} finally {
679
+ active = false;
680
+ }
681
+ }
682
+ };
683
+ }
684
+ function createMemoryDbClient(sqlite) {
685
+ return {
686
+ async execute(statement, args) {
687
+ return executeSqlite(sqlite, statement, args);
688
+ },
689
+ async transaction(mode) {
690
+ return createTransaction(sqlite, mode);
691
+ },
692
+ close() {
693
+ sqlite.close();
694
+ }
695
+ };
696
+ }
697
+ async function listColumns(executor, tableName) {
698
+ const result = await executor.execute(`PRAGMA table_info(${tableName})`);
699
+ return new Set(result.rows.map((row) => String(row.name)));
700
+ }
701
+ async function ensureColumns(executor, tableName, columns) {
702
+ const existing = await listColumns(executor, tableName);
703
+ for (const [columnName, definition] of columns) {
704
+ if (!existing.has(columnName)) {
705
+ await executor.execute(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);
706
+ }
707
+ }
708
+ }
709
+ async function ensureSchema(db) {
710
+ for (const statement of SCHEMA_STATEMENTS) {
711
+ await db.client.execute(statement);
712
+ }
713
+ await ensureColumns(db.client, "memory_events", MEMORY_EVENT_COLUMNS);
714
+ await ensureColumns(db.client, "memory_items", MEMORY_ITEM_COLUMNS);
715
+ }
716
+ async function openMemoryDb(dbPath) {
717
+ mkdirSync3(dirname4(dbPath), { recursive: true });
718
+ const sqlite = new Database(dbPath, { create: true, strict: true });
719
+ const client = createMemoryDbClient(sqlite);
720
+ const db = {
721
+ path: dbPath,
722
+ client,
723
+ async close() {
724
+ client.close();
725
+ }
726
+ };
727
+ await ensureSchema(db);
728
+ return db;
729
+ }
730
+
731
+ // packages/runtime/src/control-plane/memory-sync/read.ts
732
+ var CANONICAL_MEMORY_DB_PATH = "rig/memory/project-memory.db";
733
+ var DEFAULT_READ_DEPS = {
734
+ fetchRef: nativeFetchRef,
735
+ readBlobBytesAtRef: nativeReadBlobBytesAtRef,
736
+ openMemoryDb,
737
+ makeTempDir: () => mkdtempSync(join(tmpdir3(), "memory-sync-read-")),
738
+ removeDir: (path) => rmSync3(path, { recursive: true, force: true })
739
+ };
740
+ function isMissingCanonicalMemoryBlobError(error) {
741
+ const message = error instanceof Error ? error.message : String(error);
742
+ return message.includes(`path '${CANONICAL_MEMORY_DB_PATH}' does not exist in`) || message.includes(`path '${CANONICAL_MEMORY_DB_PATH}' exists on disk, but not in`) || message.includes(`pathspec '${CANONICAL_MEMORY_DB_PATH}' did not match any file(s) known to git`);
743
+ }
744
+ async function validateReadableDatabase(dbPath, open) {
745
+ const db = await open(dbPath);
746
+ await db.close();
747
+ }
748
+ async function readCanonicalMemoryDb(projectRoot, deps = {}) {
749
+ const readDeps = { ...DEFAULT_READ_DEPS, ...deps };
750
+ const repoPath = resolveMonorepoRoot2(projectRoot);
751
+ const baseOid = readDeps.fetchRef(repoPath, "origin", "main");
752
+ const tempDir = readDeps.makeTempDir();
753
+ const dbPath = join(tempDir, "project-memory.db");
754
+ let createdFresh = false;
755
+ try {
756
+ try {
757
+ const bytes = readDeps.readBlobBytesAtRef(repoPath, baseOid, CANONICAL_MEMORY_DB_PATH);
758
+ writeFileSync2(dbPath, bytes);
759
+ } catch (error) {
760
+ if (!isMissingCanonicalMemoryBlobError(error)) {
761
+ throw error;
762
+ }
763
+ const db = await readDeps.openMemoryDb(dbPath);
764
+ await db.close();
765
+ createdFresh = true;
766
+ }
767
+ await validateReadableDatabase(dbPath, readDeps.openMemoryDb);
768
+ return {
769
+ repoPath,
770
+ baseOid,
771
+ dbPath,
772
+ createdFresh,
773
+ async cleanup() {
774
+ readDeps.removeDir(tempDir);
775
+ }
776
+ };
777
+ } catch (error) {
778
+ readDeps.removeDir(tempDir);
779
+ throw error;
780
+ }
781
+ }
782
+ export {
783
+ readCanonicalMemoryDb
784
+ };