@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/README.md CHANGED
@@ -26,7 +26,7 @@ From the repository you want built, install Autobuild as a development dependenc
26
26
  <!-- release-install:start -->
27
27
 
28
28
  ```sh
29
- bun add -d --exact @defrex/autobuild@1.1.0
29
+ bun add -d --exact @defrex/autobuild@1.2.0
30
30
  ```
31
31
 
32
32
  <!-- release-install:end -->
@@ -110,19 +110,15 @@ pipeline stays the same.
110
110
  | Seam | Decides | Adapters |
111
111
  | ---------- | --------------------- | ------------------------------------------ |
112
112
  | tickets | where work comes from | local files, Linear, hosted, plugin |
113
- | dispatcher | what starts builds | local process, scheduled (hosted) |
113
+ | dispatcher | what starts builds | local process |
114
114
  | workspace | where a build runs | git worktree, Vercel Sandbox, plugin |
115
115
  | runtime | who does the thinking | Claude Code, Codex, Pi, plugin |
116
116
  | forge | where code merges | local git, GitHub, plugin |
117
- | store | where state lives | SQLite, Postgres, any HTTP store |
118
- | operators | how you watch | terminal, web UI, MCP |
117
+ | store | where state lives | SQLite, remote HTTP store |
118
+ | operators | how you watch | terminal, stdio MCP, Operator API |
119
119
 
120
120
  Plugins are trusted Bun modules declared in `autobuild.toml` against the
121
- versioned `@defrex/autobuild/plugin-sdk`. Teams that want one durable store
122
- across hosts can deploy the optional
123
- [hosted service](packages/hosted-store-service/README.md), which adds a
124
- browser dashboard, a [scheduled dispatcher](docs/hosted-dispatcher.md), an
125
- [operator API](docs/operator-api.md), and an [MCP server](docs/mcp.md).
121
+ versioned `@defrex/autobuild/plugin-sdk`.
126
122
 
127
123
 
128
124
  ## Built for throughput, not latency
@@ -171,8 +167,6 @@ routine escalations, leaving you only the real product calls.
171
167
  configuration, as a worked example of the config surface.
172
168
  - [`docs/architecture.md`](docs/architecture.md) — how the design maps to the
173
169
  codebase: kernel, ports, processes, and stores.
174
- - [`packages/postgres-store/README.md`](packages/postgres-store/README.md) —
175
- serverless PostgreSQL persistence with S3-compatible or Vercel Blob storage.
176
170
  - [`docs/remote-store-protocol.md`](docs/remote-store-protocol.md) — the
177
171
  complete HTTP server contract and BuildStore conformance instructions.
178
172
  - [`SPEC.md`](SPEC.md) — the source of truth for the design and its
@@ -181,5 +175,3 @@ routine escalations, leaving you only the real product calls.
181
175
  ## License
182
176
 
183
177
  [Apache License 2.0](LICENSE).
184
-
185
- Deploy your own store and dashboard with the [hosted service setup](docs/hosted-service.md).
package/SPEC.md CHANGED
@@ -82,6 +82,8 @@ event log handling, state reducer. No I/O opinions — no ticket tracker, no
82
82
  telemetry vendor, no terminal.
83
83
 
84
84
  ### 3.2 Ports
85
+ Ticket sources may optionally provide native `listPage(criteria, page)` windows with a matching total. Paged operator reads use it when present, otherwise slice the exhaustive listing; unpaged and dispatcher reads remain exhaustive.
86
+
85
87
 
86
88
  Interfaces to the world, each with swappable adapters:
87
89
 
@@ -239,6 +241,21 @@ The versioned v1 launch contract consists of argv, a consumed one-shot
239
241
  `AB_DISPATCH_GENERATION` marker, graceful signals and exit reasons `stopped`,
240
242
  `handoff`, `failed`. Public invocations discard inherited markers. No private
241
243
  operational channel exists; work outcomes still come only from durable state.
244
+ The runtime-owned `--read-upgrade` reader supports an optional independently
245
+ versioned conditional environment exchange, preserving full v1 answers for old
246
+ peers. The launcher retains only its current successful answer and pre-read
247
+ repository change position per exact reader/runtime, journal, run, lineage and
248
+ recovery query. Each unchanged check makes one change-position request and reads
249
+ zero metadata, reducer values or event rows, regardless of journal length or a
250
+ fresh helper process. Full refresh samples the position before the projection;
251
+ a concurrent append therefore invalidates the next check. Unchanged checks
252
+ revalidate cached target identity and rollback retention locally, without
253
+ manufacturing durable facts. Errors discard conditional state; an unloadable
254
+ target still uses the healthy predecessor reader with the active query. The
255
+ launcher retains its filesystem/process-only boundary and polling cadence of
256
+ 1 second idle or 250 ms pending, processing child exits and pending actions on
257
+ cached answers too. Legacy peers remain functional with full reads.
258
+
242
259
  The launcher observes presentation stop/continue liveness so Ctrl-Z returns the
243
260
  shell prompt and `fg` resumes only the presentation; the kernel keeps running.
244
261
  Terminal restoration by the launcher is a fallback for abnormal termination,
@@ -988,7 +1005,8 @@ projects. Members can inspect their own organization’s active projects and ros
988
1005
  including emails and persisted identity names/joined status. Owners can manage
