@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -15,7 +15,39 @@ node fast-forwards preserve ordered contributing identities.
15
15
 
16
16
  ## Timing and evidence
17
17
 
18
- Destination observations are durable `target.moved` facts, including while an
18
+ Destination heads come only from the authoritative forge branch; dispatcher-host
19
+ refs are never a fallback. Failed remote reads retain the accepted observation;
20
+ classified rate limits use repository forge degradation and cooldown. Changed
21
+ heads require immutable commit ancestry proof against the accepted target and
22
+ the destination base already used by replay. Missing capability or failed proof
23
+ defers new replay. A non-descendant without kernel lineage records
24
+ `target.rewritten` with branch,
25
+ previous SHA and observed SHA, retains the accepted target, and raises watch/wait
26
+ attention. Repeated rewrite pairs are deduplicated. Returning to a safe target
27
+ clears attention (`target.rewrite-cleared` when the accepted tip is unchanged).
28
+ Upstream force-pushes are never adopted automatically. Accepted node reparenting
29
+ starts a new branch scope; frozen transactions recover their retained inputs.
30
+
31
+ Kernel restacks of a node are admitted through durable guarded publication
32
+ receipts, not treated as external force-pushes. The dispatcher walks an index
33
+ keyed by node and previous head, at most 64 receipt lookups from each child
34
+ baseline; cost is capped independently of journal length or total receipts.
35
+ Exact links use point lookups. When forward child landings separate restacks,
36
+ the dispatcher walks backwards from the latest publication with an indexed
37
+ previous-receipt cursor. Every gap requires immutable ancestry from the earlier
38
+ published head to the later receipt's previous head, as do the baseline and tip
39
+ ends of the proof. Missing links never imply rewrite authority.
40
+ The proven receipts travel in `target.moved.lineage`; build-scoped runners use
41
+ that recorded proof without reading another build. Clearing attention for an
42
+ unchanged accepted SHA retains newly proven lineage in `target.rewrite-cleared`.
43
+ Missing receipts or a gap
44
+ over 64 still record `target.rewritten` and raise attention. Each hop makes at
45
+ most two immutable ancestry comparisons. The exact walk and gap recovery share
46
+ the same 64-read cap, including unsuccessful lookups. Unchanged accepted
47
+ polls read no receipts or event rows.
48
+
49
+
50
+ Accepted destination observations are durable `target.moved` facts, including while an
19
51
  agent runs. Verify-entry restack freezes a current base before verification;
20
52
  path selection excludes upstream-only paths. After finalize and post-steps,
21
53
  waiting leaves restack when the target moves. Node-target finalize contributions
@@ -47,6 +79,19 @@ actual destination, processing ancestors first. Unrelated siblings stay idle;
47
79
  changes absent from all ancestors cannot trigger a speculative replay. Tickets
48
80
  remain queued until presence is observed in their destination.
49
81
 
82
+ A presence request whose identities are absent from its immediate parent remains
83
+ pending while ancestors restack or reconcile. A durable availability observation
84
+ allows unchanged idle ticks, including after restart, to skip repository preparation
85
+ and native auto-merge cancellation. Exact node/parent heads, contribution base,
86
+ request contents, accepted ancestry, foreign aliases and confirmed landing evidence
87
+ invalidate that observation when they change; polling timestamps do not. Failed
88
+ assessments never establish unavailability. Availability is not proof of destination
89
+ coverage. Moving to another destination branch explicitly settles obsolete requests
90
+ with `destination-changed`; losing identities on the same branch leaves them waiting.
91
+ Native auto-merge is suspended with confirmed, reusable receipts only when replay
92
+ is actionable, and is revalidated during recovery before rewrite effects.
93
+
94
+
50
95
  `ab restack <node>` (operator tool `builds.restack`, input `{repo, slug}`) records
51
96
  a durable request, coalescing pending demand. It refuses leaves, terminal nodes,
52
97
  and unopened nodes. Paused or blocked nodes wait for their normal safety gates.
@@ -78,7 +123,12 @@ transaction, candidate SHA and exact path list on recovery. The phase-terminal
78
123
  D5 clean-worktree rule for `ab done` remains unchanged.
79
124
 
80
125
  Before replacement the kernel publishes retained tips, displaced heads and the
