@defrex/autobuild 1.10.0 → 1.11.1

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 (255) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +745 -69
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +165 -29
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +64 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +111 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +179 -76
  41. package/packages/core/src/cli/dashboard/render.ts +159 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +40 -40
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +202 -38
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +105 -49
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +381 -30
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  95. package/packages/core/src/kernel/build-roster.ts +230 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  97. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  98. package/packages/core/src/kernel/engine.ts +43 -5
  99. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  100. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  101. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  102. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  103. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  104. package/packages/core/src/kernel/log-index.ts +19 -0
  105. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  106. package/packages/core/src/kernel/optimization.ts +183 -4
  107. package/packages/core/src/kernel/phase-failures.ts +121 -0
  108. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  109. package/packages/core/src/kernel/read-facts.ts +15 -13
  110. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  111. package/packages/core/src/kernel/reducer-revisions.ts +27 -0
  112. package/packages/core/src/kernel/reducer.ts +63 -4
  113. package/packages/core/src/kernel/rollup.ts +61 -0
  114. package/packages/core/src/kernel/setup-streak.ts +38 -0
  115. package/packages/core/src/kernel/step-durations.ts +257 -0
  116. package/packages/core/src/kernel/target-observation.ts +6 -1
  117. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  118. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  119. package/packages/core/src/kernel/verify-stages.ts +13 -3
  120. package/packages/core/src/ontology.ts +5 -0
  121. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  122. package/packages/core/src/operator/annotations.ts +75 -5
  123. package/packages/core/src/operator/attention.ts +470 -0
  124. package/packages/core/src/operator/canonical-skills.ts +35 -0
  125. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  126. package/packages/core/src/operator/context-prompts.ts +61 -0
  127. package/packages/core/src/operator/index.ts +49 -1
  128. package/packages/core/src/operator/landings.ts +28 -19
  129. package/packages/core/src/operator/optimization.ts +7 -0
  130. package/packages/core/src/operator/protocol.ts +3 -0
  131. package/packages/core/src/operator/query.ts +129 -74
  132. package/packages/core/src/operator/read-view.ts +5 -2
  133. package/packages/core/src/operator/registry.ts +406 -46
  134. package/packages/core/src/operator/requests.ts +20 -18
  135. package/packages/core/src/operator/sandbox-host.ts +107 -11
  136. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  137. package/packages/core/src/operator/sandbox.ts +778 -82
  138. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  139. package/packages/core/src/operator/ticket-assets.ts +167 -0
  140. package/packages/core/src/operator/tickets.ts +33 -2
  141. package/packages/core/src/plugin-sdk/index.ts +22 -0
  142. package/packages/core/src/plugins/manifest.ts +1 -1
  143. package/packages/core/src/ports/forge/fake.ts +92 -1
  144. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  145. package/packages/core/src/ports/forge/github.ts +82 -0
  146. package/packages/core/src/ports/forge/local-git.ts +61 -1
  147. package/packages/core/src/ports/forge-failure.ts +24 -0
  148. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  149. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  150. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  151. package/packages/core/src/ports/tickets/contract.ts +71 -0
  152. package/packages/core/src/ports/tickets/fake.ts +11 -0
  153. package/packages/core/src/ports/tickets/file.ts +18 -0
  154. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  155. package/packages/core/src/ports/tickets/github.ts +387 -30
  156. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  157. package/packages/core/src/ports/tickets/linear.ts +130 -0
  158. package/packages/core/src/ports/tickets/priority.ts +9 -0
  159. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  160. package/packages/core/src/ports/tickets/remote.ts +70 -6
  161. package/packages/core/src/ports/tickets/search.ts +139 -0
  162. package/packages/core/src/ports/types.ts +104 -2
  163. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  164. package/packages/core/src/ports/workspace/create.ts +15 -1
  165. package/packages/core/src/ports/workspace/fake.ts +340 -12
  166. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  167. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  168. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  169. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  170. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  171. package/packages/core/src/processes/agent-context.ts +469 -0
  172. package/packages/core/src/processes/build-runner.ts +387 -236
  173. package/packages/core/src/processes/dispatcher.ts +211 -55
  174. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  175. package/packages/core/src/processes/optimization-activity.ts +120 -0
  176. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  177. package/packages/core/src/processes/repo-view.ts +78 -2
  178. package/packages/core/src/processes/sandbox-state.ts +53 -6
  179. package/packages/core/src/processes/tick-publication.ts +2 -0
  180. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  181. package/packages/core/src/scenarios/harness.ts +0 -5
  182. package/packages/core/src/store/account-redaction.ts +1 -0
  183. package/packages/core/src/store/adapter.ts +52 -1
  184. package/packages/core/src/store/agent-context.ts +432 -0
  185. package/packages/core/src/store/build-feed.ts +291 -0
  186. package/packages/core/src/store/build-scope.ts +19 -1
  187. package/packages/core/src/store/contract.ts +911 -14
  188. package/packages/core/src/store/digest.ts +19 -6
  189. package/packages/core/src/store/histogram.ts +113 -0
  190. package/packages/core/src/store/local/schema.ts +62 -0
  191. package/packages/core/src/store/local/store.ts +628 -22
  192. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  193. package/packages/core/src/store/memory.ts +461 -69
  194. package/packages/core/src/store/open-builds.ts +19 -0
  195. package/packages/core/src/store/phase-session.ts +32 -4
  196. package/packages/core/src/store/reduced-reads.ts +14 -4
  197. package/packages/core/src/store/reducer-value-shapes.json +7027 -5751
  198. package/packages/core/src/store/reducer-values.ts +6 -1
  199. package/packages/core/src/store/remote/client.ts +208 -2
  200. package/packages/core/src/store/remote/compatibility.ts +1 -1
  201. package/packages/core/src/store/remote/index.ts +33 -0
  202. package/packages/core/src/store/remote/protocol.ts +69 -0
  203. package/packages/core/src/store/remote/released-clients.json +22 -0
  204. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  205. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  206. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  207. package/packages/core/src/store/retention.ts +23 -1
  208. package/packages/core/src/store/rollups.ts +337 -0
  209. package/packages/core/src/store/session-handle.ts +20 -2
  210. package/packages/core/src/store/snapshots.ts +10 -0
  211. package/packages/core/src/store/types.ts +108 -9
  212. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  213. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  214. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  215. package/packages/core/src/testing/index.ts +27 -0
  216. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  217. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  218. package/packages/core/src/web/analytics-source.ts +303 -0
  219. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  220. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  221. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  222. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  223. package/packages/core/src/web/assets/app.css +1 -0
  224. package/packages/core/src/web/assets/app.js +9 -0
  225. package/packages/core/src/web/assets/manifest.json +31 -0
  226. package/packages/core/src/web/assets/theme.js +1 -0
  227. package/packages/core/src/web/bounded.ts +31 -0
  228. package/packages/core/src/web/http.ts +315 -0
  229. package/packages/core/src/web/hub.ts +160 -0
  230. package/packages/core/src/web/options.ts +38 -0
  231. package/packages/core/src/web/overview-source.ts +322 -0
  232. package/packages/core/src/web/page.ts +56 -0
  233. package/packages/core/src/web/protocol.ts +151 -0
  234. package/packages/core/src/web/read-only.ts +23 -0
  235. package/packages/core/src/web/repository-source.ts +39 -0
  236. package/packages/core/src/web/server.ts +97 -0
  237. package/skills/code-review/SKILL.md +10 -2
  238. package/skills/guide/SKILL.md +376 -54
  239. package/skills/guide/references/accounts.md +2 -1
  240. package/skills/guide/references/integration-tree.md +2 -2
  241. package/skills/guide/references/operator-api.md +134 -6
  242. package/skills/guide/references/optimization-nodes.md +69 -11
  243. package/skills/guide/references/plugin-authoring.md +37 -1
  244. package/skills/guide/references/remote-store-protocol.md +94 -13
  245. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  246. package/skills/guide/references/restacking.md +20 -4
  247. package/skills/guide/references/setup.md +14 -2
  248. package/skills/guide/references/ticket-dependencies.md +10 -3
  249. package/skills/implement/SKILL.md +23 -4
  250. package/skills/operate/SKILL.md +134 -32
  251. package/skills/plan/SKILL.md +10 -4
  252. package/skills/plan-review/SKILL.md +9 -2
  253. package/skills/spec/SKILL.md +34 -8
  254. package/skills/tickets/SKILL.md +51 -5
  255. package/templates/hosted-service/package.json +2 -2