989
1006
  their own members but cannot remove themselves.
990
1007
  Creation does not make the super user a member. Legacy projects remain unassigned
991
- and visible only to super users until assigned. Admission and repository authority
1008
+ and visible only to super users until management assignment or an authorized
1009
+ reconnect approval assigns them. Admission and repository authority
992
1010
  are checked from current state on every browser request and MCP tool callback.
993
1011
  Removed members lose access immediately without re-login. Machine project,
994
1012
  delegated, internal and admin credentials retain their existing boundaries.
@@ -1297,8 +1315,12 @@ tokens are rejected with migration guidance. An explicit versioned owner-only
1297
1315
  break-glass admin is the sole machine cross-project exception. Internal signed
1298
1316
  owner delegation is short-lived, repository-bound and operator-only. The hosted
1299
1317
  dispatcher issues stored credentials with immutable dispatcher purpose (raw
1300
- store and tickets only) per invocation and keeps them valid through configured
1301
- expiry. Already issued delegated grants do not depend on that parent expiry.
1318
+ store and tickets only) per repository invocation. It deletes each credential on
1319
+ completion, including failures. Crash-safety expiry is the earlier of the configured
1320
+ TTL upper bound and the invocation deadline plus 60 seconds. Each served tick
1321
+ prunes at most 100 expired or revoked dispatcher rows using indexed probes;
1322
+ unexpired legacy rows retain their recorded expiry before eventual pruning.
1323
+ Already issued delegated grants do not depend on the parent row or its expiry.
1302
1324
  Owner-issued project credentials attribute operator writes to their recorded
1303
1325
  creator. Agents never receive the dispatcher's project credential. Delegated
1304
1326
  reads retain access to same-project repository state; build mutations target only
@@ -1729,6 +1751,16 @@ nonblank `AB_STORE`, `[store] url`, then local state. `AB_TOKEN` overrides saved
1729
1751
  credentials. Configured services without credentials fail closed. Connection
1730
1752
  commands require a network origin and are unavailable in phase sessions.
1731
1753
 
1754
+ A valid browser code link opens approval directly, returning there after sign-in
1755
+ when needed; missing or malformed codes retain entry. Approval always shows the
1756
+ organization. Assigned projects show a read-only name and cannot move during
1757
+ approval. Every unassigned approval requires an explicit eligible organization
1758
+ ID, including fresh, legacy and removed projects, even for super users. A sole
1759
+ choice is visibly selected; multiple choices require selection; no choices block
1760
+ approval. Assignment, registration, credential and approval commit atomically
1761
+ after current access checks. Retained unassigned history remains super-user-only
1762
+ until assignment. Denial requires no organization and changes no assignment.
1763
+
1732
1764
 
1733
1765
  ## 9. AgentRunner
1734
1766
 
@@ -2140,7 +2172,11 @@ The fixed workflow is:
2140
2172
  nonbinding ordering do not become blockers. A fresh reviewer checks
2141
2173
  coverage, semantic dedup, spec quality, evidence, and both directions of
2142
2174
  that prerequisite rule. Only approval advances.
2143
- 3. **file (deterministic)** — refresh the selected TicketSource lifecycle for
2175
+ 3. **file (deterministic)** — refresh ledger existence and resolution before
2176
+ deciding join eligibility; scan-time lifecycle facts are context only. Each
2177
+ same-source ledger ticket uses one fresh provider lookup, with hosted alias
2178
+ resolution sharing that response. Missing, resolved, and foreign-source
2179
+ ledger tickets cannot be joined. Refresh the selected TicketSource lifecycle for
2144
2180
  every declared blocker and same-source ticket that originated a create's
2145
2181
  clustered observations. Unknown agent-declared ids fail filing; missing,
2146
2182
  resolved, foreign-source, and absent origins contribute nothing. The created
@@ -2880,12 +2916,15 @@ read-decoder revision. Named and generic checkpoints use catalog-specific keys;
2880
2916
  legacy/foreign-catalog snapshots are misses and are preserved. Unrecognized
2881
2917
  reducer versions replay without repairing their cache. No lower-version write
2882
2918
  replaces a higher-version row, even at a later cursor. Corrupt caches of the
2883
- reader's own version may be conditionally repaired. Hosted named answers require
2884
- matching version, catalog identity and locally valid finished shape; otherwise
2885
- the client replays raw events locally through the returned cursor without
2886
- writing the service cache. Catalog identity travels in response header
2887
- `x-autobuild-catalog-identity`; strict JSON bodies remain exactly
2888
- `{version, cursor, value}`. Missing/malformed headers also trigger local replay.
2919
+ reader's own version may be conditionally repaired. Hosted named answers are canonical: the client accepts a representable finished
2920
+ value at its reducer version regardless of catalog identity. Version mismatches,
2921
+ invalid envelopes and invalid finished values fail with a typed incompatibility
2922
+ error naming the reducer and client/server versions. Remote clients never
2923
+ reconstruct named answers from event logs. Catalog identity travels in response
2924
+ header `x-autobuild-catalog-identity`; strict JSON bodies remain exactly
2925
+ `{version, cursor, value}`. Missing/malformed headers do not reject an answer.
2926
+ Repository digest batches are also canonical, with no client discovery or
2927
+ per-build fallback.
2889
2928
  A service omits identity for a backend without one. This guarantee excludes