81
- temporary change under immutable exact archive refs. `restack.*` facts record
126
+ temporary change under immutable exact archive refs. Remote archives also publish
127
+ commits present only on the remote: GitHub uses create-only Git-reference REST creation
128
+ when the workspace lacks the commit, retaining guarded Git pushes for local objects.
129
+ Exact remote readback confirms publication, then a depth-one fetch by the archive ref
130
+ (without tags or configured refmap expansion) restores missing commits and verifies them
131
+ locally before returning. `restack.*` facts record
82
132
  preparation, replay, intent, archived replacement, contention and completion.
83
133
  Unpublished request/loss records alone cannot preserve objects from a released
84
134
  sandbox. The forge is authoritative for publication: after a push or on recovery,
@@ -94,6 +144,8 @@ against the current destination. Remote guests park for trusted
94
144
  publication after teardown. Historical merge reconciliations keep their original
95
145
  interpretation and supply a promoted contribution base for later replay.
96
146
 
147
+ Replay retention stores thin Git packs in bounded binary chunks, with a fixed-size completion manifest written only after every chunk is acknowledged. Digest-keyed chunks make interrupted writes retryable; incomplete uploads are never restored. Recovery validates all chunk sizes and the pack digest before installation, and requires the base objects (restoring node prefixes in order). Existing single-artifact base64 packs remain readable. Retained replay artifacts are read only when the requested commit is missing locally, never by idle polling.
148
+
97
149
  ## Node contributions and recovery
98
150
 
99
151
  Node replay enumerates oldest-first first-parent contributions above the last
@@ -141,11 +193,24 @@ retry eligibility and recheck authorization after repository forge cooldown.
141
193
 
142
194
  ## Leaf publication retry recovery
143
195
 
196
+ A historical `publication.lost` does not prove that every copy of its candidate
197
+ is gone. Recovery checks the exact branch and private archive refs and retained
198
+ replay objects first. An available candidate continues guarded publication.
199
+ A genuinely missing reconcile or automatic restack candidate records
200
+ `publication.candidate-retired`, abandons its obsolete request, and replays the
201
+ producing operation with a fresh transaction identity. Its frozen target,
202
+ reconcile occurrence or automatic trigger, cycle, and message survive. The
203
+ retired candidate is excluded from archive requirements unless independently
204
+ required by proven history. This reconstruction consumes no infrastructure
205
+ attempt and no additional conflict occurrence; it needs no operator guidance.
206
+ A bare retry also clears an existing infrastructure-limit escalation through
207
+ ordinary retry semantics. Unavailable inspection defers rather than proving loss.
208
+
144
209
  Leaf restack and reconcile publication retry classified transient forge or transport
145
210
  failures six times after the initial attempt, waiting 30, 60, 120, 240, 300 and
146
211
  300 seconds. `publication.retry-scheduled` records the operation, frozen rewrite
147
212
  identity, episode anchor, failure ordinal, last error and absolute retry time;
148
- restart resumes that schedule without rerunning the resolver. These retries do
213
+ restart resumes that schedule without rerunning a resolver whose candidate remains available. These retries do
149
214
  not consume `maxPhaseAttempts`. A seventh transient failure records
150
215
  `publication.retry-exhausted` and raises `publication-retry-limit`, naming the last
151
216
  error and six retries. Answering that escalation opens a fresh publication episode
@@ -154,3 +219,40 @@ publication keeps its workspace through backoff and unresolved exhaustion.
154
219
  Classified rate limits retain repository cooldown and consume no publication
155
220
  retry allowance. Rejected pushes, lease conflicts, dirty trees and unclassified
156
221
  errors retain their existing behavior.