@@ -118,24 +118,26 @@ export function answerAction(request: OperatorAnswerRequest): {
118
118
  ? { kind: 'answer' }
119
119
  : request.resolution === 'dismiss'
120
120
  ? { kind: 'answer', text: request.text, resolve: { kind: 'dismiss-finding' } }
121
- : request.resolution === 'review-round-ceiling'
122
- ? { kind: 'answer', text: request.text, reviewRoundCeiling: request.ceiling }
123
- : {
124
- kind: 'answer',
125
- text: request.text,
126
- ...(request.ceiling !== undefined ? { reviewRoundCeiling: request.ceiling } : {}),
127
- resolve: {
128
- kind: 'revise-spec',
129
- body:
130
- request.origin === 'body'
131
- ? {
132
- kind: 'supplied',
133
- origin: 'operator API body',
134
- read: async () => request.body,
135
- }
136
- : { kind: 'ticket' },
137
- },
138
- }
121
+ : request.resolution === 'accept-target'
122
+ ? { kind: 'answer', text: request.text, resolve: { kind: 'accept-target' } }
123
+ : request.resolution === 'review-round-ceiling'
124
+ ? { kind: 'answer', text: request.text, reviewRoundCeiling: request.ceiling }
125
+ : {
126
+ kind: 'answer',
127
+ text: request.text,
128
+ ...(request.ceiling !== undefined ? { reviewRoundCeiling: request.ceiling } : {}),
129
+ resolve: {
130
+ kind: 'revise-spec',
131
+ body:
132
+ request.origin === 'body'
133
+ ? {
134
+ kind: 'supplied',
135
+ origin: 'operator API body',
136
+ read: async () => request.body,
137
+ }
138
+ : { kind: 'ticket' },
139
+ },
140
+ }
139
141
  return {
140
142
  action,
141
143
  ...(request.resolution === 'revise-spec' && request.origin === 'ticket'
@@ -9,6 +9,12 @@
9
9
  * existing `./operator` consumers (the hosted operator server among them) must
10
10
  * not grow that closure. The hosted store service imports only this subpath.
11
11
  *
12
+ * On a deployment only the `vercel-sandbox` builtin can host a checkout-less
13
+ * sandbox, so a project whose own provider is anything else gets its operator
14
+ * sandbox from the deployment's Vercel Sandbox provider instead
15
+ * (`hostedOperatorSandboxComposition`), with the deployment's forge token as
16
+ * the git read credential, placed only in the upload-pack egress transform.
17
+ *
12
18
  * Containment contract: every construction failure THROWS. The callers (the
13
19
  * hosted store service's runner factory and the dispatcher tick) contain it —
14
20
  * a broken or unsupported config degrades the sandbox tools of one binding,
@@ -20,11 +26,12 @@ import { join } from 'node:path'
20
26
  import type { Config } from '../config/schema'
21
27
  import type { Forge } from '../ports/types'
22
28
  import { createForge } from '../ports/forge/create'
23
- import { GitHubApiError } from '../ports/forge/github-transport'
29
+ import { GitHubApiError, githubTokenFromEnv } from '../ports/forge/github-transport'
24
30
  import { createWorkspaceProvider } from '../ports/workspace/create'
25
31
  import { createPluginRegistry } from '../plugins/registry'
26
32
  import type { BuildStore, Clock } from '../store/types'
27
33
  import { createOperatorSandboxService, type OperatorSandboxService } from './sandbox'
34
+ import { SandboxUnavailableError } from './sandbox-resolver'
28
35
 
29
36
  export interface HostedOperatorSandboxOptions {
30
37
  store: BuildStore
@@ -35,10 +42,12 @@ export interface HostedOperatorSandboxOptions {
35
42
  /** The repository's effective config (the deposited
36
43
  * `dispatcher-effective-config` artifact, or the checkout's parsed config).
37
44
  * `[orchestrator].enabled` is the CALLER's gate; this helper composes the
38
- * backend for any config handed to it. */
45
+ * backend for any config handed to it, substituting the deployment's
46
+ * Vercel Sandbox provider when the configured one cannot host a sandbox
47
+ * here (`hostedOperatorSandboxComposition`). */
39
48
  config: Config
40
49
  /** The serving process's environment. The Vercel SDK credential must be
41
- * reachable here for a `vercel-sandbox` workspace (`VERCEL_OIDC_TOKEN`, or
50
+ * reachable here for a `vercel-sandbox` workspace or the fallback (`VERCEL_OIDC_TOKEN`, or
42
51
  * the durable `VERCEL_TOKEN`/`VERCEL_TEAM_ID`/`VERCEL_PROJECT_ID` triple);
43
52
  * a hosted caller merges the request's `x-vercel-oidc-token` under
44
53
  * `VERCEL_OIDC_TOKEN` before calling, with an explicit env token keeping
@@ -58,6 +67,10 @@ export interface HostedOperatorSandboxOptions {
58
67
  * fails construction before any path use. */
59
68
  scratchRoot?: string
60
69
  clock?: Clock
70
+ /** The hosted background seam (Next's `after()`, the platform's
71
+ * `waitUntil`): keeps the serving function alive for a provider's host
72
+ * phase and its settlement after `sandbox.open` responds. */
73
+ background?: (work: Promise<unknown>) => void
61
74
  /** Test seam: an already-constructed forge. Production passes nothing and
62
75
  * the configured forge is built here. The forge is REQUIRED either way —
63
76
  * unlike `ab mcp`, which degrades to `canPublish: false` because its
@@ -89,12 +102,86 @@ export function remoteBranchHeadFromForge(
89
102
  }
90
103
  }
91
104
 
105
+ /** The only builtin that can host a checkout-less sandbox on a deployment:
106
+ * `git-worktree` would build a local worktree inside the serving process's
107
+ * scratch, and the hosted registry is builtin-only, so a plugin provider can
108
+ * never host one there. Every other provider falls back to the deployment's
109
+ * Vercel Sandbox provider. */
110
+ const HOSTED_SANDBOX_PROVIDER = 'vercel-sandbox'
111
+
112
+ /** The fallback's Vercel Sandbox config: 45 minutes fits every Vercel plan;
113
+ * no `gitUsernameEnv`/`gitPasswordEnv`, so the configured-clone path and its
114
+ * schema guard stay untouched. Everything else takes schema defaults. */
115
+ const FALLBACK_VERCEL_SANDBOX_CONFIG = { timeoutSeconds: 2700, runtimeProvisioning: {} }
116
+
117
+ export interface HostedOperatorSandboxComposition {
118
+ /** The config to compose: the deposited one, or a copy whose `workspace`
119
+ * is the deployment's Vercel Sandbox provider. */
120
+ config: Config
121
+ fallback: boolean
122
+ /** The deployment's git read credential for the fallback; the provider
123
+ * places it only in the upload-pack egress transform. */
124
+ egressReadCredential?: { username: string; password: string }
125
+ }
126
+
127
+ function nonblank(env: Readonly<Record<string, string | undefined>>, name: string): boolean {
128
+ const value = env[name]
129
+ return value !== undefined && value.trim() !== ''
130
+ }
131
+
132
+ /** Decide what the hosted operator sandbox composes for `config`. A
133
+ * `vercel-sandbox` project passes through unchanged. Any other provider gets
134
+ * the deployment's Vercel Sandbox provider, which needs the deployment's
135
+ * Vercel credential (`VERCEL_OIDC_TOKEN`, after the request header is
136
+ * merged, or the durable `VERCEL_TOKEN`/`VERCEL_TEAM_ID`/`VERCEL_PROJECT_ID`
137
+ * triple) and its forge token (`GITHUB_TOKEN` or `GH_TOKEN`); without them it
138
+ * throws `SandboxUnavailableError('credentials-missing')` naming every missing
139
+ * group, never a value. Pure: reads `env`, never mutates it. */
140
+ export function hostedOperatorSandboxComposition(
141
+ config: Config,
142
+ env: Readonly<Record<string, string | undefined>>,
143
+ ): HostedOperatorSandboxComposition {
144
+ if (config.workspace.provider === HOSTED_SANDBOX_PROVIDER) return { config, fallback: false }
145
+ const missing: string[] = []
146
+ const vercel =
147
+ nonblank(env, 'VERCEL_OIDC_TOKEN') ||
148
+ (nonblank(env, 'VERCEL_TOKEN') &&
149
+ nonblank(env, 'VERCEL_TEAM_ID') &&
150
+ nonblank(env, 'VERCEL_PROJECT_ID'))
151
+ if (!vercel) {
152
+ missing.push(
153
+ 'VERCEL_OIDC_TOKEN (or the x-vercel-oidc-token request header) or VERCEL_TOKEN, VERCEL_TEAM_ID and VERCEL_PROJECT_ID',
154
+ )
155
+ }
156
+ const token = githubTokenFromEnv(env)
157
+ if (token === undefined || token.trim() === '') missing.push('GITHUB_TOKEN or GH_TOKEN')
158
+ if (missing.length > 0) {
159
+ throw new SandboxUnavailableError(
160
+ 'credentials-missing',
161
+ `the hosted operator sandbox needs the deployment's Vercel and forge credentials; missing: ${missing.join('; ')}`,
162
+ )
163
+ }
164
+ return {
165
+ config: {
166
+ ...config,
167
+ workspace: {
168
+ provider: HOSTED_SANDBOX_PROVIDER,
169
+ config: { ...FALLBACK_VERCEL_SANDBOX_CONFIG },
170
+ },
171
+ },
172
+ fallback: true,
173
+ egressReadCredential: { username: 'x-access-token', password: token! },
174
+ }
175
+ }
176
+
92
177
  export interface HostedOperatorSandboxService extends OperatorSandboxService {
93
178
  dispose(): Promise<void>
94
179
  }
95
180
 
96
181
  /** Build the hosted operator-sandbox backend from the effective config and
97
- * injected seams. Throws on every construction failure (unknown provider or
182
+ * injected seams, through `hostedOperatorSandboxComposition` (which may
183
+ * substitute the deployment's Vercel provider, or refuse
184
+ * `credentials-missing`). Throws on every construction failure (unknown provider or
98
185
  * forge, missing Vercel SDK credential, forbidden forwarded env name,
99
186
  * capability-less provider, forge without `remoteBranchSha`) — the caller
100
187
  * contains and degrades to serving without the sandbox tools. */
@@ -109,10 +196,14 @@ export async function createHostedOperatorSandboxService(
109
196
  return disposal
110
197
  }
111
198
  try {
199
+ const { config, egressReadCredential } = hostedOperatorSandboxComposition(
200
+ options.config,
201
+ options.env,
202
+ )
112
203
  const forge =
113
204
  options.forge ??
114
205
  (await createForge({
115
- name: options.config.forge,
206
+ name: config.forge,
116
207
  registry: createPluginRegistry(),
117
208
  env: options.env,
118
209
  repoRoot: scratch,
@@ -123,13 +214,13 @@ export async function createHostedOperatorSandboxService(
123
214
  }))
124
215
  if (forge.remoteBranchSha === undefined) {
125
216
  throw new Error(
126
- `the configured forge "${options.config.forge}" does not resolve remote branch heads; ` +
217
+ `the configured forge "${config.forge}" does not resolve remote branch heads; ` +
127
218
  'the hosted sandbox backend has no checkout to resolve base heads against',
128
219
  )
129
220
  }
130
221
  // Builtin-only registry: a plugin-provider config fails construction here
131
222
  // (unknown provider in the empty registry) and the caller contains it.
132
- const provider = await createWorkspaceProvider(options.config.workspace, {
223
+ const provider = await createWorkspaceProvider(config.workspace, {
133
224
  registry: createPluginRegistry(),
134
225
  worktreeRoot: scratch,
135
226
  repoRoot: scratch,
@@ -138,19 +229,24 @@ export async function createHostedOperatorSandboxService(
138
229
  storeToken: options.storeToken,
139
230
  origin: async () => options.repo,
140
231
  remoteBranchHead: remoteBranchHeadFromForge(forge),
141
- sandboxSetupCommand: options.config.commands.setup,
232
+ sandboxSetupCommand: config.commands.setup,
142
233
  sandboxRoot: join(scratch, 'orchestrator-sandboxes'),
143
- sandboxEnvironmentVariables: options.config.orchestrator.sandbox.environmentVariables,
234
+ sandboxEnvironmentVariables: config.orchestrator.sandbox.environmentVariables,
235
+ sandboxIdleMinutes: config.orchestrator.sandbox.idleMinutes,
144
236
  orchestratorSandboxEnabled: true,
237
+ ...(egressReadCredential !== undefined
238
+ ? { sandboxEgressReadCredential: egressReadCredential }
239
+ : {}),
145
240
  })
146
241
  const service = await createOperatorSandboxService({
147
242
  store: options.store,
148
243
  repo: options.repo,
149
244
  provider,
150
- sandbox: options.config.orchestrator.sandbox,
151
- baseBranch: options.config.baseBranch,
245
+ sandbox: config.orchestrator.sandbox,
246
+ baseBranch: config.baseBranch,
152
247
  forge,
153
248
  ...(options.clock !== undefined ? { clock: options.clock } : {}),
249
+ ...(options.background !== undefined ? { background: options.background } : {}),
154
250
  })
155
251
  return Object.assign(service, { dispose })
156
252
  } catch (error) {
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The per-call operator-sandbox resolver (#1219): the hosted MCP binding's
3
+ * gate and cache in front of the `sandbox.*` tools.
4
+ *
5
+ * Each call reads the repository's LATEST deposited effective config (one
6
+ * repository read plus the latest artifact row, never a listing of every
7
+ * revision) and refuses with a typed `SandboxUnavailableError` when the gate
8
+ * is closed. This resolver is the hosted binding's gate by definition, so it
9
+ * resolves `[orchestrator].enabled` for the `hosted` host: an unset value is
10
+ * enabled, only an explicit `enabled = false` closes the gate. An open gate returns one composed backend per repository, keyed
11
+ * by effective-config revision and a caller-supplied credential key, reused
12
+ * across calls. The repo-scoped store token the composition needs is cached
13
+ * separately and renewed only near expiry, so a recomposition (new revision,
14
+ * changed credential) never issues a fresh credential while the token holds.
15
+ *
16
+ * Composition is injected: this module never imports the
17
+ * `operator-sandbox-host` closure, so `./operator` does not grow it.
18
+ *
19
+ * A credential key that rotates often (a short-lived OIDC value) recomposes
20
+ * on each rotation: a scratch directory plus forge and provider construction,
21
+ * still bounded and with no new store credential while the token is fresh.
22
+ */
23
+ import { redactSandboxMessage } from '../ports/workspace/operator-sandbox'
24
+ import type { Config } from '../config/schema'
25
+ import { systemClock, type BuildStore, type Clock } from '../store/types'
26
+ import { OrchestratorConfigError, readOrchestratorGate } from './query'
27
+ import type { OperatorSandboxService } from './sandbox'
28
+
29
+ export type SandboxUnavailableReason =
30
+ | 'no-effective-config'
31
+ | 'orchestrator-disabled'
32
+ | 'effective-config-invalid'
33
+ | 'backend-unavailable'
34
+ | 'credentials-missing'
35
+
36
+ /** A sandbox call cannot be served for this repository. The registry maps it
37
+ * to a `sandbox-<reason>` refusal, so a caller sees why, never `unknown tool`. */
38
+ export class SandboxUnavailableError extends Error {
39
+ override readonly name = 'SandboxUnavailableError'
40
+
41
+ constructor(
42
+ readonly reason: SandboxUnavailableReason,
43
+ message: string,
44
+ options?: { cause?: unknown },
45
+ ) {
46
+ super(message, options)
47
+ }
48
+ }
49
+
50
+ /** The request-scoped provider credential a hosted call carries. */
51
+ export interface SandboxRequestCredentials {
52
+ oidcToken?: string
53
+ }
54
+
55
+ export interface OperatorSandboxResolverOptions {
56
+ store: BuildStore
57
+ clock?: Clock
58
+ /** Whether a composed backend can publish; the registry filters
59
+ * `sandbox.publish` when false. */
60
+ canPublish: boolean
61
+ /** Issue a repo-scoped store token valid until `expiresAt`. */
62
+ issueStoreToken(repo: string, expiresAt: Date): Promise<string>
63
+ /** Lifetime requested for each issued store token. Default one hour. */
64
+ storeTokenLifetimeMs?: number
65
+ /** A cached token is renewed once less than this remains. Default ten minutes. */
66
+ storeTokenRenewMarginMs?: number
67
+ /** The part of the request credentials composition depends on. A change
68
+ * recomposes the backend. Default: none (`''`). */
69
+ credentialKey?(credentials?: SandboxRequestCredentials): string
70
+ /** Runs on a cache miss, before any store token is issued. A thrown
71
+ * `SandboxUnavailableError` refuses the call unchanged and unreported, so a
72
+ * deployment missing what composition needs never mints a credential. */
73
+ preflight?(input: {
74
+ repo: string
75
+ config: Config
76
+ credentials?: SandboxRequestCredentials
77
+ }): void | Promise<void>
78
+ compose(input: {
79
+ repo: string
80
+ config: Config
81
+ storeToken: string
82
+ credentials?: SandboxRequestCredentials
83
+ }): Promise<OperatorSandboxService>
84
+ /** Observes composition, token and disposal failures. Never thrown. */
85
+ report?(error: unknown): void | Promise<void>
86
+ }
87
+
88
+ export interface OperatorSandboxResolver {
89
+ readonly canPublish: boolean
90
+ /** Gate the call on the repository's latest effective config and return its
91
+ * cached backend. Throws `SandboxUnavailableError` when the call cannot be
92
+ * served. */
93
+ resolve(repo: string, credentials?: SandboxRequestCredentials): Promise<OperatorSandboxService>
94
+ /** Dispose every cached backend. */
95
+ dispose(): Promise<void>
96
+ }
97
+
98
+ const DEFAULT_TOKEN_LIFETIME_MS = 3_600_000
99
+ const DEFAULT_TOKEN_RENEW_MARGIN_MS = 600_000
100
+
101
+ function describe(error: unknown): string {
102
+ return redactSandboxMessage(error instanceof Error ? error.message : String(error))
103
+ }
104
+
105
+ export function createOperatorSandboxResolver(
106
+ options: OperatorSandboxResolverOptions,
107
+ ): OperatorSandboxResolver {
108
+ const clock = options.clock ?? systemClock
109
+ const lifetime = options.storeTokenLifetimeMs ?? DEFAULT_TOKEN_LIFETIME_MS
110
+ const margin = options.storeTokenRenewMarginMs ?? DEFAULT_TOKEN_RENEW_MARGIN_MS
111
+ const keyOf = options.credentialKey ?? (() => '')
112
+ const services = new Map<
113
+ string,
114
+ { revision: number; key: string; service: Promise<OperatorSandboxService> }
115
+ >()
116
+ const tokens = new Map<string, { expiresAt: number; token: Promise<string> }>()
117
+
118
+ const report = async (error: unknown): Promise<void> => {
119
+ try {
120
+ await options.report?.(error)
121
+ } catch {
122
+ // Reporting never fails a call.
123
+ }
124
+ }
125
+
126
+ const unavailable = (repo: string, error: unknown): SandboxUnavailableError =>
127
+ new SandboxUnavailableError(
128
+ 'backend-unavailable',
129
+ `the operator sandbox backend for repository "${repo}" could not be built: ${describe(error)}`,
130
+ { cause: error },
131
+ )
132
+
133
+ const storeToken = (repo: string): Promise<string> => {
134
+ const now = clock().getTime()
135
+ const cached = tokens.get(repo)
136
+ if (cached !== undefined && cached.expiresAt - now > margin) return cached.token
137
+ const expiresAt = now + lifetime
138
+ const token = options.issueStoreToken(repo, new Date(expiresAt))
139
+ const entry = { expiresAt, token }
140
+ tokens.set(repo, entry)
141
+ token.catch(() => {
142
+ if (tokens.get(repo) === entry) tokens.delete(repo)
143
+ })
144
+ return token
145
+ }
146
+
147
+ const retire = (service: Promise<OperatorSandboxService>): void => {
148
+ // A superseded backend may still serve an in-flight call. Disposal only
149
+ // removes its local scratch, which the hosted providers reach solely
150
+ // through paths the injected seams bypass, so that call is unaffected.
151
+ // Each backend serializes its own calls; a replacement mid-burst can
152
+ // briefly overlap two calls for one environment. Replacement happens only
153
+ // on a revision or credential change, so no cross-instance lock exists.
154
+ void service.then((old) => old.dispose?.()).catch((error: unknown) => report(error))
155
+ }
156
+
157
+ return {
158
+ canPublish: options.canPublish,
159
+
160
+ async resolve(repo, credentials) {
161
+ let gate: Awaited<ReturnType<typeof readOrchestratorGate>>
162
+ try {
163
+ gate = await readOrchestratorGate(options.store, repo, 'hosted')
164
+ } catch (error) {
165
+ if (error instanceof OrchestratorConfigError) {
166
+ throw new SandboxUnavailableError(
167
+ 'effective-config-invalid',
168
+ `repository "${repo}" has an unusable latest effective config (${error.message}); fix the configuration and let the dispatcher deposit it again`,
169
+ { cause: error },
170
+ )
171
+ }
172
+ throw error
173
+ }
174
+ if (!gate.enabled) {
175
+ throw gate.reason === 'orchestrator-disabled'
176
+ ? new SandboxUnavailableError(
177
+ 'orchestrator-disabled',
178
+ `repository "${repo}" disables [orchestrator] in its latest deposited effective config (\`enabled = false\`, or a dispatcher release that predates the hosted default and writes it explicitly); remove \`enabled = false\` or upgrade, and let the dispatcher deposit it again`,
179
+ )
180
+ : new SandboxUnavailableError(
181
+ 'no-effective-config',
182
+ `repository "${repo}" has no deposited effective config; sandbox tools need a dispatcher run to deposit one`,
183
+ )
184
+ }
185
+ const key = keyOf(credentials)
186
+ const cached = services.get(repo)
187
+ if (cached !== undefined && cached.revision === gate.revision && cached.key === key) {
188
+ return cached.service
189
+ }
190
+ const config = gate.config
191
+ // Preflight runs inside the cached pending operation, so concurrent
192
+ // first calls share one preflight and one composition.
193
+ const service = (async () => {
194
+ if (options.preflight !== undefined) {
195
+ try {
196
+ await options.preflight({
197
+ repo,
198
+ config,
199
+ ...(credentials !== undefined ? { credentials } : {}),
200
+ })
201
+ } catch (error) {
202
+ if (error instanceof SandboxUnavailableError) throw error
203
+ await report(error)
204
+ throw unavailable(repo, error)
205
+ }
206
+ }
207
+ let token: string
208
+ try {
209
+ token = await storeToken(repo)
210
+ } catch (error) {
211
+ await report(error)
212
+ throw unavailable(repo, error)
213
+ }
214
+ try {
215
+ return await options.compose({
216
+ repo,
217
+ config,
218
+ storeToken: token,
219
+ ...(credentials !== undefined ? { credentials } : {}),
220
+ })
221
+ } catch (error) {
222
+ // A composition that already refuses with a typed reason (a
223
+ // missing deployment credential, say) keeps it.
224
+ if (error instanceof SandboxUnavailableError) throw error
225
+ await report(error)
226
+ throw unavailable(repo, error)
227
+ }
228
+ })()
229
+ const entry = { revision: gate.revision, key, service }
230
+ services.set(repo, entry)
231
+ service.catch(() => {
232
+ if (services.get(repo) === entry) services.delete(repo)
233
+ })
234
+ if (cached !== undefined) retire(cached.service)
235
+ return service
236
+ },
237
+
238
+ async dispose() {
239
+ const all = [...services.values()]
240
+ services.clear()
241
+ tokens.clear()
242
+ await Promise.all(
243
+ all.map(async ({ service }) => {
244
+ try {
245
+ await (await service).dispose?.()
246
+ } catch (error) {
247
+ await report(error)
248
+ }
249
+ }),
250
+ )
251
+ },
252
+ }
253
+ }