@defrex/autobuild 1.2.0 → 1.3.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 (82) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +118 -14
  3. package/docs/accounts.md +12 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +120 -7
  6. package/docs/builds.md +2 -0
  7. package/docs/configuration-overview.md +6 -0
  8. package/docs/configuration.md +6 -0
  9. package/docs/integration-tree.md +16 -5
  10. package/docs/operator-api.md +44 -6
  11. package/docs/operator-surfaces.md +29 -0
  12. package/docs/plugin-authoring.md +6 -1
  13. package/docs/remote-store-protocol.md +69 -10
  14. package/docs/restacking.md +45 -0
  15. package/docs/spec-standard.md +4 -2
  16. package/docs/ticket-dependencies.md +8 -0
  17. package/package.json +3 -3
  18. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  19. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  20. package/packages/core/src/cli/dispatch.ts +64 -25
  21. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  22. package/packages/core/src/cli/forge-clear.ts +30 -0
  23. package/packages/core/src/cli/help.ts +1 -0
  24. package/packages/core/src/cli/main.ts +28 -0
  25. package/packages/core/src/cli/watch.ts +9 -13
  26. package/packages/core/src/events/catalog.ts +1 -0
  27. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  28. package/packages/core/src/events/payloads.ts +10 -0
  29. package/packages/core/src/events/policy.ts +9 -0
  30. package/packages/core/src/events/repository.ts +73 -2
  31. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +275 -0
  32. package/packages/core/src/kernel/change-presence.ts +74 -8
  33. package/packages/core/src/kernel/engine.ts +8 -0
  34. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  35. package/packages/core/src/kernel/node-polling.ts +40 -7
  36. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  37. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  38. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  39. package/packages/core/src/kernel/read-facts.ts +6 -0
  40. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  41. package/packages/core/src/kernel/reducer.ts +1 -1
  42. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  43. package/packages/core/src/operator/annotations.ts +6 -0
  44. package/packages/core/src/operator/control.ts +20 -0
  45. package/packages/core/src/operator/index.ts +2 -0
  46. package/packages/core/src/operator/registry.ts +20 -0
  47. package/packages/core/src/ports/runner/account-env.ts +60 -9
  48. package/packages/core/src/ports/runner/claude.ts +49 -45
  49. package/packages/core/src/processes/dispatcher.ts +470 -121
  50. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  51. package/packages/core/src/processes/harvest.ts +11 -16
  52. package/packages/core/src/processes/repo-view.ts +3 -0
  53. package/packages/core/src/store/artifact-meta.ts +7 -0
  54. package/packages/core/src/store/contract.ts +57 -0
  55. package/packages/core/src/store/memory.ts +4 -0
  56. package/packages/core/src/store/reducer-value-shapes.json +7302 -6668
  57. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  58. package/packages/core/src/store/remote/client.ts +48 -8
  59. package/packages/core/src/store/remote/compatibility.ts +39 -0
  60. package/packages/core/src/store/remote/index.ts +6 -0
  61. package/packages/core/src/store/remote/protocol.ts +8 -1
  62. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  63. package/packages/core/src/store/remote/version.ts +4 -0
  64. package/packages/core/src/store/repo-state-events.ts +4 -2
  65. package/packages/core/src/store/snapshots.ts +16 -3
  66. package/packages/core/src/store/types.ts +2 -0
  67. package/packages/core/src/testing/dispatch-read-budget.ts +144 -5
  68. package/packages/core/src/testing/index.ts +1 -1
  69. package/packages/core/src/testing/reduced-read-budget.ts +513 -5
  70. package/skills/guide/SKILL.md +44 -7
  71. package/skills/guide/references/accounts.md +12 -1
  72. package/skills/guide/references/integration-tree.md +16 -5
  73. package/skills/guide/references/operator-api.md +44 -6
  74. package/skills/guide/references/plugin-authoring.md +6 -1
  75. package/skills/guide/references/remote-store-protocol.md +69 -10
  76. package/skills/guide/references/restacking.md +45 -0
  77. package/skills/guide/references/spec-standard.md +4 -2
  78. package/skills/guide/references/ticket-dependencies.md +8 -0
  79. package/skills/operate/SKILL.md +21 -5
  80. package/skills/reconcile/SKILL.md +6 -0
  81. package/skills/tickets/SKILL.md +7 -3
  82. package/templates/hosted-service/package.json +2 -2
@@ -166,7 +166,8 @@ Active verification/reconcile or writer work, restack/reparent work, pause,
166
166
  pending controls, merge intent and ended PRs refuse the no-escalation path.
167
167
  A concurrent state change refuses publication with a retry explanation;
168
168
  uncited artifacts are inert. Leaves still require an open escalation and
169
- restart from `plan`.
169
+ restart from `plan` after any unfinished reconcile resumes under the revised
170
+ spec and its publication is confirmed.
170
171
 
171
172
  ## The registry's protocol face: `POST …/tools/{tool}`
172
173
 