222
+
223
+ Preserved restoration checkpoints survive repeated replacement; a published
224
+ reconcile or restack rewrite retires the old checkpoint.
225
+ Recovery context applies to the following session and its repeated hydration; later
226
+ sessions do not inherit obsolete reconstruction instructions.
227
+
228
+ ## Ticket preparation before build creation
229
+
230
+ Before claiming, the dispatcher journals a repository-scoped preparation intent;
231
+ a won claim and the exact selected creation slug are durable boundaries. Caught
232
+ asset-copy, spec-authoring, naming, and build-creation failures return the ticket
233
+ to configured Ready; a nonconforming spec goes to configured Triage. Recovery
234
+ checks the exact selected build first: a matching record and atomic
235
+ `build.created` retain ownership even if creation threw after committing.
236
+ Unavailable or conflicting readback never authorizes release or a replacement
237
+ build. Pending attempts retain the original failure, latest recovery error and
238
+ retry deadline in the canonical repository reduced value; resolved attempts
239
+ leave that value. Under repository ownership, each tick admits at most eight
240
+ due recovery attempts, before intake and independently of capacity or intake
241
+ settings, with a 30-second durable retry delay after recovery failure. Unresolved
242
+ ticket identities remain withheld. An uncertain claim outcome or unrelated
243
+ external ticket state, missing ticket/state, or conflicting slug ownership terminates
244
+ automatic recovery with an `abandoned` resolution and diagnostic reason. The
245
+ ticket is left unchanged; an operator can leave it finished or cancelled, or
246
+ inspect ownership and explicitly return it to Ready for another attempt. These
247
+ cases stop provider polling and diagnostic appends. Recovery failures are
248
+ reported without preventing janitor, lease sweep, or other dispatch recovery.
249
+ This is not general process
250
+ crash recovery. Confirmed Ready/Triage transitions settle idempotently, so a
251
+ failed bounce comment does not return an invalid ticket to Ready.
252
+
253
+ Once a build is established, ordinary interrupted-dispatch recovery completes
254
+ its missing boundaries; preparation cleanup cannot release its claim.
255
+
256
+ ## Spec revision during leaf reconcile
257
+
258
+ If a leaf spec revision arrives during an unfinished reconcile, the same reconcile attempt resumes under the revised spec on its retained frozen target. Its replay and committed contribution remain owned by reconcile. Confirmed publication must settle before the fresh plan loop opens; prior approvals and verification remain invalidated. The retained transaction and restack identity are reused; no abort or destructive reset is needed.
package/docs/setup.md CHANGED
@@ -9,6 +9,15 @@ build or phase. Work directly in the repository and involve the maintainer in
9
9
  choices that cannot be derived from source. Secrets belong in the environment
10
10
  or an ignored `.env`, never in `autobuild.toml`, commits, or validation reports.
11
11
 
12
+ Local dispatch checks selected primary and alternate account credentials before
13
+ taking the repository lease. Supply the configured environment slot or a local
14
+ ChatGPT login (`bun ab accounts login NAME --local`). Hosted account absence
15
+ appears once in repository attention: set `bun ab secrets set VARIABLE`, or
16
+ renew with `bun ab accounts login NAME --project`. The next tick resumes without
17
+ per-build retries or infrastructure-attempt consumption. Unused accounts do not
18
+ block startup; present rejected credentials keep their rejection attention.
19
+ See [account admission and remedies](accounts.md#dispatcher-admission).
20
+
12
21
  ## Choose the execution environment
13
22
 
14
23
  Keep the default `git-worktree` provider unless the maintainer explicitly opts
@@ -250,12 +259,13 @@ sources agree with the running system by construction:
250
259
  **running dispatcher's version** (read from the installed distribution's
251
260
  `package.json`), so the guest runs the dispatcher's own release.
252
261
 
253
- A service accepts stable and prerelease clients from its own `major.minor`
254
- release line and the two preceding minor lines in the same major. A major starts a new family:
255
- X.0 accepts only X.0, X.1 accepts X.0/X.1, and X.2 onward accepts three lines.
256
- Patch versions are interchangeable in both directions and must never change
257
- the protocol. Keep project clients within the instance’s published window. Supported release lines retain their wire handlers and known
258
- protocol identities; an unknown protocol is refused independently of version.
262
+ A published release line stays supported by a service until both at least two newer minor lines have been published and 90 days have passed since the first release of the line that superseded it. The rule spans majors: a new major keeps supporting earlier lines on the same terms. The policy floor is 1.2: lines before 1.2 are refused regardless of publication dates because their clients rebuild server state from the journal. Lines newer than the service stay unsupported (service first). Supported means the published clients of that line can use the service’s retained protocol handlers and read its reduced answers in the shapes their released clients accept.
263
+
264
+ Stable patches never reset a line’s first-publication date. Only actually published
265
+ lines at or below the service line count; prereleases do not start retirement clocks.
266
+ Publication facts survive removal of retired identities, contracts, and handlers.
267
+ Patch releases must retain their line’s protocol identity. Unknown historical
268
+ protocol identities are refused independently of the numeric window.
259
269
  Stable and prerelease service and client identities share their numeric major/minor
260
270
  line. Malformed or missing identities, build metadata (`+…`), prefixes and
