@defrex/autobuild 1.14.0 → 1.16.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 (35) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +44 -5
  3. package/docs/architecture.md +43 -6
  4. package/docs/configuration.md +8 -3
  5. package/docs/dispatcher-hosting.md +13 -0
  6. package/docs/remote-store-protocol.md +1 -1
  7. package/docs/troubleshooting.md +33 -3
  8. package/docs/workspaces.md +2 -1
  9. package/package.json +3 -3
  10. package/packages/core/src/cli/dispatch.ts +171 -5
  11. package/packages/core/src/cli/repository-status.ts +15 -0
  12. package/packages/core/src/events/policy.ts +1 -0
  13. package/packages/core/src/events/repository.ts +95 -6
  14. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/23d33121de6d3325.json +107 -0
  15. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  16. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  17. package/packages/core/src/kernel/repository-read-facts.ts +9 -0
  18. package/packages/core/src/ports/types.ts +10 -4
  19. package/packages/core/src/ports/workspace/vercel-sandbox.ts +281 -75
  20. package/packages/core/src/processes/dispatcher.ts +1142 -265
  21. package/packages/core/src/processes/invocation-budget.ts +6 -0
  22. package/packages/core/src/processes/launch-cut.ts +37 -0
  23. package/packages/core/src/processes/pass-stages.ts +294 -0
  24. package/packages/core/src/store/reducer-value-shapes.json +5285 -5003
  25. package/packages/core/src/store/remote/released-clients.json +22 -0
  26. package/packages/core/src/store/remote/released-reducer-values/1.15.0.json +36354 -0
  27. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  28. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  29. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  30. package/packages/core/src/store/repo-state-events.ts +1 -0
  31. package/packages/core/src/testing/reduced-read-budget.ts +285 -8
  32. package/skills/guide/SKILL.md +25 -3
  33. package/skills/guide/references/remote-store-protocol.md +1 -1
  34. package/skills/operate/SKILL.md +16 -4
  35. package/templates/hosted-service/package.json +2 -2
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.14.0
29
+ bun add -d --exact @defrex/autobuild@1.16.0
30
30
  ```
31
31
 
32
32
  <!-- release-install:end -->
package/SPEC.md CHANGED
@@ -2005,11 +2005,49 @@ attempt. A tick that defers such work counts it as `provisioningDeferred` or
2005
2005
  reported idle. It records those builds in the latest-only, advisory
2006
2006
  `dispatcher.work-deferred` fact (a deferral noted after the work deadline is
2007
2007
  written in teardown, under the cleanup deadline, while the repository lease is
2008
- still held), and the next invocation sweeps them before its
2008
+ still held), and the next invocation serves them before its
2009
2009
  other stages, re-deriving every decision from build state. The fact is a
2010
2010
  scheduling hint, never authority; an entry leaves it only after its own pass
2011
- finishes without deferring again. Several carried recoveries can use most of
2012
- that invocation's window before the janitor runs.
2011
+ finishes without deferring again. Carried recoveries start within half of the
2012
+ window that remains.
2013
+ Every start a bounded pass admits but does not finish is carried this way, so a
2014
+ held slot always has its start in progress or first in the next pass. A first
2015
+ provision the budget defers right after a claim is carried as `provision`, and
2016
+ the next invocation serves a carried build that is still queued by completing
2017
+ its dispatch. A launch the work deadline cuts after claiming the build's
2018
+ execution lease is carried as `launch`. Bounded teardown awaits it before the
2019
+ repository lease is released. A start never requested releases the exact-holder
2020
+ lease. A requested start is fenced first and released only after the fence is
2021
+ confirmed, because a released but running guest could re-claim the lease beside
2022
+ a replacement. When teardown cannot confirm the fence or the release, the entry
2023
+ keeps the cut execution's `instance` and the step still owed (`fence` or
2024
+ `launch`). The next invocation finishes that exact work first, and only while
2025
+ that instance still holds the lease; the lease never waits on its TTL. A
2026
+ carried entry retires without launching when its build is aborted, discarded,
2027
+ paused or no longer needs the start.
2028
+ No stage consumes a bounded pass. Its stages run in order (deferred work,
2029
+ settlement, ticket preparations, janitor, recovery, lease sweep, admission,
2030
+ intake), and each may start new items only until its share of the time left
2031
+ when it starts: a half for deferred work, the janitor and the lease sweep, a
2032
+ quarter for the others, and intake runs to the work deadline. Each helper in a
2033
+ stage still starts its first item while the work deadline has not passed, and
2034
+ in-flight work is never cancelled at a share. Loops whose items stay listed
2035
+ after handling (execution, harvest and operator-sandbox settlement, the
2036
+ janitor, hand-back settlement, dispatch recovery, startup resume and the lease
2037
+ sweep) visit their items in key order from the last item they started, so
2038
+ every item is reached within a bounded number of passes whatever order the
2039
+ listing returns; their positions are the latest-only, advisory
2040
+ `dispatcher.pass-cursors` fact, written at most once per pass and only when
2041
+ one changed; a pass the work deadline abandons mid-visit records them in
2042
+ teardown, so the visit cut short is not retried first. Priority-ordered loops (node admission, start requests, ready
2043
+ tickets, parked admission, ticket waits) keep their order. In a bounded pass a
2044
+ node's integration receipts are recovered at the start of its own janitor
2045
+ visit, and listings are not filtered for mixed-version deferral: the build a
2046
+ decision reads, writes or acts on is checked itself, at most once a pass. Each
2047
+ bounded pass logs `stages:` with each stage's time and items; a pass the work
2048
+ deadline cuts short logs `tick: work deadline reached during <stage>` with the
2049
+ part in flight and how far it got, records that partial summary in teardown,
2050
+ and `ab repository status` shows the latest pass as `last pass stages:`.
2013
2051
  A budget stop is a normal run stop. Credential deletion then gets the remaining
2014
2052
  budget and at least 5 seconds; issuance or deletion unsettled by then is
2015
2053
  reported and left to the capped expiry. Each served tick
@@ -6134,8 +6172,9 @@ down. A workspace
6134
6172
  flagged by `workspace.cleanup-required` is never launched into: the dispatcher
6135
6173
  releases it and provisions the next generation. Provisioning cut off by a
6136
6174
  recorded dispatcher teardown is the exception: the next invocation asks the
6137
- provider to verify and finish the same generation, and if it cannot, the
6138
- replacement consumes no infrastructure attempt. A preservation or release
6175
+ provider to verify and finish the same generation (the Vercel provider resumes
6176
+ after its last completed stage, at the commit it cloned), and if it cannot,
6177
+ the replacement consumes no infrastructure attempt. A preservation or release
6139
6178
  failure is recorded against its build, as an infrastructure failure or janitor
6140
6179
  attention, and never stops the dispatcher from advancing other builds.
6141
6180
  Fencing is revalidated after restart; a saved receipt alone never authorizes
@@ -826,8 +826,9 @@ down. A workspace
826
826
  flagged by `workspace.cleanup-required` is never launched into: the dispatcher
827
827
  releases it and provisions the next generation. Provisioning cut off by a
828
828
  recorded dispatcher teardown is the exception: the next invocation asks the
829
- provider to verify and finish the same generation, and if it cannot, the
830
- replacement consumes no infrastructure attempt. A preservation or release
829
+ provider to verify and finish the same generation (the Vercel provider resumes
830
+ after its last completed stage, at the commit it cloned), and if it cannot,
831
+ the replacement consumes no infrastructure attempt. A preservation or release
831
832
  failure is recorded against its build, as an infrastructure failure or janitor
832
833
  attention, and never stops the dispatcher from advancing other builds.
833
834
  Work a bounded invocation defers for budget (a provision, or a stopped-sandbox
@@ -837,11 +838,47 @@ counted as `provisioningDeferred` or `recoveryDeferred` with one diagnostic line
837
838
  per build, and carried in the latest-only `dispatcher.work-deferred` fact; one
838
839
  noted after the work signal aborts is written through the tick's
839
840
  `teardownWrite` scope under the cleanup signal. The
840
- next tick's first stage, `serviceDeferredWork`, runs the ordinary `sweepBuild`
841
- pass for those builds before settlement and the janitor; the lease sweep and
842
- settlement skip what it took up. A resume the deadline cuts short is stopped or
843
- left uncertain, and observation reports a budget deferral as a `running`
841
+ next tick's first stage, `serviceDeferredWork`, serves those builds before
842
+ settlement and the janitor through `serviceCarriedStart`: a carried cut
843
+ holder first, then `attemptDispatchCompletion` for a build still queued (a
844
+ first provision the budget gate deferred after a claim), and the ordinary
845
+ `sweepBuild` pass otherwise, with the facts it already read and without the
846
+ first-claim grace. Settlement, dispatch recovery (`recoverDispatches`) and the
847
+ lease sweep skip what it took up. A resume the deadline cuts short is stopped
848
+ or left uncertain, and observation reports a budget deferral as a `running`
844
849
  observation marked `deferred`.
850
+ A launch the work deadline cuts after `DispatchLoop.launchRunner` claimed the
851
+ build's execution lease records nothing itself: it throws `LaunchCutByDeadline`
852
+ (`processes/launch-cut.ts`) carrying the instance and whether the provider
853
+ start was requested, and `launchRunner` re-checks `acceptingBuildLaunches`
854
+ immediately before that start. `Dispatcher.startRunner` catches it and runs
855
+ `settleCutLaunch`, and `settleCutHolder` does the work through the tick's
856
+ teardown scope: it fences a requested start with the owning provider's
857
+ `recovery.fence` (passing `{ teardown: true }`, so Vercel bounds the calls by
858
+ its operation timeout and the cleanup scope), then releases the exact-holder
859
+ lease. What it cannot finish is noted with the cut `instance` and the step
860
+ still owed, and the next invocation's `serviceCarriedStart` settles that exact
861
+ holder before anything else. Starts are tracked in flight, and bounded
862
+ teardown awaits `Dispatcher.settleCutStarts()` as a racer beside provisioning
863
+ abandonment, before the repository lease is released; it prints each deferral
864
+ line the tick has not reported, and the cut pass's partial summary counts them.
865
+ Stage fairness lives in `processes/pass-stages.ts` (pure: shares, rotation,
866
+ the stage record and its rendering). `Dispatcher.runTick` wraps each stage in
867
+ `runStage`, which hands its helpers a copy of the tick options whose
868
+ `deadlineAt` is the stage's cut, and every per-item loop gates on `stageGate`,
869
+ which stops at the invocation budget or, past the cut, after the part's first
870
+ item. Rotated loops go through `rotated()`, which orders items after the
871
+ position read from the reduced `dispatcher.pass-cursors` fact;
872
+ `persistPassCursors` appends changed positions once a pass, through the same
873
+ hint-write discipline as the deferral hint. Each started item's key becomes the
874
+ live position at once, and bounded teardown calls `persistPassPositions`, so a
875
+ pass abandoned mid-visit still records where its loops reached. In a bounded pass `tickDigests()`
876
+ lists unfiltered and `checkCompatibility` checks the build each decision acts
877
+ on, memoized per pass. `passSummary()` closes a stage still in flight as
878
+ stopped by the deadline; bounded teardown in `cli/dispatch.ts` prints it and
879
+ closes the open tick boundary with that partial summary under the cleanup
880
+ scope. Those advisory writes race beside provisioning abandonment and
881
+ execution teardown, so a stalled one never postpones them.
845
882
  Fencing is revalidated after restart; a saved receipt alone never authorizes
846
883
  cleanup of a newer execution. Current recovery notes are linked by the session
847
884
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -1628,7 +1628,10 @@ treated as running:
1628
1628
  the tick counts it as `recoveryDeferred`, logs
1629
1629
  `build <slug>: <step> deferred by the invocation budget`, and records the
1630
1630
  build in the latest-only `dispatcher.work-deferred` fact. The next
1631
- invocation sweeps those builds before anything else.
1631
+ invocation runs those builds first, within half of the window. A launch the
1632
+ work deadline cuts after claiming the build's execution lease is carried
1633
+ the same way, as step `launch`: teardown fences the sandbox if the start was
1634
+ requested, then releases the lease, or the next invocation does both first.
1632
1635
  - **No redundant stops.** Fence and cleanup skip `stop()` for a sandbox the
1633
1636
  provider already reports stopped.
1634
1637
  - **Failures name their step.** `infrastructure.failed` and the exhaustion
@@ -1653,11 +1656,13 @@ The dispatcher releases it automatically, recording an empty
1653
1656
  checkout that never started executing lacks its objects, and provisions
1654
1657
  the next generation. A sandbox whose provisioning a dispatcher teardown cut off
1655
1658
  is different: the next invocation verifies it and finishes it in the same
1656
- generation. If it cannot be finished, it is released and replaced without
1659
+ generation, resuming after its last completed stage at the commit it cloned. If it cannot be finished, it is released and replaced without
1657
1660
  consuming `maxInfrastructureAttempts`. A bounded dispatcher invocation does not
1658
1661
  start provisioning with less than about 150 s of budget left; it records
1659
1662
  `provisioningDeferred` in the tick report, logs the build, and records it in
1660
- `dispatcher.work-deferred`, so the next invocation provisions it first.
1663
+ `dispatcher.work-deferred`, so the next invocation provisions it first. That
1664
+ includes the first provision of a build intake just claimed: the build keeps
1665
+ its slot, and the next invocation completes its dispatch first.
1661
1666
 
1662
1667
  The representative actual-provider check is opt-in and must point at an
1663
1668
  independent consuming repository whose `autobuild.toml` selects the universal
@@ -87,6 +87,19 @@ next tick recovers automatically without spending build infrastructure attempts.
87
87
  Project account slots never fall back to service-environment credentials.
88
88
  Observation, controls and cleanup continue during the hold.
89
89
 
90
+ Each hosted invocation is one bounded pass. Its stages share the window: the
91
+ janitor, the lease sweep and deferred work may each start items for half of the
92
+ time left when they begin, the other stages for a quarter, and intake runs to
93
+ the work deadline. Loops whose items stay listed (settlement, the janitor,
94
+ hand-backs, dispatch recovery, resume and the lease sweep) continue on the next
95
+ invocation after the last item they started; priority-ordered loops (node
96
+ admission, start requests, ready tickets, ticket waits) keep their order. Each
97
+ pass logs a `stages:` line; see
98
+ [a stage keeps stopping at the work deadline](troubleshooting.md#a-stage-keeps-stopping-at-the-work-deadline).
99
+ Deferred work is every start a pass admitted but didn't finish (a provision, a
100
+ launch the work deadline cut, or a stopped-sandbox recovery); the next
101
+ invocation runs it first.
102
+
90
103
  ### Origin-mode dispatcher with remote workspaces
91
104
 
92
105
  Commit a remote-compatible configuration to the base branch:
@@ -776,7 +776,7 @@ builds.
776
776
  | `appendRepo` | `POST /repos/{repo}/events` | event write | `201` + repository event envelope |
777
777
  | `appendRepoIfCurrent` | `POST /repos/{repo}/events/conditional` | `{"expectedSeq": nonnegative integer, "event": event write}` | appended: `201` + repository event envelope; journal advanced: `200 null` (mirroring section 3's build compare-and-append). A server without the route answers `404`; callers report it and never fall back to an unconditional append |
778
778
  | `getRepoEvents` / `getRepositoryTail` | `GET /repos/{repo}/events?since={n}&through={n}&wait={s}` | optional `since` query value, parsed as in section 3; absence defaults to `0`. Optional `wait` in whole seconds, per the event-wait rules of section 3 | `200` + envelopes with `seq > since`, up to the frozen head; optional `through` caps the response at `seq <= through`; `409 cursor-too-old` below `max(0, head - 1000)` |
779
- | `getRepoStateEvents` | `GET /repos/{repo}/state-events` | none | `200` + the bounded repository-journal subset (AUT-489): every durable event type (`ticket-preparation.*`, `harvest.*`, `orchestrator.sandbox.*`, the three dispatcher setting types, and cross-generation handoff correlation facts: target-prepared, yield-requested, upgrade-failed, handoff-started, terminal-released, takeover, drain-deadline, drain-settled and handoff-completed) plus the latest-only `dispatcher.ticket-scan-completed`, `dispatcher.placement-set` and `dispatcher.work-deferred` facts and, when the journal has one, the tail from the latest `dispatcher.run-started`, in increasing sequence order; served inside the repository-existence gate like `GET events`, so an unknown repository is `404` |
779
+ | `getRepoStateEvents` | `GET /repos/{repo}/state-events` | none | `200` + the bounded repository-journal subset (AUT-489): every durable event type (`ticket-preparation.*`, `harvest.*`, `orchestrator.sandbox.*`, the three dispatcher setting types, and cross-generation handoff correlation facts: target-prepared, yield-requested, upgrade-failed, handoff-started, terminal-released, takeover, drain-deadline, drain-settled and handoff-completed) plus the latest-only `dispatcher.ticket-scan-completed`, `dispatcher.placement-set`, `dispatcher.work-deferred` and `dispatcher.pass-cursors` facts and, when the journal has one, the tail from the latest `dispatcher.run-started`, in increasing sequence order; served inside the repository-existence gate like `GET events`, so an unknown repository is `404` |
780
780
  | `getReducerSnapshot` (repo scope) | `GET /repos/{repo}/snapshots/{reducer}?version={n}` | required `version` query value, a positive integer; `reducer` is a registry name (`^[A-Za-z][A-Za-z0-9._-]{0,63}$`) | `200` + `{"version", "cursor", "state"}` or `200 null` when absent, written by another reducer version, ahead of the journal's tail, or the repository has no journal record; an unknown repository is `404`, which the shipped client also maps to `null` |
781
781
  | `putReducerSnapshot` (repo scope) | `PUT /repos/{repo}/snapshots/{reducer}` | `{"version": int >= 1, "cursor": int >= 0, "state": JSON}`, at most 16 MiB (`413` above) | `200 {"written": boolean}`; the stored cursor never decreases, so a write at an equal or lower cursor (or an equal cursor at an equal or lower version) and one past the journal's tail answer `written: false` |
782
782
  | `appendRepoWithArtifacts` | `POST /repos/{repo}/deposits` | atomic deposit request | `201` + `{event, artifacts}` using repository shapes |
@@ -60,6 +60,7 @@ bun ab harvest status
60
60
  - **Forge cooldown:** `forge landing/polling paused until <reset>` means a GitHub rate limit holds forge work until that reset, whether a request was refused or a successful response reported the quota exhausted. `forge rate limit <resource>` lines show the last observed quota and when it was seen.
61
61
  - **Capacity:** a build holds a slot while Autobuild owes its next move. Paused builds, builds blocked on a question once nothing is still working on them, builds waiting for a merge decision or on other tickets, and idle collecting nodes hold none. An answered or resumed build, a finished build that must re-verify or reconcile, and a build whose ticket wait ended wait as parked work for a slot ahead of claims at its level; higher-level work, including higher-level ready tickets, goes first, and `ab priority <slug> urgent` expedites a waiting build. Occupancy never exceeds `capacity`.
62
62
  - **Harvest:** check the acknowledged harvest gate and unclaimed observations. Harvest triggers at `policy.harvestThreshold` observations, or `policy.harvestMaxDrift` other merged builds since the oldest observation (zero disables drift), and uses no build slot.
63
+ - **Bounded passes:** a hosted invocation also prints `stages:`. If `intake` is missing from it, see [a stage keeps stopping at the work deadline](#a-stage-keeps-stopping-at-the-work-deadline).
63
64
 
64
65
  ## Worktree destination not isolated
65
66
 
@@ -130,20 +131,49 @@ See [answering blocked builds](operating.md#answer-and-pause). Preserve event lo
130
131
  A step the invocation deadline defers is not a failure:
131
132
 
132
133
  - It charges no infrastructure attempt.
133
- - The dispatch log names it: `build <slug>: <step> deferred by the invocation budget`.
134
+ - The dispatch log names it: `build <slug>: <step> deferred by the invocation budget`. The step is `provision`, `launch` or a recovery step.
134
135
  - The tick counts it as `recoveryDeferred` (or `provisioningDeferred`) and never reports `tick: idle`.
135
- - The next invocation runs that build first.
136
+ - The build keeps its slot, and the next invocation runs it first.
137
+ - A `launch` the deadline cut never waits on a lease TTL. Teardown fences the sandbox when the start was requested, then releases the lease; the next invocation's first stage finishes whatever teardown couldn't.
136
138
 
137
139
  See [Vercel sandbox recovery](configuration.md#vercel-sandbox).
138
140
 
139
141
  ## A build stays STARTING with repeated deferral lines
140
142
 
141
- **Symptom.** The same build logs `resume deferred by the invocation budget` or `provision deferred by the invocation budget` on several invocations in a row, and stays STARTING.
143
+ **Symptom.** The same build logs `resume`, `provision` or `launch deferred by the invocation budget` on several invocations in a row, and stays STARTING.
142
144
 
143
145
  **Cause.** Even with the build served first, the hosted invocation budget can't fit the work. A provision needs about 150 s; a resume needs about 105 s by default (a realistic resume plus the cleanup reserve).
144
146
 
145
147
  **Action.** Report it to the instance operator: the invocation budget is too small for this work. Retrying the build doesn't help.
146
148
 
149
+ A repeating `fence deferred by the invocation budget` line with an infrastructure failure at step `fence` is different: the provider can't confirm the sandbox stopped, so the cut launch's lease is kept and nothing relaunches. Check the sandbox in the provider.
150
+
151
+ ## A provision is cut off at teardown on several invocations
152
+
153
+ **Symptom.** A STARTING build's provisioning is abandoned at dispatcher teardown on more than one invocation.
154
+
155
+ **Cause.** The provision is longer than one invocation. That is normal: each invocation resumes the same sandbox after its last completed stage, at the commit it cloned, so the provision still finishes.
156
+
157
+ **Action.** If teardown keeps cutting off the same stage, that one stage outlasts the invocation budget. Report the stage to the instance operator.
158
+
159
+ ## A stage keeps stopping at the work deadline
160
+
161
+ **Symptom.** Hosted invocations log `tick: work deadline reached during <stage>`, or `ab repository status` shows `last pass stages: … stopped by the work deadline during …` on pass after pass.
162
+
163
+ **Reading the lines.** Every bounded pass prints one `stages:` line, for example:
164
+
165
+ ```text
166
+ stages: settlement 3.1s 6/11 (executions 5/9, harvest 1/2, sandboxes 0/0) · janitor 131.4s 4/12 (share) · sweep 40.2s 9/9 · intake 12.0s 1/1
167
+ ```
168
+
169
+ - **Time and items:** each stage's seconds and the items it reached out of those it listed.
170
+ - **`(share)`:** the stage used its share of the window and stopped starting items. In settlement, the janitor, hand-backs, dispatch recovery, resume and the lease sweep, the loop continues on the next invocation after the last item it started, so it works through its whole listing over successive passes. Priority-ordered loops (node admission, start requests, ready tickets, ticket waits) start from the top again.
171
+ - **`(deadline)`:** the work deadline stopped the pass inside that stage. The `tick: work deadline reached during …` line names the part in flight, such as `settlement: harvest 1 of 2 (6 of 11 overall)`.
172
+
173
+ **Cause.** One visit in the named stage takes most of the window: usually a slow forge or provider call for one build.
174
+
175
+ **Action.** Report the stage and part to the instance operator with the `stages:` lines from several invocations. A stage stopped by `share` alone is normal under load.
176
+
147
177
  ## Remote project access
148
178
 
149
179
  **Symptom.** Remote requests refuse a project despite a configured URL.
@@ -115,6 +115,7 @@ Sandbox preparation order:
115
115
 
116
116
  - **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.
117
117
  - **Repetition.** New sandboxes repeat provisioning and preflights rerun before each build-runner; keep setup idempotent.
118
+ - **Resumption.** A provision cut off by a dispatcher teardown resumes in place on the next invocation, at the commit it cloned. Stages already completed with unchanged inputs (checkout, Bun, each `provisioning` step, distribution, dependencies, runtime installs) are skipped; a stage whose inputs changed reruns with every stage after it.
118
119
  - **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, Claude and Kimi project secrets report readiness from write-only status metadata instead; the first hosted build is the live check.
119
120
  - **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 archive refs or, where the forge refuses them, BuildStore copies, 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).
120
121
 
@@ -154,4 +155,4 @@ The suite certifies only the basic working copy. Remote execution adds trusted s
154
155
  - Publication reports confirmed SHA and cache tips and supports the required guarded rewrites.
155
156
  - Store grants go through the host's `delegateCredential` callback; never serialize host tokens into execution identity.
156
157
  - An optional `provisionEstimateMs` declares the expected wall time of one `provision`; a bounded dispatcher invocation does not start provisioning with less budget left.
157
- - `provision` may receive `adoptAbandoned` when the previous attempt at the same generation was cut off by a recorded dispatcher teardown. Finish that environment in place only after verifying it; otherwise throw `WorkspaceCleanupRequired`.
158
+ - `provision` may receive `adoptAbandoned` when the previous attempt at the same generation was cut off by a recorded dispatcher teardown. Finish that environment in place only after verifying it, resuming from verified progress and keeping the commit it already holds; otherwise throw `WorkspaceCleanupRequired`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.14.0",
3
+ "version": "1.16.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -162,8 +162,8 @@
162
162
  },
163
163
  "devDependencies": {
164
164
  "@biomejs/biome": "2.5.5",
165
- "@defrex/autobuild-postgres-store": "1.14.0",
166
- "@defrex/autobuild-vercel-sandbox": "1.14.0",
165
+ "@defrex/autobuild-postgres-store": "1.16.0",
166
+ "@defrex/autobuild-vercel-sandbox": "1.16.0",
167
167
  "@resvg/resvg-js": "2.6.2",
168
168
  "@types/bun": "^1.3.14",
169
169
  "@types/node": "^24.0.0",
@@ -234,6 +234,11 @@ import {
234
234
  type LaunchRunnerResult,
235
235
  type TickReport,
236
236
  } from '../processes/dispatcher'
237
+ import {
238
+ formatDeadlineStop,
239
+ formatPassStages,
240
+ type PassStageRecord,
241
+ } from '../processes/pass-stages'
237
242
  import { RepoViewStore } from '../processes/repo-view'
238
243
  import {
239
244
  BuildControlError,
@@ -253,6 +258,8 @@ import {
253
258
  budgetedFetch,
254
259
  DEFAULT_TIMERS,
255
260
  InvocationBudgetExhaustedError,
261
+ InvocationDeadlineError,
262
+ LaunchCutByDeadline,
256
263
  invocationSignal,
257
264
  untilAborted,
258
265
  withInvocationSignal,
@@ -437,6 +444,9 @@ export {
437
444
  budgetedFetch,
438
445
  InvocationDeadlineError,
439
446
  InvocationBudgetExhaustedError,
447
+ LaunchCutByDeadline,
448
+ isLaunchCutByDeadline,
449
+ type CutLaunch,
440
450
  type InvocationBudget,
441
451
  } from '../processes/invocation-budget'
442
452
 
@@ -878,6 +888,9 @@ interface ActiveBuildExecution {
878
888
  detaching?: boolean
879
889
  /** A wait failure being recorded; teardown lets it finish rather than drop it. */
880
890
  recording?: Promise<void>
891
+ /** Set immediately before the provider start is requested: from here a
892
+ * deadline-cut launch may have a guest running and must be fenced. */
893
+ startRequested?: boolean
881
894
  }
882
895
 
883
896
  /** The dispatch loop owns deterministic decisions and supervises one
@@ -1600,6 +1613,7 @@ class DispatchLoop {
1600
1613
 
1601
1614
  private dispatcherTick(resumeCurrent: boolean): Promise<Awaited<ReturnType<Dispatcher['tick']>>> {
1602
1615
  return this.serialize(async () => {
1616
+ this.stagesPrinted = false
1603
1617
  // The yield observer may have accepted while this tick was queued.
1604
1618
  if (this.retirement !== undefined) return emptyTickReport()
1605
1619
  // Refresh before every watch decision. The owner publishes atomically;
@@ -1646,7 +1660,10 @@ class DispatchLoop {
1646
1660
  const readyObservation =
1647
1661
  settings.intake || (!this.dashboard && this.opts.kernelRunId === undefined)
1648
1662
  ? undefined
1649
- : await this.dispatcher.observeReady({ viewRefreshed: true })
1663
+ : await this.dispatcher.observeReady({
1664
+ viewRefreshed: true,
1665
+ ...(this.opts.deadlineAt !== undefined ? { deadlineAt: this.opts.deadlineAt } : {}),
1666
+ })
1650
1667
  await this.wiring.renewAccounts?.({ repo: this.repoIdentity, run: this.runId })
1651
1668
  const report = await this.dispatcher.tick({
1652
1669
  resumeCurrent,
@@ -3744,10 +3761,18 @@ class DispatchLoop {
3744
3761
  const active: ActiveBuildExecution = { reservation, instance, stopping: false }
3745
3762
  this.activeBuildRuns.set(slug, active)
3746
3763
  let leaseClaimed = false
3764
+ /** The claim was sent but not acknowledged: it may have committed. */
3765
+ let claimUnacknowledged = false
3766
+ let cutWorkspace: { provider: string; ref: string } | undefined
3767
+ /** Whether the owning provider can fence its workspace (stop a guest
3768
+ * that outlives this process). */
3769
+ let cutFenceable = false
3747
3770
 
3748
3771
  try {
3749
3772
  await this.publishBuildConfig(slug)
3773
+ claimUnacknowledged = true
3750
3774
  leaseClaimed = await this.repoView.claimLease(slug, instance, BUILD_EXECUTION_LEASE_TTL_MS)
3775
+ claimUnacknowledged = false
3751
3776
  if (!leaseClaimed) {
3752
3777
  this.activeBuildRuns.delete(slug)
3753
3778
  await this.appendStatus({
@@ -3766,7 +3791,11 @@ class DispatchLoop {
3766
3791
  // provisioned before a provider switch still runs where it lives.
3767
3792
  const owning =
3768
3793
  workspaceProvider === undefined || workspaceProvider === this.wiring.workspaces.name
3769
- ? { name: this.wiring.workspaces.name, execution: this.wiring.buildExecution }
3794
+ ? {
3795
+ name: this.wiring.workspaces.name,
3796
+ execution: this.wiring.buildExecution,
3797
+ recovery: this.wiring.workspaces.recovery,
3798
+ }
3770
3799
  : (() => {
3771
3800
  const retired = this.wiring.retiredWorkspaces?.find(
3772
3801
  (runtime) => runtime.provider.name === workspaceProvider,
@@ -3776,8 +3805,14 @@ class DispatchLoop {
3776
3805
  `build ${slug} workspace ${workspaceRef} belongs to provider "${workspaceProvider}", which is no longer configured`,
3777
3806
  )
3778
3807
  }
3779
- return { name: retired.provider.name, execution: retired.execution }
3808
+ return {
3809
+ name: retired.provider.name,
3810
+ execution: retired.execution,
3811
+ recovery: retired.provider.recovery,
3812
+ }
3780
3813
  })()
3814
+ cutWorkspace = { provider: owning.name, ref: workspaceRef }
3815
+ cutFenceable = owning.recovery !== undefined
3781
3816
  // A prior publication acknowledgement may have been lost after its push
3782
3817
  // reached the durable branch. Reconcile that fact before a replacement
3783
3818
  // runner can rerun the phase and create a non-fast-forward successor.
@@ -3795,6 +3830,9 @@ class DispatchLoop {
3795
3830
  ),
3796
3831
  }
3797
3832
  : undefined
3833
+ // No launch starts after the work deadline (teardown's invariant).
3834
+ if (!this.acceptingBuildLaunches) throw new InvocationDeadlineError('work')
3835
+ active.startRequested = true
3798
3836
  const handle = await owning.execution.start(
3799
3837
  {
3800
3838
  slug,
@@ -3951,6 +3989,25 @@ class DispatchLoop {
3951
3989
  if (isRecoveryDeferred(error)) throw error
3952
3990
  return 'already-active'
3953
3991
  }
3992
+ if (
3993
+ (leaseClaimed || claimUnacknowledged) &&
3994
+ this.opts.invocationBudget?.work.aborted === true &&
3995
+ (active.handle === undefined || (await this.releaseCutHandle(active.handle, cutFenceable)))
3996
+ ) {
3997
+ // The work deadline cut the launch after its lease claim — before
3998
+ // the claim's acknowledgement (it may have committed; the exact-holder
3999
+ // release is a no-op if not), before the provider returned, or
4000
+ // before `execution.started` committed.
4001
+ // Record nothing here: the dispatcher fences when the start was
4002
+ // requested, releases the exact holder in teardown and carries the
4003
+ // launch.
4004
+ throw new LaunchCutByDeadline({
4005
+ slug,
4006
+ instance,
4007
+ startRequested: active.startRequested === true,
4008
+ ...(cutWorkspace !== undefined ? { workspace: cutWorkspace } : {}),
4009
+ })
4010
+ }
3954
4011
  if (leaseClaimed) {
3955
4012
  // The runner appended through its own handle: take the delta.
3956
4013
  await this.repoView.refreshBuild(slug)
@@ -3985,6 +4042,28 @@ class DispatchLoop {
3985
4042
  }
3986
4043
  }
3987
4044
 
4045
+ /** A handle whose `execution.started` the work deadline cut: nothing will
4046
+ * settle it, so stop supervising it. A guest that outlives this process is
4047
+ * detached for the dispatcher's workspace fence; a local child is stopped
4048
+ * here. False when neither can prove the execution gone — the ordinary
4049
+ * start failure then keeps the lease until its TTL fences it. */
4050
+ private async releaseCutHandle(
4051
+ handle: BuildExecutionHandle,
4052
+ fenceable: boolean,
4053
+ ): Promise<boolean> {
4054
+ handle.completion.catch(() => {})
4055
+ if (handle.supervision === 'environment') {
4056
+ if (!fenceable) return false
4057
+ await handle.detach().catch(() => {})
4058
+ return true
4059
+ }
4060
+ try {
4061
+ return (await handle.stop())?.outcome !== 'unknown'
4062
+ } catch {
4063
+ return false
4064
+ }
4065
+ }
4066
+
3988
4067
  private get stopped(): boolean {
3989
4068
  return (
3990
4069
  this.cutoverRequested || this.opts.signal?.aborted === true || this.inputStop.signal.aborted
@@ -4333,7 +4412,31 @@ class DispatchLoop {
4333
4412
  }
4334
4413
  }
4335
4414
 
4415
+ /** Whether this pass's `stages:` line was printed, by its report or by
4416
+ * bounded teardown; a pass prints it once. */
4417
+ private stagesPrinted = false
4418
+
4336
4419
  private printReport(report: Awaited<ReturnType<Dispatcher['tick']>>, printIdle = true): boolean {
4420
+ const printed = this.printReportLines(report, printIdle)
4421
+ // A bounded pass's per-stage time and items (#1409): display only, never
4422
+ // a counter.
4423
+ if (report.stages !== undefined && !this.stagesPrinted) this.printStages(report.stages)
4424
+ return printed
4425
+ }
4426
+
4427
+ /** A bounded pass's deadline line, when the work deadline stopped a stage,
4428
+ * then its `stages:` line; once per pass. */
4429
+ private printStages(stages: readonly PassStageRecord[]): void {
4430
+ this.stagesPrinted = true
4431
+ const stop = formatDeadlineStop(stages)
4432
+ if (stop !== undefined) this.say(`tick: ${stop}`)
4433
+ this.say(`stages: ${formatPassStages(stages)}`)
4434
+ }
4435
+
4436
+ private printReportLines(
4437
+ report: Awaited<ReturnType<Dispatcher['tick']>>,
4438
+ printIdle: boolean,
4439
+ ): boolean {
4337
4440
  // `queued` is a standing depth, not a tick action — the header owns it;
4338
4441
  // repeating it in the notice would make every saturated tick look busy.
4339
4442
  const {
@@ -4345,6 +4448,7 @@ class DispatchLoop {
4345
4448
  agentContextDiagnostics,
4346
4449
  deferredDiagnostics,
4347
4450
  queued: _queued,
4451
+ stages: _stages,
4348
4452
  ...counts
4349
4453
  } = report
4350
4454
  for (const line of janitorDiagnostics) this.routineDiagnostic(line)
@@ -5526,7 +5630,9 @@ class DispatchLoop {
5526
5630
  for (const report of settledReports) {
5527
5631
  settledPrinted = this.printReport(report, false) || settledPrinted
5528
5632
  }
5529
- if (!initialPrinted && !settledPrinted) {
5633
+ // A pass the work deadline cut short is reported by bounded teardown,
5634
+ // never as idle.
5635
+ if (!initialPrinted && !settledPrinted && !this.budgetStopped()) {
5530
5636
  this.printReport(emptyTickReport())
5531
5637
  }
5532
5638
  // One delivery pass per configured hook; the next invocation retries.
@@ -5570,6 +5676,18 @@ class DispatchLoop {
5570
5676
  // Whether or not the deadline fired, no launch may start during
5571
5677
  // teardown: provisioning abandonment runs beside execution teardown.
5572
5678
  this.onWorkDeadline()
5679
+ // Runner starts the work deadline cut mid-flight settle their execution
5680
+ // leases (fence, exact-holder release) and carry the launch in the
5681
+ // deferred-work hint while the repository lease is still held.
5682
+ const starts = untilAborted(
5683
+ withInvocationSignal(budget.cleanup, async () => {
5684
+ for (const line of await this.dispatcher.settleCutStarts()) this.say(line)
5685
+ }),
5686
+ budget.cleanup,
5687
+ )
5688
+ // The cut pass's lines print now; its advisory writes race beside the
5689
+ // other cleanup, so a stalled write never postpones unrelated teardown.
5690
+ const summary = this.reportCutPass(budget, starts)
5573
5691
  const provisioning = untilAborted(
5574
5692
  withInvocationSignal(budget.cleanup, () => this.dispatcher.stopProvisioning()),
5575
5693
  budget.cleanup,
@@ -5585,7 +5703,7 @@ class DispatchLoop {
5585
5703
  }),
5586
5704
  budget.cleanup,
5587
5705
  )
5588
- const cleanup = await Promise.allSettled([provisioning, optional])
5706
+ const cleanup = await Promise.allSettled([provisioning, optional, summary, starts])
5589
5707
  await untilAborted(
5590
5708
  withInvocationSignal(budget.final, () => this.releaseRepoLease()),
5591
5709
  budget.final,
@@ -5594,6 +5712,54 @@ class DispatchLoop {
5594
5712
  if (failed !== undefined) throw failed.reason
5595
5713
  }
5596
5714
 
5715
+ /** A pass the work deadline abandoned before its report printed (#1409):
5716
+ * name the stage and part in flight and print the stages so far, at once;
5717
+ * then, as a teardown racer bounded by the cleanup deadline, record where
5718
+ * the pass's loops reached and close the still-open tick boundary with
5719
+ * that partial summary, so `ab repository status` shows it. Never rejects:
5720
+ * a concurrent abandoned publication may already have closed the boundary. */
5721
+ private reportCutPass(budget: InvocationBudget, starts: Promise<unknown>): Promise<void> {
5722
+ const writes: Promise<void>[] = []
5723
+ const write = (what: string, run: () => Promise<unknown>) =>
5724
+ writes.push(
5725
+ untilAborted(run(), budget.cleanup).then(
5726
+ () => undefined,
5727
+ (error: unknown) => this.warn(`${what} not recorded: ${formatDispatcherError(error)}`),
5728
+ ),
5729
+ )
5730
+ // The next invocation continues after the visit the deadline cut short.
5731
+ // A no-op when the pass already recorded its positions; the write itself
5732
+ // goes through teardownWrite.
5733
+ write('pass positions', () => this.dispatcher.persistPassPositions())
5734
+ const stages = this.stagesPrinted ? undefined : this.dispatcher.passReport()?.stages
5735
+ if (stages !== undefined && stages.length > 0) {
5736
+ this.printStages(stages)
5737
+ if (this.tickStartedAt !== undefined) {
5738
+ write('partial pass summary', async () => {
5739
+ // The closed tick counts the starts teardown carried.
5740
+ await starts.catch(() => {})
5741
+ const partial = this.dispatcher.passReport()
5742
+ if (partial === undefined) return
5743
+ const {
5744
+ queued: _queued,
5745
+ janitorDiagnostics: _janitorDiagnostics,
5746
+ blockedDiagnostics: _blockedDiagnostics,
5747
+ ticketDiagnostics: _ticketDiagnostics,
5748
+ creationDiagnostics: _creationDiagnostics,
5749
+ dependencyDiagnostics: _dependencyDiagnostics,
5750
+ agentContextDiagnostics: _agentContextDiagnostics,
5751
+ deferredDiagnostics: _deferredDiagnostics,
5752
+ ...counters
5753
+ } = partial
5754
+ await this.teardownWrite(budget)(() =>
5755
+ this.finishTick({ outcome: 'completed', counters }, []),
5756
+ )
5757
+ })
5758
+ }
5759
+ }
5760
+ return Promise.all(writes).then(() => undefined)
5761
+ }
5762
+
5597
5763
  async run(): Promise<void> {
5598
5764
  // Before the `--once` branch, so both modes report it exactly once.
5599
5765
  this.reportRoleDiagnostics()
@@ -1,3 +1,4 @@
1
+ import { deadlineStopDetail, formatPassStages } from '../processes/pass-stages'
1
2
  import { startTierOf, type StartTier } from '../ports/tickets/priority'
2
3
  import { repositoryReadFactsReducer } from '../kernel/read-facts'
3
4
  import {
@@ -525,6 +526,19 @@ function renderUpgradeStatus({ handoff, current, previous }: RepositoryUpgradeSt
525
526
  ]
526
527
  }
527
528
 
529
+ /** The latest bounded pass's per-stage time and items (#1409), and where the
530
+ * work deadline stopped it. */
531
+ function passStagesStatus(
532
+ tick: NonNullable<RepositoryStatus['dispatcher']['latestRun']>['lastTick'] | undefined,
533
+ ): string[] {
534
+ const stages = tick?.outcome === 'completed' ? tick.counters.stages : undefined
535
+ if (stages === undefined || stages.length === 0) return []
536
+ const stop = deadlineStopDetail(stages)
537
+ return [
538
+ `last pass stages: ${formatPassStages(stages)}${stop === undefined ? '' : `; stopped by the work deadline during ${stop}`}`,
539
+ ]
540
+ }
541
+
528
542
  export function renderRepositoryStatus(status: RepositoryStatus): string[] {
529
543
  const tick = (
530
544
  status.dispatcher.holder ??
@@ -611,6 +625,7 @@ export function renderRepositoryStatus(status: RepositoryStatus): string[] {
611
625
  ]
612
626
  : [],
613
627
  ),
628
+ ...passStagesStatus(tick),
614
629
  ...(status.dispatcher.latestStoppedRun
615
630
  ? [
616
631
  `last dispatcher stop: ${status.dispatcher.latestStoppedRun.stoppedAt}; ${status.dispatcher.latestStoppedRun.stop?.outcome}; signal ${status.dispatcher.latestStoppedRun.stop?.signal ?? 'none'}`,