@@ -241,18 +242,23 @@ Dispatcher liveness is also visible through `ab repository status --json`:
241
242
  of `latestRun`. Each run includes its recorded `runtime` (version, commit, and
242
243
  source kind/location), or null for unrecorded historical starts. Heartbeat age measures attributable renewals; tick age measures
243
244
  durable progress. Missing historical evidence is null. The liveness query uses
244
- bounded repository facts first, with a full-history fallback when a later
245
- invocation hides the holder start or the latest stop. Other state reads retain
246
- their bounded semantics.
245
+ persisted repository and exact per-run reduced values, including when newer
246
+ invocations hide an older holder or stop. Missing facts never trigger a full-log
247
+ fallback.
247
248
 
248
249
  Repository-following `ab watch` additionally emits a read-only `dispatcher.lost`
249
250
  observation when an observed lease expires without a matching stop or validated
250
- successor takeover. A completed ownership transfer suppresses predecessor loss
251
+ successor takeover. Any recorded stop, normal or abnormal, suppresses loss;
252
+ abnormal stops retain their own default attention event. A completed ownership transfer suppresses predecessor loss
251
253
  even while its sessions drain; a handoff without takeover still reports loss on
252
254
  expiry. Successor loss and upgrade-failure/rollback attention remain independent. JSON carries
253
255
  `observation` instead of `event`, with run, observedAt, leaseExpiresAt and available
254
256
  identity, plus the usual repo/build/state/cursor fields. It invents no durable
255
257
  sequence or actor. Retain the cursor to avoid repeat reports across invocations.
258
+ A watch retains sampled owners after authoritative lease release. Once-run teardown
259
+ stops heartbeat and releases only its own lease; release is best effort because
260
+ expiry fences ambiguous ownership. A retained sample or failed release cannot
261
+ override a persisted stop.
256
262
  No lease alone is not evidence of death. SIGINT, SIGHUP and SIGTERM drain dispatch,
257
263
  record the first signal in the stop fact, and release its lease before exit.
258
264
 
@@ -284,7 +290,10 @@ The default watch reports actionable conditions only:
284
290
  for five minutes in one run. A successful tick, new run, or matching stop
285
291
  ends the episode. Source grace and cooldown-driven failures do not start
286
292
  this clock; after grace, the first qualifying failure starts a new five-minute
287
- interval. Each persistence episode is reported once.
293
+ interval. Each persistence episode is reported once. Unavailable failure writes delay durable visibility:
294
+ watch keeps running, warns locally and reports one bounded unreported window
295
+ on recovery. These local warnings do not start the durable attention clock
296
+ retroactively. Explicit stops still stop dispatch.
288
297
 
289
298
  Repository conditions are included with no slugs or with `--repository`.
290
299
  Routine outcomes and self-healing failures are silent. Repeatable
@@ -502,3 +511,32 @@ the same store identity, token and prefixed pathname as uploads. Missing objects
502
511
  are successful cleanup; provider errors never count as completed deletion.
503
512
 
504
513
  Paged ticket listings use the source's optional native `listPage(criteria, page)` capability when present, otherwise read the full listing and reverse/slice it. Native errors propagate. PostgreSQL counts matches without bodies and reads only the requested window. Zero limits and offsets past the end still report the full matching total. Unpaged listings remain exhaustive; the wire payload is the same for both paths.
514
+
515
+
516
+ ### Forge cooldown admission and explicit recovery
517
+
518
+ Hosted repository event appends and atomic artifact deposits validate
519
+ `dispatcher.forge-degraded` before any durable mutation. The payload must match
520
+ its event schema, with a finite ISO `resetAt` at most 24 hours after server time
521
+ (inclusive). Already-expired deadlines are accepted. Invalid or out-of-horizon
522
+ writes return `400 validation` (the remote adapter exposes `EventValidationError`);
523
+ the server never clamps or invents a provider reset. Historical decoding has no clock-relative restriction.
524
+
525
+ Build-runner and build-phase grants may POST only the kernel-authored
526
+ `dispatcher.forge-degraded` repository fact through the events route. The
527
+ preceding `requireProject` check binds this exception to the exact repository
528
+ in the delegated claim. A hosted project identifies one repository. Delegates
529
+ cannot write recovery, deposits or other repository facts, regardless of the
530
+ actor claimed in an envelope.
531
+
532
+ An authorized operator can explicitly clear erroneous state through
533
+ `repository.forge_clear {repo, forge, reason}` or
534
+ `ab repository forge-clear --forge <name> --reason <text> [--json] [--store <ref>]`.
535
+ The reason is required and nonblank. The result contains the durable recovery
536
+ `event`, attributed to the authenticated human with normal `via` attribution.
537
+ Build and harvest delegates cannot invoke this operator mutation. CLI use
538
+ requires an operator outside build/harvest sessions. This is an override, not
539
+ proof of provider success. A clear appends once without reading history, even
540
+ when already healthy; later degradation wins by ordinary journal order.
541
+ Existing dispatcher/kernel automatic recovery and old payloads remain valid;
542
+ the recovered payload additionally accepts an optional nonblank `reason`.
@@ -75,3 +75,32 @@ There's no operator-surface plugin map. Build a client of the versioned, authent
75
75
  - A new surface adds no pipeline phase and no embedded operator agent.
