@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
package/docs/setup.md CHANGED
@@ -32,7 +32,7 @@ maintainer before selecting it:
32
32
  - a dispatcher-side push-capable `GITHUB_TOKEN` or `GH_TOKEN`;
33
33
  - for a private repository, a separate read-only clone identity named by
34
34
  `gitUsernameEnv` and `gitPasswordEnv`;
35
- - an HTTPS hosted service reachable from Vercel, configured through `ab connect <url>`;
35
+ - a remote store that speaks the remote BuildStore protocol and is reachable from Vercel, configured through `ab connect <url>`;
36
36
  - each selected role and alternate's runtime/model, its pinned
37
37
  `[workspace.config.runtimeProvisioning.<runtime>]` commands, and the API
38
38
  credential names it needs in `[workspace.config].environmentVariables`.
@@ -67,8 +67,7 @@ preflight = "test \"$(pi --version)\" = \"0.84.4\" && pi update --models"
67
67
  ```
68
68
 
69
69
  Use a `vercel-ai-gateway/...` Pi model with `AI_GATEWAY_API_KEY` in the
70
- dispatcher environment. Do not copy `~/.pi`, OAuth refresh tokens, or any local
71
- runtime auth state, and do not attempt interactive login in a sandbox. Runtime
70
+ dispatcher environment. For Claude Code, configure [accounts](accounts.md) with a manually provisioned `claude setup-token` credential or a Kimi Code membership key; use the unmodified runtime, your own subscription, and ordinary individual usage. ChatGPT subscription accounts use `bun ab accounts login NAME` on your machine with one dispatcher or hosted refresh owner. Pi and ambient Codex login state are not copied, and interactive sandbox login is unsupported. Runtime
72
71
  names are open: a plugin runtime uses the same strict map, for example
73
72
  `[workspace.config.runtimeProvisioning.opencode]`, with its own immutable
74
73
  install and exact-version preflight commands.
@@ -96,7 +95,10 @@ checkout dependencies in every fresh/replacement sandbox and before the
96
95
  readiness probe, writes the marker only after success, and reruns every
97
96
  preflight before each build runner. A failure names the runtime, selecting
98
97
  role/alternate, and field and starts no agent. Runtime provisioning receives
99
- only the API credentials named by `[workspace.config].environmentVariables`.
98
+ allowlisted legacy API credentials named by
99
+ `[workspace.config].environmentVariables` and automatically supplied placeholders
100
+ for every declared account credential variable. Account variables need no
101
+ allowlist entry; their real credentials remain on the dispatcher host.
100
102
 
101
103
  Keep package-level and checkout-level bootstrap in an idempotent
102
104
  `[commands].setup`. It runs after system provisioning and must remain safe to
@@ -156,7 +158,7 @@ to `workspace.config.provisioning` (or a package dependency to setup) while
156
158
  retaining the universal image; add a runtime credential name to
157
159
  `environmentVariables` and its value to the dispatcher environment; correct the
158
160
  Vercel team/project credential set; provide separate private-clone credentials;
159
- use an HTTPS GitHub origin and hosted Store; authorize the Store token; or commit
161
+ use an HTTPS GitHub origin and remote Store; authorize the Store token; or commit
160
162
  and push the selected base branch.
161
163
 
162
164
  ## Keep per-build records in separate fragments
@@ -183,7 +185,7 @@ shared edit surface; the repository owns the release-time assembly tooling.
183
185
  ## Repository identity is the origin, not a checkout path
184
186
 
185
187
  Repository identity in the Store, dispatcher, `ab builds`, `ab build status`,
186
- `ab repository status`, and the web app is the repository's **normalized origin
188
+ `ab repository status` is the repository's **normalized origin
187
189
  URL** (`https://github.com/owner/repository`), not a checkout's absolute path.
188
190
  Two checkouts of the same repository — on different hosts, or a dispatcher and
189
191
  its sandboxes — agree on one identity.
@@ -245,15 +247,14 @@ sources agree with the running system by construction:
245
247
  runs the dispatcher's own code.
246
248
  - **Origin mode** (checkout-less dispatcher): the guest archive is the release
247
249
  asset `autobuild-<version>.tgz` fetched from the canonical repository at the
248
- **running dispatcher's version** (read from the deployed distribution's
250
+ **running dispatcher's version** (read from the installed distribution's
249
251
  `package.json`), so the guest runs the dispatcher's own release.
250
252
 
251
253
  A service accepts stable and prerelease clients from its own `major.minor`
