@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,260 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/state-sync/reconcile.ts
3
+ var STALE_CLAIM_MS = 24 * 60 * 60 * 1000;
4
+ function parseTimestamp(value) {
5
+ if (!value) {
6
+ return null;
7
+ }
8
+ const parsed = Date.parse(value);
9
+ return Number.isFinite(parsed) ? parsed : null;
10
+ }
11
+ function inProgressOwnershipMetadataIssue(metadata) {
12
+ if (!metadata?.claimId || !metadata.ownerId || !metadata.claimedAt || !metadata.lastEvidenceAt) {
13
+ return "missing-ownership-metadata";
14
+ }
15
+ if (parseTimestamp(metadata.claimedAt) == null || parseTimestamp(metadata.lastEvidenceAt) == null) {
16
+ return "invalid-ownership-timestamps";
17
+ }
18
+ return null;
19
+ }
20
+ function hasExplicitPullRequestEvidence(evidence) {
21
+ return evidence != null && Object.prototype.hasOwnProperty.call(evidence, "pr");
22
+ }
23
+ function hasPrCloseoutCompletionEvidence(evidence) {
24
+ const pr = evidence?.pr;
25
+ return evidence?.closeoutPassed === true && (pr?.isOpen === true || pr?.isMerged === true);
26
+ }
27
+ function isTaskClaimStale(metadata, nowIso) {
28
+ if (!metadata) {
29
+ return false;
30
+ }
31
+ const now = parseTimestamp(nowIso);
32
+ if (now == null) {
33
+ return false;
34
+ }
35
+ const reference = parseTimestamp(metadata.lastEvidenceAt) ?? parseTimestamp(metadata.claimedAt);
36
+ if (reference == null) {
37
+ return false;
38
+ }
39
+ return now - reference > STALE_CLAIM_MS;
40
+ }
41
+ function projectTaskReconciliation(input) {
42
+ const reasons = [];
43
+ const nowIso = input.evidence?.now ?? new Date().toISOString();
44
+ const isStale = isTaskClaimStale(input.metadata, nowIso);
45
+ const pr = input.evidence?.pr ?? null;
46
+ const hasExplicitPrEvidence = hasExplicitPullRequestEvidence(input.evidence);
47
+ const activeOwnerIds = (input.evidence?.activeOwnerIds ?? []).filter(Boolean);
48
+ if (new Set(activeOwnerIds).size > 1) {
49
+ return {
50
+ valid: false,
51
+ reasons: ["multiple-active-owners"],
52
+ isStale,
53
+ wouldReconcileTo: null,
54
+ nextMetadata: input.metadata
55
+ };
56
+ }
57
+ if (input.lifecycleStatus === "blocked" || input.lifecycleStatus === "cancelled") {
58
+ return {
59
+ valid: true,
60
+ reasons,
61
+ isStale,
62
+ wouldReconcileTo: null,
63
+ nextMetadata: input.metadata
64
+ };
65
+ }
66
+ if (input.lifecycleStatus === "in_progress") {
67
+ const ownershipMetadataIssue = inProgressOwnershipMetadataIssue(input.metadata);
68
+ const hasOwnershipMetadata = ownershipMetadataIssue == null;
69
+ if (hasPrCloseoutCompletionEvidence(input.evidence)) {
70
+ return {
71
+ valid: hasOwnershipMetadata,
72
+ reasons: hasOwnershipMetadata ? reasons : [ownershipMetadataIssue],
73
+ isStale,
74
+ wouldReconcileTo: "completed",
75
+ nextMetadata: input.metadata ? {
76
+ ...input.metadata,
77
+ status: "completed",
78
+ lastEvidenceAt: nowIso,
79
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
80
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
81
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
82
+ } : {
83
+ status: "completed",
84
+ lastEvidenceAt: nowIso,
85
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
86
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
87
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
88
+ }
89
+ };
90
+ }
91
+ if (ownershipMetadataIssue) {
92
+ return {
93
+ valid: false,
94
+ reasons: [ownershipMetadataIssue],
95
+ isStale,
96
+ wouldReconcileTo: pr?.isOpen ? "under_review" : "ready",
97
+ nextMetadata: pr?.isOpen ? {
98
+ ...input.metadata ?? { status: "under_review" },
99
+ status: "under_review",
100
+ lastEvidenceAt: nowIso,
101
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
102
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
103
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
104
+ } : null
105
+ };
106
+ }
107
+ if (isStale) {
108
+ if (pr?.isOpen) {
109
+ return {
110
+ valid: false,
111
+ reasons: ["stale-claim"],
112
+ isStale,
113
+ wouldReconcileTo: "under_review",
114
+ nextMetadata: {
115
+ ...input.metadata,
116
+ status: "under_review",
117
+ lastEvidenceAt: nowIso,
118
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
119
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
120
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
121
+ }
122
+ };
123
+ }
124
+ return {
125
+ valid: false,
126
+ reasons: ["stale-claim"],
127
+ isStale,
128
+ wouldReconcileTo: "ready",
129
+ nextMetadata: null
130
+ };
131
+ }
132
+ }
133
+ if (hasPrCloseoutCompletionEvidence(input.evidence) && (input.lifecycleStatus === "open" || input.lifecycleStatus === "ready" || input.lifecycleStatus === "queued")) {
134
+ return {
135
+ valid: false,
136
+ reasons: ["pr-closeout-before-completion"],
137
+ isStale,
138
+ wouldReconcileTo: "completed",
139
+ nextMetadata: {
140
+ ...input.metadata ?? { status: "completed" },
141
+ status: "completed",
142
+ lastEvidenceAt: nowIso,
143
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
144
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
145
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
146
+ }
147
+ };
148
+ }
149
+ if (input.lifecycleStatus === "under_review") {
150
+ const hasPrLink = Boolean(input.metadata?.prNumber || input.metadata?.prUrl || pr?.prNumber || pr?.prUrl);
151
+ if (!hasPrLink) {
152
+ return {
153
+ valid: false,
154
+ reasons: ["missing-pr-metadata"],
155
+ isStale,
156
+ wouldReconcileTo: "ready",
157
+ nextMetadata: null
158
+ };
159
+ }
160
+ if (hasExplicitPrEvidence && !pr) {
161
+ return {
162
+ valid: false,
163
+ reasons: ["missing-pr-evidence"],
164
+ isStale,
165
+ wouldReconcileTo: "ready",
166
+ nextMetadata: null
167
+ };
168
+ }
169
+ if (pr?.reviewState === "changes_requested") {
170
+ const ownershipMetadataIssue = inProgressOwnershipMetadataIssue(input.metadata);
171
+ if (ownershipMetadataIssue) {
172
+ return {
173
+ valid: false,
174
+ reasons: [ownershipMetadataIssue],
175
+ isStale,
176
+ wouldReconcileTo: "ready",
177
+ nextMetadata: null
178
+ };
179
+ }
180
+ return {
181
+ valid: true,
182
+ reasons,
183
+ isStale,
184
+ wouldReconcileTo: "in_progress",
185
+ nextMetadata: input.metadata ? {
186
+ ...input.metadata,
187
+ status: "in_progress",
188
+ lastEvidenceAt: nowIso,
189
+ reviewState: "changes_requested"
190
+ } : null
191
+ };
192
+ }
193
+ if (hasPrCloseoutCompletionEvidence(input.evidence)) {
194
+ return {
195
+ valid: true,
196
+ reasons,
197
+ isStale,
198
+ wouldReconcileTo: "completed",
199
+ nextMetadata: input.metadata ? {
200
+ ...input.metadata,
201
+ status: "completed",
202
+ lastEvidenceAt: nowIso,
203
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
204
+ } : null
205
+ };
206
+ }
207
+ if (pr && !pr.isOpen && !pr.isMerged) {
208
+ return {
209
+ valid: false,
210
+ reasons: ["closed-pr-without-merge"],
211
+ isStale,
212
+ wouldReconcileTo: "ready",
213
+ nextMetadata: null
214
+ };
215
+ }
216
+ }
217
+ if (input.lifecycleStatus === "completed" && pr?.isOpen && !hasPrCloseoutCompletionEvidence(input.evidence)) {
218
+ return {
219
+ valid: false,
220
+ reasons: ["completed-with-open-pr"],
221
+ isStale,
222
+ wouldReconcileTo: "under_review",
223
+ nextMetadata: {
224
+ ...input.metadata ?? { status: "under_review" },
225
+ status: "under_review",
226
+ lastEvidenceAt: nowIso,
227
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
228
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
229
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
230
+ }
231
+ };
232
+ }
233
+ if (pr?.isOpen && (input.lifecycleStatus === "draft" || input.lifecycleStatus === "open" || input.lifecycleStatus === "ready" || input.lifecycleStatus === "queued" || input.lifecycleStatus === "in_progress")) {
234
+ return {
235
+ valid: true,
236
+ reasons,
237
+ isStale,
238
+ wouldReconcileTo: "under_review",
239
+ nextMetadata: {
240
+ ...input.metadata ?? { status: "under_review" },
241
+ status: "under_review",
242
+ lastEvidenceAt: nowIso,
243
+ ...pr?.prNumber != null ? { prNumber: pr?.prNumber } : {},
244
+ ...pr?.prUrl ? { prUrl: pr?.prUrl } : {},
245
+ ...pr?.reviewState ? { reviewState: pr?.reviewState } : {}
246
+ }
247
+ };
248
+ }
249
+ return {
250
+ valid: true,
251
+ reasons,
252
+ isStale,
253
+ wouldReconcileTo: null,
254
+ nextMetadata: input.metadata
255
+ };
256
+ }
257
+ export {
258
+ projectTaskReconciliation,
259
+ isTaskClaimStale
260
+ };
@@ -0,0 +1,302 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/state-sync/repo.ts
3
+ import { existsSync as existsSync4 } from "fs";
4
+ import { resolve as resolve4 } from "path";
5
+
6
+ // packages/runtime/src/layout.ts
7
+ import { existsSync } from "fs";
8
+ import { basename, dirname, resolve } from "path";
9
+ function resolveMonorepoRoot(projectRoot) {
10
+ const normalizedProjectRoot = resolve(projectRoot);
11
+ const explicit = process.env.MONOREPO_ROOT?.trim();
12
+ if (explicit) {
13
+ const explicitRoot = resolve(explicit);
14
+ const explicitParent = dirname(explicitRoot);
15
+ if (basename(explicitParent) === ".worktrees") {
16
+ const owner = dirname(explicitParent);
17
+ const ownerHasGit = existsSync(resolve(owner, ".git"));
18
+ const ownerHasTaskConfig = existsSync(resolve(owner, ".rig", "task-config.json"));
19
+ const ownerHasRigConfig = existsSync(resolve(owner, "rig.config.ts"));
20
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
21
+ return owner;
22
+ }
23
+ throw new Error(`MONOREPO_ROOT points to worktree ${explicitRoot}, but the owner checkout is incomplete at ${owner}.`);
24
+ }
25
+ if (!existsSync(resolve(explicitRoot, ".git"))) {
26
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but no git checkout was found there.`);
27
+ }
28
+ const hasTaskConfig = existsSync(resolve(explicitRoot, ".rig", "task-config.json"));
29
+ const hasRigConfig = existsSync(resolve(explicitRoot, "rig.config.ts"));
30
+ if (!hasTaskConfig && !hasRigConfig) {
31
+ throw new Error(`MONOREPO_ROOT points to ${explicitRoot}, but neither .rig/task-config.json nor rig.config.ts exists there.`);
32
+ }
33
+ return explicitRoot;
34
+ }
35
+ const projectParent = dirname(normalizedProjectRoot);
36
+ if (basename(projectParent) === ".worktrees") {
37
+ const worktreeOwner = dirname(projectParent);
38
+ const ownerHasGit = existsSync(resolve(worktreeOwner, ".git"));
39
+ const ownerHasTaskConfig = existsSync(resolve(worktreeOwner, ".rig", "task-config.json"));
40
+ const ownerHasRigConfig = existsSync(resolve(worktreeOwner, "rig.config.ts"));
41
+ if (ownerHasGit && (ownerHasTaskConfig || ownerHasRigConfig)) {
42
+ return worktreeOwner;
43
+ }
44
+ }
45
+ return normalizedProjectRoot;
46
+ }
47
+
48
+ // packages/runtime/src/control-plane/native/runtime-native.ts
49
+ import { dlopen, ptr, suffix, toBuffer } from "bun:ffi";
50
+ import { copyFileSync, existsSync as existsSync2, mkdirSync, renameSync, rmSync, statSync } from "fs";
51
+ import { tmpdir } from "os";
52
+ import { dirname as dirname2, resolve as resolve2 } from "path";
53
+ var sharedNativeRuntimeOutputDir = resolve2(tmpdir(), "rig-native");
54
+ var sharedNativeRuntimeOutputPath = resolve2(sharedNativeRuntimeOutputDir, `runtime-native-${process.platform}-${process.arch}.${suffix}`);
55
+ var colocatedNativeRuntimeFileName = `runtime-native.${suffix}`;
56
+ var nativeRuntimeLibrary = await loadNativeRuntimeLibrary();
57
+ async function ensureNativeRuntimeLibraryPath(outputPath = sharedNativeRuntimeOutputPath, options = {}) {
58
+ if (await buildNativeRuntimeLibrary(outputPath, options)) {
59
+ return outputPath;
60
+ }
61
+ return !options.force && existsSync2(outputPath) ? outputPath : null;
62
+ }
63
+ async function loadNativeRuntimeLibrary() {
64
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
65
+ return null;
66
+ }
67
+ for (const candidate of nativeRuntimeLibraryCandidates()) {
68
+ if (!candidate || !existsSync2(candidate)) {
69
+ continue;
70
+ }
71
+ const loaded = tryDlopenNativeRuntimeLibrary(candidate);
72
+ if (loaded) {
73
+ return loaded;
74
+ }
75
+ }
76
+ const builtLibraryPath = await ensureNativeRuntimeLibraryPath(sharedNativeRuntimeOutputPath, { force: true });
77
+ if (!builtLibraryPath) {
78
+ return null;
79
+ }
80
+ return tryDlopenNativeRuntimeLibrary(builtLibraryPath);
81
+ }
82
+ function nativePackageLibraryCandidates(fromDir, names) {
83
+ const candidates = [];
84
+ let cursor = resolve2(fromDir);
85
+ for (let index = 0;index < 8; index += 1) {
86
+ for (const name of names) {
87
+ candidates.push(resolve2(cursor, "native", `${process.platform}-${process.arch}`, name), resolve2(cursor, "native", `${process.platform}-${process.arch}`, "lib", name), resolve2(cursor, "native", name), resolve2(cursor, "native", "lib", name));
88
+ }
89
+ const parent = dirname2(cursor);
90
+ if (parent === cursor)
91
+ break;
92
+ cursor = parent;
93
+ }
94
+ return candidates;
95
+ }
96
+ function nativeRuntimeLibraryCandidates() {
97
+ const explicit = process.env.RIG_NATIVE_RUNTIME_LIB?.trim() || "";
98
+ const execDir = process.execPath?.trim() ? dirname2(process.execPath.trim()) : "";
99
+ const platformSpecific = `runtime-native-${process.platform}-${process.arch}.${suffix}`;
100
+ return [...new Set([
101
+ explicit,
102
+ ...nativePackageLibraryCandidates(import.meta.dir, [colocatedNativeRuntimeFileName, platformSpecific]),
103
+ execDir ? resolve2(execDir, colocatedNativeRuntimeFileName) : "",
104
+ execDir ? resolve2(execDir, platformSpecific) : "",
105
+ execDir ? resolve2(execDir, "..", colocatedNativeRuntimeFileName) : "",
106
+ execDir ? resolve2(execDir, "..", platformSpecific) : "",
107
+ execDir ? resolve2(execDir, "lib", colocatedNativeRuntimeFileName) : "",
108
+ execDir ? resolve2(execDir, "..", "lib", colocatedNativeRuntimeFileName) : "",
109
+ sharedNativeRuntimeOutputPath
110
+ ].filter(Boolean))];
111
+ }
112
+ function resolveNativeRuntimeSourcePath() {
113
+ const explicit = process.env.RIG_NATIVE_RUNTIME_SOURCE?.trim();
114
+ if (explicit && existsSync2(explicit)) {
115
+ return explicit;
116
+ }
117
+ const bundled = resolve2(import.meta.dir, "../../../native/snapshot.zig");
118
+ return existsSync2(bundled) ? bundled : null;
119
+ }
120
+ async function buildNativeRuntimeLibrary(outputPath, options = {}) {
121
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
122
+ return false;
123
+ }
124
+ const zigBinary = Bun.which("zig");
125
+ const sourcePath = resolveNativeRuntimeSourcePath();
126
+ if (!zigBinary || !sourcePath) {
127
+ return false;
128
+ }
129
+ const tempOutputPath = `${outputPath}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`;
130
+ try {
131
+ mkdirSync(dirname2(outputPath), { recursive: true });
132
+ const needsBuild = options.force === true || !existsSync2(outputPath) || statSync(sourcePath).mtimeMs > statSync(outputPath).mtimeMs;
133
+ if (!needsBuild) {
134
+ return true;
135
+ }
136
+ const build = Bun.spawn([
137
+ zigBinary,
138
+ "build-lib",
139
+ sourcePath,
140
+ "-dynamic",
141
+ "-O",
142
+ "ReleaseFast",
143
+ `-femit-bin=${tempOutputPath}`
144
+ ], {
145
+ cwd: import.meta.dir,
146
+ stdout: "pipe",
147
+ stderr: "pipe"
148
+ });
149
+ const exitCode = await build.exited;
150
+ if (exitCode !== 0 || !existsSync2(tempOutputPath)) {
151
+ rmSync(tempOutputPath, { force: true });
152
+ return false;
153
+ }
154
+ renameSync(tempOutputPath, outputPath);
155
+ return true;
156
+ } catch {
157
+ rmSync(tempOutputPath, { force: true });
158
+ return false;
159
+ }
160
+ }
161
+ function tryDlopenNativeRuntimeLibrary(outputPath) {
162
+ try {
163
+ return dlopen(outputPath, {
164
+ rig_scope_match: {
165
+ args: ["ptr", "ptr"],
166
+ returns: "u8"
167
+ },
168
+ snapshot_capture: {
169
+ args: ["ptr", "u64", "ptr", "u64"],
170
+ returns: "ptr"
171
+ },
172
+ snapshot_delta: {
173
+ args: ["ptr", "ptr"],
174
+ returns: "ptr"
175
+ },
176
+ snapshot_store_delta: {
177
+ args: ["ptr", "ptr", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
178
+ returns: "ptr"
179
+ },
180
+ snapshot_inspect_delta: {
181
+ args: ["ptr", "u64"],
182
+ returns: "ptr"
183
+ },
184
+ snapshot_apply_delta: {
185
+ args: ["ptr", "u64", "ptr", "u64"],
186
+ returns: "ptr"
187
+ },
188
+ snapshot_release: {
189
+ args: ["ptr"],
190
+ returns: "void"
191
+ },
192
+ runtime_hash_file: {
193
+ args: ["ptr", "u64"],
194
+ returns: "ptr"
195
+ },
196
+ runtime_hash_tree: {
197
+ args: ["ptr", "u64"],
198
+ returns: "ptr"
199
+ },
200
+ runtime_prepare_paths: {
201
+ args: ["ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64", "ptr", "u64"],
202
+ returns: "ptr"
203
+ },
204
+ runtime_link_dependency_layer: {
205
+ args: ["ptr", "u64", "ptr", "u64"],
206
+ returns: "ptr"
207
+ },
208
+ runtime_scan_worktrees: {
209
+ args: ["ptr", "u64"],
210
+ returns: "ptr"
211
+ }
212
+ });
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+
218
+ // packages/runtime/src/control-plane/native/utils.ts
219
+ function resolveMonorepoRoot2(projectRoot) {
220
+ return resolveMonorepoRoot(projectRoot);
221
+ }
222
+ var scopeRegexCache = new Map;
223
+
224
+ // packages/runtime/src/control-plane/repos/layout.ts
225
+ import { existsSync as existsSync3 } from "fs";
226
+ import { basename as basename2, dirname as dirname3, join, resolve as resolve3 } from "path";
227
+
228
+ // packages/runtime/src/control-plane/repos/registry.ts
229
+ var MANAGED_REPOS = new Map;
230
+ function getManagedRepoEntry(repoId) {
231
+ const entry = MANAGED_REPOS.get(repoId);
232
+ if (!entry) {
233
+ throw new Error(`managed repo not registered: ${repoId}. Plugins contribute repos via RigPlugin.contributes.repoSources; ` + `make sure a plugin declares this id and the plugin host has been initialized.`);
234
+ }
235
+ return entry;
236
+ }
237
+ function listManagedRepoEntries() {
238
+ return Array.from(MANAGED_REPOS.values());
239
+ }
240
+
241
+ // packages/runtime/src/control-plane/repos/layout.ts
242
+ function resolveRepoStateDir(projectRoot) {
243
+ const normalizedProjectRoot = resolve3(projectRoot);
244
+ const projectParent = dirname3(normalizedProjectRoot);
245
+ if (basename2(projectParent) === ".worktrees") {
246
+ const ownerRoot = dirname3(projectParent);
247
+ const ownerHasRepoMarkers = existsSync3(resolve3(ownerRoot, ".git")) || existsSync3(resolve3(ownerRoot, ".rig", "state"));
248
+ if (ownerHasRepoMarkers) {
249
+ return resolve3(ownerRoot, ".rig", "state");
250
+ }
251
+ }
252
+ return resolve3(projectRoot, ".rig", "state");
253
+ }
254
+ function resolveManagedRepoLayout(projectRoot, repoId) {
255
+ const normalizedProjectRoot = resolve3(projectRoot);
256
+ const entry = getManagedRepoEntry(repoId);
257
+ const stateDir = resolveRepoStateDir(normalizedProjectRoot);
258
+ const metadataRelativePath = join("repos", entry.id);
259
+ const metadataRoot = resolve3(stateDir, metadataRelativePath);
260
+ const runtimeWorkspace = process.env.RIG_TASK_WORKSPACE?.trim();
261
+ const runsInsideTaskWorktree = runtimeWorkspace && resolve3(runtimeWorkspace) === normalizedProjectRoot || basename2(dirname3(normalizedProjectRoot)) === ".worktrees";
262
+ const isPrimaryManagedRepo = listManagedRepoEntries()[0]?.id === repoId;
263
+ const checkoutRoot = isPrimaryManagedRepo && runsInsideTaskWorktree ? resolveMonorepoRoot(normalizedProjectRoot) : entry.checkoutEnvVar && process.env[entry.checkoutEnvVar]?.trim() ? resolve3(process.env[entry.checkoutEnvVar].trim()) : resolve3(normalizedProjectRoot, entry.alias);
264
+ return {
265
+ projectRoot: normalizedProjectRoot,
266
+ repoId: entry.id,
267
+ alias: entry.alias,
268
+ defaultBranch: entry.defaultBranch,
269
+ remoteUrl: entry.remoteEnvVar && process.env[entry.remoteEnvVar]?.trim() ? process.env[entry.remoteEnvVar].trim() : entry.defaultRemoteUrl,
270
+ checkoutRoot,
271
+ worktreesRoot: resolve3(checkoutRoot, ".worktrees"),
272
+ stateDir,
273
+ metadataRoot,
274
+ metadataRelativePath,
275
+ mirrorRoot: resolve3(metadataRoot, "mirror.git"),
276
+ mirrorStatePath: resolve3(metadataRoot, "mirror-state.json"),
277
+ mirrorStateRelativePath: join(metadataRelativePath, "mirror-state.json")
278
+ };
279
+ }
280
+ function resolveMonorepoRepoLayout(projectRoot) {
281
+ const entries = listManagedRepoEntries();
282
+ if (entries.length === 0) {
283
+ throw new Error("resolveMonorepoRepoLayout: no managed repos registered. Either contribute one via " + "RigPlugin.contributes.repoSources (with defaultBranch set), or avoid calling this " + "function for projects where the project root IS the monorepo.");
284
+ }
285
+ const primary = entries[0];
286
+ return resolveManagedRepoLayout(projectRoot, primary.id);
287
+ }
288
+
289
+ // packages/runtime/src/control-plane/state-sync/repo.ts
290
+ function resolveTrackerRepoPath(projectRoot) {
291
+ const monorepoRoot = resolveMonorepoRoot2(projectRoot);
292
+ try {
293
+ const layout = resolveMonorepoRepoLayout(projectRoot);
294
+ if (existsSync4(resolve4(layout.mirrorRoot, "HEAD"))) {
295
+ return layout.mirrorRoot;
296
+ }
297
+ } catch {}
298
+ return monorepoRoot;
299
+ }
300
+ export {
301
+ resolveTrackerRepoPath
302
+ };
@@ -0,0 +1,111 @@
1
+ // @bun
2
+ // packages/runtime/src/control-plane/state-sync/types.ts
3
+ var SUPPORTED_TASK_STATE_SCHEMA_VERSION = 1;
4
+ var CANONICAL_TASK_LIFECYCLE_STATUSES = new Set([
5
+ "draft",
6
+ "open",
7
+ "ready",
8
+ "queued",
9
+ "in_progress",
10
+ "under_review",
11
+ "blocked",
12
+ "completed",
13
+ "cancelled"
14
+ ]);
15
+ function normalizeTaskLifecycleStatus(status) {
16
+ switch (status) {
17
+ case "draft":
18
+ case "open":
19
+ case "ready":
20
+ case "queued":
21
+ case "in_progress":
22
+ case "under_review":
23
+ case "blocked":
24
+ case "completed":
25
+ case "cancelled":
26
+ return status;
27
+ case "closed":
28
+ return "completed";
29
+ case "running":
30
+ return "in_progress";
31
+ case "failed":
32
+ return "ready";
33
+ default:
34
+ return null;
35
+ }
36
+ }
37
+ function normalizeTaskStateMetadataStatus(status) {
38
+ if (CANONICAL_TASK_LIFECYCLE_STATUSES.has(status)) {
39
+ return status;
40
+ }
41
+ switch (status) {
42
+ case "closed":
43
+ return "completed";
44
+ case "running":
45
+ return "in_progress";
46
+ case "failed":
47
+ return "ready";
48
+ default:
49
+ return;
50
+ }
51
+ }
52
+ function canonicalizeTaskStateMetadata(raw) {
53
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
54
+ return null;
55
+ }
56
+ const metadata = raw;
57
+ const claimId = typeof metadata.claimId === "string" && metadata.claimId.length > 0 ? metadata.claimId : undefined;
58
+ const status = normalizeTaskStateMetadataStatus(metadata.status);
59
+ if (!status) {
60
+ return null;
61
+ }
62
+ return {
63
+ ...claimId ? { claimId } : {},
64
+ status,
65
+ ...typeof metadata.ownerId === "string" && metadata.ownerId.length > 0 ? { ownerId: metadata.ownerId } : {},
66
+ ...typeof metadata.claimedAt === "string" && metadata.claimedAt.length > 0 ? { claimedAt: metadata.claimedAt } : {},
67
+ ...typeof metadata.lastEvidenceAt === "string" && metadata.lastEvidenceAt.length > 0 ? { lastEvidenceAt: metadata.lastEvidenceAt } : {},
68
+ ...typeof metadata.runId === "string" && metadata.runId.length > 0 ? { runId: metadata.runId } : {},
69
+ ...typeof metadata.branchName === "string" && metadata.branchName.length > 0 ? { branchName: metadata.branchName } : {},
70
+ ...typeof metadata.prNumber === "number" ? { prNumber: metadata.prNumber } : {},
71
+ ...typeof metadata.prUrl === "string" && metadata.prUrl.length > 0 ? { prUrl: metadata.prUrl } : {},
72
+ ...typeof metadata.reviewState === "string" && metadata.reviewState.length > 0 ? { reviewState: metadata.reviewState } : {},
73
+ ...typeof metadata.blockerReason === "string" && metadata.blockerReason.length > 0 ? { blockerReason: metadata.blockerReason } : {},
74
+ ...typeof metadata.sourceCommit === "string" && metadata.sourceCommit.length > 0 ? { sourceCommit: metadata.sourceCommit } : {}
75
+ };
76
+ }
77
+ function discardMismatchedTaskStateMetadata(input) {
78
+ input.taskId;
79
+ const canonicalMetadata = canonicalizeTaskStateMetadata(input.metadata);
80
+ if (!canonicalMetadata || !input.lifecycleStatus) {
81
+ return null;
82
+ }
83
+ const metadataStatus = canonicalMetadata.status ?? null;
84
+ if (metadataStatus && metadataStatus !== input.lifecycleStatus) {
85
+ return null;
86
+ }
87
+ return canonicalMetadata;
88
+ }
89
+ function readTaskStateMetadataEnvelope(raw) {
90
+ if (!raw || typeof raw !== "object") {
91
+ return { schemaVersion: SUPPORTED_TASK_STATE_SCHEMA_VERSION, supported: true, baseTrackerCommit: null, tasks: {} };
92
+ }
93
+ const envelope = raw;
94
+ const schemaVersion = typeof envelope.schemaVersion === "number" ? envelope.schemaVersion : SUPPORTED_TASK_STATE_SCHEMA_VERSION;
95
+ if (schemaVersion !== SUPPORTED_TASK_STATE_SCHEMA_VERSION) {
96
+ return { schemaVersion, supported: false, baseTrackerCommit: null, tasks: {} };
97
+ }
98
+ const rawTasks = envelope.tasks && typeof envelope.tasks === "object" && !Array.isArray(envelope.tasks) ? envelope.tasks : {};
99
+ const tasks = Object.fromEntries(Object.entries(rawTasks).map(([taskId, metadata]) => [taskId, canonicalizeTaskStateMetadata(metadata)]).filter((entry) => entry[1] != null));
100
+ return {
101
+ schemaVersion,
102
+ supported: true,
103
+ baseTrackerCommit: typeof envelope.baseTrackerCommit === "string" && envelope.baseTrackerCommit.length > 0 ? envelope.baseTrackerCommit : null,
104
+ tasks
105
+ };
106
+ }
107
+ export {
108
+ readTaskStateMetadataEnvelope,
109
+ normalizeTaskLifecycleStatus,
110
+ discardMismatchedTaskStateMetadata
111
+ };