@defrex/autobuild 1.11.1 → 1.12.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 (102) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +177 -54
  3. package/docs/answering-blocked-builds.md +10 -2
  4. package/docs/architecture.md +66 -6
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/configuration.md +13 -11
  7. package/docs/dispatcher.md +1 -1
  8. package/docs/integration-tree.md +28 -16
  9. package/docs/operator-api.md +4 -4
  10. package/docs/operator-surfaces.md +35 -0
  11. package/docs/optimization-nodes.md +3 -2
  12. package/docs/tickets.md +1 -1
  13. package/docs/troubleshooting.md +1 -1
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/ambient-errors.ts +17 -0
  16. package/packages/core/src/cli/bounded-io.ts +174 -0
  17. package/packages/core/src/cli/dashboard/model.ts +81 -23
  18. package/packages/core/src/cli/dashboard/poll.ts +20 -31
  19. package/packages/core/src/cli/dashboard/render.ts +14 -37
  20. package/packages/core/src/cli/dashboard/row-text.ts +24 -7
  21. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  22. package/packages/core/src/cli/dashboard/vocabulary.ts +161 -20
  23. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  24. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  25. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  26. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  27. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  28. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  29. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  30. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  31. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  32. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  33. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  34. package/packages/core/src/cli/dispatch.ts +68 -5
  35. package/packages/core/src/cli/env.ts +2 -15
  36. package/packages/core/src/cli/help.ts +5 -4
  37. package/packages/core/src/cli/main.ts +4 -2
  38. package/packages/core/src/cli/production-store.ts +102 -0
  39. package/packages/core/src/cli/repo-state.ts +2 -3
  40. package/packages/core/src/cli/repository-status.ts +28 -22
  41. package/packages/core/src/cli/sessionless-store.ts +26 -0
  42. package/packages/core/src/cli/status.ts +169 -40
  43. package/packages/core/src/cli/store-opening.ts +15 -58
  44. package/packages/core/src/cli/store-ref.ts +6 -1
  45. package/packages/core/src/config/schema.ts +1 -1
  46. package/packages/core/src/distribution-packaging.ts +156 -18
  47. package/packages/core/src/events/catalog-identity.ts +28 -0
  48. package/packages/core/src/events/catalog.ts +3 -9
  49. package/packages/core/src/events/compatibility.ts +2 -30
  50. package/packages/core/src/events/payloads.ts +11 -0
  51. package/packages/core/src/events/policy.ts +3 -0
  52. package/packages/core/src/events/repository.ts +1 -1
  53. package/packages/core/src/events/sessions.ts +1 -1
  54. package/packages/core/src/events/validation-error.ts +12 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +9 -0
  56. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  57. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  58. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  59. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  60. package/packages/core/src/kernel/capacity-build.ts +21 -0
  61. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  62. package/packages/core/src/kernel/dispatch-capacity.ts +354 -147
  63. package/packages/core/src/kernel/engine.ts +2 -8
  64. package/packages/core/src/kernel/measurement.ts +24 -0
  65. package/packages/core/src/kernel/read-facts.ts +8 -370
  66. package/packages/core/src/kernel/reducer-registry.ts +40 -125
  67. package/packages/core/src/kernel/reducer-revisions.ts +3 -0
  68. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  69. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  70. package/packages/core/src/kernel/reducer.ts +57 -9
  71. package/packages/core/src/kernel/reopen-state.ts +10 -0
  72. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  73. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  74. package/packages/core/src/operator/presentation.ts +13 -0
  75. package/packages/core/src/operator/query.ts +40 -39
  76. package/packages/core/src/operator/registry.ts +3 -3
  77. package/packages/core/src/ports/workspace/fake.ts +15 -3
  78. package/packages/core/src/processes/dispatcher.ts +232 -75
  79. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  80. package/packages/core/src/store/local/capabilities.ts +115 -0
  81. package/packages/core/src/store/local/store.ts +86 -56
  82. package/packages/core/src/store/reduced-reads.ts +9 -1
  83. package/packages/core/src/store/reducer-value-read.ts +235 -0
  84. package/packages/core/src/store/reducer-value-shapes.json +1437 -1349
  85. package/packages/core/src/store/reducer-values.ts +36 -204
  86. package/packages/core/src/store/remote/released-clients.json +11 -0
  87. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  88. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  89. package/packages/core/src/store/rollup-lease.ts +41 -0
  90. package/packages/core/src/store/rollups.ts +7 -38
  91. package/packages/core/src/store/snapshots.ts +1 -1
  92. package/packages/core/src/testing/dispatch-read-budget.ts +265 -4
  93. package/packages/core/src/testing/import-graph.ts +78 -0
  94. package/packages/core/src/testing/reduced-read-budget.ts +221 -22
  95. package/packages/core/src/testing/slot-agreement.ts +52 -0
  96. package/packages/core/src/web/assets/app.js +5 -5
  97. package/skills/guide/SKILL.md +115 -44
  98. package/skills/guide/references/integration-tree.md +28 -16
  99. package/skills/guide/references/operator-api.md +4 -4
  100. package/skills/guide/references/optimization-nodes.md +3 -2
  101. package/skills/operate/SKILL.md +38 -20
  102. package/templates/hosted-service/package.json +2 -2
@@ -98,22 +98,34 @@ execution lease or dispatch capacity. A PR opens or is adopted when the node
98
98
  has commits its current parent lacks; parent-only advancement remains empty.