252
254
  release line and the two preceding minor lines in the same major. A major starts a new family:
253
255
  X.0 accepts only X.0, X.1 accepts X.0/X.1, and X.2 onward accepts three lines.
254
256
  Patch versions are interchangeable in both directions and must never change
255
- the protocol. Upgrade the service first, then projects independently within
256
- its window. Supported release lines retain their wire handlers and known
257
+ the protocol. Keep project clients within the instance’s published window. Supported release lines retain their wire handlers and known
257
258
  protocol identities; an unknown protocol is refused independently of version.
258
259
  Stable and prerelease service and client identities share their numeric major/minor
259
260
  line. Malformed or missing identities, build metadata (`+…`), prefixes and
@@ -274,11 +275,12 @@ It warns and continues when the target is outside the range, naming the
274
275
  required service upgrade for a newer target or a compatible project range for
275
276
  an older one. An unavailable or malformed probe warns that connectivity may
276
277
  fail after upgrade. Legacy health without a range means exact-version matching;
277
- upgrade that service to the compatibility-window release first.
278
+ the hosted instance must publish a compatibility window before clients can
279
+ use release-line compatibility.
278
280
 
279
281
  A distribution fix reaches origin-mode guests after a release is cut and the
280
282
  dispatcher is upgraded. Guests continue to run the dispatcher's own version;
281
- the hosted service must support that release line.
283
+ the instance must support that release line.
282
284
 
283
285
  Provisioning records the installed distribution's identity — package version
284
286
  and remote-store protocol version — in the guest's
@@ -305,29 +307,20 @@ perspective:
305
307
  Local `git-worktree` dispatch keeps working from a checkout exactly as before;
306
308
  apart from the identity change, `ab dispatch` behaves as it did.
307
309
 
308
- ## Hosted deployment variables
309
-
310
- A hosted-store deployment configures its web/auth variables once — see the
311
- hosted service README and the complete environment reference in the pinned
312
- distribution checkout: `BETTER_AUTH_URL`, `AB_WEB_SUPER_USER_EMAILS`,
313
- and the optional `AB_WEB_MCP_RESOURCE` — the protected
314
- resource the hosted MCP server (docs/mcp.md) binds its OAuth tokens to,
315
- defaulting to `<BETTER_AUTH_URL>/mcp`. Set it only when a proxy or custom
316
- domain fronts the deployment under a different public URL than
317
- `BETTER_AUTH_URL`; the value must be an absolute http(s) URL (https in
318
- production) or every MCP client's discovery binds tokens to the wrong
319
- resource.
320
-
321
-
322
310
  ## Connect a project
323
311
 
324
312
  From a checkout with an origin remote, run `ab connect https://YOUR_ORIGIN`.
325
313
  The CLI prints a verification URL and short code and attempts to open a browser.
326
- Sign in as an allowed owner, check the full repository identity and code, and
327
- approve or deny. Another device can open the printed URL, or visit `/connect`
328
- and enter the code. Approval requires the web-enabled service origin; a
329
- standalone machine-only listener cannot present browser consent. Requests
330
- expire after ten minutes. Denial and timeout leave local configuration unchanged.
314
+ The code link opens approval directly; if sign-in is needed, it returns there.
315
+ Check the full repository identity and code, and approve or deny. For an
316
+ unassigned project, choose an eligible organization; a sole option is visibly
317
+ selected. Approval requires that destination even for previously registered
318
+ unassigned projects. Assigned projects show their organization as read-only;
319
+ moving them uses project management. With no eligible organization, approval is
320
+ unavailable until a super user creates one. Another device can open the printed
321
+ URL, or visit `/connect` and enter the code. Approval uses the instance’s browser
322
+ consent endpoint. Requests expire after ten minutes. Denial requires no
323
+ organization choice; denial and timeout leave local configuration unchanged.
331
324
 
332
325
  On approval the service registers the project and issues a project credential.