76
76
 
77
77
  [Writing a plugin](plugin-authoring.md) covers infrastructure adapters.
78
+
79
+
80
+ ### Forge cooldown admission and explicit recovery
81
+
82
+ Hosted repository event appends and atomic artifact deposits validate
83
+ `dispatcher.forge-degraded` before any durable mutation. The payload must match
84
+ its event schema, with a finite ISO `resetAt` at most 24 hours after server time
85
+ (inclusive). Already-expired deadlines are accepted. Invalid or out-of-horizon
86
+ writes return `400 validation` (the remote adapter exposes `EventValidationError`);
87
+ the server never clamps or invents a provider reset. Historical decoding has no clock-relative restriction.
88
+
89
+ Build-runner and build-phase grants may POST only the kernel-authored
90
+ `dispatcher.forge-degraded` repository fact through the events route. The
91
+ preceding `requireProject` check binds this exception to the exact repository
92
+ in the delegated claim. A hosted project identifies one repository. Delegates
93
+ cannot write recovery, deposits or other repository facts, regardless of the
94
+ actor claimed in an envelope.
95
+
96
+ An authorized operator can explicitly clear erroneous state through
97
+ `repository.forge_clear {repo, forge, reason}` or
98
+ `ab repository forge-clear --forge <name> --reason <text> [--json] [--store <ref>]`.
99
+ The reason is required and nonblank. The result contains the durable recovery
100
+ `event`, attributed to the authenticated human with normal `via` attribution.
101
+ Build and harvest delegates cannot invoke this operator mutation. CLI use
102
+ requires an operator outside build/harvest sessions. This is an override, not
103
+ proof of provider success. A clear appends once without reading history, even
104
+ when already healthy; later degradation wins by ordinary journal order.
105
+ Existing dispatcher/kernel automatic recovery and old payloads remain valid;
106
+ the recovered payload additionally accepts an optional nonblank `reason`.
@@ -27,7 +27,7 @@ Import public types only from `@defrex/autobuild/plugin-sdk`; internal module pa
27
27
 
28
28
  All four manifest maps have production selectors. Omitted forge and workspace selectors default to builtin `github` and `git-worktree`; roles keep normal runtime inheritance.
29
29
 
30
- `BuildStore` and `BlobStore` contract types are exported for remote-server authors, but BuildStore is **not** an in-process manifest map: implement the language-neutral remote store protocol and run its conformance path. `TelemetrySource` is a frozen port type with no plugin registration surface in this release.
30
+ `BuildStore` and `BlobStore` contract types are exported for remote-server authors, but BuildStore is **not** an in-process manifest map: implement the language-neutral remote store protocol and run its conformance path. The optional `BuildStore.getLatestArtifactMeta` capability must return only the latest metadata in constant-size reads without loading blob content or listing revisions; omit it when unsupported. `TelemetrySource` is a frozen port type with no plugin registration surface in this release.
31
31
 
32
32
  ### `ticket-source`
33
33
 
@@ -445,3 +445,8 @@ listings, CLI ticket lists and dispatcher ready scans remain exhaustive through
445
445
  `listReady`/`listAll`. The hosted PostgreSQL source counts matches without
446
446
  bodies and reads only the SQL-bounded window. File, Linear and the remote
447
447
  `HostedTicketSource` retain fallback; the POST list-ready protocol stays exhaustive.
