@defrex/autobuild 1.1.0 → 1.2.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 (114) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +140 -10
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/architecture.md +107 -8
  7. package/docs/build-store.md +3 -41
  8. package/docs/cli.md +14 -0
  9. package/docs/configuration-overview.md +111 -0
  10. package/docs/configuration.md +260 -141
  11. package/docs/dispatcher-hosting.md +18 -33
  12. package/docs/intake.md +2 -0
  13. package/docs/merge-policy.md +1 -3
  14. package/docs/operating.md +1 -2
  15. package/docs/operator-api.md +100 -47
  16. package/docs/operator-surfaces.md +3 -20
  17. package/docs/overview.md +1 -1
  18. package/docs/plugin-authoring.md +21 -0
  19. package/docs/remote-store-protocol.md +198 -89
  20. package/docs/remote-ticket-protocol.md +29 -49
  21. package/docs/seams.md +8 -8
  22. package/docs/setup.md +34 -129
  23. package/docs/ticket-sources.md +18 -0
  24. package/docs/troubleshooting.md +7 -11
  25. package/docs/upgrading.md +1 -1
  26. package/docs/workspaces.md +4 -4
  27. package/package.json +14 -5
  28. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  29. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  30. package/packages/core/src/accounts/local-credentials.ts +194 -0
  31. package/packages/core/src/accounts/local-inference.ts +106 -0
  32. package/packages/core/src/accounts/local-owner.ts +123 -0
  33. package/packages/core/src/accounts/sensitive.ts +2 -0
  34. package/packages/core/src/cli/accounts.ts +147 -0
  35. package/packages/core/src/cli/binary.ts +3 -1
  36. package/packages/core/src/cli/connect.ts +3 -3
  37. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  38. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  39. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  40. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  41. package/packages/core/src/cli/dispatch.ts +71 -2
  42. package/packages/core/src/cli/help.ts +16 -0
  43. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  44. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  45. package/packages/core/src/cli/init-validation.ts +160 -18
  46. package/packages/core/src/cli/main.ts +44 -0
  47. package/packages/core/src/cli/publication-settlement.ts +4 -1
  48. package/packages/core/src/cli/secrets.ts +173 -0
  49. package/packages/core/src/cli/store-opening.ts +11 -1
  50. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  51. package/packages/core/src/cli/watch.ts +3 -1
  52. package/packages/core/src/config/accounts.ts +101 -0
  53. package/packages/core/src/config/live.ts +14 -1
  54. package/packages/core/src/config/roles.ts +54 -3
  55. package/packages/core/src/config/schema.ts +60 -0
  56. package/packages/core/src/events/compatibility.ts +2 -1
  57. package/packages/core/src/events/payloads.ts +3 -0
  58. package/packages/core/src/events/repository.ts +2 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +3 -0
  60. package/packages/core/src/kernel/reducer.ts +4 -1
  61. package/packages/core/src/operator/index.ts +2 -0
  62. package/packages/core/src/operator/protocol.ts +6 -0
  63. package/packages/core/src/operator/registry.ts +22 -1
  64. package/packages/core/src/operator/tickets.ts +25 -4
  65. package/packages/core/src/plugins/manifest.ts +2 -1
  66. package/packages/core/src/ports/runner/account-env.ts +88 -0
  67. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  68. package/packages/core/src/ports/runner/claude.ts +26 -2
  69. package/packages/core/src/ports/runner/codex.ts +63 -31
  70. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  71. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  72. package/packages/core/src/ports/runner/routing.ts +35 -4
  73. package/packages/core/src/ports/tickets/contract.ts +58 -0
  74. package/packages/core/src/ports/tickets/tree.ts +1 -1
  75. package/packages/core/src/ports/types.ts +28 -7
  76. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  77. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  78. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  79. package/packages/core/src/ports/workspace/create.ts +2 -0
  80. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  81. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  82. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  83. package/packages/core/src/processes/build-runner.ts +32 -1
  84. package/packages/core/src/processes/dispatcher.ts +23 -0
  85. package/packages/core/src/processes/execution-settlement.ts +21 -3
  86. package/packages/core/src/processes/harvest-runner.ts +68 -8
  87. package/packages/core/src/project-secrets.ts +105 -0
  88. package/packages/core/src/secret-name.ts +41 -0
  89. package/packages/core/src/store/account-redaction.ts +156 -0
  90. package/packages/core/src/store/contract.ts +3 -1
  91. package/packages/core/src/store/reducer-value-shapes.json +2889 -2781
  92. package/packages/core/src/store/remote/client.ts +42 -47
  93. package/packages/core/src/store/remote/compatibility.ts +18 -0
  94. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  95. package/packages/core/src/testing/index.ts +1 -0
  96. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  97. package/skills/guide/SKILL.md +120 -30
  98. package/skills/guide/references/accounts.md +119 -0
  99. package/skills/guide/references/merge-policy.md +1 -3
  100. package/skills/guide/references/operator-api.md +100 -47
  101. package/skills/guide/references/plugin-authoring.md +21 -0
  102. package/skills/guide/references/remote-store-protocol.md +198 -89
  103. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  104. package/skills/guide/references/setup.md +34 -129
  105. package/skills/harvest/SKILL.md +3 -1
  106. package/skills/harvest-review/SKILL.md +3 -1
  107. package/skills/operate/SKILL.md +5 -6
  108. package/skills/spec/SKILL.md +1 -1
  109. package/skills/tickets/SKILL.md +3 -2
  110. package/templates/hosted-service/package.json +2 -2
  111. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  112. package/docs/hosted-dispatcher.md +0 -278
  113. package/docs/hosted-service.md +0 -304
  114. package/docs/mcp.md +0 -150