333
326
  The CLI keeps it in `$XDG_CONFIG_HOME/autobuild/credentials` (or
@@ -359,55 +352,6 @@ saved credential for CI and other non-interactive hosts. A service override
359
352
  never borrows another service's credential. Build and harvest sessions keep
360
353
  their explicit scoped authority.
361
354
 
362
- ## Connected projects
363
-
364
- Migrate PostgreSQL from the pinned release before deploying (`bun run
365
- postgres:migrate`). The service keeps an independent, durable project registry;
366
- existing build or ticket data does not register a project. An administrator
367
- with deployment database credentials manages it without redeploying:
368
-
369
- ```sh
370
- ab-hosted-store projects list
371
- ab-hosted-store projects add https://github.com/owner/project --user owner@example.com
372
- ab-hosted-store projects remove https://github.com/owner/project --user owner@example.com
373
- ```
374
-
375
- From a source checkout, substitute `bun packages/hosted-store-service/src/bin.ts`
376
- for `ab-hosted-store`. Configure `AB_POSTGRES_URL` or `DATABASE_URL` in that
377
- process. Database possession grants administration; `--user` is declared audit
378
- attribution, not a verified login. Ordinary project/store tokens cannot manage
379
- registrations. Each entry records the normalized origin URL, addition time,
380
- and adding identity. SSH git spellings normalize to HTTPS; local paths and
381
- credential-bearing HTTPS URLs are rejected. Duplicate adds preserve metadata;
382
- remove is idempotent, and re-adding records a fresh addition.
383
-
384
- Super users can operate every registered project. Organization members can
385
- operate only active projects assigned to their organizations; legacy unassigned
386
- projects are visible only to super users. Membership is granted by normalized
387
- email, including before first sign-in, and is rechecked on every request. The dashboard,
388
- MCP discovery and calls, and every operator API route consult current
389
- registration. Removal hides a project from all these surfaces and subsequent
390
- hosted dispatcher invocations; builds, events, artifacts and tickets remain,
391
- and re-registration restores access. Already-started work is not cancelled.
392
- Project credentials issued by connect authorize only their registered project. Administrative credential issuance remains available for non-interactive hosts.
393
-
394
- Link directly to `/?repo=<URL-encoded normalized origin>`. The page selects the
395
- first registered origin when the requested one is missing or removed, and an
396
- empty registry shows no project data or controls. Registry errors fail closed;
397
- there is no environment fallback on database failure.
398
-
399
- `AB_WEB_REPOSITORIES` is deprecated. A nonempty CSV is imported exactly once per
400
- database, on the first registry initialization with that variable configured,
401
- with actor `system:AB_WEB_REPOSITORIES`. The import and durable marker commit
402
- atomically across concurrent starts. An absent variable does not consume the
403
- marker. Later restarts or edits to the variable never re-add removed projects;
404
- use the owner commands for subsequent administration.
405
-
406
- The hosted dispatcher queries current registrations on every authorized
407
- invocation. With `AB_DISPATCHER_REPOSITORIES` unset, it serves all registered
408
- projects; an explicit list preserves its order and is intersected with current
409
- registration. An empty registry is a successful zero-project invocation.
410
-
411
355
  ## Authoring an agent verifier
412
356
 
413
357
  A repository-owned agent-verify skill is a verifier, not a reviewer: it drives
@@ -480,45 +424,8 @@ cannot select another project. See [local builds with hosted tickets](#local-bui
480
424
 
481
425
  The service never contacts Linear. Projects with external sources (including
482
426
  file and Linear) keep using those sources directly through their dispatcher;
483
- service ticket HTTP, operator and MCP surfaces refuse with project/source
484
- feedback rather than returning an empty queue. Removed `AB_TICKET_BACKEND` and
485
- `LINEAR_API_KEY` values are ignored with one startup removal message, including
486
- blank/unknown values. Removed `AB_TICKET_TRIAGE_STATE`, `AB_TICKET_READY_STATE`,
487
- `AB_TICKET_DOING_STATE` and `AB_TICKET_DONE_STATE` values are ignored even when
488
- malformed. None of these retired settings prevents startup.
489
-
490
- The environment-aware migration imports `AB_WEB_REPOSITORIES` once before
491
- ownership preflight, including released main-v9 deployments without registry
492
- tables. A failed migration rolls back the import, main-schema promotion and
493
- ticket changes together. Owner `projects add` and `tickets assign-team` commands
494
- bootstrap only the registry/recovery journals and work while the main marker
495
- is still v9. Without the retired environment, first register the intended
496
- project with `ab-hosted-store projects add REPOSITORY --user IDENTITY`, then
497
- assign the team and rerun migration. A successful one-time import is never
498
- reapplied from later environment edits.
499
-
500
- Ticket schema v1 migration assigns each whole legacy team to its sole claimant
501
- among registered projects' latest effective configs, reading their actual blob
502
- bytes. Projects with no dispatcher run or no effective-config reference make
503
- no team claim and do not block other projects. Unclaimed teams still fail closed.
504
- When inferring ownership, a selected configuration whose revision/blob is missing,
505
- unreadable or invalid stops unchanged with recovery guidance. Restore the selected
506
- configuration or assign every remaining legacy team explicitly; complete owner
507
- assignments to registered projects bypass unrelated configuration reads. Conflicts
508
- and asset ownership mismatches also stop unchanged. Resolve ownership, then rerun:
509
-
510
- ```sh
511
- ab-hosted-store tickets assign-team TEAM https://github.com/acme/app --user owner@example.com
512
- ab-postgres-store migrate
513
- ```
514
-
515
- The assignment journal works before v2 assertion, retains the actor, and grants
516
- no future cross-project access. Migration preserves ids, states, comments,
517
- blockers, timestamps and assets. Populated-v1 migration and deployment builds
518
- require the running service's blob backend, access mode, credentials and prefix
519
- (`AB_BLOB_PREFIX`), not just PostgreSQL access. `deploy:build` inherits this
520
- environment and migration failure stops Next build. Fresh databases, empty v1
521
- queues and v2 reruns stay SQL-only and do not initialize blob storage.
427
+ service ticket HTTP and operator surfaces refuse with project/source
428
+ feedback rather than returning an empty queue.
522
429
 
523
430
  ## Local builds with hosted tickets
524
431
 
@@ -591,14 +498,12 @@ Follow [ticket migration](ticket-migration.md), keeping the existing BuildStore
591
498
  and recording continuity before resuming build-related ticket writes.
592
499
 
593
500
 
594
- The retired `AB_WEB_ALLOWED_EMAILS` variable is refused at startup, even if empty.
595
- Replace it with `AB_WEB_SUPER_USER_EMAILS`; review the list because these identities
596
- are deployment maintainers. Open Organizations from the account menu to create
597
- the first organization, then Members to add people by email and choose an owner,
598
- and Projects to assign legacy unassigned projects. The
599
- [browser management contract](operator-api.md#organization-management-browser)
600
- also documents the underlying HTTP routes. Super users alone
601
- create orgs, set or clear the single owner, and assign or move projects. Owners
602
- manage their org's members. Removing the last membership or super-user designation
603
- revokes human access on the next request without re-login; existing project
604
- credentials remain valid until revoked.
501
+ Permanent hosted data removal is available on the web app's Projects page to
502
+ super users and owners of the project's organization. `ab disconnect` only
503
+ revokes a credential; admin `projects remove` only unregisters access and retains
504
+ data. Project deletion removes hosted builds, tickets, blobs, secrets and accounts,
505
+ revokes every credential and retains only a minimal deletion audit. It does not
506
+ change local files or configuration. Failed cleanup is retryable with access
507
+ already refused. Reconnecting requires fresh browser approval and starts empty,
508
+ with hosted ticket numbering reset to 1. See
509
+ [permanent project deletion](operator-api.md#permanent-project-deletion).
@@ -130,3 +130,21 @@ bun ab plugin test ticket-source acme
130
130
  ```
131
131
 
132
132
  Declare tree support only if you keep the [optional tree contract](plugin-authoring.md#optional-ticket-tree-capability) on the same port and harness: exhaustive pagination, canonical targets, revision coverage and atomic rejection.
133
+
134
+ Native paging is an optional API 1.9 ticket-source capability:
135
+ `listPage?(criteria: TicketCriteria, page: TicketPage): Promise<TicketPageListing>`.
136
+ The SDK exports these types; the result is `TicketListing & { total: number }`.
137
+ Criteria retain state, labels (AND), and assignee semantics. The page has a
138
+ nonnegative integer `limit`, optional nonnegative integer `offset` (default 0),
139
+ and optional `order: 'oldest' | 'newest'` (default oldest). Newest reverses the
140
+ entire source order before offset and limit. Total counts all matches, even
141
+ with limit zero or an offset past the end. Records, diagnostics and errors
142
+ match the exhaustive listing. The shared `describeTicketSourceContract` suite
143
+ automatically compares declared native paging with full-read windows.
144
+
145
+ Only paged operator listings select this capability. Sources without it retain
146
+ the full-read/reverse/slice fallback; native errors propagate. Unpaged operator
147
+ listings, CLI ticket lists and dispatcher ready scans remain exhaustive through
148
+ `listReady`/`listAll`. The hosted PostgreSQL source counts matches without
149
+ bodies and reads only the SQL-bounded window. File, Linear and the remote
150
+ `HostedTicketSource` retain fallback; the POST list-ready protocol stays exhaustive.
@@ -96,16 +96,12 @@ bun ab builds --queued
96
96
 
97
97
  See [answering blocked builds](operating.md#answer-and-pause). Preserve event logs; let the kernel manage leases and recovery.
98
98
 
99
- ## Hosted project selection
99
+ ## Remote project access
100
100
 
101
- **Symptom.** A project is missing from connected tools or the dashboard, or hosted dispatch ignores it despite valid credentials.
101
+ **Symptom.** Remote requests refuse a project despite a configured URL.
102
102
 
103
- **Cause.** Registration, allowed-user access, project credentials and dispatcher selection are separate gates.
104
-
105
- - **Registration.** Check the active PostgreSQL project registry; build or ticket data doesn't register a project.
106
- - **Access.** Super users see all active entries; members see only their organizations’ projects; verify sign-in separately from credentials.
107
- - **Administration.** With deployment database credentials, an administrator runs `ab-hosted-store projects list`, `projects add` or `projects remove`. Mutations require `--user IDENTITY` for attribution; project tokens can't administer registrations.
108
- - **Dispatcher selection.** `AB_DISPATCHER_REPOSITORIES` in the hosted dispatch environment selects projects: unset selects every active registration; an explicit ordered list is intersected with current registrations.
109
- - **Dashboard fallback.** With no selection, the dashboard shows the first registered origin.
110
-
111
- Registry errors fail closed.
103
+ Run `bun ab connect` to check the instance, normalized origin and credential.
104
+ Reconnect on this host/user if credentials are missing or rejected. A project
105
+ must be actively registered with the instance; data alone grants no access.
106
+ If access remains refused, give the instance operator the project identity and
107
+ sanitized error. See the [authentication contract](remote-store-protocol.md#7-authentication-and-project-authority).
package/docs/upgrading.md CHANGED
@@ -50,6 +50,6 @@ bun ab dispatch
50
50
  - **One writer.** Don't run old and new dispatchers at once.
51
51
  - **Durable resume.** Work resumes from durable state after a clean stop. Restart doesn't answer escalations.
52
52
  - **Old behavior.** Drain old work before switching if it must keep the old execution behavior; no claim-version switch preserves it.
53
- - **Hosted services.** Upgrade the hosted service before its connected projects, within its compatibility window.
53
+ - **Remote clients.** Check the instance’s `/health` compatibility window before upgrading connected projects.
54
54
 
55
55
  Read [Infrastructure seams](seams.md) and [Repository configuration](configuration-overview.md) before changing infrastructure or merge policy.
@@ -47,7 +47,7 @@ Run `bun ab init`, install and authenticate your runtime, then run `bun ab init
47
47
 
48
48
  Runs build-runners, agents and checks on remote machines. Install `@defrex/autobuild-vercel-sandbox`, register it in `plugins`, and commit your setup and configuration so remote clones see them. Requires:
49
49
 
50
- - an HTTPS hosted BuildStore
50
+ - a remote store that speaks the remote BuildStore protocol over HTTPS
51
51
  - an HTTPS `github.com/owner/repository` origin and `forge = "github"`
52
52
  - a push-capable `GITHUB_TOKEN` or `GH_TOKEN` on the dispatcher (a `gh` login isn't enough)
53
53
  - `VERCEL_TOKEN`, `VERCEL_TEAM_ID` and `VERCEL_PROJECT_ID` on the dispatcher host
@@ -110,9 +110,9 @@ Sandbox preparation order:
110
110
  4. `runtimeProvisioning.<runtime>` installs
111
111
  5. `commands.setup`
112
112
 
113
- - **Runtimes.** Every primary and alternate runtime needs a pinned install and exact-version preflight, and gets only the credentials named in `environmentVariables`; subscription logins aren't copied.
113
+ - **Runtimes.** Every primary and alternate runtime needs a pinned install and exact-version preflight, and gets only the credentials named in `environmentVariables`, except declared [accounts](configuration-overview.md#accounts), whose credentials remain on the host and are brokered by egress policy using guest placeholders.
114
114
  - **Repetition.** New sandboxes repeat provisioning and preflights rerun before each build-runner; keep setup idempotent.
115
- - **Validation.** `bun ab init --validate` runs named provisioning, setup, runtime and Store checks in a disposable environment, deletes it even on failure, and starts no build or agent.
115
+ - **Validation.** `bun ab init --validate` runs named provisioning, setup, runtime and Store checks in a disposable environment, deletes it even on failure, and starts no build. For every declared account, including unused accounts, it runs a tool-free model probe through the account's runtime (Claude Code for Claude/Kimi, Codex for ChatGPT); these probes create no ordinary build phase or persistent agent session. Hosted ChatGPT project secrets report readiness from write-only status metadata instead; the first hosted build is the live check.
116
116
  - **Lifetime.** `timeoutSeconds` bounds a sandbox; provider operations have their own timeouts. An intact sandbox resumes; an expired or lost one is rebuilt from durable workspace and publication evidence, losing unpublished work that lived only on it.
117
117
 
118
118
  ### Private repositories
@@ -126,7 +126,7 @@ export AB_GIT_READ_TOKEN='<read-only repository token>'
126
126
 
127
127
  - Use a repository-scoped read token, separate from the push identity. For a public clone, remove `gitUsernameEnv` and `gitPasswordEnv`.
128
128
  - Autobuild passes these as the authenticated Git source for [Vercel private-repository cloning](https://vercel.com/kb/guide/sandbox-private-github-repositories); don't embed credentials in the origin URL.
129
- - `environmentVariables` is only for runtime API credentials. Never forward `AB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, Vercel tokens or the clone token; Autobuild supplies scoped Store authority, keeps clone secrets out of guest commands, and publishes from the host.
129
+ - `environmentVariables` forwards legacy runtime API credentials; declared account credentials become placeholders even when listed here. Never forward `AB_TOKEN`, `GITHUB_TOKEN`, `GH_TOKEN`, Vercel tokens or the clone token; Autobuild supplies scoped Store authority, keeps clone secrets out of guest commands, and publishes from the host.
130
130
 
131
131
  ## Writing your own
132
132
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -90,6 +90,14 @@
90
90
  "./connection": {
91
91
  "types": "./packages/core/src/connection.ts",
92
92
  "import": "./packages/core/src/connection.ts"
93
+ },
94
+ "./project-secrets": {
95
+ "types": "./packages/core/src/project-secrets.ts",
96
+ "import": "./packages/core/src/project-secrets.ts"
97
+ },
98
+ "./secret-name": {
99
+ "types": "./packages/core/src/secret-name.ts",
100
+ "import": "./packages/core/src/secret-name.ts"
93
101
  }
94
102
  },
95
103
  "files": [
@@ -127,13 +135,13 @@
127
135
  "release": "bun tools/release.ts",
128
136
  "postgres:migrate": "bun packages/postgres-store/src/bin.ts migrate",
129
137
  "docs:configuration": "bun tools/configuration-reference.ts --write",
130
- "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
138
+ "check": "bun tools/biome-check.ts && bun tools/product-name-check.ts && bun tools/docs-asset-check.ts && bun tools/reducer-value-shapes.ts --check && bun tools/configuration-reference.ts --check && bun tools/docs-reference-sync.ts && bun tools/docs-integrity-check.ts && bun tools/skill-docs-asset-check.ts && bun tools/readme-headline.ts --check && bun tools/website-hero.ts --check && bun tools/package-boundary-check.ts",
131
139
  "check:build": "bun tools/workspace-manifest-check.ts && bun tools/bin-mode-check.ts && bun tools/publish-contents-check.ts && bun tools/publish-imports-check.ts",
132
140
  "format:staged": "git-format-staged --formatter './node_modules/.bin/biome format --stdin-file-path {}' '*.js' '*.jsx' '*.ts' '*.tsx' '*.json' '*.jsonc' '*.css' '*.graphql' '*.gql'",
133
141
  "prepare": "husky",
134
142
  "test": "bun tools/test-temp-leaks.ts unit",
135
143
  "test:integration": "bun tools/test-temp-leaks.ts integration",
136
- "typecheck": "tsc --noEmit"
144
+ "typecheck": "node --max-old-space-size=4096 ./node_modules/typescript/bin/tsc --noEmit"
137
145
  },
138
146
  "dependencies": {
139
147
  "@ai-sdk/gateway": "4.0.82",
@@ -141,14 +149,15 @@
141
149
  "@vercel/sandbox": "^3.1.0",
142
150
  "ai": "^7.0.101",
143
151
  "drizzle-orm": "^0.45.2",
152
+ "jose": "^6.2.13",
144
153
  "semver": "^7.7.4",
145
154
  "smol-toml": "^1.7.0",
146
155
  "zod": "^4.4.3"
147
156
  },
148
157
  "devDependencies": {
149
158
  "@biomejs/biome": "2.5.5",
150
- "@defrex/autobuild-postgres-store": "1.1.0",
151
- "@defrex/autobuild-vercel-sandbox": "1.1.0",
159
+ "@defrex/autobuild-postgres-store": "1.2.0",
160
+ "@defrex/autobuild-vercel-sandbox": "1.2.0",
152
161
  "@resvg/resvg-js": "2.6.2",
153
162
  "@types/bun": "^1.3.14",
154
163
  "@types/node": "^24.0.0",
@@ -0,0 +1,216 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { createRemoteJWKSet, jwtVerify, type JWTVerifyGetKey } from 'jose'
3
+ import { chatgptStateSchema, earliestRefreshAt, type ChatGPTState } from './chatgpt-state'
4
+
5
+ const issuer = 'https://auth.openai.com'
6
+ export const CHATGPT_RESOURCE = 'https://api.openai.com/v1'
7
+ const tokenEndpoint = `${issuer}/api/accounts/oauth/token`
8
+ const scopes = 'openid profile email offline_access resource.invoke chatgpt.tokens.use.direct'
9
+ const failure = () => new Error('ChatGPT authorization failed; sign in again')
10
+ type Fetch = typeof globalThis.fetch
11
+ export interface OAuthTransaction {
12
+ state: string
13
+ nonce: string
14
+ verifier: string
15
+ redirectUri: string
16
+ hostId: string
17
+ previous?: ChatGPTState
18
+ }
19
+ export function transaction(
20
+ redirectUri: string,
21
+ hostId: string,
22
+ previous?: ChatGPTState,
23
+ ): OAuthTransaction {
24
+ const random = () => randomBytes(32).toString('base64url')
25
+ return {
26
+ state: random(),
27
+ nonce: random(),
28
+ verifier: random(),
29
+ redirectUri,
30
+ hostId,
31
+ ...(previous ? { previous } : {}),
32
+ }
33
+ }
34
+ export function authorizationUrl(t: OAuthTransaction): string {
35
+ const url = new URL(`${issuer}/api/accounts/authorize`)
36
+ url.search = new URLSearchParams({
37
+ client_id: t.previous?.clientId ?? 'dynamic_agent_client',
38
+ ...(t.previous ? { id_token_hint: t.previous.idToken } : { agent_name_hint: 'autobuild' }),
39
+ ext_agent_host_id: t.hostId,
40
+ response_type: 'code',
41
+ redirect_uri: t.redirectUri,
42
+ resource: CHATGPT_RESOURCE,
43
+ scope: scopes,
44
+ state: t.state,
45
+ nonce: t.nonce,
46
+ code_challenge_method: 'S256',
47
+ code_challenge: createHash('sha256').update(t.verifier).digest('base64url'),
48
+ }).toString()
49
+ return url.href
50
+ }
51
+ export function callback(t: OAuthTransaction, url: URL): { code: string; clientId: string } {
52
+ if (
53
+ url.pathname !== '/auth/callback' ||
54
+ url.searchParams.getAll('state').length !== 1 ||
55
+ url.searchParams.get('state') !== t.state ||
56
+ url.searchParams.has('error')
57
+ )
58
+ throw failure()
59
+ const clientId = url.searchParams.get('client_id') ?? t.previous?.clientId
60
+ const code = url.searchParams.get('code')
61
+ if (
62
+ !code ||
63
+ !clientId ||
64
+ clientId === 'dynamic_agent_client' ||
65
+ (t.previous && clientId !== t.previous.clientId) ||
66
+ url.searchParams.getAll('code').length !== 1 ||
67
+ url.searchParams.getAll('client_id').length > 1
68
+ )
69
+ throw failure()
70
+ return { code, clientId }
71
+ }
72
+ const jwks = createRemoteJWKSet(new URL(`${issuer}/.well-known/jwks.json`), {
73
+ timeoutDuration: 15000,
74
+ })
75
+ export async function verifyIdentity(
76
+ idToken: string,
77
+ clientId: string,
78
+ nonce?: string,
79
+ keys: JWTVerifyGetKey = jwks,
80
+ ): Promise<string> {
81
+ const { payload } = await jwtVerify(idToken, keys, {
82
+ issuer,
83
+ audience: clientId,
84
+ requiredClaims: ['exp', 'sub', ...(nonce ? ['nonce'] : [])],
85
+ algorithms: ['RS256'],
86
+ clockTolerance: 5,
87
+ })
88
+ if (!payload.sub || (nonce !== undefined && payload.nonce !== nonce)) throw failure()
89
+ return payload.sub
90
+ }
91
+ async function request(
92
+ body: URLSearchParams,
93
+ signal: AbortSignal,
94
+ fetcher: Fetch,
95
+ ): Promise<Record<string, unknown>> {
96
+ try {
97
+ const response = await fetcher(tokenEndpoint, {
98
+ method: 'POST',
99
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
100
+ body,
101
+ signal,
102
+ redirect: 'error',
103
+ })
104
+ if (!response.ok) throw failure()
105
+ const text = await response.text()
106
+ if (text.length > 300000) throw failure()
107
+ const value: unknown = JSON.parse(text)
108
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw failure()
109
+ return value as Record<string, unknown>
110
+ } catch {
111
+ throw failure()
112
+ }
113
+ }
114
+ export async function parseTokens(
115
+ raw: Record<string, unknown>,
116
+ registration: {
117
+ hostId: string
118
+ clientId: string
119
+ subject?: string
120
+ nonce?: string
121
+ previous?: ChatGPTState
122
+ },
123
+ verify = verifyIdentity,
124
+ now = Date.now(),
125
+ ): Promise<ChatGPTState> {
126
+ try {
127
+ if (
128
+ typeof raw.access_token !== 'string' ||
129
+ typeof raw.refresh_token !== 'string' ||
130
+ typeof raw.expires_in !== 'number' ||
131
+ !Number.isFinite(raw.expires_in) ||
132
+ raw.expires_in <= 30 ||
133
+ typeof raw.token_type !== 'string' ||
134
+ raw.token_type.toLowerCase() !== 'bearer'
135
+ )
136
+ throw failure()
137
+ const idToken = raw.id_token === undefined ? registration.previous?.idToken : raw.id_token
138
+ if (typeof idToken !== 'string') throw failure()
139
+ const subject =
140
+ raw.id_token === undefined && registration.previous
141
+ ? registration.previous.subject
142
+ : await verify(idToken, registration.clientId, registration.nonce)
143
+ if (registration.subject !== undefined && registration.subject !== subject) throw failure()
144
+ const granted =
145
+ raw.scope === undefined && registration.previous
146
+ ? registration.previous.scopes
147
+ : typeof raw.scope === 'string'
148
+ ? raw.scope.split(/\s+/)
149
+ : []
150
+ const earliest = earliestRefreshAt(raw.earliest_refresh_at)
151
+ return chatgptStateSchema.parse({
152
+ version: 1,
153
+ hostId: registration.hostId,
154
+ clientId: registration.clientId,
155
+ subject,
156
+ scopes: granted,
157
+ accessToken: raw.access_token,
158
+ refreshToken: raw.refresh_token,
159
+ idToken,
160
+ expiresAt: now + raw.expires_in * 1000 - 5000,
161
+ ...(earliest === undefined ? {} : { earliestRefreshAt: earliest }),
162
+ })
163
+ } catch {
164
+ throw failure()
165
+ }
166
+ }
167
+ export async function exchangeCode(
168
+ t: OAuthTransaction,
169
+ url: URL,
170
+ signal: AbortSignal,
171
+ fetcher: Fetch = fetch,
172
+ ): Promise<ChatGPTState> {
173
+ const { code, clientId } = callback(t, url)
174
+ const raw = await request(
175
+ new URLSearchParams({
176
+ grant_type: 'authorization_code',
177
+ client_id: clientId,
178
+ code,
179
+ code_verifier: t.verifier,
180
+ redirect_uri: t.redirectUri,
181
+ resource: CHATGPT_RESOURCE,
182
+ }),
183
+ signal,
184
+ fetcher,
185
+ )
186
+ return parseTokens(raw, {
187
+ hostId: t.hostId,
188
+ clientId,
189
+ nonce: t.nonce,
190
+ subject: t.previous?.subject,
191
+ })
192
+ }
193
+ export async function refreshChatGPT(
194
+ state: ChatGPTState,
195
+ signal: AbortSignal,
196
+ fetcher: Fetch = fetch,
197
+ ): Promise<ChatGPTState> {
198
+ chatgptStateSchema.parse(state)
199
+ if ((state.earliestRefreshAt ?? 0) > Date.now()) throw failure()
200
+ const raw = await request(
201
+ new URLSearchParams({
202
+ grant_type: 'refresh_token',
203
+ client_id: state.clientId,
204
+ refresh_token: state.refreshToken,
205
+ resource: CHATGPT_RESOURCE,
206
+ }),
207
+ signal,
208
+ fetcher,
209
+ )
210
+ return parseTokens(raw, {
211
+ hostId: state.hostId,
212
+ clientId: state.clientId,
213
+ subject: state.subject,
214
+ previous: state,
215
+ })
216
+ }