@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,1547 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/native/git-native.ts
3
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
4
+ import { tmpdir } from "os";
5
+ import { dirname, isAbsolute, resolve } from "path";
6
+ import { createHash } from "crypto";
7
+ function isTextTreeCommitUpdate(update) {
8
+ return typeof update.content === "string";
9
+ }
10
+ var sharedGitNativeOutputDir = resolve(tmpdir(), "rig-native");
11
+ var sharedGitNativeOutputPath = resolve(sharedGitNativeOutputDir, `rig-git-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`);
12
+ var trackerCommandUsageProbe = "usage: rig-git fetch-ref <repo-path> <remote> <branch>";
13
+ function temporaryGitBinaryOutputPath(outputPath) {
14
+ const suffix = process.platform === "win32" ? ".exe" : "";
15
+ return resolve(dirname(outputPath), `.rig-git-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}${suffix}`);
16
+ }
17
+ function publishGitBinary(tempOutputPath, outputPath) {
18
+ try {
19
+ renameSync(tempOutputPath, outputPath);
20
+ } catch (error) {
21
+ if (process.platform === "win32" && existsSync(outputPath)) {
22
+ rmSync(outputPath, { force: true });
23
+ renameSync(tempOutputPath, outputPath);
24
+ return;
25
+ }
26
+ throw error;
27
+ }
28
+ }
29
+ function runtimeRigGitFileName() {
30
+ return `rig-git${process.platform === "win32" ? ".exe" : ""}`;
31
+ }
32
+ function rigGitSourceCandidates() {
33
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
34
+ const cwd = process.cwd()?.trim() || "";
35
+ const projectRoot = process.env.PROJECT_RIG_ROOT?.trim() || "";
36
+ const hostProjectRoot = process.env.RIG_HOST_PROJECT_ROOT?.trim() || "";
37
+ const moduleRelativeSource = resolve(import.meta.dir, "../../../native/rig-git.zig");
38
+ return [...new Set([
39
+ process.env.RIG_NATIVE_GIT_SOURCE?.trim() || "",
40
+ moduleRelativeSource,
41
+ projectRoot ? resolve(projectRoot, "packages/runtime/native/rig-git.zig") : "",
42
+ hostProjectRoot ? resolve(hostProjectRoot, "packages/runtime/native/rig-git.zig") : "",
43
+ cwd ? resolve(cwd, "packages/runtime/native/rig-git.zig") : "",
44
+ execDir ? resolve(execDir, "..", "..", "packages/runtime/native/rig-git.zig") : "",
45
+ execDir ? resolve(execDir, "..", "native", "rig-git.zig") : ""
46
+ ].filter(Boolean))];
47
+ }
48
+ function nativePackageBinaryCandidates(fromDir, fileName) {
49
+ const candidates = [];
50
+ let cursor = resolve(fromDir);
51
+ for (let index = 0;index < 8; index += 1) {
52
+ 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));
53
+ const parent = dirname(cursor);
54
+ if (parent === cursor)
55
+ break;
56
+ cursor = parent;
57
+ }
58
+ return candidates;
59
+ }
60
+ function rigGitBinaryCandidates() {
61
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
62
+ const fileName = runtimeRigGitFileName();
63
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
64
+ return [...new Set([
65
+ explicit,
66
+ ...nativePackageBinaryCandidates(import.meta.dir, fileName),
67
+ execDir ? resolve(execDir, fileName) : "",
68
+ execDir ? resolve(execDir, "..", fileName) : "",
69
+ execDir ? resolve(execDir, "..", "bin", fileName) : "",
70
+ sharedGitNativeOutputPath
71
+ ].filter(Boolean))];
72
+ }
73
+ function resolveGitSourcePath() {
74
+ for (const candidate of rigGitSourceCandidates()) {
75
+ if (candidate && existsSync(candidate)) {
76
+ return candidate;
77
+ }
78
+ }
79
+ return null;
80
+ }
81
+ function resolveGitBinaryPath() {
82
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
83
+ return null;
84
+ }
85
+ for (const candidate of rigGitBinaryCandidates()) {
86
+ if (candidate && existsSync(candidate)) {
87
+ return candidate;
88
+ }
89
+ }
90
+ return null;
91
+ }
92
+ function preferredGitBinaryOutputPath() {
93
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
94
+ return explicit || sharedGitNativeOutputPath;
95
+ }
96
+ function binarySupportsTrackerCommandsSync(binaryPath) {
97
+ try {
98
+ const probe = Bun.spawnSync([binaryPath, "fetch-ref", "."], {
99
+ stdout: "pipe",
100
+ stderr: "pipe"
101
+ });
102
+ const stdout = probe.stdout.toString().trim();
103
+ const stderr = probe.stderr.toString().trim();
104
+ if (stdout.includes('"error":"unknown command"')) {
105
+ return false;
106
+ }
107
+ return probe.exitCode === 2 && stderr.includes(trackerCommandUsageProbe);
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ function nativeBuildManifestPath(outputPath) {
113
+ return `${outputPath}.build-manifest.json`;
114
+ }
115
+ function hasMatchingNativeBuildManifestSync(manifestPath, buildKey) {
116
+ if (!existsSync(manifestPath)) {
117
+ return false;
118
+ }
119
+ try {
120
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
121
+ return manifest.version === 1 && manifest.buildKey === buildKey;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ function sha256FileSync(path) {
127
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
128
+ }
129
+ function ensureRigGitBinaryPathSync(outputPath = preferredGitBinaryOutputPath()) {
130
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
131
+ throw new Error("Zig native git is disabled via RIG_DISABLE_ZIG_NATIVE=1");
132
+ }
133
+ const sourcePath = resolveGitSourcePath();
134
+ if (!sourcePath) {
135
+ const binaryPath = resolveGitBinaryPath();
136
+ if (binaryPath) {
137
+ return binaryPath;
138
+ }
139
+ throw new Error("rig-git.zig source file not found.");
140
+ }
141
+ const zigBinary = Bun.which("zig");
142
+ if (!zigBinary) {
143
+ throw new Error("zig is required to build native Rig git tools.");
144
+ }
145
+ mkdirSync(dirname(outputPath), { recursive: true });
146
+ const sourceDigest = sha256FileSync(sourcePath);
147
+ const buildKey = JSON.stringify({
148
+ version: 1,
149
+ zigBinary,
150
+ platform: process.platform,
151
+ arch: process.arch,
152
+ sourcePath,
153
+ sourceDigest
154
+ });
155
+ const manifestPath = nativeBuildManifestPath(outputPath);
156
+ const needsBuild = !existsSync(outputPath) || !hasMatchingNativeBuildManifestSync(manifestPath, buildKey) || !binarySupportsTrackerCommandsSync(outputPath);
157
+ if (!needsBuild) {
158
+ chmodSync(outputPath, 493);
159
+ return outputPath;
160
+ }
161
+ const tempOutputPath = temporaryGitBinaryOutputPath(outputPath);
162
+ const build = Bun.spawnSync([
163
+ zigBinary,
164
+ "build-exe",
165
+ sourcePath,
166
+ "-O",
167
+ "ReleaseFast",
168
+ `-femit-bin=${tempOutputPath}`
169
+ ], {
170
+ cwd: dirname(sourcePath),
171
+ stdout: "pipe",
172
+ stderr: "pipe"
173
+ });
174
+ if (build.exitCode !== 0 || !existsSync(tempOutputPath)) {
175
+ const stderr = build.stderr.toString().trim();
176
+ const stdout = build.stdout.toString().trim();
177
+ const details = [stderr, stdout].filter(Boolean).join(`
178
+ `);
179
+ throw new Error(`Failed to build native Rig git tools: ${details || `zig exited with code ${build.exitCode}`}`);
180
+ }
181
+ chmodSync(tempOutputPath, 493);
182
+ if (existsSync(outputPath) && hasMatchingNativeBuildManifestSync(manifestPath, buildKey)) {
183
+ rmSync(tempOutputPath, { force: true });
184
+ chmodSync(outputPath, 493);
185
+ return outputPath;
186
+ }
187
+ publishGitBinary(tempOutputPath, outputPath);
188
+ if (!binarySupportsTrackerCommandsSync(outputPath)) {
189
+ rmSync(outputPath, { force: true });
190
+ throw new Error("Failed to build native Rig git tools: tracker command probe failed");
191
+ }
192
+ writeFileSync(manifestPath, `${JSON.stringify({ version: 1, buildKey }, null, 2)}
193
+ `, "utf8");
194
+ return outputPath;
195
+ }
196
+ function runGitNative(command, args) {
197
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
198
+ return { ok: false, error: "rig-git native disabled" };
199
+ }
200
+ const trackerCommand = command === "fetch-ref" || command === "read-blob-at-ref" || command === "write-tree-commit" || command === "push-ref-with-lease";
201
+ let binaryPath = null;
202
+ if (trackerCommand) {
203
+ try {
204
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
205
+ } catch (error) {
206
+ const message = error instanceof Error ? error.message : String(error);
207
+ if (message.includes("rig-git.zig source file not found")) {
208
+ return { ok: false, error: "rig-git binary not found" };
209
+ }
210
+ return { ok: false, error: message };
211
+ }
212
+ } else {
213
+ const explicitBinaryPath = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
214
+ binaryPath = explicitBinaryPath && existsSync(explicitBinaryPath) ? explicitBinaryPath : !explicitBinaryPath ? resolveGitBinaryPath() : null;
215
+ if (!binaryPath) {
216
+ try {
217
+ binaryPath = ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
218
+ } catch (error) {
219
+ const message = error instanceof Error ? error.message : String(error);
220
+ if (message.includes("rig-git.zig source file not found")) {
221
+ return { ok: false, error: "rig-git binary not found" };
222
+ }
223
+ return { ok: false, error: message };
224
+ }
225
+ }
226
+ }
227
+ try {
228
+ const proc = Bun.spawnSync([binaryPath, command, ...args], {
229
+ stdout: "pipe",
230
+ stderr: "pipe",
231
+ env: process.env
232
+ });
233
+ if (proc.exitCode !== 0) {
234
+ const stdoutText = proc.stdout.toString().trim();
235
+ if (stdoutText) {
236
+ try {
237
+ const parsed = JSON.parse(stdoutText);
238
+ if (!parsed.ok) {
239
+ return parsed;
240
+ }
241
+ } catch {}
242
+ }
243
+ const errText = proc.stderr.toString().trim() || `exit code ${proc.exitCode}`;
244
+ return { ok: false, error: errText };
245
+ }
246
+ const output = proc.stdout.toString().trim();
247
+ return JSON.parse(output);
248
+ } catch (err) {
249
+ return { ok: false, error: String(err) };
250
+ }
251
+ }
252
+ function requireGitNative(command, args) {
253
+ const result = runGitNative(command, args);
254
+ if (!result.ok) {
255
+ throw new Error(`rig-git ${command} failed: ${result.error}`);
256
+ }
257
+ return result;
258
+ }
259
+ function requireGitNativeString(command, args) {
260
+ const result = requireGitNative(command, args);
261
+ if ("value" in result && typeof result.value === "string") {
262
+ return result.value;
263
+ }
264
+ throw new Error(`rig-git ${command} returned an unexpected result payload`);
265
+ }
266
+ function nativeFetchRef(repoPath, remote, branch) {
267
+ return requireGitNativeString("fetch-ref", [repoPath, remote, branch]);
268
+ }
269
+ function nativeReadBlobBytesAtRef(repoPath, ref, path) {
270
+ const requestDir = resolve(sharedGitNativeOutputDir, "reads", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
271
+ mkdirSync(requestDir, { recursive: true });
272
+ const outputPath = resolve(requestDir, "blob.bin");
273
+ try {
274
+ requireGitNative("read-blob-at-ref", [repoPath, ref, path, outputPath]);
275
+ return readFileSync(outputPath);
276
+ } finally {
277
+ rmSync(requestDir, { recursive: true, force: true });
278
+ }
279
+ }
280
+ function serializeTreeCommitUpdates(updates) {
281
+ return updates.map((update) => {
282
+ if (isTextTreeCommitUpdate(update)) {
283
+ return { path: update.path, kind: "text", content: update.content };
284
+ }
285
+ if (!isAbsolute(update.sourceFilePath)) {
286
+ throw new Error("tree commit binary updates require an absolute sourceFilePath");
287
+ }
288
+ return { path: update.path, kind: "file", sourceFilePath: update.sourceFilePath };
289
+ });
290
+ }
291
+ function buildTreeCommitUpdatesJson(updates) {
292
+ return `${JSON.stringify(serializeTreeCommitUpdates(updates), null, 2)}
293
+ `;
294
+ }
295
+ function nativeWriteTreeCommit(repoPath, baseRef, updates, message) {
296
+ const requestDir = resolve(sharedGitNativeOutputDir, "requests", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
297
+ mkdirSync(requestDir, { recursive: true });
298
+ const messagePath = resolve(requestDir, "message.txt");
299
+ const updatesPath = resolve(requestDir, "updates.json");
300
+ try {
301
+ writeFileSync(messagePath, message, "utf8");
302
+ writeFileSync(updatesPath, buildTreeCommitUpdatesJson(updates), "utf8");
303
+ return requireGitNativeString("write-tree-commit", [repoPath, baseRef, messagePath, updatesPath]);
304
+ } finally {
305
+ rmSync(requestDir, { recursive: true, force: true });
306
+ }
307
+ }
308
+ function nativePushRefWithLease(repoPath, localOid, remoteRef, expectedOldOid, remote = "origin") {
309
+ return requireGitNativeString("push-ref-with-lease", [
310
+ repoPath,
311
+ localOid,
312
+ remoteRef,
313
+ expectedOldOid,
314
+ remote
315
+ ]);
316
+ }
317
+
318
+ // packages/runtime/src/control-plane/memory-sync/db.ts
319
+ import { Database } from "bun:sqlite";
320
+ import { mkdirSync as mkdirSync2 } from "fs";
321
+ import { dirname as dirname2 } from "path";
322
+
323
+ // packages/runtime/src/control-plane/memory-sync/types.ts
324
+ var NO_MATCH_RETRIEVAL_CANONICAL_KEY = "__memory_recall__:none";
325
+
326
+ // packages/runtime/src/control-plane/memory-sync/db.ts
327
+ var SCHEMA_STATEMENTS = [
328
+ `CREATE TABLE IF NOT EXISTS memory_events (
329
+ event_id TEXT PRIMARY KEY,
330
+ event_type TEXT NOT NULL,
331
+ canonical_key TEXT NOT NULL,
332
+ summary TEXT,
333
+ kind TEXT,
334
+ category TEXT,
335
+ confidence REAL,
336
+ source_run_id TEXT,
337
+ source_task_id TEXT,
338
+ branch TEXT,
339
+ source_canonical_key TEXT,
340
+ replacement_canonical_key TEXT,
341
+ retrieval_query TEXT,
342
+ retrieval_rank INTEGER,
343
+ feedback_outcome TEXT,
344
+ details_json TEXT,
345
+ created_at TEXT NOT NULL
346
+ )`,
347
+ `CREATE TABLE IF NOT EXISTS memory_items (
348
+ canonical_key TEXT PRIMARY KEY,
349
+ summary TEXT NOT NULL,
350
+ kind TEXT,
351
+ category TEXT,
352
+ status TEXT NOT NULL,
353
+ confidence REAL NOT NULL,
354
+ source_run_id TEXT,
355
+ source_task_id TEXT,
356
+ branch TEXT,
357
+ details_json TEXT,
358
+ created_at TEXT NOT NULL,
359
+ updated_at TEXT NOT NULL,
360
+ last_event_id TEXT NOT NULL,
361
+ superseded_by TEXT,
362
+ embedding TEXT
363
+ )`,
364
+ `CREATE TABLE IF NOT EXISTS memory_links (
365
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
366
+ from_key TEXT NOT NULL,
367
+ to_key TEXT NOT NULL,
368
+ relation TEXT NOT NULL,
369
+ source_event_id TEXT NOT NULL,
370
+ created_at TEXT NOT NULL
371
+ )`,
372
+ `CREATE TABLE IF NOT EXISTS task_runs (
373
+ run_id TEXT PRIMARY KEY,
374
+ task_id TEXT,
375
+ branch TEXT,
376
+ first_event_id TEXT,
377
+ last_event_id TEXT,
378
+ created_at TEXT NOT NULL,
379
+ updated_at TEXT NOT NULL
380
+ )`,
381
+ `CREATE TABLE IF NOT EXISTS retrieval_feedback (
382
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
383
+ canonical_key TEXT NOT NULL,
384
+ outcome TEXT NOT NULL,
385
+ retrieval_rank INTEGER,
386
+ source_run_id TEXT,
387
+ source_task_id TEXT,
388
+ query_text TEXT,
389
+ source_event_id TEXT NOT NULL,
390
+ created_at TEXT NOT NULL
391
+ )`
392
+ ];
393
+ var MEMORY_EVENT_COLUMNS = [
394
+ ["summary", "TEXT"],
395
+ ["kind", "TEXT"],
396
+ ["category", "TEXT"],
397
+ ["confidence", "REAL"],
398
+ ["source_run_id", "TEXT"],
399
+ ["source_task_id", "TEXT"],
400
+ ["branch", "TEXT"],
401
+ ["source_canonical_key", "TEXT"],
402
+ ["replacement_canonical_key", "TEXT"],
403
+ ["retrieval_query", "TEXT"],
404
+ ["retrieval_rank", "INTEGER"],
405
+ ["feedback_outcome", "TEXT"],
406
+ ["details_json", "TEXT"]
407
+ ];
408
+ var MEMORY_ITEM_COLUMNS = [
409
+ ["kind", "TEXT"],
410
+ ["category", "TEXT"],
411
+ ["branch", "TEXT"],
412
+ ["details_json", "TEXT"],
413
+ ["superseded_by", "TEXT"],
414
+ ["embedding", "TEXT"]
415
+ ];
416
+ function jsonText(value) {
417
+ if (value == null) {
418
+ return null;
419
+ }
420
+ return JSON.stringify(value);
421
+ }
422
+ function parseJsonRecord(value) {
423
+ if (typeof value !== "string" || value.length === 0) {
424
+ return null;
425
+ }
426
+ return JSON.parse(value);
427
+ }
428
+ function parseEmbedding(value) {
429
+ if (typeof value !== "string" || value.length === 0) {
430
+ return null;
431
+ }
432
+ return JSON.parse(value);
433
+ }
434
+ function rowString(row, key) {
435
+ const value = row[key];
436
+ return value == null ? null : String(value);
437
+ }
438
+ function eventSummary(event) {
439
+ return "summary" in event ? event.summary : null;
440
+ }
441
+ function eventKind(event) {
442
+ return "kind" in event ? event.kind : null;
443
+ }
444
+ function eventCategory(event) {
445
+ return "category" in event ? event.category ?? null : null;
446
+ }
447
+ function eventConfidence(event) {
448
+ return "confidence" in event ? event.confidence : null;
449
+ }
450
+ function eventDetails(event) {
451
+ return "details" in event ? event.details ?? null : null;
452
+ }
453
+ function eventSourceCanonicalKey(event) {
454
+ return "sourceCanonicalKey" in event ? event.sourceCanonicalKey : null;
455
+ }
456
+ function eventReplacementCanonicalKey(event) {
457
+ return "replacementCanonicalKey" in event ? event.replacementCanonicalKey : null;
458
+ }
459
+ function eventRetrievalQuery(event) {
460
+ return "retrievalQuery" in event ? event.retrievalQuery ?? null : null;
461
+ }
462
+ function eventRetrievalRank(event) {
463
+ return "retrievalRank" in event ? event.retrievalRank : null;
464
+ }
465
+ function eventFeedbackOutcome(event) {
466
+ return "feedbackOutcome" in event ? event.feedbackOutcome : null;
467
+ }
468
+ function normalizeStatement(statement, args) {
469
+ if (typeof statement === "string") {
470
+ return { sql: statement, args };
471
+ }
472
+ return {
473
+ sql: statement.sql,
474
+ args: statement.args ?? args
475
+ };
476
+ }
477
+ function normalizeBindings(bindings) {
478
+ return (bindings ?? []).map((binding) => binding === undefined ? null : binding);
479
+ }
480
+ function statementVerb(sql) {
481
+ const match = sql.trim().match(/^[A-Za-z]+/);
482
+ return match ? match[0].toUpperCase() : "";
483
+ }
484
+ function isMutationStatement(sql) {
485
+ return new Set([
486
+ "ALTER",
487
+ "ATTACH",
488
+ "BEGIN",
489
+ "COMMIT",
490
+ "CREATE",
491
+ "DELETE",
492
+ "DETACH",
493
+ "DROP",
494
+ "END",
495
+ "INSERT",
496
+ "REINDEX",
497
+ "RELEASE",
498
+ "REPLACE",
499
+ "ROLLBACK",
500
+ "SAVEPOINT",
501
+ "UPDATE",
502
+ "VACUUM"
503
+ ]).has(statementVerb(sql));
504
+ }
505
+ function executeSqlite(sqlite, statement, args) {
506
+ const normalized = normalizeStatement(statement, args);
507
+ const bindings = normalizeBindings(normalized.args);
508
+ if (isMutationStatement(normalized.sql)) {
509
+ const result = bindings.length > 0 ? sqlite.run(normalized.sql, ...bindings) : sqlite.run(normalized.sql);
510
+ return {
511
+ rows: [],
512
+ rowsAffected: Number(result.changes)
513
+ };
514
+ }
515
+ const query = sqlite.query(normalized.sql);
516
+ const rows = bindings.length > 0 ? query.all(...bindings) : query.all();
517
+ return {
518
+ rows,
519
+ rowsAffected: 0
520
+ };
521
+ }
522
+ function createTransaction(sqlite, mode) {
523
+ sqlite.run(mode === "write" ? "BEGIN IMMEDIATE" : "BEGIN");
524
+ let active = true;
525
+ return {
526
+ async execute(statement, args) {
527
+ if (!active) {
528
+ throw new Error("memory transaction is closed");
529
+ }
530
+ return executeSqlite(sqlite, statement, args);
531
+ },
532
+ async commit() {
533
+ if (!active) {
534
+ return;
535
+ }
536
+ sqlite.run("COMMIT");
537
+ active = false;
538
+ },
539
+ async rollback() {
540
+ if (!active) {
541
+ return;
542
+ }
543
+ sqlite.run("ROLLBACK");
544
+ active = false;
545
+ },
546
+ close() {
547
+ if (!active) {
548
+ return;
549
+ }
550
+ try {
551
+ sqlite.run("ROLLBACK");
552
+ } catch {} finally {
553
+ active = false;
554
+ }
555
+ }
556
+ };
557
+ }
558
+ function createMemoryDbClient(sqlite) {
559
+ return {
560
+ async execute(statement, args) {
561
+ return executeSqlite(sqlite, statement, args);
562
+ },
563
+ async transaction(mode) {
564
+ return createTransaction(sqlite, mode);
565
+ },
566
+ close() {
567
+ sqlite.close();
568
+ }
569
+ };
570
+ }
571
+ async function listColumns(executor, tableName) {
572
+ const result = await executor.execute(`PRAGMA table_info(${tableName})`);
573
+ return new Set(result.rows.map((row) => String(row.name)));
574
+ }
575
+ async function ensureColumns(executor, tableName, columns) {
576
+ const existing = await listColumns(executor, tableName);
577
+ for (const [columnName, definition] of columns) {
578
+ if (!existing.has(columnName)) {
579
+ await executor.execute(`ALTER TABLE ${tableName} ADD COLUMN ${columnName} ${definition}`);
580
+ }
581
+ }
582
+ }
583
+ async function ensureSchema(db) {
584
+ for (const statement of SCHEMA_STATEMENTS) {
585
+ await db.client.execute(statement);
586
+ }
587
+ await ensureColumns(db.client, "memory_events", MEMORY_EVENT_COLUMNS);
588
+ await ensureColumns(db.client, "memory_items", MEMORY_ITEM_COLUMNS);
589
+ }
590
+ function toMemoryItemRow(row) {
591
+ return {
592
+ canonicalKey: String(row.canonical_key),
593
+ summary: String(row.summary),
594
+ kind: rowString(row, "kind"),
595
+ category: rowString(row, "category"),
596
+ status: String(row.status),
597
+ confidence: Number(row.confidence),
598
+ sourceRunId: rowString(row, "source_run_id"),
599
+ sourceTaskId: rowString(row, "source_task_id"),
600
+ branch: rowString(row, "branch"),
601
+ details: parseJsonRecord(row.details_json),
602
+ createdAt: String(row.created_at),
603
+ updatedAt: String(row.updated_at),
604
+ lastEventId: String(row.last_event_id),
605
+ supersededBy: rowString(row, "superseded_by"),
606
+ embedding: parseEmbedding(row.embedding)
607
+ };
608
+ }
609
+ async function hasMemoryItem(executor, canonicalKey) {
610
+ const result = await executor.execute({
611
+ sql: "SELECT 1 AS present FROM memory_items WHERE canonical_key = ? LIMIT 1",
612
+ args: [canonicalKey]
613
+ });
614
+ return result.rows.length > 0;
615
+ }
616
+ async function assertMemoryItemExists(executor, canonicalKey, errorPrefix) {
617
+ if (!await hasMemoryItem(executor, canonicalKey)) {
618
+ throw new Error(`${errorPrefix}: unknown memory ${canonicalKey}`);
619
+ }
620
+ }
621
+ async function upsertTaskRun(executor, event) {
622
+ if (!event.sourceRunId) {
623
+ return;
624
+ }
625
+ await executor.execute({
626
+ sql: `
627
+ INSERT INTO task_runs (
628
+ run_id,
629
+ task_id,
630
+ branch,
631
+ first_event_id,
632
+ last_event_id,
633
+ created_at,
634
+ updated_at
635
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
636
+ ON CONFLICT(run_id) DO UPDATE SET
637
+ task_id = COALESCE(excluded.task_id, task_runs.task_id),
638
+ branch = COALESCE(excluded.branch, task_runs.branch),
639
+ last_event_id = excluded.last_event_id,
640
+ updated_at = excluded.updated_at
641
+ `,
642
+ args: [
643
+ event.sourceRunId,
644
+ event.sourceTaskId ?? null,
645
+ event.branch ?? null,
646
+ event.eventId,
647
+ event.eventId,
648
+ event.createdAt,
649
+ event.createdAt
650
+ ]
651
+ });
652
+ }
653
+ async function insertEventRow(executor, event) {
654
+ await executor.execute({
655
+ sql: `
656
+ INSERT INTO memory_events (
657
+ event_id,
658
+ event_type,
659
+ canonical_key,
660
+ summary,
661
+ kind,
662
+ category,
663
+ confidence,
664
+ source_run_id,
665
+ source_task_id,
666
+ branch,
667
+ source_canonical_key,
668
+ replacement_canonical_key,
669
+ retrieval_query,
670
+ retrieval_rank,
671
+ feedback_outcome,
672
+ details_json,
673
+ created_at
674
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
675
+ `,
676
+ args: [
677
+ event.eventId,
678
+ event.eventType,
679
+ event.canonicalKey,
680
+ eventSummary(event),
681
+ eventKind(event),
682
+ eventCategory(event),
683
+ eventConfidence(event),
684
+ event.sourceRunId ?? null,
685
+ event.sourceTaskId ?? null,
686
+ event.branch ?? null,
687
+ eventSourceCanonicalKey(event),
688
+ eventReplacementCanonicalKey(event),
689
+ eventRetrievalQuery(event),
690
+ eventRetrievalRank(event),
691
+ eventFeedbackOutcome(event),
692
+ jsonText(eventDetails(event)),
693
+ event.createdAt
694
+ ]
695
+ });
696
+ }
697
+ async function upsertProjectedMemory(executor, event, status = "active") {
698
+ await executor.execute({
699
+ sql: `
700
+ INSERT INTO memory_items (
701
+ canonical_key,
702
+ summary,
703
+ kind,
704
+ category,
705
+ status,
706
+ confidence,
707
+ source_run_id,
708
+ source_task_id,
709
+ branch,
710
+ details_json,
711
+ created_at,
712
+ updated_at,
713
+ last_event_id,
714
+ superseded_by,
715
+ embedding
716
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
717
+ ON CONFLICT(canonical_key) DO UPDATE SET
718
+ summary = excluded.summary,
719
+ kind = excluded.kind,
720
+ category = excluded.category,
721
+ status = excluded.status,
722
+ confidence = COALESCE(excluded.confidence, memory_items.confidence),
723
+ source_run_id = COALESCE(excluded.source_run_id, memory_items.source_run_id),
724
+ source_task_id = COALESCE(excluded.source_task_id, memory_items.source_task_id),
725
+ branch = COALESCE(excluded.branch, memory_items.branch),
726
+ details_json = COALESCE(excluded.details_json, memory_items.details_json),
727
+ updated_at = excluded.updated_at,
728
+ last_event_id = excluded.last_event_id,
729
+ superseded_by = excluded.superseded_by,
730
+ embedding = excluded.embedding
731
+ `,
732
+ args: [
733
+ event.canonicalKey,
734
+ eventSummary(event),
735
+ eventKind(event),
736
+ eventCategory(event),
737
+ status,
738
+ eventConfidence(event) ?? 0,
739
+ event.sourceRunId ?? null,
740
+ event.sourceTaskId ?? null,
741
+ event.branch ?? null,
742
+ jsonText(eventDetails(event)),
743
+ event.createdAt,
744
+ event.createdAt,
745
+ event.eventId,
746
+ eventReplacementCanonicalKey(event)
747
+ ]
748
+ });
749
+ }
750
+ async function insertMemoryLink(executor, fromKey, toKey, relation, event) {
751
+ await executor.execute({
752
+ sql: `
753
+ INSERT INTO memory_links (from_key, to_key, relation, source_event_id, created_at)
754
+ VALUES (?, ?, ?, ?, ?)
755
+ `,
756
+ args: [fromKey, toKey, relation, event.eventId, event.createdAt]
757
+ });
758
+ }
759
+ async function markSuperseded(executor, event) {
760
+ const result = await executor.execute({
761
+ sql: `
762
+ UPDATE memory_items
763
+ SET
764
+ status = 'superseded',
765
+ superseded_by = ?,
766
+ updated_at = ?,
767
+ last_event_id = ?
768
+ WHERE canonical_key = ?
769
+ `,
770
+ args: [eventReplacementCanonicalKey(event), event.createdAt, event.eventId, event.canonicalKey]
771
+ });
772
+ if ((result.rowsAffected ?? 0) === 0) {
773
+ throw new Error(`cannot supersede unknown memory ${event.canonicalKey}`);
774
+ }
775
+ if (eventReplacementCanonicalKey(event)) {
776
+ await insertMemoryLink(executor, event.canonicalKey, eventReplacementCanonicalKey(event), "superseded_by", event);
777
+ }
778
+ }
779
+ async function activeMemoryItem(executor, canonicalKey) {
780
+ const result = await executor.execute({
781
+ sql: `
782
+ SELECT
783
+ canonical_key,
784
+ summary,
785
+ kind,
786
+ category,
787
+ status,
788
+ confidence,
789
+ source_run_id,
790
+ source_task_id,
791
+ branch,
792
+ details_json,
793
+ created_at,
794
+ updated_at,
795
+ last_event_id,
796
+ superseded_by,
797
+ embedding
798
+ FROM memory_items
799
+ WHERE canonical_key = ?
800
+ LIMIT 1
801
+ `,
802
+ args: [canonicalKey]
803
+ });
804
+ const row = result.rows[0];
805
+ return row ? toMemoryItemRow(row) : null;
806
+ }
807
+ async function markRetracted(executor, event) {
808
+ const result = await executor.execute({
809
+ sql: `
810
+ UPDATE memory_items
811
+ SET
812
+ status = 'retracted',
813
+ updated_at = ?,
814
+ last_event_id = ?
815
+ WHERE canonical_key = ?
816
+ `,
817
+ args: [event.createdAt, event.eventId, event.canonicalKey]
818
+ });
819
+ if ((result.rowsAffected ?? 0) === 0) {
820
+ throw new Error(`cannot retract unknown memory ${event.canonicalKey}`);
821
+ }
822
+ }
823
+ async function recordRetrievalFeedback(executor, event) {
824
+ await executor.execute({
825
+ sql: `
826
+ INSERT INTO retrieval_feedback (
827
+ canonical_key,
828
+ outcome,
829
+ retrieval_rank,
830
+ source_run_id,
831
+ source_task_id,
832
+ query_text,
833
+ source_event_id,
834
+ created_at
835
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
836
+ `,
837
+ args: [
838
+ event.canonicalKey,
839
+ eventFeedbackOutcome(event) ?? "ignored",
840
+ eventRetrievalRank(event),
841
+ event.sourceRunId ?? null,
842
+ event.sourceTaskId ?? null,
843
+ eventRetrievalQuery(event),
844
+ event.eventId,
845
+ event.createdAt
846
+ ]
847
+ });
848
+ }
849
+ async function applyReinforcement(executor, event) {
850
+ const existing = await activeMemoryItem(executor, event.canonicalKey);
851
+ if (!existing) {
852
+ throw new Error(`cannot reinforce unknown memory ${event.canonicalKey}`);
853
+ }
854
+ if (existing.status !== "active") {
855
+ throw new Error(`cannot reinforce non-active memory ${event.canonicalKey}`);
856
+ }
857
+ const result = await executor.execute({
858
+ sql: `
859
+ UPDATE memory_items
860
+ SET
861
+ status = 'active',
862
+ confidence = ?,
863
+ source_run_id = COALESCE(?, source_run_id),
864
+ source_task_id = COALESCE(?, source_task_id),
865
+ branch = COALESCE(?, branch),
866
+ updated_at = ?,
867
+ last_event_id = ?,
868
+ superseded_by = NULL
869
+ WHERE canonical_key = ?
870
+ `,
871
+ args: [
872
+ eventConfidence(event),
873
+ event.sourceRunId ?? null,
874
+ event.sourceTaskId ?? null,
875
+ event.branch ?? null,
876
+ event.createdAt,
877
+ event.eventId,
878
+ event.canonicalKey
879
+ ]
880
+ });
881
+ if ((result.rowsAffected ?? 0) === 0) {
882
+ throw new Error(`cannot reinforce unknown memory ${event.canonicalKey}`);
883
+ }
884
+ }
885
+ async function validateEventTargets(executor, event) {
886
+ switch (event.eventType) {
887
+ case "observed":
888
+ return;
889
+ case "promoted":
890
+ case "corrected":
891
+ await assertMemoryItemExists(executor, event.sourceCanonicalKey, `cannot ${event.eventType}`);
892
+ return;
893
+ case "superseded":
894
+ await assertMemoryItemExists(executor, event.replacementCanonicalKey, "cannot supersede");
895
+ await assertMemoryItemExists(executor, event.canonicalKey, "cannot supersede");
896
+ return;
897
+ case "retracted":
898
+ case "feedback_recorded":
899
+ await assertMemoryItemExists(executor, event.canonicalKey, `cannot ${event.eventType}`);
900
+ return;
901
+ case "reinforced":
902
+ await assertMemoryItemExists(executor, event.canonicalKey, "cannot reinforce");
903
+ return;
904
+ case "retrieved":
905
+ if (event.retrievalRank === 0 && event.canonicalKey === NO_MATCH_RETRIEVAL_CANONICAL_KEY) {
906
+ return;
907
+ }
908
+ await assertMemoryItemExists(executor, event.canonicalKey, `cannot ${event.eventType}`);
909
+ return;
910
+ default: {
911
+ const _exhaustive = event;
912
+ return _exhaustive;
913
+ }
914
+ }
915
+ }
916
+ async function openMemoryDb(dbPath) {
917
+ mkdirSync2(dirname2(dbPath), { recursive: true });
918
+ const sqlite = new Database(dbPath, { create: true, strict: true });
919
+ const client = createMemoryDbClient(sqlite);
920
+ const db = {
921
+ path: dbPath,
922
+ client,
923
+ async close() {
924
+ client.close();
925
+ }
926
+ };
927
+ await ensureSchema(db);
928
+ return db;
929
+ }
930
+ async function applyMemoryEvent(db, event) {
931
+ const transaction = await db.client.transaction("write");
932
+ try {
933
+ await validateEventTargets(transaction, event);
934
+ await insertEventRow(transaction, event);
935
+ await upsertTaskRun(transaction, event);
936
+ switch (event.eventType) {
937
+ case "observed":
938
+ await upsertProjectedMemory(transaction, event, "active");
939
+ break;
940
+ case "promoted":
941
+ await upsertProjectedMemory(transaction, event, "active");
942
+ if (event.sourceCanonicalKey) {
943
+ await insertMemoryLink(transaction, event.canonicalKey, event.sourceCanonicalKey, "promoted_from", event);
944
+ }
945
+ break;
946
+ case "corrected":
947
+ await upsertProjectedMemory(transaction, event, "active");
948
+ if (event.sourceCanonicalKey) {
949
+ await insertMemoryLink(transaction, event.canonicalKey, event.sourceCanonicalKey, "corrected_from", event);
950
+ }
951
+ break;
952
+ case "superseded":
953
+ await markSuperseded(transaction, event);
954
+ break;
955
+ case "retracted":
956
+ await markRetracted(transaction, event);
957
+ break;
958
+ case "reinforced":
959
+ await applyReinforcement(transaction, event);
960
+ break;
961
+ case "retrieved":
962
+ break;
963
+ case "feedback_recorded":
964
+ await recordRetrievalFeedback(transaction, event);
965
+ break;
966
+ }
967
+ await transaction.commit();
968
+ } catch (error) {
969
+ await transaction.rollback();
970
+ throw error;
971
+ } finally {
972
+ transaction.close();
973
+ }
974
+ }
975
+ async function setMemoryItemEmbedding(db, canonicalKey, embedding) {
976
+ await db.client.execute({
977
+ sql: `
978
+ UPDATE memory_items
979
+ SET embedding = ?
980
+ WHERE canonical_key = ?
981
+ `,
982
+ args: [JSON.stringify(embedding), canonicalKey]
983
+ });
984
+ }
985
+ async function getMemoryItemByKey(db, canonicalKey) {
986
+ const result = await db.client.execute({
987
+ sql: `
988
+ SELECT
989
+ canonical_key,
990
+ summary,
991
+ kind,
992
+ category,
993
+ status,
994
+ confidence,
995
+ source_run_id,
996
+ source_task_id,
997
+ branch,
998
+ details_json,
999
+ created_at,
1000
+ updated_at,
1001
+ last_event_id,
1002
+ superseded_by,
1003
+ embedding
1004
+ FROM memory_items
1005
+ WHERE canonical_key = ?
1006
+ LIMIT 1
1007
+ `,
1008
+ args: [canonicalKey]
1009
+ });
1010
+ const row = result.rows[0];
1011
+ return row ? toMemoryItemRow(row) : null;
1012
+ }
1013
+ async function hasMemoryEvent(db, eventId) {
1014
+ const result = await db.client.execute({
1015
+ sql: "SELECT 1 AS present FROM memory_events WHERE event_id = ? LIMIT 1",
1016
+ args: [eventId]
1017
+ });
1018
+ return result.rows.length > 0;
1019
+ }
1020
+
1021
+ // packages/runtime/src/control-plane/memory-sync/embed.ts
1022
+ import { createHash as createHash2 } from "crypto";
1023
+ var DEFAULT_EMBEDDING_API_BASE_URL = "https://api.openai.com/v1";
1024
+ var DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small";
1025
+ var DETERMINISTIC_EMBEDDER_MODE = "deterministic";
1026
+ var DETERMINISTIC_VECTOR_DIMS = 32;
1027
+ var MISSING_MEMORY_EMBEDDER_WARNING = "Shared memory embeddings disabled: OPENAI_API_KEY is not set. Continuing with lexical-only memory.";
1028
+ var missingMemoryEmbedderWarningShown = false;
1029
+ function embeddingTextForItem(item) {
1030
+ const parts = [item.summary, item.kind ?? "", item.category ?? "", item.details ? JSON.stringify(item.details) : ""];
1031
+ return parts.filter(Boolean).join(`
1032
+ `);
1033
+ }
1034
+ function tokenizeForDeterministicEmbedding(text) {
1035
+ const tokens = text.toLowerCase().match(/[a-z0-9_./:-]+/g) ?? [];
1036
+ return tokens.length > 0 ? tokens : [text.toLowerCase()];
1037
+ }
1038
+ function deterministicTokenVector(token) {
1039
+ const hash = createHash2("sha256").update(token).digest();
1040
+ const vector = new Array(DETERMINISTIC_VECTOR_DIMS).fill(0);
1041
+ for (let index = 0;index < 8; index += 1) {
1042
+ const slot = (hash[index] ?? 0) % DETERMINISTIC_VECTOR_DIMS;
1043
+ const sign = ((hash[index + 8] ?? 0) & 1) === 0 ? 1 : -1;
1044
+ const magnitude = ((hash[index + 16] ?? 0) + 1) / 256;
1045
+ vector[slot] = (vector[slot] ?? 0) + sign * magnitude;
1046
+ }
1047
+ return vector;
1048
+ }
1049
+ function normalizeVector(vector) {
1050
+ const norm = Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0));
1051
+ if (norm === 0) {
1052
+ return vector.map(() => 0);
1053
+ }
1054
+ return vector.map((value) => Number((value / norm).toFixed(6)));
1055
+ }
1056
+ function createDeterministicMemoryEmbedder() {
1057
+ return {
1058
+ async embed(texts) {
1059
+ return texts.map((text) => {
1060
+ const vector = new Array(DETERMINISTIC_VECTOR_DIMS).fill(0);
1061
+ for (const token of tokenizeForDeterministicEmbedding(text)) {
1062
+ const tokenVector = deterministicTokenVector(token);
1063
+ for (let index = 0;index < tokenVector.length; index += 1) {
1064
+ vector[index] = (vector[index] ?? 0) + (tokenVector[index] ?? 0);
1065
+ }
1066
+ }
1067
+ return normalizeVector(vector);
1068
+ });
1069
+ }
1070
+ };
1071
+ }
1072
+ function embeddingResponseMessage(payload, status) {
1073
+ if (typeof payload === "object" && payload !== null) {
1074
+ const maybeMessage = payload.error?.message;
1075
+ if (maybeMessage) {
1076
+ return maybeMessage;
1077
+ }
1078
+ }
1079
+ return `memory embedding request failed with status ${status}`;
1080
+ }
1081
+ function createOpenAiMemoryEmbedder(options) {
1082
+ const apiKey = options.apiKey.trim();
1083
+ const model = options.model?.trim() || DEFAULT_EMBEDDING_MODEL;
1084
+ const apiBaseUrl = (options.apiBaseUrl?.trim() || DEFAULT_EMBEDDING_API_BASE_URL).replace(/\/+$/, "");
1085
+ const fetchImpl = options.fetchImpl ?? fetch;
1086
+ if (!apiKey) {
1087
+ throw new Error("memory embedding api key must be non-empty");
1088
+ }
1089
+ return {
1090
+ async embed(texts) {
1091
+ if (texts.length === 0) {
1092
+ return [];
1093
+ }
1094
+ const response = await fetchImpl(`${apiBaseUrl}/embeddings`, {
1095
+ method: "POST",
1096
+ headers: {
1097
+ authorization: `Bearer ${apiKey}`,
1098
+ "content-type": "application/json"
1099
+ },
1100
+ body: JSON.stringify({
1101
+ input: texts,
1102
+ model
1103
+ })
1104
+ });
1105
+ const payload = await response.json();
1106
+ if (!response.ok) {
1107
+ throw new Error(embeddingResponseMessage(payload, response.status));
1108
+ }
1109
+ if (!Array.isArray(payload.data) || payload.data.length !== texts.length) {
1110
+ throw new Error(`memory embedding provider returned ${payload.data?.length ?? 0} embeddings for ${texts.length} inputs`);
1111
+ }
1112
+ const byIndex = new Map;
1113
+ for (const row of payload.data) {
1114
+ if (typeof row.index !== "number" || !Array.isArray(row.embedding)) {
1115
+ throw new Error("memory embedding provider returned an invalid response payload");
1116
+ }
1117
+ byIndex.set(row.index, row.embedding);
1118
+ }
1119
+ return texts.map((_text, index) => {
1120
+ const embedding = byIndex.get(index);
1121
+ if (!embedding) {
1122
+ throw new Error(`memory embedding provider omitted embedding ${index}`);
1123
+ }
1124
+ return embedding;
1125
+ });
1126
+ }
1127
+ };
1128
+ }
1129
+ function createConfiguredMemoryEmbedder(options = {}) {
1130
+ const env = options.env ?? process.env;
1131
+ const mode = env.RIG_MEMORY_EMBEDDER?.trim();
1132
+ if (mode === DETERMINISTIC_EMBEDDER_MODE) {
1133
+ return createDeterministicMemoryEmbedder();
1134
+ }
1135
+ const apiKey = env.OPENAI_API_KEY?.trim();
1136
+ if (!apiKey) {
1137
+ throw new Error("memory embeddings require OPENAI_API_KEY or RIG_MEMORY_EMBEDDER=deterministic");
1138
+ }
1139
+ return createOpenAiMemoryEmbedder({
1140
+ apiKey,
1141
+ model: env.RIG_MEMORY_EMBEDDING_MODEL?.trim() || DEFAULT_EMBEDDING_MODEL,
1142
+ apiBaseUrl: options.apiBaseUrl ?? env.RIG_MEMORY_EMBEDDING_API_BASE_URL?.trim() ?? DEFAULT_EMBEDDING_API_BASE_URL,
1143
+ fetchImpl: options.fetchImpl
1144
+ });
1145
+ }
1146
+ function warnMissingMemoryEmbedderOnce(warn) {
1147
+ if (missingMemoryEmbedderWarningShown) {
1148
+ return;
1149
+ }
1150
+ missingMemoryEmbedderWarningShown = true;
1151
+ warn(MISSING_MEMORY_EMBEDDER_WARNING);
1152
+ }
1153
+ function embeddingTargetsForEvent(event) {
1154
+ switch (event.eventType) {
1155
+ case "observed":
1156
+ case "promoted":
1157
+ case "corrected":
1158
+ case "reinforced":
1159
+ return [event.canonicalKey];
1160
+ case "superseded":
1161
+ case "retracted":
1162
+ case "retrieved":
1163
+ case "feedback_recorded":
1164
+ return [];
1165
+ }
1166
+ }
1167
+ function memoryEventRequiresEmbedding(event) {
1168
+ return embeddingTargetsForEvent(event).length > 0;
1169
+ }
1170
+ function maybeCreateConfiguredMemoryEmbedder(options = {}, warn = (message) => {
1171
+ console.warn(message);
1172
+ }) {
1173
+ const env = options.env ?? process.env;
1174
+ const mode = env.RIG_MEMORY_EMBEDDER?.trim();
1175
+ if (mode === DETERMINISTIC_EMBEDDER_MODE) {
1176
+ return createConfiguredMemoryEmbedder(options);
1177
+ }
1178
+ const apiKey = env.OPENAI_API_KEY?.trim();
1179
+ if (!apiKey) {
1180
+ warnMissingMemoryEmbedderOnce(warn);
1181
+ return null;
1182
+ }
1183
+ return createConfiguredMemoryEmbedder(options);
1184
+ }
1185
+ async function embedChangedMemoryItems(db, event, embedder) {
1186
+ const targets = [...new Set(embeddingTargetsForEvent(event))];
1187
+ if (targets.length === 0) {
1188
+ return [];
1189
+ }
1190
+ const items = [];
1191
+ for (const canonicalKey of targets) {
1192
+ const item = await getMemoryItemByKey(db, canonicalKey);
1193
+ if (item && item.status === "active") {
1194
+ items.push(item);
1195
+ }
1196
+ }
1197
+ if (items.length === 0) {
1198
+ return [];
1199
+ }
1200
+ const texts = items.map(embeddingTextForItem);
1201
+ const embeddings = await embedder.embed(texts);
1202
+ for (const [index, item] of items.entries()) {
1203
+ const embedding = embeddings[index];
1204
+ if (!embedding) {
1205
+ throw new Error(`missing embedding for ${item.canonicalKey}`);
1206
+ }
1207
+ await setMemoryItemEmbedding(db, item.canonicalKey, embedding);
1208
+ }
1209
+ return texts;
1210
+ }
1211
+
1212
+ // packages/runtime/src/control-plane/memory-sync/read.ts
1213
+ import { mkdtempSync, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "fs";
1214
+ import { tmpdir as tmpdir3 } from "os";
1215
+ import { join } from "path";
1216
+
1217
+ // packages/runtime/src/layout.ts
1218
+ import { existsSync as existsSync2 } from "fs";
1219
+ import { basename, dirname as dirname3, resolve as resolve2 } from "path";
1220
+ function resolveMonorepoRoot(projectRoot) {
1221
+ const normalizedProjectRoot = resolve2(projectRoot);
1222
+ const explicit = process.env.MONOREPO_ROOT?.trim();
1223
+ if (explicit) {
1224
+ const explicitRoot = resolve2(explicit);
1225
+ const explicitParent = dirname3(explicitRoot);
1226
+ if (basename(explicitParent) === ".worktrees") {
1227
+ const owner = dirname3(explicitParent);
1228
+ const ownerHasGit = existsSync2(resolve2(owner, ".git"));
1229
+ const ownerHasTaskConfig = existsSync2(resolve2(owner, ".rig", "task-config.json"));
1230
+ const ownerHasRigConfig = existsSync2(resolve2(owner, "rig.config.ts"));
1231
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
1232
+ return owner;
1233
+ }
1234
+ throw new Error(`MONOREPO_ROOT points to worktree ${explicitRoot}, but the owner checkout is incomplete at ${owner}.`);
1235
+ }
1236
+ if (!existsSync2(resolve2(explicitRoot, ".git"))) {
1237
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there.`);
1238
+ }
1239
+ const hasTaskConfig = existsSync2(resolve2(explicitRoot, ".rig", "task-config.json"));
1240
+ const hasRigConfig = existsSync2(resolve2(explicitRoot, "rig.config.ts"));
1241
+ if (!hasTaskConfig && !hasRigConfig) {
1242
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but neither .rig/task-config.json nor rig.config.ts exists there.`);
1243
+ }
1244
+ return explicitRoot;
1245
+ }
1246
+ const projectParent = dirname3(normalizedProjectRoot);
1247
+ if (basename(projectParent) === ".worktrees") {
1248
+ const worktreeOwner = dirname3(projectParent);
1249
+ const ownerHasGit = existsSync2(resolve2(worktreeOwner, ".git"));
1250
+ const ownerHasTaskConfig = existsSync2(resolve2(worktreeOwner, ".rig", "task-config.json"));
1251
+ const ownerHasRigConfig = existsSync2(resolve2(worktreeOwner, "rig.config.ts"));
1252
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
1253
+ return worktreeOwner;
1254
+ }
1255
+ }
1256
+ return normalizedProjectRoot;
1257
+ }
1258
+
1259
+ // packages/runtime/src/control-plane/native/runtime-native.ts
1260
+ import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
1261
+ import { copyFileSync as copyFileSync2, existsSync as existsSync3, mkdirSync as mkdirSync3, renameSync as renameSync2, rmSync as rmSync2, statSync } from "fs";
1262
+ import { tmpdir as tmpdir2 } from "os";
1263
+ import { dirname as dirname4, resolve as resolve3 } from "path";
1264
+ var sharedNativeRuntimeOutputDir = resolve3(tmpdir2(), "rig-native");
1265
+ var sharedNativeRuntimeOutputPath = resolve3(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
1266
+ var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
1267
+ var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
1268
+ async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
1269
+ if (await buildNativeRuntimeLibrary(outputPath, options)) {
1270
+ return outputPath;
1271
+ }
1272
+ return !options.force && existsSync3(outputPath) ? outputPath : null;
1273
+ }
1274
+ async function loadNativeRuntimeLibrary() {
1275
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
1276
+ return null;
1277
+ }
1278
+ for (const candidate of nativeRuntimeLibraryCandidates()) {
1279
+ if (!candidate || !existsSync3(candidate)) {
1280
+ continue;
1281
+ }
1282
+ const loaded = tryDlopenNativeRuntimeLibrary(candidate);
1283
+ if (loaded) {
1284
+ return loaded;
1285
+ }
1286
+ }
1287
+ const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
1288
+ if (!builtLibraryPath) {
1289
+ return null;
1290
+ }
1291
+ return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
1292
+ }
1293
+ function nativePackageLibraryCandidates(fromDir, names) {
1294
+ const candidates = [];
1295
+ let cursor = resolve3(fromDir);
1296
+ for (let index = 0;index < 8; index += 1) {
1297
+ for (const name of names) {
1298
+ 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));
1299
+ }
1300
+ const parent = dirname4(cursor);
1301
+ if (parent === cursor)
1302
+ break;
1303
+ cursor = parent;
1304
+ }
1305
+ return candidates;
1306
+ }
1307
+ function nativeRuntimeLibraryCandidates() {
1308
+ const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
1309
+ const execDir = process.execPath?.trim() ? dirname4(process.execPath.trim()) : "";
1310
+ const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
1311
+ return [...new Set([
1312
+ explicit,
1313
+ ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
1314
+ execDir ? resolve3(execDir, colocatedNativeRuntimeFileName) : "",
1315
+ execDir ? resolve3(execDir, platformSpecific) : "",
1316
+ execDir ? resolve3(execDir, "..", colocatedNativeRuntimeFileName) : "",
1317
+ execDir ? resolve3(execDir, "..", platformSpecific) : "",
1318
+ execDir ? resolve3(execDir, "lib", colocatedNativeRuntimeFileName) : "",
1319
+ execDir ? resolve3(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
1320
+ sharedNativeRuntimeOutputPath
1321
+ ].filter(Boolean))];
1322
+ }
1323
+ function resolveNativeRuntimeSourcePath() {
1324
+ const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
1325
+ if (explicit && existsSync3(explicit)) {
1326
+ return explicit;
1327
+ }
1328
+ const bundled = resolve3(import.meta.dir, "../../../native/snapshot.zig");
1329
+ return existsSync3(bundled) ? bundled : null;
1330
+ }
1331
+ async function buildNativeRuntimeLibrary(outputPath, options = {}) {
1332
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
1333
+ return false;
1334
+ }
1335
+ const zigBinary = Bun.which("zig");
1336
+ const sourcePath = resolveNativeRuntimeSourcePath();
1337
+ if (!zigBinary || !sourcePath) {
1338
+ return false;
1339
+ }
1340
+ const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
1341
+ try {
1342
+ mkdirSync3(dirname4(outputPath), { recursive: true });
1343
+ const needsBuild = options.force === true || !existsSync3(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
1344
+ if (!needsBuild) {
1345
+ return true;
1346
+ }
1347
+ const build = Bun.spawn([
1348
+ zigBinary,
1349
+ "build-lib",
1350
+ sourcePath,
1351
+ "-dynamic",
1352
+ "-O",
1353
+ "ReleaseFast",
1354
+ `-femit-bin=${tempOutputPath}`
1355
+ ], {
1356
+ cwd: import.meta.dir,
1357
+ stdout: "pipe",
1358
+ stderr: "pipe"
1359
+ });
1360
+ const exitCode = await build.exited;
1361
+ if (exitCode !== 0 || !existsSync3(tempOutputPath)) {
1362
+ rmSync2(tempOutputPath, { force: true });
1363
+ return false;
1364
+ }
1365
+ renameSync2(tempOutputPath, outputPath);
1366
+ return true;
1367
+ } catch {
1368
+ rmSync2(tempOutputPath, { force: true });
1369
+ return false;
1370
+ }
1371
+ }
1372
+ function tryDlopenNativeRuntimeLibrary(outputPath) {
1373
+ try {
1374
+ return dlopen(outputPath, {
1375
+ rig_scope_match: {
1376
+ args: ["ptr", "ptr"],
1377
+ returns: "u8"
1378
+ },
1379
+ snapshot_capture: {
1380
+ args: ["ptr", "u64", "ptr", "u64"],
1381
+ returns: "ptr"
1382
+ },
1383
+ snapshot_delta: {
1384
+ args: ["ptr", "ptr"],
1385
+ returns: "ptr"
1386
+ },
1387
+ snapshot_store_delta: {
1388
+ args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
1389
+ returns: "ptr"
1390
+ },
1391
+ snapshot_inspect_delta: {
1392
+ args: ["ptr", "u64"],
1393
+ returns: "ptr"
1394
+ },
1395
+ snapshot_apply_delta: {
1396
+ args: ["ptr", "u64", "ptr", "u64"],
1397
+ returns: "ptr"
1398
+ },
1399
+ snapshot_release: {
1400
+ args: ["ptr"],
1401
+ returns: "void"
1402
+ },
1403
+ runtime_hash_file: {
1404
+ args: ["ptr", "u64"],
1405
+ returns: "ptr"
1406
+ },
1407
+ runtime_hash_tree: {
1408
+ args: ["ptr", "u64"],
1409
+ returns: "ptr"
1410
+ },
1411
+ runtime_prepare_paths: {
1412
+ args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
1413
+ returns: "ptr"
1414
+ },
1415
+ runtime_link_dependency_layer: {
1416
+ args: ["ptr", "u64", "ptr", "u64"],
1417
+ returns: "ptr"
1418
+ },
1419
+ runtime_scan_worktrees: {
1420
+ args: ["ptr", "u64"],
1421
+ returns: "ptr"
1422
+ }
1423
+ });
1424
+ } catch {
1425
+ return null;
1426
+ }
1427
+ }
1428
+
1429
+ // packages/runtime/src/control-plane/native/utils.ts
1430
+ function resolveMonorepoRoot2(projectRoot) {
1431
+ return resolveMonorepoRoot(projectRoot);
1432
+ }
1433
+ var scopeRegexCache = new Map;
1434
+
1435
+ // packages/runtime/src/control-plane/memory-sync/read.ts
1436
+ var CANONICAL_MEMORY_DB_PATH = "rig/memory/project-memory.db";
1437
+ var DEFAULT_READ_DEPS = {
1438
+ fetchRef: nativeFetchRef,
1439
+ readBlobBytesAtRef: nativeReadBlobBytesAtRef,
1440
+ openMemoryDb,
1441
+ makeTempDir: () => mkdtempSync(join(tmpdir3(), "memory-sync-read-")),
1442
+ removeDir: (path) => rmSync3(path, { recursive: true, force: true })
1443
+ };
1444
+ function isMissingCanonicalMemoryBlobError(error) {
1445
+ const message = error instanceof Error ? error.message : String(error);
1446
+ 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`);
1447
+ }
1448
+ async function validateReadableDatabase(dbPath, open) {
1449
+ const db = await open(dbPath);
1450
+ await db.close();
1451
+ }
1452
+ async function readCanonicalMemoryDb(projectRoot, deps = {}) {
1453
+ const readDeps = { ...DEFAULT_READ_DEPS, ...deps };
1454
+ const repoPath = resolveMonorepoRoot2(projectRoot);
1455
+ const baseOid = readDeps.fetchRef(repoPath, "origin", "main");
1456
+ const tempDir = readDeps.makeTempDir();
1457
+ const dbPath = join(tempDir, "project-memory.db");
1458
+ let createdFresh = false;
1459
+ try {
1460
+ try {
1461
+ const bytes = readDeps.readBlobBytesAtRef(repoPath, baseOid, CANONICAL_MEMORY_DB_PATH);
1462
+ writeFileSync2(dbPath, bytes);
1463
+ } catch (error) {
1464
+ if (!isMissingCanonicalMemoryBlobError(error)) {
1465
+ throw error;
1466
+ }
1467
+ const db = await readDeps.openMemoryDb(dbPath);
1468
+ await db.close();
1469
+ createdFresh = true;
1470
+ }
1471
+ await validateReadableDatabase(dbPath, readDeps.openMemoryDb);
1472
+ return {
1473
+ repoPath,
1474
+ baseOid,
1475
+ dbPath,
1476
+ createdFresh,
1477
+ async cleanup() {
1478
+ readDeps.removeDir(tempDir);
1479
+ }
1480
+ };
1481
+ } catch (error) {
1482
+ readDeps.removeDir(tempDir);
1483
+ throw error;
1484
+ }
1485
+ }
1486
+
1487
+ // packages/runtime/src/control-plane/memory-sync/write.ts
1488
+ var CANONICAL_MEMORY_DB_PATH2 = "rig/memory/project-memory.db";
1489
+ var MAX_PROMOTION_ATTEMPTS = 2;
1490
+ var DEFAULT_WRITE_DEPS = {
1491
+ readCanonicalMemoryDb,
1492
+ openMemoryDb,
1493
+ applyMemoryEvent,
1494
+ hasMemoryEvent,
1495
+ embedChangedMemoryItems,
1496
+ writeTreeCommit: nativeWriteTreeCommit,
1497
+ pushRefWithLease: nativePushRefWithLease
1498
+ };
1499
+ async function promoteCanonicalMemoryEvent(projectRoot, input, deps = {}) {
1500
+ const writeDeps = { ...DEFAULT_WRITE_DEPS, ...deps };
1501
+ let lastError;
1502
+ for (let attempt = 0;attempt < MAX_PROMOTION_ATTEMPTS; attempt += 1) {
1503
+ const snapshot = await writeDeps.readCanonicalMemoryDb(projectRoot);
1504
+ try {
1505
+ const db = await writeDeps.openMemoryDb(snapshot.dbPath);
1506
+ try {
1507
+ if (await writeDeps.hasMemoryEvent(db, input.event.eventId)) {
1508
+ return {
1509
+ outcome: "applied",
1510
+ baseOid: snapshot.baseOid,
1511
+ commitOid: snapshot.baseOid
1512
+ };
1513
+ }
1514
+ await writeDeps.applyMemoryEvent(db, input.event);
1515
+ const embedder = input.embedder ?? (memoryEventRequiresEmbedding(input.event) ? maybeCreateConfiguredMemoryEmbedder() : null);
1516
+ if (embedder) {
1517
+ await writeDeps.embedChangedMemoryItems(db, input.event, embedder);
1518
+ }
1519
+ } finally {
1520
+ await db.close();
1521
+ }
1522
+ const updates = [
1523
+ {
1524
+ path: CANONICAL_MEMORY_DB_PATH2,
1525
+ sourceFilePath: snapshot.dbPath
1526
+ }
1527
+ ];
1528
+ const commitOid = writeDeps.writeTreeCommit(snapshot.repoPath, snapshot.baseOid, updates, input.message ?? `chore(memory): ${input.event.eventType} ${input.event.canonicalKey}`);
1529
+ try {
1530
+ await Promise.resolve(writeDeps.pushRefWithLease(snapshot.repoPath, commitOid, "refs/heads/main", snapshot.baseOid));
1531
+ return {
1532
+ outcome: "applied",
1533
+ baseOid: snapshot.baseOid,
1534
+ commitOid
1535
+ };
1536
+ } catch (error) {
1537
+ lastError = error;
1538
+ }
1539
+ } finally {
1540
+ await snapshot.cleanup();
1541
+ }
1542
+ }
1543
+ throw lastError instanceof Error ? lastError : new Error(String(lastError ?? "memory promotion failed"));
1544
+ }
1545
+ export {
1546
+ promoteCanonicalMemoryEvent
1547
+ };