@@ -1,278 +0,0 @@
1
- # The hosted dispatcher
2
-
3
- The optional [`@defrex/autobuild-hosted-dispatcher`](../packages/hosted-dispatcher/README.md)
4
- package lets a deployment own the dispatch kernel. Installing it and mounting
5
- its route — `GET /api/dispatch`, backed by the package's
6
- `dispatcherEndpoint()` singleton — makes the hosted deployment the kernel
7
- owner. One authenticated HTTP invocation runs, for each configured
8
- repository, one bounded origin-mode dispatcher
9
- tick: the kernel claims ready tickets, provisions and launches sandboxes,
10
- observes running builds, settles publications, opens and merges PRs, and runs
11
- the janitor, exactly as a local `ab dispatch --once --repository <origin>`
12
- pass does. The schedule is what you attach to that endpoint (Vercel Cron calls
13
- it once a minute by default), so builds no longer depend on a maintainer's
14
- machine. A deployment that does not install the package serves the hosted
15
- store, ticket, operator, and web endpoints and never attempts a dispatch tick.
16
-
17
- The [minimal hosted service deployment](hosted-service.md) defaults to store-only
18
- mode and supplies no cron. The source-checkout deployment below retains the
19
- opt-in dispatcher packing and shipping pipeline.
20
-
21
- For a dispatcher running as a local user or service manager, first
22
- [connect the project](hosted-service.md#connect-a-project). Origin-mode dispatch
23
- can read the committed `[store] url` and the same user credential by origin.
24
- A deployment running under another identity needs its own project credential;
25
- `AB_TOKEN` remains the explicit CI override.
26
-
27
- ## Enabling the schedule
28
-
29
- 1. Deploy the hosted service with the dispatcher package installed and the
30
- dispatcher variables from
31
- [its README](../packages/hosted-dispatcher/README.md)
32
- — `AB_DISPATCHER_ORIGIN`, the repository set, `CRON_SECRET`, and the forge
33
- credentials the kernel needs (`GITHUB_TOKEN` or `GH_TOKEN`, plus any
34
- guest-forwarded variables such as `AI_GATEWAY_API_KEY`). A deployment
35
- serving repositories across GitHub identities configures per-repository
36
- tokens with `AB_DISPATCHER_GITHUB_TOKENS`; repositories without an
37
- override keep using the shared credential. A served repository with
38
- neither fails its tick: origin-mode dispatch requires an exported token
39
- and never falls back to the gh CLI login of whoever runs the service.
40
- 2. Schedule the route by adding a `crons` entry to the deployment's
41
- `vercel.json` and redeploying. Vercel issues a plain GET with
42
- `Authorization: Bearer <CRON_SECRET>` once per minute:
43
-
44
- ```json
45
- {
46
- "crons": [{ "path": "/api/dispatch", "schedule": "* * * * *" }]
47
- }
48
- ```
49
-
50
- 3. Verify: `curl -H "Authorization: Bearer $CRON_SECRET" https://YOUR_ORIGIN/api/dispatch`
51
- returns `200 {"ok":true,"repositories":[{"repository":"…","outcome":"ticked","runId":"hosted-dispatcher-…"}]}`.
52
- Unauthenticated or wrongly authorized calls are rejected (401) and do no
53
- work; a deployment without `CRON_SECRET` answers 403 with the endpoint
54
- disabled. One repository's failure never prevents another's tick.
55
-
56
- ## Shipping the guest distribution
57
-
58
- Every sandbox installs the Autobuild distribution the launching dispatcher
59
- runs. A local dispatcher packs it from its source checkout with `bun pm pack`;
60
- a bundled deployment has neither `bun` nor a source tree at runtime, so it
61
- must pack the archive while both exist — in its build step — and carry it into
62
- the function bundle. The script lives in the hosted store service package
63
- (`packages/hosted-store-service/package.json`), whose directory is the Next.js
64
- project directory and the deployment build's working directory:
65
-
66
- ```json
67
- { "scripts": { "deploy:build": "bun ../../packages/hosted-dispatcher/src/bin.ts pack-distribution --root . && bun ../../packages/postgres-store/src/bin.ts migrate && bun run build && bun ../../packages/hosted-dispatcher/src/ship-packed-distribution.ts && bun ../../packages/hosted-dispatcher/src/ship-provider-plugin.ts" } }
68
- ```
69
-
70
- `pack-distribution` (the `ab-hosted-dispatcher` bin) writes
71
- `.autobuild-dist/autobuild-<version>.tgz` under the
72
- distribution root (`--root DIR` overrides) — this deployment passes
73
- `--root .`, because the packer's default root is the repository's distribution
74
- root while the trace step below and the Next config's
75
- `outputFileTracingIncludes: { '/api/dispatch': ['./.autobuild-dist/**'] }`
76
- resolve against the deployment build's working directory, where the archive
77
- must merge beside the built output. The Next.js config's
78
- `outputFileTracingIncludes` records the intent to include that directory in the cron route's bundle, but
79
- Next 16's default Turbopack builds never apply `outputFileTracingIncludes`
80
- (only webpack builds do), so a deployment cannot rely on the config alone. The
81
- autobuild-api pipeline therefore ends `deploy:build` with a post-build trace
82
- step (`bun ../../packages/hosted-dispatcher/src/ship-packed-distribution.ts`) that appends the archive to the
83
- dispatch route's `route.js.nft.json` — the trace file Vercel's Next builder
84
- consumes when assembling the function bundle — and fails the deploy loudly if
85
- nothing was packed or the trace file is missing. The same step appends the
86
- distribution root's `package.json`, which provisioning reads for the running
87
- version and which no import traces once the Next.js project directory sits
88
- below the repository root. A deployment using this
89
- pipeline cannot ship without the archive; deployments that skip both packing
90
- and the trace step still fail at runtime.
91
-
92
- A second post-build trace step ships the provider plugin package (AUT-517):
93
- `bun ../../packages/hosted-dispatcher/src/ship-provider-plugin.ts` locates the
94
- plugin's source through the repository root's `workspaces` tree (never through
95
- `node_modules`, so a previous run's staged directory cannot shadow the source),
96
- bundles its entrypoint with `bun build --target=bun --format=esm` into a
97
- single self-contained module (the plugin-sdk closure inlines — the
98
- deployment's repository-root `node_modules` carries no `@defrex/autobuild`
99
- either — while node builtins stay external), stages it into
100
- `<repoRoot>/node_modules/@defrex/autobuild-vercel-sandbox/` (replacing the
101
- workspace symlink a local `bun install` leaves there — or a previous run's
102
- staged directory, which `bun install` does not relink; the deployment never
103
- runs `bun install` again), and appends the staged files to the dispatch
104
- route's trace at the same repository-root depth as the existing
105
- `node_modules/.bun/**` entries. A bare plugin specifier resolves only
106
- through a `node_modules/` path, and the compiled dispatcher's
107
- `distributionRoot()` is the repository root, so only this staging makes
108
- `plugins = ["@defrex/autobuild-vercel-sandbox"]` loadable inside the
109
- deployed function. The step is idempotent across runs — including in a
110
- fresh process after an earlier run consumed the workspace link — and fails
111
- the deploy loudly when the package, its entrypoint, or the trace file is
112
- missing. The npm published package remains the real `src` — only the
113
- deployment stages the bundle.
114
-
115
- What the staged directory does afterwards depends on the build environment.
116
- Inside a Vercel deployment build (which always sets `VERCEL`, including a
117
- local `vercel build` run) the staged directory stays: the deployment never
118
- runs `bun install` again and the function bundle's runtime resolution needs
119
- it — a deployment building outside Vercel must set `VERCEL=1` in its build
120
- environment to keep the staged bundle. A plain local `bun run deploy:build`
121
- (no `VERCEL` environment) removes the staged directory afterwards and
122
- restores the workspace symlink, so a local run leaves the checkout exactly
123
- as `bun install` had it and local test runs keep resolving the workspace
124
- source (the capability parity test's reference equality holds). On checkouts
125
- of older versions the staged directory stayed behind and survived `bun
126
- install` — it reports "no changes" because the staged package satisfies the
127
- manifest — so later local runs resolved the plugin to the self-contained
128
- bundle and the parity test failed on its reference-equality assertion; the
129
- recovery is `rm -rf node_modules/@defrex/autobuild-vercel-sandbox && bun
130
- install`, or simply re-run `deploy:build` locally on a version with this
131
- fix, which restores the symlink itself.
132
-
133
- At runtime the kernel takes, in order: `AB_DISTRIBUTION_ARCHIVE` (an explicit
134
- archive path), the single archive under `.autobuild-dist/` of the
135
- distribution root or working directory, a source checkout packed on the spot,
136
- and finally the running version's published distribution — the npm registry
137
- tarball, else the GitHub release asset. A tick that
138
- reports `Executable not found in $PATH: "bun"` during `provision` is a
139
- deployment that skipped the pack step (or, outside this pipeline, the trace
140
- step that ships the archive).
141
-
142
- ## Bounding the invocation
143
-
144
- The endpoint is pinned to `maxDuration = 300` seconds (Vercel Pro's default
145
- function duration). `AB_DISPATCHER_BUDGET_SECONDS` (default 240) bounds the
146
- kernel's work inside that: an already-expired budget skips the tick, a budget
147
- reached mid-drain stops awaiting running builds, and a repository whose budget
148
- no longer covers a minimum-remaining floor is answered as `skipped`. Unfinished
149
- work resumes on the next invocation: guests keep running while the supervising
150
- function detaches, and the next tick settles their completion from the Store
151
- plus provider liveness. Raise `maxDuration` and the budget **together** (e.g.
152
- `"maxDuration": 800` with a budget of 780 — the parser clamps 10–780); keep the
153
- budget at least ~20 s below the function duration so the response always
154
- returns.
155
-
156
- ## Overlap and missed ticks
157
-
158
- Invocations are serialized by the durable repository supervisor lease: a second
159
- overlapping invocation yields (it records `dispatcher.tick-yielded` naming the
160
- holder in the repository journal and performs no claims, launches, or
161
- publications), and the loser's response still answers 200. A missed or late
162
- invocation is never incorrect: a build whose guest finished while no invocation
163
- ran is settled — completion facts, lease, publication — by the next
164
- invocation's settlement stage, and a build whose sandbox timed out is recovered
165
- by the lease sweep as with any dispatcher.
166
-
167
- One provider behavior matters for that settlement: Vercel's plain command
168
- lookup reports no exit code for a command that finished while no client was
169
- waiting on it, and keeps reporting none until some client issues a wait on the
170
- command. The dispatcher's execution observation therefore issues one bounded
171
- (~5 s) wait on the recorded command whenever the lookup shows no exit: a wait
172
- that resolves proves the guest command's end (with its exit code). Before
173
- settlement the provider must also confirm that the whole sandbox has stopped,
174
- including descendants. A failed or ambiguous stop leaves the execution and lease
175
- open, with publication and relaunch deferred until a later tick confirms teardown.
176
- A timed-out command wait leaves the guest running — one
177
- observation never approaches the tick's operation timeout, and the next tick
178
- retries. Settlement of a guest that exited after the launching invocation
179
- detached is expected within one tick of its exit.
180
-
181
- ## Pausing during an incident
182
-
183
- - **Stop the schedule**: remove the `crons` entry (or disable the cron in the
184
- Vercel dashboard) and redeploy.
185
- - **Revoke the credential**: rotate `CRON_SECRET` — every in-flight schedule
186
- call starts answering 401.
187
- - **Soft stop**: turn repository intake OFF (operator API `PUT
188
- /operator/v1/repos/{repo}/settings/intake` with `{"enabled": false}`, or the
189
- web dashboard) — running builds finish their current phases but no new ticket
190
- is claimed. A repository-wide or per-build pause holds queued work the same
191
- way and takes effect on the next invocation.
192
-
193
- ## Observing the hosted dispatcher
194
-
195
- Every invocation is durable: tick reports
196
- (`dispatcher.tick-started`/`-completed`/`-yielded`), run boundaries
197
- (`dispatcher.run-started`/`-stopped`), and a per-minute
198
- `dispatcher-effective-config` artifact deposit all carry the
199
- `hosted-dispatcher-<uuid>` run id, so the web dashboard's repository journal
200
- and the operator API show hosted activity exactly as they show a local
201
- dispatcher. Expect the repository journal to grow by roughly one config
202
- artifact per minute per repository; the dispatcher run/config artifacts
203
- themselves are retention-bounded (see below), while the journal's events keep
204
- accumulating by design.
205
-
206
- This is true of *every* dispatcher, not only the hosted one. A local `ab
207
- dispatch` pointed at the hosted Store — a watch, an operator cron on a host,
208
- a manual one-shot — synthesizes its own `<host>-dispatch-<id>` run id and
209
- journals the same run boundaries and tick facts under it. That makes cutover
210
- verification answerable from the journal alone:
211
-
212
- - Every `dispatcher.*` event with a non-`hosted-dispatcher` run id is direct
213
- evidence that another dispatcher was writing to the hosted Store.
214
- - A journal window with no `dispatcher.*` events at all means no dispatcher
215
- ran against the Store in that window.
216
- - The launch-flag facts (`dispatcher.intake-set`,
217
- `dispatcher.auto-merge-default-set`) carry the writing invocation's run id
218
- alongside their human actor, so even those writes identify the dispatcher
219
- that performed them.
220
-
221
- ### Runtime logs
222
-
223
- Every invocation also writes to the deployment's runtime logs (Vercel's
224
- **Logs** tab, or `vercel logs`), which is where to look first when the journal
225
- shows no hosted activity at all — a rejected or misconfigured invocation never
226
- reaches the journal. Every line starts with `hosted-dispatcher <invocation id>`
227
- so one invocation's lines can be filtered together:
228
-
229
- - the request line (`GET /api/dispatch agent="vercel-cron/1.0"`) — the user
230
- agent tells a cron call apart from an operator's curl;
231
- - `rejected 401|403|405 <kind>: <reason>` at error level, with whether the
232
- authorization header was absent or present-but-wrong (never its value);
233
- - `500 configuration invalid: <error>` naming the offending variable;
234
- - `tick start repositories=N budgetSeconds=S origin=…`, then per repository
235
- `tick run=hosted-dispatcher-…`, `ticked … ms=…`, `skipped`, or
236
- `failed … : <error with stack>` at error level, then
237
- `tick complete ticked=… failed=… skipped=…` and `200 ok ms=…`;
238
- - the kernel's own report lines (the same lines `ab dispatch --plain` prints
239
- locally) prefixed `<repository> [kernel]`, warnings at error level.
240
-
241
- Secrets, forge tokens, and minted guest tokens never appear in any line.
242
-
243
- ## Artifact retention
244
-
245
- Dispatcher-generated run/config artifacts — the repository-scoped
246
- `dispatcher-effective-config` and `dispatcher-config` kinds and the
247
- build-scoped `build-runner-effective-config` kind — keep the **latest 200
248
- revisions per kind** (per repository, respectively per build). When a new
249
- revision of one of these kinds is deposited, the store prunes the older
250
- revisions past the bound at deposit time, inside the same transaction.
251
- Events and journal entries are never pruned, so historical event payloads may
252
- reference a pruned revision; the current run's snapshot is always among the
253
- newest deposits and stays retrievable, and every existing read surface
254
- (latest-by-default artifact reads, listings) works unchanged. The bound is
255
- overridable per deployment with `AB_ARTIFACT_RETENTION_MAX_REVISIONS` (a
256
- positive integer; see the store environment documentation). All other
257
- artifact kinds (build logs, `pr-description`, phase artifacts) are not
258
- subject to retention.
259
-
260
- ## Sandbox authentication
261
-
262
- Inside a Vercel Function the Sandbox SDK authenticates with the deployment's
263
- own OIDC identity: Vercel hands each invocation its token on the
264
- `x-vercel-oidc-token` request header (not as a `VERCEL_OIDC_TOKEN` environment
265
- variable), and the endpoint passes it to the kernel under that name for the
266
- duration of the tick. The tick log line reports which credential the kernel
267
- presents (`sandboxAuth=oidc-header`, `oidc-env`, `token`, or `none`); `none`
268
- means the project has OIDC federation disabled (Settings → Security). No
269
- long-lived `VERCEL_TOKEN` belongs on the service. Guests never receive a Vercel
270
- token or forge credential; they authenticate to the Store with the short-TTL
271
- stored project credential the dispatcher issues for each repository tick
272
- (`AB_DISPATCHER_TOKEN_TTL_SECONDS`, default 7 days — keep it longer than your
273
- largest `timeoutSeconds` guest lifetime). Its immutable dispatcher purpose
274
- permits raw Store and hosted tickets only, never operator controls. The service
275
- checks registration and revocation on each request. Tick return does not revoke
276
- it; spawned builds may outlive the tick. Owner-issued project credentials and
277
- the owner-only break-glass admin are documented in the
278
- [remote Store protocol](remote-store-protocol.md#7-authentication-and-project-authority).
@@ -1,304 +0,0 @@
1
- # Deploy a hosted service
2
-
3
- A service hosts the BuildStore, tickets, dashboard, sign-in, and MCP endpoint.
4
- The default deployment stores state while dispatch runs on another machine.
5
- You need Bun 1.4.x, a Git repository, a Vercel project, PostgreSQL, a blob
6
- backend, and a GitHub OAuth application.
7
-
8
- Create a new directory containing these two files (also shipped in the hosted
9
- package's `deployment/` directory and in `templates/hosted-service/`).
10
-
11
- `package.json`:
12
-
13
- ```json
14
- {
15
- "private": true,
16
- "scripts": {
17
- "build": "ab-hosted-service-build"
18
- },
19
- "dependencies": {
20
- "@defrex/autobuild-hosted-store-service": "1.1.0",
21
- "@defrex/autobuild": "1.1.0",
22
- "next": "16.1.6",
23
- "react": "19.2.4",
24
- "react-dom": "19.2.4"
25
- }
26
- }
27
- ```
28
-
29
- `vercel.json`:
30
-
31
- ```json
32
- {
33
- "$schema": "https://openapi.vercel.sh/vercel.json",
34
- "framework": "nextjs",
35
- "installCommand": "bun install --frozen-lockfile",
36
- "buildCommand": "bun run build",
37
- "bunVersion": "1.4.x"
38
- }
39
- ```
40
-
41
- Run `bun install`, then commit both files and `bun.lock`. Add `.gitignore`
42
- entries for `node_modules/`, `.next/`, `.vercel/`, `app/`, `next.config.ts`,
43
- `next-env.d.ts`, `tsconfig.json`, and `.autobuild-service-assets.json`.
44
- These application assets are generated during each build. Keep your own files
45
- outside those names; the builder refuses to overwrite consumer-owned files.
46
- Do not commit generated application sources or edit them to customize deployment.
47
-
48
- Push the directory to your Git host. Import it in Vercel with the repository
49
- root as Root Directory and Next.js as the framework. The checked-in platform
50
- configuration installs the lockfile and runs `bun run build`. Each build stages
51
- the installed package, runs its idempotent database migrations against the
52
- configured database, then builds Next into the root `.next/`. Missing database
53
- configuration, incompatible schema, or a failed migration stops the build.
54
- Provide database access from the build environment as well as runtime.
55
-
56
- ## Connect a project
57
-
58
- From a checkout with an origin remote, run `ab connect https://YOUR_ORIGIN`.
59
- The CLI prints a verification URL and short code and attempts to open a browser.
60
- Sign in as an allowed owner, check the full repository identity and code, and
61
- approve or deny. Another device can open the printed URL, or visit `/connect`
62
- and enter the code. Approval requires the web-enabled service origin; a
63
- standalone machine-only listener cannot present browser consent. Requests
64
- expire after ten minutes. Denial and timeout leave local configuration unchanged.
65
-
66
- On approval the service registers the project and issues a project credential.
67
- The CLI keeps it in `$XDG_CONFIG_HOME/autobuild/credentials` (or
68
- `~/.config/autobuild/credentials`), keyed by normalized service and origin,
69
- with directory mode 0700 and file mode 0600. Credentials never belong in the
70
- repository. It adds the non-secret `[store] url` to `autobuild.toml` when
71
- absent; review and commit that change yourself. An existing different URL
72
- must be changed explicitly before connecting. Reconnecting replaces the saved
73
- credential only after approval and revokes the previous credential.
74
-
75
- All worktrees share the main checkout's configuration and the user's saved
76
- credential. A service manager running as that user uses the same HOME and
77
- XDG_CONFIG_HOME, with no AB_STORE or AB_TOKEN exports. A fresh clone with
78
- committed store configuration but no saved credential fails with `ab connect`
79
- guidance; it never silently creates local state. Run connect on each host/user.
80
-
81
- `ab connect` without a URL reports service, project, and credential status:
82
- accepted, rejected, missing, or unreachable. `ab disconnect` revokes the saved
83
- credential remotely before removing it locally, keeping the project registered,
84
- its data, and store configuration. A network/server failure retains the local
85
- entry for retry; an already revoked credential can be removed. If saving a new
86
- connection fails, the CLI cancels/revokes it and retains the previous entry.
87
- If remote cleanup cannot be confirmed, check the printed credential id with
88
- the owner's administrative tools before retrying.
89
-
90
- Store selection is `--store` > nonblank `AB_STORE` > `[store] url` > the
91
- main checkout's `.autobuild/`. `AB_TOKEN` overrides the exact service/project's
92
- saved credential for CI and other non-interactive hosts. A service override
93
- never borrows another service's credential. Build and harvest sessions keep
94
- their explicit scoped authority.
95
-
96
- ## Environment
97
-
98
- Set these server-side variables in every Vercel environment you deploy:
99
-
100
- - `AB_POSTGRES_URL` or `DATABASE_URL`: PostgreSQL connection URL. The explicit
101
- `AB_POSTGRES_URL` takes precedence; use the same database at build and runtime.
102
- - `AB_STORE_SECRET`: a high-entropy secret for machine token signing.
103
- - `AB_BLOB_BACKEND=vercel` with `BLOB_READ_WRITE_TOKEN`, or `AB_BLOB_BACKEND=s3`
104
- with `AB_S3_BUCKET`, `AB_S3_REGION`, `AB_S3_ACCESS_KEY_ID`, and
105
- `AB_S3_SECRET_ACCESS_KEY` (and optional endpoint for compatible storage).
106
- - `BETTER_AUTH_SECRET`: an independent high-entropy secret of at least 32 characters.
107
- - `BETTER_AUTH_URL`: the exact production HTTPS origin, with no path.
108
- - `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`: GitHub OAuth application credentials.
109
- - `AB_WEB_AUTH_PROVIDERS=github`.
110
- - `AB_WEB_SUPER_USER_EMAILS`: comma-separated super-user emails. Other operators require organization membership.
111
- - `AB_WEB_REPOSITORIES`: comma-separated repository origins visible to operators.
112
-
113
- Register `https://YOUR_ORIGIN/api/auth/callback/github` as the GitHub callback
114
- and allow read-only email access (`user:email`). Sign-in must use the configured
115
- production origin. Do not expose secrets through `NEXT_PUBLIC_` variables.
116
- See the [complete environment reference](configuration.md) for storage,
117
- project ticket lifecycle, credential administration, and optional MCP resource configuration.
118
-
119
- ## Check the deployment
120
-
121
- `GET /health` returns service and protocol versions. Open `/sign-in` and sign
122
- in; `/` redirects unauthenticated browsers to sign-in. Machine routes
123
- require a machine token; `/mcp` challenges an unauthenticated client with OAuth
124
- resource metadata. Check both discovery documents:
125
-
126
- ```sh
127
- curl https://YOUR_ORIGIN/.well-known/oauth-protected-resource
128
- curl https://YOUR_ORIGIN/.well-known/oauth-authorization-server
129
- ```
130
-
131
- The authorization-server document advertises a reachable `/api/auth/jwks`
132
- URI and `/api/auth/mcp/register` dynamic registration endpoint. MCP clients
133
- register with `redirect_uris` as an array of strings and
134
- `token_endpoint_auth_method: "none"`; treat the returned `client_id` as opaque.
135
- See [MCP](mcp.md) for authorization and client setup.
136
-
137
- Without the optional hosted dispatcher installed, `GET /api/dispatch` returns
138
- 503 JSON: `{"error":"dispatch runs elsewhere for this deployment"}`. The
139
- template has no cron and installs no dispatcher/provider package. Run dispatch
140
- from a connected project or follow the separate, opt-in
141
- [hosted dispatcher procedure](hosted-dispatcher.md), which retains its
142
- source-checkout packaging and cron setup.
143
-
144
- ## Upgrade
145
-
146
- Bump the exact hosted-service and core package pins in `package.json` to the
147
- same new release, run `bun install` to refresh `bun.lock`, commit, and push.
148
- Vercel's Git integration migrates and builds the pinned package automatically.
149
- Upgrade the service **before connected projects**: that is the order expected
150
- by the protocol compatibility window. No source extraction, patch application,
151
- or manual production deployment is required.
152
-
153
- ## Hosted ticket projects and v1 migration
154
-
155
- Hosted queues are partitioned by registered repository. Credentials select the
156
- project. Independent ticket policy selects lifecycle; `ab connect --tickets URL`
157
- publishes it before dispatch. Older clients retain uploaded dispatcher configuration
158
- as a fallback. See the [ticket protocol](remote-ticket-protocol.md). Projects using file,
159
- Linear or another external source continue to access it directly through their
160
- dispatcher. Service ticket surfaces refuse those projects with source feedback.
161
- The service never connects to Linear.
162
-
163
- The removed `AB_TICKET_BACKEND` and `LINEAR_API_KEY` settings are ignored for
164
- all values, including blanks, with one startup message asking for removal.
165
- The removed `AB_TICKET_TRIAGE_STATE`, `AB_TICKET_READY_STATE`,
166
- `AB_TICKET_DOING_STATE` and `AB_TICKET_DONE_STATE` settings are ignored even if
167
- malformed. Lifecycle now comes only from project configuration.
168
-
169
- The environment-aware migration first imports `AB_WEB_REPOSITORIES` into the
170
- registry once, including upgrades from released main schema v9 where registry
171
- tables do not yet exist. This import and the main-schema promotion share the
172
- ticket transaction: a stopped ticket migration rolls them back too. The owner
173
- `projects add` and `tickets assign-team` commands can independently bootstrap
174
- the registry while that old main marker remains, so recovery does not require
175
- a successful ticket migration. If the retired environment is unavailable,
176
- register the intended project with `ab-hosted-store projects add REPOSITORY
177
- --user IDENTITY` before assigning its legacy team. Once the import succeeds,
178
- later changes to the retired environment are ignored.
179
-
180
- Fresh databases install ticket schema v2 directly. Existing team-keyed v1
181
- queues migrate in one transaction. For each registered project, migration reads
182
- the effective configuration selected by its latest dispatcher run and reloads,
183
- including the actual immutable artifact bytes in blob storage. A legacy team
184
- must have one claimant, or an explicit owner assignment. A registered project
185
- with no dispatcher run or no selected effective-config reference makes no team
186
- claim and does not block other projects. Unclaimed teams still stop unchanged.
187
- When ownership must be inferred, a selected but missing, inaccessible or invalid
188
- configuration fails closed with the project and remaining teams in the message.
189
- Restore those bytes or explicitly assign every remaining legacy team, then
190
- rerun; complete assignments to registered projects settle ownership without
191
- reading unrelated configurations. Conflicting claimants and asset ownership
192
- conflicts also stop without changing schema markers or tickets.
193
- Historical ids, states, timestamps, blockers, comments and asset rows remain
194
- unchanged. Review the named projects and resolve a shared legacy team locally:
195
-
196
- ```sh
197
- ab-hosted-store tickets assign-team ENG https://github.com/acme/app --user owner@example.com
198
- ab-postgres-store migrate
199
- ```
200
-
201
- The assignment command works before the v2 migration succeeds and records the
202
- actor in an append-only journal. The latest assignment moves the whole legacy
203
- team once; it grants no future cross-project access. It must name a registered
204
- project. Rerun migration after resolving every named team or configuration error.
205
-
206
- For populated-v1 upgrades, both the owner migration CLI and `deploy:build` need
207
- the same blob backend, access, credentials and `AB_BLOB_PREFIX` as the running
208
- service: S3 bucket/region/credentials (and endpoint/path style when configured),
209
- or Vercel access mode and token/OIDC store identity. The deployment build inherits
210
- these variables and runs the environment-aware migration before Next build.
211
- Missing blob configuration or denied reads stop deployment before Next builds;
212
- diagnostics never print credentials. SQL-only fresh installs, empty-v1 upgrades
213
- and already-v2 reruns do not open blob storage and keep their existing database
214
- requirements. Migration reruns are idempotent.
215
-
216
- ## Local builds with hosted tickets
217
-
218
- Hosted tickets do not require hosted builds. Set `[tickets] source = "hosted"`
219
- and `teamKey = "ENG"`, then run `ab connect --tickets https://your-service.example`.
220
- Approve the project in the browser. This saves a service-scoped credential and
221
- `[tickets] url` while leaving `[store]` unchanged. Ticket commands work immediately,
222
- before any dispatcher runs. `ab connect` reports every service and whether it serves
223
- builds, tickets, or both. Use `ab disconnect --tickets` to revoke ticket access;
224
- when services differ use `--builds` to select build access. Shared uses share one
225
- credential, so disconnecting either shared use affects both.
226
-
227
- Ticket URL selection is `[tickets] url`, then the selected build service (including
228
- AB_STORE or a supported --store override). With local builds, `[tickets] url` is
229
- required. Builds, events, artifacts, and harvest journals remain in the local store.
230
- The service stores ticket records, project ticket policy, and restricted ticket
231
- grants. Normal project clients synchronize current `[tickets]` policy before use;
232
- failed synchronization fails the operation. Harvest grants can read and create;
233
- phase grants can only read. Neither can change policy or access BuildStore routes.
234
-
235
- New hosted policy defaults to `triage`, `ready`, `doing`, `done`, with creation and
236
- harvest proposals in `triage`. Explicit state names preserve their spelling.
237
- To retain earlier names configure `triageState = "Backlog"`,
238
- `claimedState = "Doing"`, `doneState = "Done"`, and the desired `readyState`.
239
- Existing ticket rows are never renamed. Older combined-service clients continue
240
- using the uploaded dispatcher configuration until independent policy is published.
241
-
242
- ## Integration tree metadata
243
-
244
- Hosted tickets store `kind` (`work` or `node`, default `work`) and optional
245
- `target`, the canonical readable id of a node in the same project. Create accepts
246
- both fields; update and guarded update preserve omitted fields and accept
247
- `target: null` to clear an edge. Targets must exist and be nodes. Self-targets,
248
- ancestor cycles, and demoting a node with targeting tickets (including completed
249
- work) are rejected before any part of a mixed patch is written. Graph mutations
250
- serialize per project in the same transaction as validation and revision checks.
251
- Effective metadata changes increment the revision; equivalent aliases are no-ops.
252
-
253
- Ticket responses include these fields only with `x-autobuild-ticket-tree: 1`.
254
- This capability is independent of revision and comment capabilities and of the
255
- client version. Without it, both fields are projected away, preserving historical
256
- strict decoders. Current hosted clients send all three capability headers and
257
- default absent kind to `work`. Unfiltered listing includes all ticket states and
258
- empty nodes for `ab ticket tree`; dispatch and merge behavior are unchanged.
259
-
260
- ## Reading across upgrades
261
-
262
- Within the advertised client compatibility window, readers with mixed-version
263
- read support tolerate newer build and repository facts. Raw event endpoints
264
- retain unknown types, payload fields and the producer's `compatibility`
265
- metadata (`writerVersion` and `classification`). Known payload fields remain
266
- validated. Adding an advisory field to an existing type is safe; a semantic
267
- change that older kernels must respect requires a new decisive event type.
268
-
269
- Named reduction responses retain exactly `{version, cursor, value}`. The
270
- `x-autobuild-catalog-identity` response header identifies the backend's read
271
- catalog independently of its package release and reducer version. Clients
272
- accept an answer only when that identity, reducer version and finished shape
273
- match their own; otherwise they replay raw events locally through the response
274
- cursor. A missing header from an earlier service also triggers replay. A
275
- service never invents an identity for a backend that supplies none. This keeps
276
- released strict JSON decoders working without a new request capability.
277
-
278
- Unknown advisory facts are counted and skipped. Unknown decisive facts defer
279
- claiming, routing, merge and publication only for their build; status,
280
- context and dashboards remain readable. One `build.compatibility-deferred`
281
- attention fact per decisive boundary appears in the default `ab watch` stream.
282
- Its diagnostic names unsupported types and producer releases: restart with a
283
- build that understands those types. The type names matter even when both
284
- processes report the same package version, as source builds may differ.
285
- Legacy unknown facts lacking metadata are decisive and report that the writer
286
- version is unavailable. Restarting with a reader that understands the facts
287
- clears the guard through replay, without an escalation answer.
288
-
289
- Caches are scoped to the reader's catalog. Replaying a reduction from an
290
- unrecognized reducer version never overwrites its bytes; lower-version snapshot
291
- writes cannot replace higher-version rows even at a later cursor. This
292
- protects both upgrade directions. Readers predating this support still fail
293
- closed; this guarantee does not widen the advertised client window.
294
-
295
-
296
- The retired `AB_WEB_ALLOWED_EMAILS` variable is refused at startup, even if empty.
297
- Replace it with `AB_WEB_SUPER_USER_EMAILS`; review the list because these identities
298
- are deployment maintainers. Bootstrap the first organization through the
299
- [browser management contract](operator-api.md#organization-management-browser),
300
- then add members by email and assign legacy unassigned projects. Super users alone
301
- create orgs, set or clear the single owner, and assign or move projects. Owners
302
- manage their org's members. Removing the last membership or super-user designation
303
- revokes human access on the next request without re-login; existing project
304
- credentials remain valid until revoked.