2890
2929
  readers predating this contract and does not widen the supported client window.
2891
2930
 
@@ -4151,3 +4190,94 @@ Shared requests are attributed to their first requester; cache hits count zero.
4151
4190
  A failed node verification cycle records `integration.verification-failed` with its prepared cycle id, failed steps, exact head and parent, and guidance to file a repair child targeting the node. The kernel reports durable failed receipts; dispatcher housekeeping recovers missing reports for the current cycle using a per-cycle CAS guard. Superseded cycles are never backfilled with repair instructions: recovery requires the latest prepared cycle to match the node’s observed head and parent. This fact is decisive evidence and bookkeeping, and does not change verification or leaf routing.
4152
4191
 
4153
4192
  Default `ab watch` includes this event. Watch cursors deliver each failed cycle once and baseline failures when first armed; reconcile build status after arming. `ab wait --for attention` also detects a current failed node cycle before the report is written. Historical facts remain queryable after repair without retaining current attention. Explicit event globs and existing stored wake choices are preserved.
4193
+
4194
+
4195
+ ### Project secrets
4196
+
4197
+ Project secrets are product-managed write-only project environment values,
4198
+ separate from machine credentials and BuildStore artifacts. A connected member's
4199
+ saved owner credential can list metadata, set/replace and remove; every operation
4200
+ revalidates project membership. Build, dispatcher, delegated, internal and admin
4201
+ credentials cannot manage them. The current setter is the owner; values serve all
4202
+ builds of the project. Values and refresh/access state are authenticated-encrypted
4203
+ under a deployment-held key; audit records contain only actor, time and operation.
4204
+ No public surface returns material. Authority and process-control names are reserved.
4205
+
4206
+ Every hosted tick resolves a coherent complete set, overlays project values onto
4207
+ its own deployment environment, and records revision-fenced supply timestamps at
4208
+ kernel handoff. Encryption keys are excluded from child environments. A failed
4209
+ resolution prevents intake and launches for that project. If ready credentials can
4210
+ be read and revision-fenced, an observation-only recovery pass supplies them solely
4211
+ to repair running execution policies, withholding unavailable names. Unrelated
4212
+ account transforms remain active; no janitor, resume, lease-sweep, or harvest work
4213
+ is launched. If the ready subset cannot be read, the project is skipped. Projects without secrets
4214
+ resolve and hand off an empty set without encryption configuration; all secret
4215
+ mutations still require a valid key. Adding a secret invalidates an earlier empty
4216
+ snapshot before handoff. Local dispatch behavior
4217
+ is unchanged. Refresh kinds serialize external rotation with a committed CAS
4218
+ attempt, persist replacement state before delivery, and fail expired attempts
4219
+ without takeover. A failed credential requires explicit replacement. Valid
4220
+ credentials before their earliest refresh time remain usable, even inside a
4221
+ requested future validity horizon. The first eligible five-minute hosted tick
4222
+ refreshes and persists rotation before supply, including expired access state
4223
+ after downtime when the refresh credential remains ready. Providers without an
4224
+ earliest refresh time use a ten-minute pre-expiry margin. Failed or uncertain
4225
+ refresh attempts prevent supply. A refresh window shorter than five minutes plus a one-minute
4226
+ margin emits typed advisory metadata, never invalidates a valid credential and
4227
+ never causes revocation. The public
4228
+ CLI writes static values or typed ChatGPT registrations. The fifth web tab,
4229
+ Settings, lets any project organization member or super user inspect metadata
4230
+ and account credential slots, set static values, and remove secrets. Browser
4231
+ writes use the unexpired cookie session and fresh project membership, attribute
4232
+ the normalized signed-in email, and require same-origin JSON. Browser replacement
4233
+ atomically refuses non-static credentials; renewing those stays in
4234
+ `ab accounts login <account> --project`. Password fields are transient and clear
4235
+ on acknowledgment; reads never refill them. Removal requires the shared
4236
+ confirmation dialog. Secret management remains available without recorded
4237
+ dispatcher configuration. See the project-secrets section of the remote-store protocol.
4238
+
4239
+ ### Named billing accounts
4240
+
4241
+ Deployment-owned `[accounts.<name>]` descriptors contain `kind` and
4242
+ `credentialEnv`, plus the closed Kimi `region` (`overseas` by default or `china`).
4243
+ Role and alternate `account` axes inherit independently. Claude routes default
4244
+ to the sole Claude subscription account; ambiguity, unknown references and
4245
+ incompatible runtimes fail configuration. No accounts preserves legacy behavior.
4246
+ Claude and Kimi accounts require the unmodified Claude Code runtime; ChatGPT
4247
+ subscription accounts require explicit Codex selection. Use the user's own plan
4248
+ for ordinary individual usage. Claude and Kimi credentials are provisioned
4249
+ manually. ChatGPT credentials are authorized with `ab accounts login NAME
4250
+ [--local|--project]`. The local dispatcher or hosted refreshing project secret
4251
+ is the sole refresh owner; no sandbox refreshes. Local Codex uses a protected
4252
+ loopback inference transport and isolated CODEX_HOME, preserving the shell HOME
4253
+ and leaving ambient login untouched.
4254
+ Hosted validation uses write-only metadata and states that the first hosted
4255
+ build is the live check; local validation makes a minimal runtime request.
4256
+
4257
+ Local sessions resolve host credentials after ambient merging. Remote sessions
4258
+ receive account placeholders; exact provider hostname and placeholder header
4259
+ matches broker real credentials on the host. Both Kimi endpoint and host derive
4260
+ from one closed regional mapping, without cross-region retry. Observation ticks
4261
+ refresh the live egress policy from dispatcher environment values. Selected
4262
+ account descriptors persist with sessions for continuation; configuration and
4263
+ launch artifacts contain no secret values. Credential rejections require renewal
4264
+ and bypass alternates; quota and availability retain existing fallback behavior.
4265
+ Account secrets are redacted at persistence boundaries, including split streamed
4266
+ deltas and prior values retained across rotation.
4267
+
4268
+
4269
+ ### Hosted project deletion
4270
+
4271
+ The Projects web surface allows super users and organization owners to preview
4272
+ counts and permanently delete their authorized projects with the shared confirmation dialog.
4273
+ PostgreSQL fences the registration generation before physical blob cleanup and
4274
+ retains durable pending inventory for restart/retry. Upload ownership is reserved
4275
+ in a separate committed transaction before provider I/O; transaction-scoped shared
4276
+ blob locks cover upload/publication, and exclusive locks cover reference checks
4277
+ and physical deletion. Other projects' references and reservations preserve shared
4278
+ bytes. Completion removes all project rows except repository, actor, deletion time
4279
+ and an opaque generation id in the deletion audit. Old credentials receive 401;
4280
+ repository-established requests receive 403 project not registered. Approval of a
4281
+ fresh connection starts empty and resets hosted ticket numbering. `ab disconnect`
4282
+ revokes credentials only; admin `projects remove` unregisters without purging.
4283
+ See [project deletion protocol](docs/operator-api.md#permanent-project-deletion).
@@ -4,19 +4,26 @@ import { cachedRuntime } from '../packages/core/src/cli/dispatch-runtime-cache'
4
4
  import { distributionRoot } from '../packages/core/src/distribution'
5
5
  import {
6
6
  consumeGenerationMarker,
7
+ consumeUpgradeCondition,
8
+ DISPATCH_CONDITIONAL_ENV,
7
9
  GENERATION_EXITS,
8
10
  DISPATCH_LAUNCH_CONTEXT_ENV,
9
11
  } from '../packages/core/src/cli/dispatch-launch-contract'
10
12
  import { watchDispatchParent } from '../packages/core/src/cli/dispatch-parent-watch'
11
13
  let code: number = GENERATION_EXITS.failed
14
+ const readerMode = process.argv[2]?.startsWith('--read-') ?? false
12
15
  let presentationOwner = process.argv[2] !== '--preflight'
13
16
  try {
17
+ const condition =
18
+ process.argv[2] === '--read-upgrade' ? consumeUpgradeCondition(process.env) : undefined
19
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
14
20
  const launch = consumeGenerationMarker(process.env, distributionRoot())
15
21
  if (!(await cachedRuntime(launch.runtimeRoot)))
16
22
  throw new Error('dispatcher generation requires a completed cached runtime')
17
23
  const { loadDotEnv } = await import('../packages/core/src/cli/dotenv')
18
24
  const { join } = await import('node:path')
19
25
  loadDotEnv(join(launch.checkout, '.env'), process.env)
26
+ delete process.env[DISPATCH_CONDITIONAL_ENV]
20
27
  const { readHandoff } = await import('../packages/core/src/cli/dispatch-handoff')
21
28
  if (process.argv[2] === '--read-journal') {
22
29
  const { readGenerationJournal } = await import('../packages/core/src/cli/dispatch-handoff')
@@ -33,7 +40,9 @@ try {
33
40
  if (process.argv[2] === '--read-upgrade') {
34
41
  const { readUpgradeProjection } = await import('../packages/core/src/cli/dispatch-handoff')
35
42
  console.log(
36
- JSON.stringify(await readUpgradeProjection(launch, process.argv.slice(3), process.env)),
43
+ JSON.stringify(
44
+ await readUpgradeProjection(launch, process.argv.slice(3), process.env, { condition }),
45
+ ),
37
46
  )
38
47
  process.exit(0)
39
48
  }
@@ -87,7 +96,7 @@ try {
87
96
  watch.close()
88
97
  }
89
98
  } catch (error) {
90
- if (presentationOwner && ownsDispatchPresentation())
99
+ if (readerMode || (presentationOwner && ownsDispatchPresentation()))
91
100
  console.error(error instanceof Error ? error.message : String(error))
92
101
  }
93
102
  process.exit(code)
@@ -0,0 +1,119 @@
1
+ # Billing accounts
2
+
3
+ Named accounts select billing for Claude Code or Codex, using the user's own
4
+ subscription within ordinary individual usage. Claude and Kimi credentials are
5
+ provisioned manually; Autobuild never runs `claude setup-token`. ChatGPT
6
+ accounts use OpenAI's browser authorization through the CLI.
7
+
8
+ ```toml
9
+ [accounts.personal]
10
+ kind = "claude-subscription"
11
+ credentialEnv = "CLAUDE_CODE_OAUTH_TOKEN"
12
+
13
+ [accounts.kimi]
14
+ kind = "kimi-code"
15
+ credentialEnv = "KIMI_CODE_KEY"
16
+ region = "overseas"
17
+
18
+ [accounts.kimi-china]
19
+ kind = "kimi-code"
20
+ credentialEnv = "KIMI_CHINA_KEY"
21
+ region = "china"
22
+
23
+ [roles.implement]
24
+ runtime = "claude"
25
+ account = "kimi"
26
+ model = "kimi-for-coding"
27
+ ```
28
+
29
+ `account` inherits independently on roles and alternates. Without an explicit
30
+ selection, a Claude route chooses the sole Claude subscription account; multiple
31
+ subscription accounts require an explicit selection. ChatGPT accounts require explicit selection on Codex; Claude and Kimi accounts
32
+ require Claude Code. Incompatible runtime selections are rejected. Repositories with no accounts retain legacy authentication.
33
+ Locally a Claude subscription can use its named token or the host login; Kimi
34
+ requires its membership key. Invalid credentials need renewal (`claude setup-token`
35
+ for Claude, replacement membership key for Kimi); quota and overload failures
36
+ retain alternate fallback.
37
+
38
+ Choose the region of your Kimi membership. The default `overseas` selects
39
+ `https://api.kimi.ai/coding/`; `china` selects `https://api.kimi.com/coding/`.
40
+ The base URL and egress hostname are fixed together and cannot be overridden
41
+ independently. There is no cross-region retry or assertion that keys work across
42
+ regions. Claude Code keeps its native User-Agent.
43
+
44
+ In Vercel Sandbox the guest holds stable nonsecret placeholders, including when
45
+ credential variables are explicitly allowlisted. The host egress policy replaces
46
+ an exact account placeholder header only on its provider's exact hostname.
47
+ The next dispatcher observation tick refreshes credentials for subsequent
48
+ requests without reprovisioning. Changing a local dispatcher's `.env` still needs
49
+ a restart. Accounts are deployment-owned descriptors; configuration artifacts
50
+ contain variable names, never values. Validation reports host credential presence
51
+ and makes one minimal request using each account's actual runtime, including
52
+ unused accounts, in the disposable sandbox. Hosted ChatGPT credentials use the
53
+ metadata readiness boundary described below.
54
+
55
+
56
+ ## ChatGPT subscriptions
57
+
58
+ ChatGPT Plus and Pro are eligible for [Sign in with ChatGPT](https://developers.openai.com/siwc/quickstart).
59
+ Authorization grants plan usage for eligible Responses requests; it does not
60
+ grant access to ChatGPT conversations. Included usage is shared with the plan
61
+ and other authorized apps. Plan exhaustion retains configured alternate fallback.
62
+
63
+ ```toml
64
+ [accounts.chatgpt]
65
+ kind = "chatgpt-subscription"
66
+ credentialEnv = "CHATGPT_ACCESS_TOKEN"
67
+
68
+ [roles.implement]
69
+ runtime = "codex"
70
+ account = "chatgpt"
71
+ ```
72
+
73
+ Run `bun ab accounts login chatgpt --local` on your own machine for a local
74
+ dispatcher, or `bun ab accounts login chatgpt --project` for a connected
75
+ project. Without a destination flag, connected projects choose project storage;
76
+ others choose local storage. The destination is shown before the browser opens.
77
+ OpenAI handles consent and authorization. No token is printed.
78
+
79
+ Local credentials live in protected, ignored main-checkout
80
+ `.autobuild/accounts/` state shared by worktrees. Project sign-in transfers
81
+ credentials directly to the encrypted refreshing project secret named by
82
+ `credentialEnv`; it retains no renewable credential locally. This name
83
+ identifies a host access-token slot, not a refresh token supplied in TOML.
84
+ ChatGPT accounts must use slots distinct from every other account. Existing
85
+ ChatGPT descriptors cannot change during live configuration reload; stop dispatch
86
+ before replacing a descriptor, or introduce a new account name.
87
+
88
+ The stable opaque host identifier belongs to the destination; the issued
89
+ client identifier belongs to the authorized ChatGPT registration. Reauthorization
90
+ keeps identity and registration associated. Never copy the ambient Codex login.
91
+
92
+ Exactly one owner refreshes each connection: the local dispatcher or the
93
+ hosted refreshing secret. Credentials rotate atomically before delivery. Expired access tokens remain
94
+ refreshable after dispatcher downtime; a live validator or dispatcher claim
95
+ cannot be displaced. Only a proven dead process or a released claim permits
96
+ a successor to own renewal.
97
+ Sandboxes hold stable placeholders; only an exact bearer match on
98
+ `api.openai.com` receives the current access token at egress. Local Codex uses
99
+ an isolated CODEX_HOME and a capability-protected loopback Responses forwarder which
100
+ reads current durable state and never refreshes. The shell HOME stays intact
101
+ for Git identity and other operator tools. Missing sandbox credentials revoke
102
+ only their egress transforms; unrelated routes keep running. If hosted secret
103
+ resolution fails, intake and new execution launches wait for recovery. A
104
+ revision-fenced observation-only pass uses ready credentials to repair running
105
+ policies; if those credentials cannot be read, the project is skipped. A failed policy
106
+ update stops the sandbox because revocation could not be confirmed.
107
+
108
+ A failed or uncertain refresh is terminal for that credential generation.
109
+ Sign in again with `bun ab accounts login chatgpt` for the same destination;
110
+ do not retry the old refresh token. Token rejection raises account-specific
111
+ attention rather than an alternate or retry loop.
112
+
113
+ For local credentials, `bun ab init --validate` checks the owner and current
114
+ credential and makes a minimal Codex request. Validation uses a temporary
115
+ exclusive ownership claim only when no dispatcher owns the record. For hosted
116
+ project credentials it uses write-only metadata: presence, owner, set time,
117
+ refresh status and any refresh-window warning. It never downloads tokens.
118
+ **The first hosted build is the live check.** A short refresh-window warning is
119
+ advisory and does not revoke a still-valid credential.
@@ -16,11 +16,11 @@ A runtime transports agent turns: it starts, continues, cancels and ends session
16
16
 
17
17
  Install with `bun add -d --exact @defrex/autobuild`. Examples are complete minimal configs for local execution: install and authenticate the CLI on the dispatcher host, then run `bun ab init --validate`.
18
18
 
19
- A subscription login is host state and doesn't reach a remote sandbox. Remotely, provision every selected runtime and alternate and forward only API credentials; see [Workspaces](workspaces.md).
19
+ Claude Code supports named subscription and Kimi Code billing [accounts](configuration-overview.md#accounts). In a remote sandbox, the guest holds placeholders and host egress policy supplies credentials only to the selected provider. Use the unmodified runtime with your own subscription for ordinary individual usage. Provision every selected runtime and alternate; Pi retains its existing authentication. Codex can explicitly select a ChatGPT subscription account; see [billing accounts](configuration-overview.md#accounts). See [Workspaces](workspaces.md).
20
20
 
21
21
  | Runtime | Models | Model ids | Default model |
22
22
  |---|---|---|---|
23
- | `claude` | Anthropic, via Claude Code | `claude-` family | the CLI's default |
23
+ | `claude` | Anthropic or a selected Kimi Code account, via Claude Code | `claude-` family; Kimi membership IDs with a Kimi account | CLI default; `kimi-for-coding` for Kimi |
24
24
  | `codex` | OpenAI, via the Codex CLI | `gpt-` family | the CLI's default |
25
25
  | `pi` | many providers | `provider/model` | `kimi-coding/k3` |
26
26
 
@@ -28,7 +28,7 @@ Set the model with the role's `model` field, not in `args`; the adapter owns mod
28
28
 
29
29
  ### Claude Code (`claude`)
30
30
 
31
- Install `claude` ([setup](https://code.claude.com/docs/en/setup)) and log in. API-backed environments need a provider credential such as `ANTHROPIC_API_KEY`, not copied login state; see [Claude authentication](https://code.claude.com/docs/en/authentication).
31
+ Install `claude` ([setup](https://code.claude.com/docs/en/setup)) and log in. Remote environments can select a declared subscription or Kimi Code account; legacy API routes can use `ANTHROPIC_API_KEY`. Host login files are not copied; see [Claude authentication](https://code.claude.com/docs/en/authentication).
32
32
 
33
33
  <!-- seam-config:start -->
34
34
  ```toml
@@ -43,7 +43,7 @@ runtime = "claude"
43
43
 
44
44
  ### Codex (`codex`)
45
45
 
46
- Install `codex` ([CLI instructions](https://developers.openai.com/codex/cli)) and run `codex login`. API use needs its own credential, commonly `OPENAI_API_KEY`, with billing authority; see [Codex authentication](https://developers.openai.com/codex/auth).
46
+ Install `codex` ([CLI instructions](https://developers.openai.com/codex/cli)). Legacy routes use `codex login`; named ChatGPT subscription routes use `bun ab accounts login NAME` and leave that ambient login untouched. API use needs its own credential, commonly `OPENAI_API_KEY`, with billing authority; see [Codex authentication](https://developers.openai.com/codex/auth).
47
47
 
48
48
  <!-- seam-config:start -->
49
49
  ```toml
@@ -111,7 +111,7 @@ workspace validates its environment,
111
111
  serves health without touching persistence, and lazily retains one
112
112
  `openPostgresBuildStoreFromEnv` promise per warm process. Its Fetch handler has
113
113
  no Vercel branch; the package's `server.ts` is the sole `Bun.serve()` composition point.
114
- The fixed 1 MiB decoded artifact policy is enforced before backing mutation.
114
+ The fixed 2.5 MiB decoded artifact policy is enforced before backing mutation.
115
115
  The `ab-hosted-store` binary signs admin or build/session tokens offline from
116
116
  `AB_STORE_SECRET`; the running service exposes no mint endpoint. Machine routes
117
117
  and later server-session human routes intentionally share one deployment.
@@ -180,15 +180,18 @@ project known payloads before adapting selector rows, while build and repository
180
180
  facts retain compatibility counts across incremental resumes. Unknown facts
181
181
  still advance sequence cursors. `kernel/mixed-version.ts` guards affected build
182
182
  decisions and deduplicates the default-watch attention fact. Other builds and
183
- read-only queries continue. The [hosted upgrade guarantee](hosted-service.md#reading-across-upgrades)
183
+ read-only queries continue. The [hosted upgrade guarantee](remote-store-protocol.md)
184
184
  describes recovery and the supported-window boundary.
185
185
 
186
186
  All event-derived checkpoints include the combined read-catalog fingerprint in
187
187
  their keys, independently of numeric reducer versions. Snapshot envelopes validate
188
188
  that fingerprint; another catalog's rows remain untouched. Remote named values
189
- use `x-autobuild-catalog-identity` for cache acceptance, keeping their strict
190
- three-field JSON body unchanged. Missing or mismatching identity, version or
191
- finished shape causes bounded local replay without a remote cache write.
189
+ are canonical regardless of `x-autobuild-catalog-identity`, keeping their strict
190
+ three-field JSON body unchanged. A reducer version mismatch, invalid envelope or
191
+ unrepresentable finished shape raises `ReducerValueIncompatibilityError` with
192
+ client/server versions and validation detail. No remote named read replays events.
193
+ Repository digest batches likewise return the server batch with one scoped
194
+ request and no discovery or per-build fallback.
192
195
 
193
196
  **Named reducer values.** `BuildStore.getReducerValue(scope, {reducer, args?})`
194
197
  returns `{version, cursor, value}` for each eligible entry in the executable
@@ -464,6 +467,20 @@ The runtime-owned `dispatch-handoff.ts` reader lets the filesystem-only launcher
464
467
  supervise overlapping generations without owning Store or config decisions.
465
468
  A runtime-owned repository-record projection binds the journal transport before
466
469
  initial spawn and across handoffs, including when later config edits are invalid.
470
+ The optional conditional `--read-upgrade` environment extension in
471
+ `dispatch-launch-contract.ts` is versioned independently of launch/overlap v1.
472
+ The launcher caches only the current successful projection, guard inputs and
473
+ pre-read position for each exact runtime/journal/run/lineage/recovery query.
474
+ `dispatch-handoff.ts` checks `getRepoChangePosition` before any metadata or
475
+ reducer reads on a bound query: unchanged helpers make one request and read zero
476
+ event rows, including with cold process/store facades. Changed helpers share one
477
+ store handle and attach the earlier position, so concurrent appends invalidate
478
+ the following check. Durable handoff selection is separate from local target
479
+ identity and rollback-retention guards, which run on every check. Errors clear
480
+ conditional state; a separate predecessor-reader cache uses the active run's
481
+ journal context when the target cannot load. Old peers keep full v1 responses.
482
+ Polling stays at 1 second idle / 250 ms pending, and cached projections still
483
+ pass through ordinary child-exit, pending-preflight and recovery handling.
467
484
  `dispatch-frontend.ts` acknowledges terminal release only after joining input
468
485
  and rendering. The old kernel releases repository authority but retains local
469
486
  execution supervision until completion or the hot policy deadline. Build-log
@@ -1208,7 +1225,7 @@ metadata, not ordering. Runtime opens assert schema and never run DDL.
1208
1225
  The service exposes one lazy live reader to the operator server, web gateway,
1209
1226
  MCP and server-rendered repository picker. Initialization failures clear the
1210
1227
  cached promise for retry. The dispatcher opens its own shared pool and queries
1211
- membership each invocation. See [owner workflow](setup.md#connected-projects).
1228
+ membership each invocation. See [owner workflow](remote-store-protocol.md#7-authentication-and-project-authority).
1212
1229
 
1213
1230
  ## Delegated execution authority
1214
1231
 
@@ -1240,9 +1257,13 @@ Service requests reread durable state; detached executions need neither renewal
1240
1257
  secrets nor their original dispatcher. Local stores retain their existing path.
1241
1258
  Project onboarding uses `cli/connect.ts`, user-level `cli/project-credentials.ts`,
1242
1259
  the shared `connection.ts` wire types, and Postgres `connections.ts`. Approval
1243
- commits registry membership, a credential digest, and the outcome atomically.
1260
+ commits registry membership, organization assignment, a credential digest, and
1261
+ the outcome atomically. Assignment classification is independent of registry
1262
+ history; every unassigned approval requires an explicit eligible organization.
1244
1263
  The web connection routes authenticate the existing Better Auth session and
1245
- reuse the sign-in/consent layout; CLI polling uses a separate private capability.
1264
+ reuse the sign-in/consent layout. Valid code links look up approval immediately,
1265
+ including on return from sign-in; the view shows selected destinations or the
1266
+ read-only assigned organization. CLI polling uses a separate private capability.
1246
1267
 
1247
1268
  ## Revision-checked ticket writes
1248
1269
 
@@ -1668,3 +1689,81 @@ Dashboard destination distance is projected from durable `target.distance`
1668
1689
  are `+N`, empty when current, and `+?` when unknown, suppressed after merge or
1669
1690
  close. Terminal headers reserve space for the destination before the slug;
1670
1691
  web views keep their own layout and share the wording.
1692
+
1693
+
1694
+ ## Project-secret boundary
1695
+
1696
+ `packages/core/src/project-secrets.ts` owns the write-only DTO; browser-safe reserved-name
1697
+ rules and the shared public explanation live in `packages/core/src/secret-name.ts`. `packages/postgres-store/src/project-secrets.ts` stores authenticated encrypted
1698
+ payloads outside the BuildStore namespace, with metadata, mutation audit, a deployment
1699
+ key verifier and generation/revision fences. Short transactions implement refresh
1700
+ claim/completion CAS; provider HTTP occurs after the claim commits, with no backend
1701
+ session affinity. An expired pending rotation fails without token reuse.
1702
+
1703
+ The separate `packages/hosted-store-service/src/web/project-secrets.ts` handler
1704
+ uses fresh cookie-session organization membership or super-user authority for
1705
+ Settings metadata and static writes. Its durable effective-config projection
1706
+ returns only account names, kinds, credential slots and readiness. Browser writes
1707
+ use the same transaction and project lock through `setStaticOnly`, refusing an
1708
+ existing refreshing kind atomically. The Settings client fences stale polls and
1709
+ keeps write acknowledgments separate from failed metadata rereads.
1710
+
1711
+ `packages/hosted-store-service/src/project-secrets.ts` authenticates owner-purpose
1712
+ credentials and fresh membership before reading write bodies. It returns metadata
1713
+ or acknowledgments and fixed safe errors. `ab secrets` uses saved connection
1714
+ credentials directly and hidden input. The hosted dispatcher internally resolves
1715
+ the complete set per tick, validates the handoff under the mutation lock, overlays
1716
+ a fresh project environment, strips the encryption key, and redacts supplied
1717
+ values in output/errors. Effective-config artifacts serialize declarative config,
1718
+ not the process environment. Empty snapshots bypass decryption/key validation only
1719
+ after reading and validating the complete version set under the project lock;
1720
+ new secrets invalidate an earlier empty handoff. Writes always validate the key.
1721
+ No operator/MCP/raw-store accessor resolves plaintext.
1722
+
1723
+ ### Named billing accounts
1724
+
1725
+ Deployment-owned `[accounts.<name>]` descriptors contain `kind` and
1726
+ `credentialEnv`, plus the closed Kimi `region` (`overseas` by default or `china`).
1727
+ Role and alternate `account` axes inherit independently. Claude routes default
1728
+ to the sole Claude subscription account; ambiguity, unknown references and
1729
+ incompatible runtimes fail configuration. No accounts preserves legacy behavior.
1730
+ Claude and Kimi accounts require the unmodified Claude Code runtime; ChatGPT
1731
+ subscription accounts require explicit Codex selection. Use the user's own plan
1732
+ for ordinary individual usage. Claude and Kimi credentials are provisioned
1733
+ manually. ChatGPT credentials are authorized with `ab accounts login NAME
1734
+ [--local|--project]`. The local dispatcher or hosted refreshing project secret
1735
+ is the sole refresh owner; no sandbox refreshes. Local Codex uses a protected
1736
+ loopback inference transport and isolated CODEX_HOME, preserving the shell HOME
1737
+ and leaving ambient login untouched.
1738
+ Hosted validation uses write-only metadata and states that the first hosted
1739
+ build is the live check; local validation makes a minimal runtime request.
1740
+
1741
+ Local sessions resolve host credentials after ambient merging. Remote sessions
1742
+ receive account placeholders; exact provider hostname and placeholder header
1743
+ matches broker real credentials on the host. Both Kimi endpoint and host derive
1744
+ from one closed regional mapping, without cross-region retry. Observation ticks
1745
+ refresh the live egress policy from dispatcher environment values. Selected
1746
+ account descriptors persist with sessions for continuation; configuration and
1747
+ launch artifacts contain no secret values. Credential rejections require renewal
1748
+ and bypass alternates; quota and availability retain existing fallback behavior.
1749
+ Account secrets are redacted at persistence boundaries, including split streamed
1750
+ deltas and prior values retained across rotation.
1751
+
1752
+
1753
+ ### Hosted project deletion
1754
+
1755
+ The Projects web surface allows super users and organization owners to preview
1756
+ counts and permanently delete their authorized projects with the shared confirmation dialog.
1757
+ PostgreSQL fences the registration generation before physical blob cleanup and
1758
+ retains durable pending inventory for restart/retry. Upload ownership is reserved
1759
+ in a separate committed transaction before provider I/O; transaction-scoped shared
1760
+ blob locks cover upload/publication, and exclusive locks cover reference checks
1761
+ and physical deletion. Other projects' references and reservations preserve shared
1762
+ bytes. Completion removes all project rows except repository, actor, deletion time
1763
+ and an opaque generation id in the deletion audit. Old credentials receive 401;
1764
+ repository-established requests receive 403 project not registered. Approval of a
1765
+ fresh connection starts empty and resets hosted ticket numbering. `ab disconnect`
1766
+ revokes credentials only; admin `projects remove` unregisters without purging.
1767
+ See [project deletion protocol](operator-api.md#permanent-project-deletion).
1768
+
1769
+ The ticket-source port optionally exposes `listPage(criteria, page)` for paged operator reads. PostgreSQL counts matches and applies SQL LIMIT/OFFSET; other sources retain exhaustive-read slicing. CLI and dispatcher reads stay exhaustive. See [ticket source contract](ticket-sources.md#writing-your-own).