99
99
 
100
100
 
101
- A node requesting reconcile, verification or, for an optimization node,
102
- propose is admitted before normal ticket claims; urgent work goes first. The request is durable: a
103
- prepared verification cycle, a restack conflict or an open proposal request,
104
- with no runner yet. Until the node holds its slot, intake reserves one
105
- slot for it, and the dispatcher checks its admission every tick regardless of
106
- idle node polling, so a slot freed in any tick goes to the node, not to a new
107
- normal claim. Its candidate occupancy excludes itself and capacity-bearing blocked or
108
- paused descendants, following accepted source-qualified build target ancestry.
109
- Running descendants and unrelated builds still count; ordinary blocked and
110
- paused work retains its slot for every other admission, except a work build
111
- parked by a ticket wait, which holds none. Provisioning reserves
112
- node occupancy before the runner starts. This exception never raises the budget
113
- for new claims. Status and both dashboards report actual occupancy, configured
114
- capacity, effective display capacity and the nodes using descendant-held slots.
115
- Status, `ab builds` and both dashboards report each node waiting for a slot
116
- ahead of normal ticket claims, marking urgent ones. Idle collecting nodes remain free.
101
+ A node takes a slot only by admission for runner work: `reconcile` for a
102
+ restack conflict, `verification` for an integration cycle or a measurement, and
103
+ `propose` for an optimization node's open proposal request. The request is
104
+ durable and is admitted before normal ticket claims, urgent work first. Until
105
+ the node holds its slot, intake reserves one slot for it, and the dispatcher
106
+ checks its admission every tick regardless of idle node polling, so a slot
107
+ freed in any tick goes to the node, not to a new normal claim. Admission counts
108
+ every build that holds a slot, as every admission does.
109
+
110
+ - **Recorded before provisioning.** Admission is a durable `slot.admitted`
111
+ fact naming the work it admitted.
112
+ - **Held through the work.** The node keeps the slot through provisioning,
113
+ launch and relaunch after a crashed runner or expired lease, and across a
114
+ dispatcher restart, until that work is done: the cycle verified or failed,
115
+ the measurement recorded, the proposal deposited or the restack settled.
116
+ - **Released on an outside wait.** A paused node, or one blocked on a question
117
+ (a restack conflict's escalation included), holds none. Once answered or
118
+ resumed, it requests its slot again.
119
+ - **Never held by idling.** An idle collecting node, a node waiting for a
120
+ repair child and a node's retained workspace hold none. Paused descendants,
121
+ and blocked ones with nothing still working on them, hold none either, so they never stand between a node and the
122
+ slot it needs to unblock them.
123
+
124
+ Status and both dashboards report occupancy against configured capacity, and
125
+ each node waiting for a slot ahead of normal ticket claims, marking urgent
126
+ ones.
127
+ Status also reports every build's slot state (`slot`, `capacity.slots`):
128
+ an admitted node reports `held`; a node awaiting admission reports its request.
117
129
 
118
130
  Claims freeze the destination build generation and branch. Missing, unopened,
119
131
  merged, closed or aborted targets leave work queued with diagnostics. The newest
@@ -82,10 +82,10 @@ raw session-event append. External operator harnesses own agent execution.
82
82
 
83
83
  | Method and path | Result |
84
84
  |---|---|
85
- | `GET …/builds?scope=active\|queued\|all` | Build summaries, newest update first. `queued` means active plus queued, matching `ab builds --queued`. |
86
- | `GET …/builds/{slug}` | `{detail, dashboardRow}`; `detail.runnerAttaches` records chronological attach boundaries and their runtime identity (version, commit, source kind/location), with null runtime for unrecorded historical attaches; `dashboardRow` remains a `CLEANING` row after `build.aborted` and becomes `null` only when the dashboard stops listing it (after cleanup's `build.completed`). |
87
- | `GET …/dashboard` | `{generatedAt, model, settingsHeader}`. `model` is the dashboard's rows, steps, elapsed timing inputs, harvest row, triage (when the dispatcher published one)/queue/capacity and settings projection. `model.configuration` is `"no-dispatcher-run"` when the repository records no dispatcher run, and absent otherwise. Optional `rollback` contains `correlation`, `lineage`, full `failed` and `restored` runtime identities and rollback event `ts` for the authoritative dispatcher lineage’s unresolved hold. Both dashboards name failed, restored and held runtime plus timestamp. Matching durable different-target hold clearance removes it; a fresh operator lineage hides it only after a committed operational tick or accepted takeover. Run-started and yielded ticks alone cannot replace authority; same-lineage generations retain the notice. Historical rollback records are not fallback notices. Optional `handoffs` lists all accepted unfinished handoffs with predecessor `run`, optional `successor`, `correlation`, full `from`/`to` runtimes, `mode` and optional `deadline`. Outstanding drain-mode builds carry `draining: true`, also on build-detail `dashboardRow`; matching settlement removes it. Accepted completion removes the handoff; neither takeover nor the clock does. Missing historical mode means cutover and missing deadline displays unknown. |
88
- | `GET …/status` | Repository intake, pause, and default-auto-merge projection, plus `ticketStarts` (`{pending, recent}`, each entry with its `priority`) when single-ticket start requests are pending or recently settled. Its `operator` is `{presence: "unavailable", reason}`: this route does not load presence registrations, so it is not evidence that no operator is present. |
85
+ | `GET …/builds?scope=active\|queued\|all` | Build summaries, newest update first. `queued` means active plus queued, matching `ab builds --queued`. Each nonterminal summary's `slot` is `{state: "held"}`, `{state: "requested", request, priority?: "urgent"}` or `{state: "none"}`; absent means unknown (an older server), never `none`. Its `statusWord` is `{word, tone, note?}`, the status word every surface shows; `status` stays the reducer's lifecycle status. |
86
+ | `GET …/builds/{slug}` | `{detail, dashboardRow}`; `detail.slot` and `dashboardRow.slot` carry the build's slot state, shaped as in `GET …/builds`; `detail.runnerAttaches` records chronological attach boundaries and their runtime identity (version, commit, source kind/location), with null runtime for unrecorded historical attaches; `dashboardRow` remains a `CLEANING` row after `build.aborted` and becomes `null` only when the dashboard stops listing it (after cleanup's `build.completed`). |
87
+ | `GET …/dashboard` | `{generatedAt, model, settingsHeader}`. `model` is the dashboard's rows, steps, elapsed timing inputs, harvest row, triage (when the dispatcher published one)/queue/capacity and settings projection. `model.capacity.slots` maps each build to its slot state, and each `model.builds[].slot` repeats it; absent means unknown. `model.configuration` is `"no-dispatcher-run"` when the repository records no dispatcher run, and absent otherwise. Optional `rollback` contains `correlation`, `lineage`, full `failed` and `restored` runtime identities and rollback event `ts` for the authoritative dispatcher lineage’s unresolved hold. Both dashboards name failed, restored and held runtime plus timestamp. Matching durable different-target hold clearance removes it; a fresh operator lineage hides it only after a committed operational tick or accepted takeover. Run-started and yielded ticks alone cannot replace authority; same-lineage generations retain the notice. Historical rollback records are not fallback notices. Optional `handoffs` lists all accepted unfinished handoffs with predecessor `run`, optional `successor`, `correlation`, full `from`/`to` runtimes, `mode` and optional `deadline`. Outstanding drain-mode builds carry `draining: true`, also on build-detail `dashboardRow`; matching settlement removes it. Accepted completion removes the handoff; neither takeover nor the clock does. Missing historical mode means cutover and missing deadline displays unknown. |
88
+ | `GET …/status` | Repository intake, pause, and default-auto-merge projection, plus `ticketStarts` (`{pending, recent}`, each entry with its `priority`) when single-ticket start requests are pending or recently settled. `capacity.slots`, when the held configuration is readable, maps each nonterminal build to its slot state; `capacity.occupied` counts its `held` entries. Its `operator` is `{presence: "unavailable", reason}`: this route does not load presence registrations, so it is not evidence that no operator is present. |
89
89
  | `GET …/harvest/status` | Harvest gate, runs, steps, recovery, and attention projection. |
90
90
  | `GET …/builds/{slug}/artifacts/{kind}?rev=N` | Raw bytes (`application/octet-stream`) plus content-disposition and `X-Autobuild-Artifact-*` metadata headers. Omit `rev` for latest. |
91
91
  | `GET …/tickets?state=S&label=L&limit=N&offset=K&order=O` | `{states,tickets,diagnostics,criteria,triageState,readyState,doneState,total}`. The three lifecycle names come from effective repository configuration (including provider fallback). With no `state`, `criteria.state` is `triageState`; repeated `label` parameters narrow that state with AND filters. An explicit `state` selects that exact backend workflow state. `limit` (0–200) returns one page, after skipping `offset`, in `order` `oldest` (the default: dispatch order, urgent tickets first, then the source order) or `newest` (newest filed first, regardless of urgency; see paging below); `total` counts every match before paging. |
@@ -48,6 +48,41 @@ When a leaf with an open pull request waits on the PR but has no landing decisio
48
48
 
49
49
  If none of these apply, the line says no refusal is recorded and the dispatcher decides at its next janitor poll. Repository-wide forge deferrals appear in `ab repository status`. When a decision is recorded for the current candidate, the line and the field are no longer shown.
50
50
 
51
+ Status output reports each nonterminal build's slot state, by the rules the dispatcher admits work by ([slots](dispatcher.md#ready-work-becomes-a-build)):
52
+
53
+ | Surface | Text | JSON |
54
+ |---|---|---|
55
+ | `ab builds`, `ab build status` | `SLOT` column, `slot:` line | `slot` |
56
+ | `ab repository status` | `slots:` line after `capacity:` | `capacity.slots`, by slug |
57
+
58
+ - Values: `{"state":"held"}`, `{"state":"requested","request":…,"priority":"urgent"}` (`request` is `resume`, `reconcile`, `verification`, `reopen` or `propose`; `priority` only when urgent), or `{"state":"none"}`.
59
+ - `capacity.occupied` counts exactly the `held` entries. A requested build is a slot waiter.
60
+ - A missing value is unknown, from a server older than this field. It is never `none`, and text prints `unknown`. A `done` build reports no slot state.
61
+
62
+ ### Status words
63
+
64
+ Every nonterminal build row on both dashboards, `ab builds` and `ab build status` shows one word from one closed vocabulary. The color says whether the build holds a slot; the word says why, and a short note says which case.
65
+
66
+ | Word | Color | Slot | Shown when |
67
+ |---|---|---|---|
68
+ | `RUNNING` | green | held | A runner is working. |
69
+ | `STARTING` | green | held | No runner works yet: a newly claimed build provisioning, a relaunch, spec publication, an upgrade drain, a suspended session. |
70
+ | `PAUSING` | green | held | A pause was requested and the runner is still stopping. |
71
+ | `ABORTING` | green | held | An abort was requested and the runner is still stopping. |
72
+ | `QUEUED` | teal | requested | Parked work waiting for admission. The note names the request (`resume`, `reconcile`, `verification`, `reopen`, `propose`) and marks urgent waiters. |
73
+ | `WAITING` | amber | none | A finished pipeline waiting for a merge decision (`merge decision`) or on hold (`on hold`), a ticket wait (`on <ids>`), or a `revise-spec` answer waiting for its revision (`spec revision`). |
74
+ | `MERGING` | amber | none | A finished pipeline with merge consent, waiting for merge gates or the forge. |
75
+ | `PAUSED` | amber | none | An acknowledged pause. |
76
+ | `COLLECTING` | amber | none | An integration build collecting child work. |
77
+ | `BLOCKED` | red | none | An open escalation, or a failed node verification waiting for a repair child. |
78
+ | `CLEANING` | dim | none | Abort cleanup. |
79
+
80
+ - Green means held: the active counter `<occupied>/<capacity>` counts the green rows.
81
+ - `PAUSING` and `ABORTING` appear only on a build that holds a slot. A build without one keeps its word until the pause or abort is acknowledged.
82
+ - A Harvest row never holds a slot: `HARVESTING` (teal) while it works, `PAUSED` or `SUSPENDED` (amber) while stopped, `ESCALATED` or `FAILED` (red) when it needs a human.
83
+ - `ab builds` prints the word and note in `STATUS`; JSON adds `statusWord` (`{word, tone, note?}`), while `status` stays the lifecycle status the filters select on.
84
+ - `ab builds` and `ab build status` color the word with its tone on an interactive terminal, and print it plain when piped or under `--json`.
85
+
51
86
  A local CLI can use a remote Store:
52
87
 
53
88
  <!-- seam-config:start -->
@@ -295,8 +295,9 @@ spread. A command node uses the objective's pairing and sample count (see
295
295
  [judge panel](#judge-panels) of its harness pin against itself: its starting
296
296
  value is 0.5, and its spread is the distance of that self-comparison win rate
297
297
  from 0.5. The dispatcher admits that run as it admits a node verification: the
298
- node takes a runner slot, gets a workspace for the run, and releases it once
299
- the starting value is recorded.
298
+ node holds a runner slot from admission until the starting value is recorded,
299
+ through any relaunch of its runner. The workspace for the run is provisioned
300
+ after admission and released separately; it never holds the slot.
300
301
 
301
302
  **Noise check.** When ε, in metric units, is smaller than the measured spread,
302
303
  the gate would accept noise. A panel's ε is a win-rate margin, compared with
package/docs/tickets.md CHANGED
@@ -90,7 +90,7 @@ Moving a ticket back to triage, backlog or ready restores ordinary behavior. "Bu
90
90
  Ordinary intake claims only tickets in the ready state with the required labels and any source-specific listing filter, such as a ready assignee. A ticket named by `ab start` (`tickets.start`) must still be in the ready state, but those listing labels and the ready assignee are not applied to it. A ready ticket still waits on:
91
91
 
92
92
  - **Blockers.** Unresolved prerequisite tickets keep it queued; they don't create a blocked build. With nodes, prerequisites with builds must be present at the sampled destination; see [integration and blocker presence](integration-overview.md).
93
- - **Destination and capacity.** Its target must accept new work, and a capacity slot must be free and not reserved for an integration node awaiting verification, a finished build waiting to re-verify or reconcile, or a build resuming after its ticket wait ends; each of those is admitted before normal claims (see [slot admission order](dispatcher.md#slot-admission-order)). A pending `ab start` request reserves a slot ahead of the claims and parked work its tier outranks.
93
+ - **Destination and capacity.** Its target must accept new work, and a capacity slot must be free and not reserved for an integration node awaiting verification, a finished build waiting to re-verify or reconcile, or a build resuming after an answered escalation, a resumed pause or an ended ticket wait; each of those is admitted before normal claims (see [slot admission order](dispatcher.md#slot-admission-order)). A pending `ab start` request reserves a slot ahead of the claims and parked work its tier outranks.
94
94
  - **Open-PR backpressure.** When the repository configures `maxOpenPrs` and that many root build PRs are open and unmerged, the dispatcher pauses ordinary ready-queue normal-priority claims, even with a free slot, until the count drains to `resumeOpenPrs` (below `maxOpenPrs` when the two are equal). Urgent tickets bypass this gate, and so does every `ab start` tier, which still respects capacity and repository pause. See [`[policy]`](configuration.md#policy) for the thresholds.
95
95
 
96
96
  When a slot is free, the dispatcher takes urgent ready tickets first, then normal ones, each in the source's order. Urgent tickets also go ahead of normal builds waiting to re-verify, reconcile or resume, though not ahead of urgent ones. An ordinary claimed ticket's priority becomes its build's priority. An [optimization node's attempts](optimization-nodes.md#attempts) claim at the node's current priority instead: a later `ab priority` on the node affects attempts claimed afterwards, while an already claimed attempt keeps its build priority. To expedite a build that already exists, run `ab priority <slug> urgent`. Urgent tickets also bypass open-PR backpressure: a blocked urgent ticket waits like any other while normal work proceeds, and an urgent ticket never stops or pauses a running build. The web dashboard's Queue tab lists tickets in the same order and marks urgent ones `URGENT`; the mark shows priority, not that the ticket will dispatch next.
@@ -58,7 +58,7 @@ bun ab harvest status
58
58
  - **Blockers and destination:** blockers done, target node open, required changes in the destination. A target node built by another dispatcher's store never opens here; see [several dispatchers](build-store.md#several-dispatchers-on-one-repository). `ab repository status` lists the queue diagnostics.
59
59
  - **Claims:** claimed tickets aren't reclaimed.
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
- - **Capacity:** paused unfinished work, and work blocked on a question, keeps its slot; builds waiting for a merge decision, builds waiting on other tickets, and idle collecting nodes take none. A finished build that must re-verify or reconcile, or a build whose ticket wait ended, reserves a slot ahead of normal claims; urgent work, including urgent ready tickets, goes first, and `ab priority <slug> urgent` expedites a waiting build. Node verification and reconciliation account specially for descendants' slots.
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 normal claims; urgent work, including urgent 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
63
 
64
64
  ## Worktree destination not isolated
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.11.1",
3
+ "version": "1.12.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.11.1",
166
- "@defrex/autobuild-vercel-sandbox": "1.11.1",
165
+ "@defrex/autobuild-postgres-store": "1.12.0",
166
+ "@defrex/autobuild-vercel-sandbox": "1.12.0",
167
167
  "@resvg/resvg-js": "2.6.2",
168
168
  "@types/bun": "^1.3.14",
169
169
  "@types/node": "^24.0.0",
@@ -0,0 +1,17 @@
1
+ /** Ambient-identity errors, free of the session resolvers so store openers can
2
+ * raise them without initializing `./env`, which re-exports them. */
3
+ const BUILD_AMBIENT_TUPLE = 'AB_STORE/AB_BUILD/AB_PHASE/AB_SESSION'
4
+ const HARVEST_AMBIENT_TUPLE = 'AB_STORE/AB_REPO/AB_HARVEST/AB_PHASE/AB_SESSION'
5
+
6
+ /** Optional ambient identity is present but cannot safely select one scope. */
7
+ export class InvalidAmbientContextError extends Error {
8
+ override readonly name = 'InvalidAmbientContextError'
9
+
10
+ constructor(detail: string) {
11
+ super(
12
+ `invalid ambient context: ${detail}. Expected no agent identity markers, ` +
13
+ `a complete build tuple (${BUILD_AMBIENT_TUPLE}), or a complete Harvest tuple ` +
14
+ `(${HARVEST_AMBIENT_TUPLE})`,
15
+ )
16
+ }
17
+ }
@@ -0,0 +1,174 @@
1
+ /** Bounded concurrency for runtime tree IO. Every helper caps in-flight work at
2
+ * an explicit finite limit, stops starting work after the first failure and
3
+ * settles only once every started operation has settled, so callers can clean
4
+ * up without racing outstanding writes. Stage-level helpers join whole
5
+ * concurrent branches under the same settle-before-report contract. */
6
+
7
+ /** Filesystem operations in flight per traversal, and the prefetch window. */
8
+ export const TREE_IO_CONCURRENCY = 16
9
+ /** Dependency packages digested or copied at once. */
10
+ export const PACKAGE_CONCURRENCY = 4
11
+
12
+ function assertLimit(limit: number): void {
13
+ if (!Number.isInteger(limit) || limit < 1)
14
+ throw new RangeError(`concurrency limit must be a positive integer: ${limit}`)
15
+ }
16
+
17
+ /** Runs `work` over a growing LIFO stack with at most `limit` items in flight.
18
+ * `work` may push more items. After the first failure no item starts; the
19
+ * returned promise settles only once every in-flight item has settled, then
20
+ * rejects with the first error. */
21
+ export async function drainStack<T>(
22
+ initial: T[],
23
+ limit: number,
24
+ work: (item: T, push: (item: T) => void) => Promise<void>,
25
+ ): Promise<void> {
26
+ assertLimit(limit)
27
+ const stack = [...initial]
28
+ let active = 0
29
+ let failed = false
30
+ let error: unknown
31
+ let waiting: Array<() => void> = []
32
+ const wake = () => {
33
+ const ready = waiting
34
+ waiting = []
35
+ for (const resolve of ready) resolve()
36
+ }
37
+ const push = (item: T) => {
38
+ stack.push(item)
39
+ wake()
40
+ }
41
+ const worker = async (): Promise<void> => {
42
+ for (;;) {
43
+ if (failed) return
44
+ if (stack.length === 0) {
45
+ if (active === 0) return wake()
46
+ await new Promise<void>((resolve) => waiting.push(resolve))
47
+ continue
48
+ }
49
+ const item = stack.pop() as T
50
+ active++
51
+ try {
52
+ await work(item, push)
53
+ } catch (cause) {
54
+ if (!failed) {
55
+ failed = true
56
+ error = cause
57
+ }
58
+ } finally {
59
+ active--
60
+ wake()
61
+ }
62
+ }
63
+ }
64
+ await Promise.all(Array.from({ length: limit }, worker))
65
+ if (failed) throw error
66
+ }
67
+
68
+ /** Runs `work` over a fixed list with at most `limit` items in flight, under the
69
+ * same failure contract as {@link drainStack}. */
70
+ export async function forEachBounded<T>(
71
+ items: readonly T[],
72
+ limit: number,
73
+ work: (item: T, index: number) => Promise<void>,
74
+ ): Promise<void> {
75
+ assertLimit(limit)
76
+ let next = 0
77
+ let failed = false
78
+ let error: unknown
79
+ const worker = async (): Promise<void> => {
80
+ while (!failed && next < items.length) {
81
+ const index = next++
82
+ try {
83
+ await work(items[index] as T, index)
84
+ } catch (cause) {
85
+ if (!failed) {
86
+ failed = true
87
+ error = cause
88
+ }
89
+ }
90
+ }
91
+ }
92
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
93
+ if (failed) throw error
94
+ }
95
+
96
+ /** Starts at most `window` fetches ahead of the consumer and hands results to
97
+ * `consume` strictly in input order. On a fetch or consume failure it starts
98
+ * no more fetches, awaits the outstanding ones, then rethrows. */
99
+ export async function orderedPrefetch<T, R>(
100
+ items: readonly T[],
101
+ window: number,
102
+ fetch: (item: T) => Promise<R>,
103
+ consume: (result: R, item: T) => void | Promise<void>,
104
+ ): Promise<void> {
105
+ assertLimit(window)
106
+ const pending: Array<Promise<R>> = []
107
+ let started = 0
108
+ const fill = () => {
109
+ while (pending.length < window && started < items.length) {
110
+ const item = items[started++] as T
111
+ const promise = Promise.resolve().then(() => fetch(item))
112
+ // Observed here so an early rejection is never unhandled; the consumer
113
+ // still receives it when it reaches this slot.
114
+ promise.catch(() => {})
115
+ pending.push(promise)
116
+ }
117
+ }
118
+ try {
119
+ for (let index = 0; index < items.length; index++) {
120
+ fill()
121
+ const result = await (pending.shift() as Promise<R>)
122
+ await consume(result, items[index] as T)
123
+ }
124
+ } catch (error) {
125
+ await Promise.allSettled(pending)
126
+ throw error
127
+ }
128
+ }
129
+
130
+ /** Awaits every task, then rejects with the first failure in argument order or
131
+ * resolves with every value in order. Concurrent branches therefore all settle
132
+ * before a caller cleans up, and report the error a serial run would have hit
133
+ * first. Build every task in the argument expression so none rejects unheard. */
134
+ export async function settleInOrder<T extends readonly unknown[]>(
135
+ tasks: {
136
+ readonly [K in keyof T]: Promise<T[K]>
137
+ },
138
+ ): Promise<T> {
139
+ const outcomes = await Promise.allSettled(tasks as readonly Promise<unknown>[])
140
+ for (const outcome of outcomes) if (outcome.status === 'rejected') throw outcome.reason
141
+ return outcomes.map((outcome) => (outcome as PromiseFulfilledResult<unknown>).value) as never
142
+ }
143
+
144
+ /** Starts `start` speculatively and runs `body` alongside it. `take` awaits the
145
+ * speculative value, rethrowing its error at the point the body needs it. When
146
+ * the body ends without taking it, the signal aborts and its outcome, even a
147
+ * failure, is discarded. Either way this settles only after the speculative
148
+ * task has settled, so nothing it started outlives the caller. */
149
+ export async function withSpeculation<T, R>(
150
+ start: (signal: AbortSignal) => Promise<T>,
151
+ body: (take: () => Promise<T>) => Promise<R>,
152
+ ): Promise<R> {
153
+ const controller = new AbortController()
154
+ let taken = false
155
+ // Contained at once, synchronous throws included, so a failure is never
156
+ // an unhandled rejection however early it lands.
157
+ const outcome: Promise<{ value: T } | { error: unknown }> = Promise.resolve()
158
+ .then(() => start(controller.signal))
159
+ .then(
160
+ (value) => ({ value }),
161
+ (error: unknown) => ({ error }),
162
+ )
163
+ try {
164
+ return await body(async () => {
165
+ taken = true
166
+ const settled = await outcome
167
+ if ('error' in settled) throw settled.error
168
+ return settled.value
169
+ })
170
+ } finally {
171
+ if (!taken) controller.abort()
172
+ await outcome
173
+ }
174
+ }
@@ -1,6 +1,5 @@
1
1
  import { workTargetDistance } from './target-distance'
2
2
  import { openTicketWait, waitingOnLine } from '../../kernel/ticket-wait'
3
- import { migrationIdentity, ticketMigrationsReducer } from '../../kernel/ticket-migrations'
4
3
  import { openPrBackpressureReducer } from '../../kernel/open-pr-backpressure-state'
5
4
  import type { DashboardRollback } from './rollback'
6
5
  import type { DispatchUpgradeState } from '../../kernel/dispatch-upgrade'
@@ -14,16 +13,18 @@ import {
14
13
  } from './integration-row'
15
14
  import {
16
15
  dispatchCapacity,
16
+ epilogueLeaf,
17
17
  slotWaitText,
18
18
  startClaimDemand,
19
19
  urgentClaimDemand,
20
20
  type DispatchCapacity,
21
+ type SlotState,
21
22
  } from '../../kernel/dispatch-capacity'
22
23
  import { openBuildWorkspace, provisionMarkerReducer } from '../../processes/dispatcher-selectors'
23
24
  import { projectTree, treeVocabulary, type TreeProjection } from './tree'
24
25
  import { holdReason } from './landing-display'
25
26
  import { reopenedSummary, reopenedText } from './reopen-display'
26
- import { reopenSpecPending } from '../../kernel/reopen-state'
27
+ import { reopenSpecPending, reviseSpecPending } from '../../kernel/reopen-state'
27
28
  import { ciFailureText, currentCiFailure } from '../../kernel/forge-checks'
28
29
  export { treeVocabulary, consentQueue } from './tree'
29
30
  import {
@@ -32,6 +33,7 @@ import {
32
33
  landingFallbackReason,
33
34
  } from '../../kernel/landing-state'
34
35
  import { projectObjectiveRow, type ObjectiveRow } from './objective-row'
36
+ import type { StatusBasis } from './vocabulary'
35
37
  export {
36
38
  objectiveElapsedHours,
37
39
  objectiveNumber,
@@ -249,6 +251,13 @@ export function dashboardWait(state: BuildState): DashboardWait | undefined {
249
251
  }
250
252
 
251
253
  export interface DashboardBuild {
254
+ /** Display-only lifecycle facts the row's status word is chosen from
255
+ * (`buildStatusText`); absent on hand-built rows, which imply it from
256
+ * `status`. */
257
+ statusBasis?: StatusBasis
258
+ /** The build's slot state from the frame's capacity projection (SPEC §12
259
+ * "What holds a slot"); absent is unknown, never `none`. */
260
+ slot?: SlotState
252
261
  draining?: boolean
253
262
  /** A work row's standing alert, such as a parked build waiting for a slot. */
254
263
  alert?: { tone: 'yellow' | 'red'; text: string }
@@ -400,7 +409,8 @@ export interface DashboardModel {
400
409
  repo: string
401
410
  /** Ready tickets waiting for a slot — the dispatcher's standing queue depth. */
402
411
  queued: number
403
- /** Shared occupied/effective slot counter; idle integration nodes are free. */
412
+ /** Shared slot counter: builds holding a slot against configured capacity;
413
+ * paused, blocked and idle builds hold none. */
404
414
  active: DashboardCounter
405
415
  capacity?: DispatchCapacity
406
416
  /** Absent: the recorded run's effective configuration projected this model.
@@ -462,6 +472,21 @@ export function effectiveStatus(state: BuildState): EffectiveStatus | BuildState
462
472
  if (state.status === 'done') return 'done'
463
473
  if (state.status === 'aborted') return 'cleaning'
464
474
  if (state.pendingCommands.some((command) => command.command === 'abort')) return 'aborting'
475
+ const resting = restingStatus(state)
476
+ if (resting === 'running' && state.pendingCommands.some((command) => command.command === 'pause'))
477
+ return 'pausing'
478
+ if (resting === 'paused' && state.pendingCommands.some((command) => command.command === 'resume'))
479
+ return 'resuming'
480
+ return resting
481
+ }
482
+
483
+ /** `effectiveStatus` with every pending command ignored: what the build rests
484
+ * on until a pause, resume or abort is acknowledged. */
485
+ export function restingStatus(
486
+ state: BuildState,
487
+ ): Exclude<EffectiveStatus, 'pausing' | 'resuming' | 'aborting'> | 'done' {
488
+ if (state.status === 'done') return 'done'
489
+ if (state.status === 'aborted') return 'cleaning'
465
490
  if (state.kind === 'node' && integrationFailed(state)) return 'blocked'
466
491
  // A ticket wait whose escalation is the only one open reads as waiting; any
467
492
  // other open question outranks it and the build reads blocked.
@@ -477,19 +502,37 @@ export function effectiveStatus(state: BuildState): EffectiveStatus | BuildState
477
502
  ) {
478
503
  return 'blocked'
479
504
  }
480
- if (state.status === 'running') {
481
- return state.pendingCommands.some((command) => command.command === 'pause')
482
- ? 'pausing'
483
- : 'running'
484
- }
485
- if (state.status === 'paused') {
486
- return state.pendingCommands.some((command) => command.command === 'resume')
487
- ? 'resuming'
488
- : 'paused'
489
- }
490
505
  return state.status
491
506
  }
492
507
 
508
+ /** The lifecycle facts a nonterminal build's status word is chosen from
509
+ * (`buildStatusText`), or undefined for a `done` build. Display-only. */
510
+ export function statusBasis(state: BuildState): StatusBasis | undefined {
511
+ const resting = restingStatus(state)
512
+ if (resting === 'done') return undefined
513
+ const pending = (command: string) => state.pendingCommands.some((c) => c.command === command)
514
+ const settled = epilogueLeaf(state)
515
+ ? state.landing?.command?.kind === 'hold'
516
+ ? ('hold' as const)
517
+ : landingAuthorized(state.landing)
518
+ ? ('merging' as const)
519
+ : ('decision' as const)
520
+ : undefined
521
+ const waitTickets =
522
+ resting === 'waiting' ? openTicketWait(state)?.tickets.map((ticket) => ticket.id) : undefined
523
+ return {
524
+ resting,
525
+ ...(pending('pause') ? { pause: true as const } : {}),
526
+ ...(pending('abort') ? { abort: true as const } : {}),
527
+ ...(pending('resume') ? { resume: true as const } : {}),
528
+ runner: state.openExecution !== undefined,
529
+ ...(state.kind === 'node' ? { node: true as const } : {}),
530
+ ...(settled !== undefined ? { settled } : {}),
531
+ ...(reviseSpecPending(state) ? { reviseSpec: true as const } : {}),
532
+ ...(waitTickets?.length ? { waitTickets } : {}),
533
+ }
534
+ }
535
+
493
536
  function isVisible(status: EffectiveStatus | BuildState['status']): status is EffectiveStatus {
494
537
  return (
495
538
  status === 'queued' ||
@@ -670,6 +713,7 @@ export function projectBuildFromFacts(
670
713
  const dashboard = facts.dashboard
671
714
  const status = effectiveStatus(state)
672
715
  if (!isVisible(status)) return null
716
+ const basis = statusBasis(state)
673
717
  const wait = dashboardWait(state)
674
718
  const objective = projectObjectiveRow(state)
675
719
  const abortProgress =
@@ -748,6 +792,7 @@ export function projectBuildFromFacts(
748
792
  createdAt: record.createdAt,
749
793
  },
750
794
  status,
795
+ ...(basis !== undefined ? { statusBasis: basis } : {}),
751
796
  alsoPaused: false,
752
797
  ...(record.ticket?.id !== undefined ? { ticketId: record.ticket.id } : {}),
753
798
  steps: [],
@@ -797,6 +842,7 @@ export function projectBuildFromFacts(
797
842
  createdAt: record.createdAt,
798
843
  },
799
844
  status,
845
+ ...(basis !== undefined ? { statusBasis: basis } : {}),
800
846
  alsoPaused: false,
801
847
  ...(record.ticket?.id !== undefined ? { ticketId: record.ticket.id } : {}),
802
848
  steps: [],
@@ -881,7 +927,7 @@ export function projectBuildFromFacts(
881
927
  // away, so they are derived here (display-only, at the one call site that
882
928
  // already has the log in hand). A running build keeps its open interval live
883
929
  // (the renderer ticks it against `now`); a paused build freezes every open
884
- // interval at its acknowledgement (including while RESUMING), while a
930
+ // interval at its acknowledgement (including while a resume is pending), while a
885
931
  // blocked build freezes at the latest non-distance durable event. Timers do
886
932
  // not advance behind either gate (AC 10). Each step scopes by the SAME seq boundary its state uses, so
887
933
  // durations and states restart in lockstep (AC 12).
@@ -1168,6 +1214,7 @@ export function projectBuildFromFacts(
1168
1214
  createdAt: record.createdAt,
1169
1215
  },
1170
1216
  status,
1217
+ ...(basis !== undefined ? { statusBasis: basis } : {}),
1171
1218
  alsoPaused: state.status === 'paused' && (status === 'blocked' || status === 'waiting'),
1172
1219
  ...(record.ticket?.id !== undefined ? { ticketId: record.ticket.id } : {}),
1173
1220
  steps:
@@ -1499,6 +1546,20 @@ export function decorateSlotWaits(
1499
1546
  })
1500
1547
  }
1501
1548
 
1549
+ /** Each row's slot state from the capacity projection. Returns copies;
1550
+ * cached projected rows stay intact. */
1551
+ function decorateSlots(
1552
+ rows: readonly DashboardBuild[],
1553
+ capacity: DispatchCapacity | undefined,
1554
+ ): DashboardBuild[] {
1555
+ const slots = capacity?.slots
1556
+ if (!slots) return [...rows]
1557
+ return rows.map((row) => {
1558
+ const slot = slots[row.slug]
1559
+ return slot ? { ...row, slot } : row
1560
+ })
1561
+ }
1562
+
1502
1563
  export function buildDashboardFromProjected(
1503
1564
  projectedBuilds: readonly DashboardBuild[],
1504
1565
  header: DashboardHeader,
@@ -1511,8 +1572,11 @@ export function buildDashboardFromProjected(
1511
1572
  repositoryEvents,
1512
1573
  upgrades,
1513
1574
  )
1514
- const builds = decorateSlotWaits(
1515
- enrichIntegrationRows(projectedBuilds.map((row) => enrichDrainingRow(row, draining))),
1575
+ const builds = decorateSlots(
1576
+ decorateSlotWaits(
1577
+ enrichIntegrationRows(projectedBuilds.map((row) => enrichDrainingRow(row, draining))),
1578
+ header.capacityProjection,
1579
+ ),
1516
1580
  header.capacityProjection,
1517
1581
  ).sort((a, b) => a.slug.localeCompare(b.slug))
1518
1582
  // Member order matches the terminal model's historical literal.
@@ -1524,7 +1588,7 @@ export function buildDashboardFromProjected(
1524
1588
  queued: repository.queued,
1525
1589
  active: {
1526
1590
  current: header.capacityProjection?.occupied ?? header.activeCount,
1527
- limit: header.capacityProjection?.effective ?? header.capacity,
1591
+ limit: header.capacityProjection?.configured ?? header.capacity,
1528
1592
  },
1529
1593
  ...(header.capacityProjection ? { capacity: header.capacityProjection } : {}),
1530
1594
  drained: repository.drained,
@@ -1563,12 +1627,6 @@ export function buildDashboard(
1563
1627
  })),
1564
1628
  config.capacity,
1565
1629
  new Date(),
1566
- migrationIdentity(
1567
- Array.isArray(repositoryEvents)
1568
- ? ticketMigrationsReducer.reduce(repositoryEvents)
1569
- : repositoryEvents.ticketMigrations,
1570
- config.tickets.source,
1571
- ),
1572
1630
  {
1573
1631
  ...(Array.isArray(repositoryEvents)
1574
1632
  ? {}