261
271
  whitespace are refused with HTTP 409.
@@ -266,8 +276,9 @@ and supported range.
266
276
  Unauthenticated `GET /health` publishes `ok`, `autobuildVersion`,
267
277
  `protocolVersion`, and `supportedClientRange: { minVersion, maxVersionExclusive }`.
268
278
  Range endpoints remain stable versions. The range is inclusive at the minimum
269
- and exclusive at the maximum; a 0.11.x
270
- service publishes `>=0.9.0 <0.12.0`. Health needs no credentials, version
279
+ and exclusive at the maximum; a 1.3.x
280
+ service publishes `>=1.2.0 <1.4.0` until later publication facts permit retirement.
281
+ The service reads the clock for each decision, so retirement needs no redeploy. Health needs no credentials, version
271
282
  headers, or available backend.
272
283
 
273
284
  `ab upgrade` probes this public range before installation or project changes.
@@ -507,3 +518,21 @@ change local files or configuration. Failed cleanup is retryable with access
507
518
  already refused. Reconnecting requires fresh browser approval and starts empty,
508
519
  with hosted ticket numbering reset to 1. See
509
520
  [permanent project deletion](operator-api.md#permanent-project-deletion).
521
+
522
+ ## Hosted dispatch and local viewing
523
+
524
+ A plain `ab dispatch` reads dispatch placement once before starting local execution.
525
+ For a hosted project it opens the Store-only viewer automatically, displaying
526
+ `viewer · dispatched by <host>` from the placement origin (including a nondefault
527
+ port). `--once`, `--plain`, and `--interval` retain their viewer meanings.
528
+ `--takeover` explicitly dispatches locally, with a warning that it can displace
529
+ the hosted dispatcher; it cannot be combined with `--viewer`. Startup intake
530
+ flags require `--takeover` when placement selects viewer.
531
+
532
+ An unreadable placement fails closed with a typed error naming the cause:
533
+ use `--viewer` to watch or `--takeover` to dispatch locally. Both explicit modes
534
+ skip placement discovery. Older services without the capability and projects
535
+ with unknown or nonhosted placement retain local dispatch behavior. Local stores
536
+ need no placement request. Origin mode (`--repository` or `AB_REPOSITORY`) and
537
+ hosted cron dispatch bypass this check. Placement is a startup snapshot, not a
538
+ liveness probe or a polling input.
package/docs/skills.md CHANGED
@@ -12,7 +12,7 @@ Skills guide the agents that plan, implement, review and operate Autobuild, one
12
12
 
13
13
  ## Strong defaults, yours to edit
14
14
 
15
- `ab init` installs the shipped skills as repository files under `.agents/skills/ab-<name>/`: a `SKILL.md` plus optional references or scripts. For example, tell `.agents/skills/ab-implement/SKILL.md` to use the shared database adapter, follow the existing error vocabulary and run the project's integration checks.
15
+ `ab init` installs the shipped skills as repository files under `.agents/skills/ab-<name>/`: a `SKILL.md` plus optional references or scripts. For example, tell `.agents/skills/ab-implement/SKILL.md` to use the shared database adapter, follow the existing error vocabulary and run the project's codegen before committing.
16
16
 
17
17
  - Change how agents work, not the lifecycle's gates. Keep each skill's typed CLI contract: context, notes deposit and completion command.
18
18
  - Commit edits so every agent shares them.
@@ -61,15 +61,16 @@ plan review, code review, the repository's full verify suite, finalize,
61
61
  merge, and a restack for everything queued behind it. Ten small tickets pay
62
62
  that cost ten times, and a blocker chain pays it in series. Prefer fewer,
63
63
  larger tickets: one ticket per coherent change, as large as one plan and one
64
- review pass can hold without the quality bar slipping.
64
+ review pass can hold without the quality bar slipping, and no larger than one
65
+ implement session can finish.
65
66
 
66
67
  A ticket is the right size when its acceptance criteria describe one feature
67
68
  or fix a reviewer can judge in a single pass, one plan can cover it without
68
69
  deferring a design decision to a later build, and its out-of-scope list is
69
70
  short and obvious. It is too big when its criteria fall into groups that share
70
- no behavior, when part of it waits on a decision nobody has made, or when its
71
+ no behavior, when part of it waits on a decision nobody has made, when its
71
72
  parts need different merge — one can ship now while another needs consent
72
- or must wait.
73
+ or must wait — or when implementing it would outgrow one session.
73
74
 
74
75
  Do not split:
75
76
 
@@ -80,6 +81,39 @@ Do not split:
80
81
  - to make progress visible, or because the spec got long. A long spec with
81
82
  clear criteria is fine.
82
83
 
84
+ ### Fit one implement session
85
+
86
+ Larger stops paying off where the work outgrows one agent session. The first
87
+ implement round is a single session, and everything it does stays in that
88
+ session's context: the spec and plan, every file it reads, every edit, every
89
+ test and check run and its output, and every debugging detour. A ticket that
90
+ fills the implementer's context window — commonly a million tokens or less —
91
+ degrades mid-build: the harness compacts away the reasoning that held the
92
+ change together, or an operator has to clear context and restart by hand.
93
+ Size each ticket to finish well inside one window, with headroom for
94
+ debugging.
95
+
96
+ Nothing measures this at grooming time, so estimate from what the
97
+ implementer must do, not from how long the spec is:
98
+
99
+ - **Reading.** Count the code it must understand before it can edit safely.
100
+ Several unfamiliar subsystems, each read end to end, cost more than the
101
+ diff itself.
102
+ - **Edit sites.** Count files touched, not lines changed. A rename or
103
+ signature change threaded through dozens of callers spends context on
104
+ every one, however mechanical.
105
+ - **Iteration.** Count the separate behaviors that each need their own
106
+ tests, failures, and fixes, and the slow or verbose loops — full suites,
107
+ UI captures, migrations — the session will repeat.
108
+ - **Your own reading.** If writing the spec meant reading most of several
109
+ subsystems, the implementer reads them again, then writes the code and
110
+ tests on top.
111
+
112
+ Most tickets sit far below this ceiling; it is a limit, not a target. A
113
+ ticket that touches one subsystem and a handful of files needs no estimate.
114
+ When the signals put a ticket near the ceiling, split it at a seam (below)
115
+ rather than gamble on the build fitting.
116
+
83
117
  ### Cut along seams
84
118
 
85
119
  A seam decides where to cut once a split is justified; it is not a reason to
@@ -131,7 +165,8 @@ The spec is the build's contract artifact (kind `spec`, revision 0).
131
165
  Every downstream reviewer approves conformance to its pinned revision.
132
166
  For leaves, a phase that discovers the spec itself is wrong raises an
133
167
  escalation (`ab escalate`); a human answers, the spec gets revision N+1,
134
- and the leaf restarts from `plan`.
168
+ and the leaf restarts from `plan` after any unfinished reconcile resumes under
169
+ the revised spec and its publication is confirmed.
135
170
 
136
171
  Operators may explicitly revise an opened idle collecting node or a node blocked on failed
137
172
  integration verification without an escalation. Use
@@ -149,4 +184,5 @@ Active verification/reconcile or writer work, restack/reparent work, pause,
149
184
  pending controls, merge intent and ended PRs refuse the no-escalation path.
150
185
  A concurrent state change refuses publication with a retry explanation;
151
186
  uncited artifacts are inert. Leaves still require an open escalation and
152
- restart from `plan`.
187
+ restart from `plan` after any unfinished reconcile resumes under the revised
188
+ spec and its publication is confirmed.
@@ -77,6 +77,14 @@ parent history. An empty completed contribution is satisfied; missing evidence,
77
77
  an open or aborted node, or ambiguous newest build generations remain queued.
78
78
  Older successful generations are never substituted for the newest build.
79
79
 
80
+ Destination observations retain versioned, head-bound Git witnesses (reachable
81
+ commit SHAs and direct build trailers) and a fixed-length evidence digest. Current
82
+ confirmed landings and aliases from only the destination's accepted ancestry are
83
+ reapplied before reuse. Unrelated merged history and ready destinations do not
84
+ invalidate this proof. Head changes require a fresh Git sample; legacy observations
85
+ without witnesses refresh once rather than replaying repository history. Current
86
+ readiness and newest-generation checks still apply before claim.
87
+
80
88
  - Same node: the blocking change merges directly into the target.
81
89
  - Ancestor: the change merges into an ancestor, then presence demand restacks only the required path to the target.
82
90
  - Sibling: the blocking node merges into their common ancestor, then presence demand reaches the target through the minimal ancestor path.
@@ -9,6 +9,15 @@ description: "Diagnose configuration, idle dispatch, authentication, stalled bui
9
9
 
10
10
  Start from the symptom and recorded state. Your operator agent inspects the CLI and suggests fixes; you manage dispatcher processes and credentials.
11
11
 
12
+ Local dispatch checks selected primary and alternate account credentials before
13
+ taking the repository lease. Supply the configured environment slot or a local
14
+ ChatGPT login (`bun ab accounts login NAME --local`). Hosted account absence
15
+ appears once in repository attention: set `bun ab secrets set VARIABLE`, or
16
+ renew with `bun ab accounts login NAME --project`. The next tick resumes without
17
+ per-build retries or infrastructure-attempt consumption. Unused accounts do not
18
+ block startup; present rejected credentials keep their rejection attention.
19
+ See [account admission and remedies](accounts.md#dispatcher-admission).
20
+
12
21
  ## Invalid configuration
13
22
 
14
23
  **Symptom.** Startup reports a TOML syntax error, invalid config with field paths, or a runtime-routing error naming a role.
@@ -113,7 +113,7 @@ Sandbox preparation order:
113
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
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
- - **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.
116
+ - **Lifetime.** `timeoutSeconds` bounds a sandbox; provider operations have their own timeouts. An intact sandbox resumes. Before replacement, the dispatcher fences it, preserves reachable unpublished commits to build-private refs, and records a receipt; the next workspace restores those commits. Loss is limited to already absent or unrecoverable work and uncommitted files; known loss appears in the next session's recovery context. See the [workspace recovery contract](architecture.md#key-boundaries).
117
117
 
118
118
  ### Private repositories
119
119
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "devDependencies": {
158
158
  "@biomejs/biome": "2.5.5",
159
- "@defrex/autobuild-postgres-store": "1.2.0",
160
- "@defrex/autobuild-vercel-sandbox": "1.2.0",
159
+ "@defrex/autobuild-postgres-store": "1.4.0",
160
+ "@defrex/autobuild-vercel-sandbox": "1.4.0",
161
161
  "@resvg/resvg-js": "2.6.2",
162
162
  "@types/bun": "^1.3.14",
163
163
  "@types/node": "^24.0.0",
@@ -165,6 +165,7 @@
165
165
  "dejavu-fonts-ttf": "2.37.0",
166
166
  "drizzle-kit": "^0.31.10",
167
167
  "git-format-staged": "4.0.1",
168
+ "happy-dom": "^21.0.4",
168
169
  "husky": "9.1.7",
169
170
  "typescript": "5.9.3"
170
171
  }
@@ -0,0 +1,96 @@
1
+ import { accountRemedy, type Accounts, type SelectedAccount } from '../config/accounts'
2
+ import type { RepositoryReadFacts } from '../store/reduced-reads'
3
+ import type { RepositoryEventWrite } from '../events/repository'
4
+ import { DISPATCHER } from '../events/envelope'
5
+
6
+ export interface MissingAccountCredential extends SelectedAccount {
7
+ source: 'environment' | 'project-secrets'
8
+ remedy: string
9
+ }
10
+
11
+ /** Presence only: no provider calls, token validation, or secret values in diagnostics. */
12
+ export function missingAccountCredentials(
13
+ accounts: Accounts,
14
+ env: Readonly<Record<string, string | undefined>>,
15
+ source: MissingAccountCredential['source'] = 'environment',
16
+ workspaceProvider = 'vercel-sandbox',
17
+ ): MissingAccountCredential[] {
18
+ return Object.entries(accounts)
19
+ .sort(([a], [b]) => a.localeCompare(b))
20
+ .filter(
21
+ ([, descriptor]) =>
22
+ !env[descriptor.credentialEnv] &&
23
+ !(
24
+ source === 'environment' &&
25
+ workspaceProvider !== 'vercel-sandbox' &&
26
+ descriptor.kind === 'claude-subscription'
27
+ ),
28
+ )
29
+ .map(([name, descriptor]) => ({
30
+ name,
31
+ descriptor,
32
+ source,
33
+ remedy:
34
+ source === 'environment'
35
+ ? accountRemedy({ name, descriptor })
36
+ : `account ${JSON.stringify(name)} (${descriptor.credentialEnv}): set the project secret with ab secrets set ${descriptor.credentialEnv}` +
37
+ (descriptor.kind === 'chatgpt-subscription'
38
+ ? ` or renew with ab accounts login ${JSON.stringify(name)} --project`
39
+ : ''),
40
+ }))
41
+ }
42
+ export function formatMissingAccountCredentials(
43
+ missing: readonly MissingAccountCredential[],
44
+ ): string {
45
+ return `Missing credentials: ${missing.map((account) => `${account.remedy} [${account.source}]`).join('; ')}`
46
+ }
47
+ export class MissingAccountCredentialsError extends Error {
48
+ constructor(readonly missing: MissingAccountCredential[]) {
49
+ super(formatMissingAccountCredentials(missing))
50
+ this.name = 'MissingAccountCredentialsError'
51
+ }
52
+ }
53
+
54
+ /** Reconcile against the canonical reduced value, shared by all launches in a tick. */
55
+ export async function reconcileMissingAccounts(
56
+ missing: readonly MissingAccountCredential[],
57
+ current: RepositoryReadFacts['missingAccounts'],
58
+ append: (event: RepositoryEventWrite) => Promise<unknown>,
59
+ ): Promise<void> {
60
+ const next = new Map(missing.map((account) => [account.name, account]))
61
+ for (const [name] of Object.entries(current))
62
+ if (!next.has(name))
63
+ await append({ actor: DISPATCHER, type: 'account.credentials-recovered', payload: { name } })
64
+ for (const account of missing)
65
+ if (!sameMissingAccount(current[account.name], account))
66
+ await append({ actor: DISPATCHER, type: 'account.credentials-unavailable', payload: account })
67
+ }
68
+
69
+ function sameMissingAccount(
70
+ left: MissingAccountCredential | undefined,
71
+ right: MissingAccountCredential,
72
+ ): boolean {
73
+ return (
74
+ !!left &&
75
+ left.name === right.name &&
76
+ left.source === right.source &&
77
+ left.remedy === right.remedy &&
78
+ left.descriptor.kind === right.descriptor.kind &&
79
+ left.descriptor.credentialEnv === right.descriptor.credentialEnv &&
80
+ (left.descriptor.kind !== 'kimi-code' ||
81
+ (right.descriptor.kind === 'kimi-code' && left.descriptor.region === right.descriptor.region))
82
+ )
83
+ }
84
+
85
+ /** The project snapshot is authoritative even when empty. Do not borrow service credentials. */
86
+ export function applyProjectAccountSnapshot(
87
+ accounts: Accounts,
88
+ env: Record<string, string | undefined>,
89
+ snapshot: Readonly<Record<string, string>>,
90
+ ) {
91
+ for (const descriptor of Object.values(accounts)) {
92
+ delete env[descriptor.credentialEnv]
93
+ if (snapshot[descriptor.credentialEnv])
94
+ env[descriptor.credentialEnv] = snapshot[descriptor.credentialEnv]
95
+ }
96
+ }
@@ -8,6 +8,7 @@ import type { ChatGPTState } from './chatgpt-state'
8
8
  * written before HTTP, and uncertain completion is terminal for that generation. */
9
9
  export class LocalAccountOwner {
10
10
  readonly id = randomUUID()
11
+ readonly injected = new Map<string, string>()
11
12
  constructor(
12
13
  readonly credentials: LocalCredentials,
13
14
  private readonly refresh = refreshChatGPT,
@@ -106,18 +107,64 @@ export async function renewLocalAccounts(
106
107
  if (descriptor.kind !== 'chatgpt-subscription') continue
107
108
  try {
108
109
  const record = owner.credentials.load(name)
109
- if (!record || record.status === 'failed') {
110
- delete env[descriptor.credentialEnv]
110
+ if (!record) {
111
+ if (owner.injected.get(descriptor.credentialEnv) === env[descriptor.credentialEnv])
112
+ delete env[descriptor.credentialEnv]
113
+ owner.injected.delete(descriptor.credentialEnv)
111
114
  continue
112
115
  }
116
+ if (
117
+ record.status === 'failed' ||
118
+ JSON.stringify(record.descriptor) !== JSON.stringify(descriptor)
119
+ )
120
+ throw new Error('ChatGPT account failed or descriptor changed; sign in again')
113
121
  owner.claim(name)
114
122
  claimed.add(name)
115
123
  // Only expose a still-valid access value during the rotating HTTP call.
116
124
  if (record.state.expiresAt > now) env[descriptor.credentialEnv] = record.state.accessToken
117
125
  else delete env[descriptor.credentialEnv]
118
126
  Object.assign(env, await owner.tick({ [name]: descriptor }, now))
127
+ owner.injected.set(descriptor.credentialEnv, env[descriptor.credentialEnv]!)
119
128
  } catch {
120
129
  delete env[descriptor.credentialEnv]
121
130
  }
122
131
  }
123
132
  }
133
+
134
+ /** Inspect transferability without claiming ownership or consuming refresh state.
135
+ * Startup may allow a live peer solely for the pre-lease presence check; actual
136
+ * resolution must still claim after acquiring the repository lease.
137
+ */
138
+ export function inspectLocalAccountEnvironment(
139
+ credentials: LocalCredentials,
140
+ accounts: Accounts,
141
+ env: Readonly<Record<string, string | undefined>>,
142
+ predecessorPid?: number,
143
+ allowLivePeer = false,
144
+ ): Record<string, string | undefined> {
145
+ const available = { ...env }
146
+ for (const [name, descriptor] of Object.entries(accounts)) {
147
+ if (descriptor.kind !== 'chatgpt-subscription') continue
148
+ try {
149
+ const record = credentials.load(name)
150
+ if (!record) continue
151
+ const ownerAvailable =
152
+ allowLivePeer ||
153
+ !record.owner ||
154
+ ownerProcessEnded(record.ownerPid) ||
155
+ (predecessorPid !== undefined && record.ownerPid === predecessorPid)
156
+ if (
157
+ record.status === 'ready' &&
158
+ (record.state.expiresAt > Date.now() ||
159
+ Date.now() >= (record.state.earliestRefreshAt ?? 0)) &&
160
+ ownerAvailable &&
161
+ JSON.stringify(record.descriptor) === JSON.stringify(descriptor)
162
+ )
163
+ available[descriptor.credentialEnv] = 'local-refreshing-source'
164
+ else delete available[descriptor.credentialEnv]
165
+ } catch {
166
+ delete available[descriptor.credentialEnv]
167
+ }
168
+ }
169
+ return available
170
+ }
@@ -41,6 +41,7 @@ export function mergeDecisionFromFacts(
41
41
  export function buildNeedsAttention(events: AbEvent[], state: BuildState): boolean {
42
42
  return (
43
43
  state.janitor?.attention === true ||
44
+ !!state.targetRewrite ||
44
45
  (state.compatibility?.decisiveFacts ?? 0) > 0 ||
45
46
  (state.openEscalations?.length ?? 0) > 0 ||
46
47
  mergeDecision(events, new Date(0), state) !== null
@@ -53,6 +54,7 @@ export function mergeIdentity(slug: string, pr: number): string {
53
54
 
54
55
  export function repositoryNeedsAttention(event: RepositoryEvent): boolean {
55
56
  switch (event.type) {
57
+ case 'account.credentials-unavailable':
56
58
  case 'harvest.escalated':
57
59
  case 'harvest.recovery-exhausted':
58
60
  case 'dispatcher.forge-readiness-failed':
@@ -1,3 +1,5 @@
1
+ import { selectDispatchMode } from './dispatch-mode'
2
+ import { spawnExec } from '../ports/workspace/git-worktree'
1
3
  import { join } from 'node:path'
2
4
  import type { DashboardRendererResolver } from './dashboard/render'
3
5
  import { loadDotEnv } from './dotenv'
@@ -27,7 +29,21 @@ export async function runBinary(
27
29
  ) {
28
30
  try {
29
31
  const args = parseDispatchArgs(argv.slice(1), process.env)
30
- if (!args.once && !args.repository) return await launchDispatcher(argv)
32
+ if (!args.viewer && !args.once && !args.repository) {
33
+ const mode = await selectDispatchMode({
34
+ ...args,
35
+ targetRepo: process.cwd(),
36
+ env: process.env,
37
+ exec: spawnExec,
38
+ stderr: console.error,
39
+ })
40
+ if (!mode.viewer) return await launchDispatcher(argv)
41
+ const { runDirectBinary } = await import('./binary-direct')
42
+ return runDirectBinary(
43
+ [...argv, '--viewer', '--dispatched-by', mode.dispatchedBy!],
44
+ resolver,
45
+ )
46
+ }
31
47
  } catch (error) {
32
48
  console.error(error instanceof Error ? error.message : String(error))
33
49
  return 1