448
+
449
+ Hosted cooldown recording rejects observed reset deadlines beyond the 24-hour
450
+ admission horizon explicitly; adapters must not shorten or invent a provider
451
+ reset to evade this validation. Operator forge-clear is an audited override,
452
+ not a successful provider observation.
@@ -321,6 +321,7 @@ it to exist. An unknown build returns `404 not-found`.
321
321
  | `putReducerSnapshot` | `PUT /builds/{slug}/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 log's tail answer `written: false` |
322
322
  | `putArtifact` | `POST /builds/{slug}/artifacts` | artifact input | `201` + build artifact metadata |
323
323
  | `getArtifact` | `GET /builds/{slug}/artifacts?kind={kind}&rev={n}` | `kind` is required and nonempty; optional `rev` is parsed below | `200` + artifact read; an absent `rev` parameter selects the latest revision; a missing kind/revision is `200 null` |
324
+ | `getLatestArtifactMeta?` | `GET /builds/{slug}/artifact-meta?kind={kind}` | required nonblank `kind` | `200` + latest validated artifact metadata or `null`; no blob content |
324
325
  | `listArtifacts` | `GET /builds/{slug}/artifact-list?kind={kind}` | optional `kind`; absence means all kinds | `200` + metadata ordered by kind and then increasing revision |
325
326
  | `claimLease` | `POST /builds/{slug}/lease/claim` | claim request | `200 {"ok": boolean}` |
326
327
  | `heartbeat` | `POST /builds/{slug}/lease/heartbeat` | holder request | `200 {"ok": boolean}` |
@@ -352,6 +353,26 @@ revisions are nonnegative; a requested revision that does not exist, including
352
353
  a negative one, produces `null`. A missing or empty `kind` on the artifact-read
353
354
  route is `400 validation`.
354
355
 
356
+ The optional `BuildStore.getLatestArtifactMeta(slug, kind)` returns
357
+ `Promise<ArtifactMeta | null>`, with the same unknown-build behavior as
358
+ `getArtifact`. Implement it as a constant-size latest-revision lookup, never
359
+ by listing revisions or loading blob content. Memory and PostgreSQL stores
360
+ support it; PostgreSQL uses the existing `(build, kind, revision)` primary key
361
+ in descending revision order with `LIMIT 1`. The route uses the same build
362
+ authorization and project scope as artifact reads. Unsupported backings return
363
+ `501 {kind: "unsupported-operation", error: "latest artifact metadata is unsupported"}`.
364
+
365
+ This additive route does not change the protocol identity. Older servers
366
+ answer `404 {kind: "not-found", error: "no route: GET /builds/:slug/artifact-meta"}`
367
+ from the store router, or the same envelope with the actual requested URL
368
+ pathname from the hosted service router. Only these explicit route-miss responses
369
+ (the literal route pattern or the exact requested metadata pathname) or the
370
+ explicit 501 operation response disable metadata probing for the lifetime of a
371
+ remote client. An unknown-build 404 remains a failure.
372
+ The dispatcher then uses ordinary full artifact reads. Authentication,
373
+ transport, malformed responses and other server errors remain failures; they
374
+ never trigger event downloads or reconstruction of server-reduced values.
375
+
355
376
  The artifact-list `kind` is optional and is normally a nonempty stored kind.
356
377
  No pagination, deletion, retention, range request, or streaming endpoint is
357
378
  part of this protocol. Retention is enforced server-side inside the store at
@@ -376,9 +397,16 @@ Server-owned snapshots are disposable caches: deletion, corruption, wrong versio
376
397
  and unreadable cache storage cause server-side replay. Log read failures remain errors.
377
398
  The server answer is canonical for remote clients, regardless of missing, malformed
378
399
  or different `x-autobuild-catalog-identity` headers. The strict body stays exactly
379
- `{version, cursor, value}`. A reducer version mismatch, invalid envelope or invalid
380
- finished value raises `ReducerValueIncompatibilityError`, naming the reducer,
381
- client/server versions and validation detail. Clients never reconstruct named
400
+ `{version, cursor, value}`. The reducer `version` is the server's cache identity, not
401
+ a compatibility gate. A client accepts any value its own finished shape can
402
+ represent and drops object properties that shape does not know. An invalid envelope
403
+ or a value the client cannot represent, such as a missing field or an unknown
404
+ variant, raises `ReducerValueIncompatibilityError`, naming the reducer,
405
+ client/server versions and validation detail. Clients send
406
+ `x-autobuild-reducer-value-projection: 1`. A 1.2.0 client predates that capability
407
+ and accepts only its own reducer version and shape. The service answers it with the
408
+ value projected onto the frozen 1.2.0 shape and the 1.2.0 reducer version, or with
409
+ the unprojected answer when that shape cannot represent it. Clients never reconstruct named
382
410
  answers from raw events. Repository build-digest batches are likewise canonical:
383
411
  one repo-scoped GET returns the batch without client build discovery or per-build
384
412
  reducer requests. This does not change the explicit snapshot or event APIs.
@@ -395,7 +423,7 @@ client version window are unchanged.
395
423
  | Scope | Reducers with no arguments |
396
424
  | --- | --- |
397
425
  | Build | `executionNoProgress`, `summaryRequests`, `build`, `buildDigest`, `currentPrAttachments`, `pendingPrAttachmentReclaims`, `openExecution`, `lastExecutionOutcome`, `infrastructureFailureReset`, `openWorkspace`, `setupStreak`, `openBuildWorkspace`, `currentDeferralObservation`, `dashboardFacts`, `pinnedAssets`, `buildDelegation` |
398
- | Repository | `harvest`, `dispatchSettings`, `sandboxStates`, `openHarvestExecutions`, `autoMergeDefault`, `effectiveConfig`, `harvestDelegation` |
426
+ | Repository | `ticketPreparation`, `harvest`, `dispatchSettings`, `sandboxStates`, `openHarvestExecutions`, `autoMergeDefault`, `effectiveConfig`, `harvestDelegation` |
399
427
 
400
428
  | Reducer | Scope | Required arguments |
401
429
  | --- | --- | --- |
@@ -502,7 +530,7 @@ without a journal record, or a repository without builds.
502
530
  | `getRepo` | `GET /repos/{repo}` | none | `200` + `RepositoryRecord`; absent is `404` (the shipped client maps this to `null`) |
503
531
  | `appendRepo` | `POST /repos/{repo}/events` | event write | `201` + repository event envelope |
504
532
  | `getRepoEvents` | `GET /repos/{repo}/events?since={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 >` parsed `since`, in increasing sequence order |
505
- | `getRepoStateEvents` | `GET /repos/{repo}/state-events` | none | `200` + the bounded repository-journal subset (AUT-489): every durable event type (`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, 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` |
533
+ | `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, 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` |
506
534
  | `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` |
507
535
  | `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` |
508
536
  | `appendRepoWithArtifacts` | `POST /repos/{repo}/deposits` | atomic deposit request | `201` + `{event, artifacts}` using repository shapes |
@@ -1124,6 +1152,7 @@ Conforming servers map failures as follows:
1124
1152
  | `409` | `conflict` | Missing/mismatched package or protocol identity, duplicate build creation, appending to a closed stream (`stream "…" is closed`), or a backing conflict reported as already existing |
1125
1153
  | `413` | `validation` | Decoded artifact or serialized stream batch exceeds the configured ceiling; a ticket-asset request or response exceeds the deployment's request ceiling; the message names the ceiling |
1126
1154
  | `422` | `validation` | `EventValidationError` from build, repository, or session catalog validation, or a ticket-asset validation failure (including the 25 MiB limit); its message is preserved verbatim |
1155
+ | `501` | `unsupported-operation` | Optional latest artifact metadata capability is unavailable on the backing adapter |
1127
1156
  | `500` | `internal` | Any other unexpected backing or server failure; the thrown error message is returned |
1128
1157
 
1129
1158
  Authentication runs before resource lookup, and session authorization runs
@@ -1496,11 +1525,12 @@ handoff. Metadata remains available for diagnosis.
1496
1525
  Refreshing kinds are internal provider integrations, not arbitrary endpoint URLs
1497
1526
  or CLI write formats. The five-minute hosted cadence is unchanged. A token that
1498
1527
  is valid now but not yet refreshable is supplied unchanged; a caller’s future
1499
- validity horizon cannot reject it. The first tick at or after the provider’s
1500
- earliest-refresh time rotates the credential and commits encrypted replacement
1501
- state before supply. Providers omitting that time use a ten-minute pre-expiry
1502
- refresh margin to tolerate a delayed five-minute tick. After downtime, expired
1503
- access state is refreshed before supply while its durable status remains ready.
1528
+ validity horizon cannot reject it. The first tick at or after both the ten-minute pre-expiry threshold and any
1529
+ provider earliest-refresh floor rotates the credential and commits encrypted
1530
+ replacement state before supply. Equality is eligible; an absent floor retains
1531
+ the ten-minute margin, which tolerates a delayed five-minute tick. After downtime,
1532
+ expired access state is refreshed before supply while its durable status remains
1533
+ ready and both gates hold. Expired access behind a future floor is never supplied.
1504
1534
  Failed or uncertain refresh attempts prevent supply and require replacement. A valid
1505
1535
  credential is never revoked merely because its refresh window is short. A durable
1506
1536
  attempt permits only one refresh caller across overlapping ticks. An abandoned attempt expires to failed without reusing the
@@ -1511,3 +1541,32 @@ Use `ab secrets list [--json]`, `ab secrets set NAME` or `ab secrets remove NAME
1511
1541
  from a connected checkout outside build/harvest sessions. Set reads hidden terminal
1512
1542
  input or redirected stdin. There is no value argument and values are never printed.
1513
1543
  The commands use the saved owner credential, even if an ambient build token exists.
1544
+
1545
+
1546
+ ### Forge cooldown admission and explicit recovery
1547
+
1548
+ Hosted repository event appends and atomic artifact deposits validate
1549
+ `dispatcher.forge-degraded` before any durable mutation. The payload must match
1550
+ its event schema, with a finite ISO `resetAt` at most 24 hours after server time
1551
+ (inclusive). Already-expired deadlines are accepted. Invalid or out-of-horizon
1552
+ writes return `400 validation` (the remote adapter exposes `EventValidationError`);
1553
+ the server never clamps or invents a provider reset. Historical decoding has no clock-relative restriction.
1554
+
1555
+ Build-runner and build-phase grants may POST only the kernel-authored
1556
+ `dispatcher.forge-degraded` repository fact through the events route. The
1557
+ preceding `requireProject` check binds this exception to the exact repository
1558
+ in the delegated claim. A hosted project identifies one repository. Delegates
1559
+ cannot write recovery, deposits or other repository facts, regardless of the
1560
+ actor claimed in an envelope.
1561
+
1562
+ An authorized operator can explicitly clear erroneous state through
1563
+ `repository.forge_clear {repo, forge, reason}` or
1564
+ `ab repository forge-clear --forge <name> --reason <text> [--json] [--store <ref>]`.
1565
+ The reason is required and nonblank. The result contains the durable recovery
1566
+ `event`, attributed to the authenticated human with normal `via` attribution.
1567
+ Build and harvest delegates cannot invoke this operator mutation. CLI use
1568
+ requires an operator outside build/harvest sessions. This is an override, not
1569
+ proof of provider success. A clear appends once without reading history, even
1570
+ when already healthy; later degradation wins by ordinary journal order.
1571
+ Existing dispatcher/kernel automatic recovery and old payloads remain valid;
1572
+ the recovered payload additionally accepts an optional nonblank `reason`.
@@ -47,6 +47,19 @@ actual destination, processing ancestors first. Unrelated siblings stay idle;
47
47
  changes absent from all ancestors cannot trigger a speculative replay. Tickets
48
48
  remain queued until presence is observed in their destination.
49
49
 
50
+ A presence request whose identities are absent from its immediate parent remains
51
+ pending while ancestors restack or reconcile. A durable availability observation
52
+ allows unchanged idle ticks, including after restart, to skip repository preparation
53
+ and native auto-merge cancellation. Exact node/parent heads, contribution base,
54
+ request contents, accepted ancestry, foreign aliases and confirmed landing evidence
55
+ invalidate that observation when they change; polling timestamps do not. Failed
56
+ assessments never establish unavailability. Availability is not proof of destination
57
+ coverage. Moving to another destination branch explicitly settles obsolete requests
58
+ with `destination-changed`; losing identities on the same branch leaves them waiting.
59
+ Native auto-merge is suspended with confirmed, reusable receipts only when replay
60
+ is actionable, and is revalidated during recovery before rewrite effects.
61
+
62
+
50
63
  `ab restack <node>` (operator tool `builds.restack`, input `{repo, slug}`) records
51
64
  a durable request, coalescing pending demand. It refuses leaves, terminal nodes,
52
65
  and unopened nodes. Paused or blocked nodes wait for their normal safety gates.
@@ -154,3 +167,35 @@ publication keeps its workspace through backoff and unresolved exhaustion.
154
167
  Classified rate limits retain repository cooldown and consume no publication
155
168
  retry allowance. Rejected pushes, lease conflicts, dirty trees and unclassified
156
169
  errors retain their existing behavior.
170
+
171
+ ## Ticket preparation before build creation
172
+
173
+ Before claiming, the dispatcher journals a repository-scoped preparation intent;
174
+ a won claim and the exact selected creation slug are durable boundaries. Caught
175
+ asset-copy, spec-authoring, naming, and build-creation failures return the ticket
176
+ to configured Ready; a nonconforming spec goes to configured Triage. Recovery
177
+ checks the exact selected build first: a matching record and atomic
178
+ `build.created` retain ownership even if creation threw after committing.
179
+ Unavailable or conflicting readback never authorizes release or a replacement
180
+ build. Pending attempts retain the original failure, latest recovery error and
181
+ retry deadline in the canonical repository reduced value; resolved attempts
182
+ leave that value. Under repository ownership, each tick admits at most eight
183
+ due recovery attempts, before intake and independently of capacity or intake
184
+ settings, with a 30-second durable retry delay after recovery failure. Unresolved
185
+ ticket identities remain withheld. An uncertain claim outcome or unrelated
186
+ external ticket state, missing ticket/state, or conflicting slug ownership terminates
187
+ automatic recovery with an `abandoned` resolution and diagnostic reason. The
188
+ ticket is left unchanged; an operator can leave it finished or cancelled, or
189
+ inspect ownership and explicitly return it to Ready for another attempt. These
190
+ cases stop provider polling and diagnostic appends. Recovery failures are
191
+ reported without preventing janitor, lease sweep, or other dispatch recovery.
192
+ This is not general process
193
+ crash recovery. Confirmed Ready/Triage transitions settle idempotently, so a
194
+ failed bounce comment does not return an invalid ticket to Ready.
195
+
196
+ Once a build is established, ordinary interrupted-dispatch recovery completes
197
+ its missing boundaries; preparation cleanup cannot release its claim.
198
+
199
+ ## Spec revision during leaf reconcile
200
+
201
+ 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.
@@ -131,7 +131,8 @@ The spec is the build's contract artifact (kind `spec`, revision 0).
131
131
  Every downstream reviewer approves conformance to its pinned revision.
132
132
  For leaves, a phase that discovers the spec itself is wrong raises an
133
133
  escalation (`ab escalate`); a human answers, the spec gets revision N+1,
134
- and the leaf restarts from `plan`.
134
+ and the leaf restarts from `plan` after any unfinished reconcile resumes under
135
+ the revised spec and its publication is confirmed.
135
136
 
136
137
  Operators may explicitly revise an opened idle collecting node or a node blocked on failed
137
138
  integration verification without an escalation. Use
@@ -149,4 +150,5 @@ Active verification/reconcile or writer work, restack/reparent work, pause,
149
150
  pending controls, merge intent and ended PRs refuse the no-escalation path.
150
151
  A concurrent state change refuses publication with a retry explanation;
151
152
  uncited artifacts are inert. Leaves still require an open escalation and
152
- restart from `plan`.
153
+ restart from `plan` after any unfinished reconcile resumes under the revised
154
+ 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.2.0",
3
+ "version": "1.3.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.3.0",
160
+ "@defrex/autobuild-vercel-sandbox": "1.3.0",
161
161
  "@resvg/resvg-js": "2.6.2",
162
162
  "@types/bun": "^1.3.14",
163
163
  "@types/node": "^24.0.0",
@@ -169,6 +169,7 @@ export class DispatchFrontend {
169
169
  this.clock = opts.clock ?? systemClock
170
170
  this.repositoryFeed = new DispatchRepositoryFeed(this.reader, opts.repo, this.clock)
171
171
  this.standbyResolver = new StandbyIdentityResolver(this.reader, opts.repo, {
172
+ selectHolder: (holder) => this.repositoryFeed.selectHolder(holder),
172
173
  allowLookup: () => this.repositoryFeed.incompleteIdentities,
173
174
  remember: (events, complete) => this.repositoryFeed.remember(events, complete),
174
175
  })
@@ -1,7 +1,7 @@
1
1
  import { DISPATCH_HANDOFF_EVENT_TYPES } from '../store/repo-state-events'
2
2
  import { type RepositoryEvent, validateRepositoryEventWrite } from '../events/repository'
3
3
  import { defineReducer } from '../kernel/incremental'
4
- import { loadReducerSnapshot, persistReducerSnapshot } from '../store/snapshots'
4
+ import { loadReducerSnapshot, persistReducerSnapshotOutcome } from '../store/snapshots'
5
5
  import type { BuildStore, Clock } from '../store/types'
6
6
 
7
7
  const handoffTypes = new Set<string>(DISPATCH_HANDOFF_EVENT_TYPES)
@@ -19,7 +19,7 @@ export function isDashboardRepositoryEvent(event: RepositoryEvent): boolean {
19
19
 
20
20
  export const dispatchFrontendReducer = defineReducer({
21
21
  version: 4,
22
- initial: (): { retained: RepositoryEvent[]; incompleteIdentities: boolean } => ({
22
+ initial: (): { retained: RepositoryEvent[]; incompleteIdentities: boolean; holder?: string } => ({
23
23
  retained: [],
24
24
  incompleteIdentities: true,
25
25
  }),
@@ -29,7 +29,15 @@ export const dispatchFrontendReducer = defineReducer({
29
29
  if (isDashboardRepositoryEvent(event) || event.type === 'dispatcher.run-started')
30
30
  facts.set(event.seq, event)
31
31
  }
32
- acc.retained = [...facts.values()].sort((a, b) => a.seq - b.seq)
32
+ const sorted = [...facts.values()].sort((a, b) => a.seq - b.seq)
33
+ const latest = sorted.findLast((event) => event.type === 'dispatcher.run-started')
34
+ const holder = sorted.findLast(
35
+ (event) => event.type === 'dispatcher.run-started' && event.payload.run === acc.holder,
36
+ )
37
+ acc.retained = sorted.filter(
38
+ (event) => event.type !== 'dispatcher.run-started' || event === latest || event === holder,
39
+ )
40
+ acc.incompleteIdentities = true
33
41
  },
34
42
  finish: (acc) => acc.retained,
35
43
  })
@@ -41,7 +49,12 @@ export class DispatchRepositoryFeed {
41
49
  private ready = false
42
50
  private retained: RepositoryEvent[] = []
43
51
  private tail: Promise<void> = Promise.resolve()
44
- private savedAt = -Infinity
52
+ private generation = 0
53
+ private settled: string | undefined
54
+ private nextSaveAt = -Infinity
55
+ private failures = 0
56
+ private saving: Promise<void> | undefined
57
+ private holder: string | undefined
45
58
  private boundary: number | undefined
46
59
  private recovery = false
47
60
  incompleteIdentities = true
@@ -95,6 +108,8 @@ export class DispatchRepositoryFeed {
95
108
  let cursor = this.cursor
96
109
  let retained = this.retained
97
110
  let incompleteIdentities = this.incompleteIdentities
111
+ let restoredKey: string | undefined
112
+ let restoredRetained: RepositoryEvent[] | undefined
98
113
  let delta: RepositoryEvent[]
99
114
  if (!this.ready) {
100
115
  if ((await this.store.getRepo(this.repo)) === null) {
@@ -115,6 +130,7 @@ export class DispatchRepositoryFeed {
115
130
  const state = snapshot.state as {
116
131
  retained: RepositoryEvent[]
117
132
  incompleteIdentities: boolean
133
+ holder?: string
118
134
  }
119
135
  if (!Array.isArray(state.retained) || typeof state.incompleteIdentities !== 'boolean')
120
136
  throw new Error('invalid projection')
@@ -127,8 +143,15 @@ export class DispatchRepositoryFeed {
127
143
  )
128
144
  )
129
145
  throw new Error('invalid retained fact')
130
- incompleteIdentities = state.incompleteIdentities
131
- retained = state.retained
146
+ if (state.holder !== undefined && typeof state.holder !== 'string')
147
+ throw new Error('invalid holder')
148
+ this.holder = state.holder
149
+ retained = dispatchFrontendReducer.advance({ ...state }, []).retained
150
+ incompleteIdentities = true
151
+ if (state.incompleteIdentities && retained.length === state.retained.length) {
152
+ restoredKey = `${snapshot.cursor}:${this.generation}`
153
+ restoredRetained = retained
154
+ }
132
155
  cursor = snapshot.cursor
133
156
  restored = true
134
157
  } catch {
@@ -161,10 +184,19 @@ export class DispatchRepositoryFeed {
161
184
  retained = this.retained
162
185
  incompleteIdentities = this.incompleteIdentities
163
186
  }
164
- retained = dispatchFrontendReducer.advance({ retained, incompleteIdentities }, delta).retained
187
+ if (delta.length > 0)
188
+ retained = dispatchFrontendReducer.advance(
189
+ { retained, incompleteIdentities, holder: this.holder },
190
+ delta,
191
+ ).retained
165
192
  this.cursor = Math.max(cursor, delta.at(-1)?.seq ?? 0)
166
- this.incompleteIdentities = incompleteIdentities
167
- this.retained = retained
193
+ this.incompleteIdentities = true
194
+ if (restoredKey !== undefined) {
195
+ this.settled = restoredKey
196
+ this.retained = restoredRetained!
197
+ }
198
+ this.replaceRetained(retained)
199
+
168
200
  this.ready = true
169
201
  this.recovery = false
170
202
  result = delta
@@ -174,28 +206,77 @@ export class DispatchRepositoryFeed {
174
206
  return next.then(() => result)
175
207
  }
176
208
 
177
- remember(events: readonly RepositoryEvent[], complete = false): void {
178
- this.retained = dispatchFrontendReducer.advance(
179
- { retained: this.retained, incompleteIdentities: this.incompleteIdentities },
180
- events.filter((e) => e.seq <= this.cursor),
181
- ).retained
182
- if (complete) this.incompleteIdentities = false
209
+ private replaceRetained(events: RepositoryEvent[]): void {
210
+ // Sequence numbers identify immutable journal facts; no deep serialization on polls.
211
+ const changed =
212
+ events !== this.retained &&
213
+ (events.length !== this.retained.length ||
214
+ events.some((event, i) => event.seq !== this.retained[i]?.seq))
215
+ this.retained = events
216
+ if (changed) this.generation++
217
+ }
218
+
219
+ selectHolder(holder: string | undefined): void {
220
+ if (this.holder === holder) return
221
+ this.generation++
222
+ this.holder = holder
223
+ this.replaceRetained(
224
+ dispatchFrontendReducer.advance(
225
+ {
226
+ retained: this.retained,
227
+ incompleteIdentities: true,
228
+ holder,
229
+ },
230
+ [],
231
+ ).retained,
232
+ )
183
233
  }
184
234
 
185
- async save(force = false): Promise<void> {
186
- if (!this.ready || (!force && this.clock().getTime() - this.savedAt < 5000)) return
187
- // A rejected equal-cursor put and an unavailable store still cost a
188
- // request. Bound attempts, not just successful writes, on quiet polls.
189
- this.savedAt = this.clock().getTime()
190
- await persistReducerSnapshot(
235
+ remember(events: readonly RepositoryEvent[], _complete = false): void {
236
+ const eligible = events.filter((e) => e.seq <= this.cursor)
237
+ this.validate(
238
+ [...eligible].sort((a, b) => a.seq - b.seq),
239
+ 0,
240
+ false,
241
+ )
242
+ this.replaceRetained(
243
+ dispatchFrontendReducer.advance(
244
+ { retained: this.retained, incompleteIdentities: true, holder: this.holder },
245
+ eligible,
246
+ ).retained,
247
+ )
248
+ }
249
+
250
+ save(force = false): Promise<void> {
251
+ if (this.saving) return force ? this.saving.then(() => this.save(true)) : this.saving
252
+ const key = `${this.cursor}:${this.generation}`
253
+ const now = this.clock().getTime()
254
+ if (!this.ready || key === this.settled || (!force && now < this.nextSaveAt))
255
+ return Promise.resolve()
256
+ const snapshot = {
257
+ version: dispatchFrontendReducer.version,
258
+ cursor: this.cursor,
259
+ state: { retained: this.retained, incompleteIdentities: true, holder: this.holder },
260
+ }
261
+ this.nextSaveAt = now + 30_000
262
+ this.saving = persistReducerSnapshotOutcome(
191
263
  this.store,
192
264
  { kind: 'repo', repo: this.repo },
193
265
  'dispatchFrontend',
194
- {
195
- version: dispatchFrontendReducer.version,
196
- cursor: this.cursor,
197
- state: { retained: this.retained, incompleteIdentities: this.incompleteIdentities },
198
- },
266
+ snapshot,
199
267
  )
268
+ .then((outcome) => {
269
+ if (outcome === 'unavailable') {
270
+ this.nextSaveAt = this.clock().getTime() + Math.min(30_000 * 2 ** this.failures, 300_000)
271
+ this.failures = Math.min(this.failures + 1, 4)
272
+ } else {
273
+ this.settled = key
274
+ this.failures = 0
275
+ }
276
+ })
277
+ .finally(() => {
278
+ this.saving = undefined
279
+ })
280
+ return this.saving
200
281
  }
201
282
  }