@defrex/autobuild 1.11.1 → 1.13.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 (213) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +601 -203
  3. package/bin/ab-build-runner.ts +8 -0
  4. package/docs/answering-blocked-builds.md +32 -2
  5. package/docs/architecture.md +188 -57
  6. package/docs/assets/headline-wide.png +0 -0
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +120 -23
  9. package/docs/dispatcher.md +19 -8
  10. package/docs/integration-overview.md +1 -1
  11. package/docs/integration-tree.md +33 -18
  12. package/docs/merge-policy.md +7 -2
  13. package/docs/operating.md +5 -3
  14. package/docs/operator-api.md +48 -25
  15. package/docs/operator-surfaces.md +39 -3
  16. package/docs/optimization-nodes.md +10 -8
  17. package/docs/plugin-authoring.md +46 -18
  18. package/docs/remote-store-protocol.md +51 -12
  19. package/docs/remote-ticket-protocol.md +85 -38
  20. package/docs/restacking.md +48 -3
  21. package/docs/setup.md +2 -1
  22. package/docs/ticket-migration.md +2 -2
  23. package/docs/ticket-sources.md +23 -8
  24. package/docs/tickets.md +4 -4
  25. package/docs/troubleshooting.md +17 -2
  26. package/docs/verification.md +3 -1
  27. package/package.json +3 -3
  28. package/packages/core/src/cli/ambient-errors.ts +17 -0
  29. package/packages/core/src/cli/bounded-io.ts +174 -0
  30. package/packages/core/src/cli/build-control.ts +72 -6
  31. package/packages/core/src/cli/dashboard/actions.ts +4 -0
  32. package/packages/core/src/cli/dashboard/integration-row.ts +43 -19
  33. package/packages/core/src/cli/dashboard/model.ts +93 -29
  34. package/packages/core/src/cli/dashboard/poll.ts +231 -34
  35. package/packages/core/src/cli/dashboard/queue.ts +21 -10
  36. package/packages/core/src/cli/dashboard/render.ts +14 -37
  37. package/packages/core/src/cli/dashboard/row-text.ts +26 -8
  38. package/packages/core/src/cli/dashboard/tone-ansi.ts +39 -0
  39. package/packages/core/src/cli/dashboard/vocabulary.ts +165 -20
  40. package/packages/core/src/cli/dispatch-frontend.ts +2 -1
  41. package/packages/core/src/cli/dispatch-handoff.ts +41 -10
  42. package/packages/core/src/cli/dispatch-launch-contract.ts +5 -0
  43. package/packages/core/src/cli/dispatch-launcher-cadence.ts +80 -0
  44. package/packages/core/src/cli/dispatch-launcher.ts +9 -10
  45. package/packages/core/src/cli/dispatch-preflight.ts +12 -3
  46. package/packages/core/src/cli/dispatch-release-observer.ts +53 -0
  47. package/packages/core/src/cli/dispatch-runtime-cache.ts +204 -82
  48. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +250 -43
  49. package/packages/core/src/cli/dispatch-tickets.ts +33 -12
  50. package/packages/core/src/cli/dispatch-upgrade-install.ts +36 -16
  51. package/packages/core/src/cli/dispatch-upgrade-source.ts +8 -2
  52. package/packages/core/src/cli/dispatch-yield-observer.ts +82 -0
  53. package/packages/core/src/cli/dispatch.ts +595 -149
  54. package/packages/core/src/cli/env.ts +2 -15
  55. package/packages/core/src/cli/help.ts +43 -28
  56. package/packages/core/src/cli/main.ts +11 -7
  57. package/packages/core/src/cli/production-store.ts +102 -0
  58. package/packages/core/src/cli/publication-settlement.ts +4 -0
  59. package/packages/core/src/cli/remote-poll.ts +22 -5
  60. package/packages/core/src/cli/repo-state.ts +2 -3
  61. package/packages/core/src/cli/repository-status.ts +44 -28
  62. package/packages/core/src/cli/sessionless-store.ts +26 -0
  63. package/packages/core/src/cli/status.ts +188 -47
  64. package/packages/core/src/cli/store-opening.ts +26 -57
  65. package/packages/core/src/cli/store-ref.ts +6 -1
  66. package/packages/core/src/cli/ticket-start.ts +3 -3
  67. package/packages/core/src/cli/ticket.ts +12 -11
  68. package/packages/core/src/cli/wait.ts +8 -28
  69. package/packages/core/src/cli/watch.ts +113 -50
  70. package/packages/core/src/config/reference-metadata.ts +7 -1
  71. package/packages/core/src/config/reference.ts +5 -2
  72. package/packages/core/src/config/schema.ts +51 -16
  73. package/packages/core/src/distribution-packaging.ts +156 -18
  74. package/packages/core/src/events/catalog-identity.ts +28 -0
  75. package/packages/core/src/events/catalog.ts +3 -9
  76. package/packages/core/src/events/compatibility.ts +2 -30
  77. package/packages/core/src/events/payloads.ts +85 -14
  78. package/packages/core/src/events/policy.ts +3 -0
  79. package/packages/core/src/events/repository.ts +15 -4
  80. package/packages/core/src/events/sessions.ts +1 -1
  81. package/packages/core/src/events/validation-error.ts +12 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +36 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/0a10010ee5cf2e47.json +577 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/227701361be6d1e0.json +490 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3064e337cc75f8d6.json +310 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/76e5043bae7a80ab.json +86 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/87a917802870bbed.json +87 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/9d85616e5b9e24c1.json +500 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a1e90a969d32a367.json +307 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/c7c94fbe7f63cf07.json +84 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/da3bc91c49211eab.json +310 -0
  92. package/packages/core/src/kernel/auto-merge-default.ts +2 -1
  93. package/packages/core/src/kernel/capacity-build.ts +21 -0
  94. package/packages/core/src/kernel/clean-restack-policy.ts +40 -0
  95. package/packages/core/src/kernel/discard-in-flight.ts +13 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +578 -235
  97. package/packages/core/src/kernel/done-escalations.ts +269 -0
  98. package/packages/core/src/kernel/engine.ts +30 -17
  99. package/packages/core/src/kernel/integration-landing.ts +24 -4
  100. package/packages/core/src/kernel/integration-stack.ts +39 -0
  101. package/packages/core/src/kernel/janitor-failure.ts +20 -1
  102. package/packages/core/src/kernel/log-index-value.ts +3 -0
  103. package/packages/core/src/kernel/log-index.ts +41 -2
  104. package/packages/core/src/kernel/measurement.ts +24 -0
  105. package/packages/core/src/kernel/open-pr-backpressure.ts +3 -3
  106. package/packages/core/src/kernel/read-facts.ts +8 -370
  107. package/packages/core/src/kernel/reducer-registry.ts +43 -125
  108. package/packages/core/src/kernel/reducer-revisions.ts +18 -0
  109. package/packages/core/src/kernel/reducer-value-entry.ts +98 -0
  110. package/packages/core/src/kernel/reducer-value-index.ts +75 -0
  111. package/packages/core/src/kernel/reducer.ts +84 -16
  112. package/packages/core/src/kernel/reopen-state.ts +10 -0
  113. package/packages/core/src/kernel/repository-attention.ts +14 -5
  114. package/packages/core/src/kernel/repository-read-facts.ts +375 -0
  115. package/packages/core/src/kernel/ticket-starts.ts +15 -4
  116. package/packages/core/src/kernel/verify-stage-state.ts +145 -3
  117. package/packages/core/src/kernel/verify-stages.ts +46 -7
  118. package/packages/core/src/operator/attention.ts +28 -3
  119. package/packages/core/src/operator/done-escalations.ts +38 -0
  120. package/packages/core/src/operator/presentation.ts +14 -1
  121. package/packages/core/src/operator/protocol.ts +8 -5
  122. package/packages/core/src/operator/query.ts +72 -57
  123. package/packages/core/src/operator/registry.ts +19 -15
  124. package/packages/core/src/operator/ticket-start.ts +8 -7
  125. package/packages/core/src/operator/tickets.ts +28 -9
  126. package/packages/core/src/plugin-sdk/index.ts +10 -0
  127. package/packages/core/src/plugins/manifest.ts +14 -1
  128. package/packages/core/src/ports/forge/create.ts +8 -0
  129. package/packages/core/src/ports/forge/github-transport.ts +5 -1
  130. package/packages/core/src/ports/forge/github.ts +3 -0
  131. package/packages/core/src/ports/tickets/contract.ts +147 -76
  132. package/packages/core/src/ports/tickets/create.ts +47 -7
  133. package/packages/core/src/ports/tickets/fake.ts +8 -4
  134. package/packages/core/src/ports/tickets/file-codec.ts +4 -3
  135. package/packages/core/src/ports/tickets/file.ts +7 -3
  136. package/packages/core/src/ports/tickets/github.ts +1 -0
  137. package/packages/core/src/ports/tickets/grants.ts +11 -3
  138. package/packages/core/src/ports/tickets/hosted-index.ts +5 -0
  139. package/packages/core/src/ports/tickets/linear.ts +28 -9
  140. package/packages/core/src/ports/tickets/migration.ts +4 -4
  141. package/packages/core/src/ports/tickets/operations.ts +4 -2
  142. package/packages/core/src/ports/tickets/priority-labels.ts +213 -0
  143. package/packages/core/src/ports/tickets/priority.ts +127 -21
  144. package/packages/core/src/ports/tickets/remote-protocol.ts +10 -0
  145. package/packages/core/src/ports/tickets/remote.ts +104 -11
  146. package/packages/core/src/ports/tickets/revision.ts +5 -3
  147. package/packages/core/src/ports/tickets/search.ts +9 -0
  148. package/packages/core/src/ports/tickets/tree.ts +8 -6
  149. package/packages/core/src/ports/types.ts +30 -15
  150. package/packages/core/src/ports/workspace/build-execution.ts +4 -0
  151. package/packages/core/src/ports/workspace/builtin-capabilities.ts +4 -0
  152. package/packages/core/src/ports/workspace/create.ts +16 -3
  153. package/packages/core/src/ports/workspace/execution-exit-marker.ts +41 -0
  154. package/packages/core/src/ports/workspace/fake.ts +15 -3
  155. package/packages/core/src/ports/workspace/recovery-step.ts +101 -0
  156. package/packages/core/src/ports/workspace/vercel-sandbox.ts +510 -145
  157. package/packages/core/src/processes/build-execution-state.ts +4 -0
  158. package/packages/core/src/processes/build-runner.ts +14 -1
  159. package/packages/core/src/processes/dispatcher.ts +777 -288
  160. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  161. package/packages/core/src/processes/execution-settlement.ts +1 -0
  162. package/packages/core/src/processes/harvest-runner.ts +12 -7
  163. package/packages/core/src/processes/infrastructure-failure-budget.ts +7 -2
  164. package/packages/core/src/processes/invocation-budget.ts +176 -0
  165. package/packages/core/src/processes/publication-loss.ts +38 -3
  166. package/packages/core/src/processes/workspace-preservation.ts +86 -15
  167. package/packages/core/src/store/contract.ts +81 -3
  168. package/packages/core/src/store/event-reads.ts +30 -1
  169. package/packages/core/src/store/local/capabilities.ts +115 -0
  170. package/packages/core/src/store/local/store.ts +86 -56
  171. package/packages/core/src/store/reduced-reads.ts +32 -1
  172. package/packages/core/src/store/reducer-value-read.ts +235 -0
  173. package/packages/core/src/store/reducer-value-shapes.json +6722 -6475
  174. package/packages/core/src/store/reducer-value-validation.ts +181 -33
  175. package/packages/core/src/store/reducer-values.ts +36 -204
  176. package/packages/core/src/store/remote/client.ts +169 -29
  177. package/packages/core/src/store/remote/compatibility.ts +113 -56
  178. package/packages/core/src/store/remote/credentials.ts +4 -1
  179. package/packages/core/src/store/remote/protocol.ts +3 -0
  180. package/packages/core/src/store/remote/released-clients.json +22 -0
  181. package/packages/core/src/store/remote/released-reducer-values/1.12.0.json +35806 -0
  182. package/packages/core/src/store/remote/released-reducer-values/1.13.0.json +35966 -0
  183. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  184. package/packages/core/src/store/remote/released-value-policy.ts +144 -0
  185. package/packages/core/src/store/remote/retry.ts +406 -0
  186. package/packages/core/src/store/rollup-lease.ts +41 -0
  187. package/packages/core/src/store/rollups.ts +7 -38
  188. package/packages/core/src/store/snapshots.ts +1 -1
  189. package/packages/core/src/testing/dispatch-read-budget.ts +409 -14
  190. package/packages/core/src/testing/import-graph.ts +78 -0
  191. package/packages/core/src/testing/index.ts +2 -0
  192. package/packages/core/src/testing/invocation-budget.ts +42 -0
  193. package/packages/core/src/testing/reduced-read-budget.ts +602 -40
  194. package/packages/core/src/testing/released-value-coverage.ts +423 -0
  195. package/packages/core/src/testing/slot-agreement.ts +52 -0
  196. package/packages/core/src/web/assets/app.js +5 -5
  197. package/packages/core/src/web/overview-source.ts +19 -6
  198. package/skills/guide/SKILL.md +245 -103
  199. package/skills/guide/references/integration-tree.md +33 -18
  200. package/skills/guide/references/merge-policy.md +7 -2
  201. package/skills/guide/references/operator-api.md +48 -25
  202. package/skills/guide/references/optimization-nodes.md +10 -8
  203. package/skills/guide/references/plugin-authoring.md +46 -18
  204. package/skills/guide/references/remote-store-protocol.md +51 -12
  205. package/skills/guide/references/remote-ticket-protocol.md +85 -38
  206. package/skills/guide/references/restacking.md +48 -3
  207. package/skills/guide/references/setup.md +2 -1
  208. package/skills/guide/references/ticket-migration.md +2 -2
  209. package/skills/operate/SKILL.md +114 -65
  210. package/skills/plan/SKILL.md +4 -3
  211. package/skills/spec/SKILL.md +9 -5
  212. package/skills/tickets/SKILL.md +25 -17
  213. package/templates/hosted-service/package.json +2 -2
@@ -2,14 +2,16 @@
2
2
  import release0 from './1.10.0.json'
3
3
  import release1 from './1.11.0.json'
4
4
  import release2 from './1.11.1.json'
5
- import release3 from './1.2.0.json'
6
- import release4 from './1.3.0.json'
7
- import release5 from './1.4.0.json'
8
- import release6 from './1.5.0.json'
9
- import release7 from './1.6.0.json'
10
- import release8 from './1.7.0.json'
11
- import release9 from './1.8.0.json'
12
- import release10 from './1.9.0.json'
5
+ import release3 from './1.12.0.json'
6
+ import release4 from './1.13.0.json'
7
+ import release5 from './1.2.0.json'
8
+ import release6 from './1.3.0.json'
9
+ import release7 from './1.4.0.json'
10
+ import release8 from './1.5.0.json'
11
+ import release9 from './1.6.0.json'
12
+ import release10 from './1.7.0.json'
13
+ import release11 from './1.8.0.json'
14
+ import release12 from './1.9.0.json'
13
15
  import type { ReducerValueCatalog } from '../../reducer-value-validation'
14
16
  export interface ReleasedReducerValues extends ReducerValueCatalog {
15
17
  versions: Record<string, number>
@@ -18,12 +20,14 @@ export const RELEASED_REDUCER_VALUES: Readonly<Record<string, ReleasedReducerVal
18
20
  '1.10.0.json': release0,
19
21
  '1.11.0.json': release1,
20
22
  '1.11.1.json': release2,
21
- '1.2.0.json': release3,
22
- '1.3.0.json': release4,
23
- '1.4.0.json': release5,
24
- '1.5.0.json': release6,
25
- '1.6.0.json': release7,
26
- '1.7.0.json': release8,
27
- '1.8.0.json': release9,
28
- '1.9.0.json': release10,
23
+ '1.12.0.json': release3,
24
+ '1.13.0.json': release4,
25
+ '1.2.0.json': release5,
26
+ '1.3.0.json': release6,
27
+ '1.4.0.json': release7,
28
+ '1.5.0.json': release8,
29
+ '1.6.0.json': release9,
30
+ '1.7.0.json': release10,
31
+ '1.8.0.json': release11,
32
+ '1.9.0.json': release12,
29
33
  }
@@ -0,0 +1,144 @@
1
+ /** Declared divergences between the canonical reducer values this service
2
+ * serves and the frozen contracts of still-supported published clients.
3
+ *
4
+ * A site is `${reducer}:${path}`. The path starts at `$` and uses `.prop` for an
5
+ * object property, `[]` for an array element and `[*]` for a record entry. A
6
+ * literal site names the property (or array element) holding the literal; an
7
+ * event or ledger variant site names the slot holding the object.
8
+ *
9
+ * - `map` rewrites a widened literal to an older one that behaves the same for
10
+ * older readers, when the release can represent the target.
11
+ * - `omit` removes an optional descriptive property holding a listed literal.
12
+ * - `refuse` records a deliberate decision that no older equivalent exists: the
13
+ * canonical answer goes back unchanged and the client raises its typed
14
+ * incompatibility. Refuse entries change no served value; they document the
15
+ * decision and are the oracle for the populated coverage sweep.
16
+ *
17
+ * The sweep in `released-value-coverage.integration.test.ts` fails on any
18
+ * populated variant that a supported contract cannot represent at an
19
+ * undeclared site, and on any entry here that no sample exercises. */
20
+ export type ReleasedValuePolicy =
21
+ | {
22
+ kind: 'map'
23
+ sites: readonly string[]
24
+ map: Readonly<Record<string, string>>
25
+ reason: string
26
+ }
27
+ | {
28
+ kind: 'omit'
29
+ sites: readonly string[]
30
+ values: readonly string[]
31
+ reason: string
32
+ }
33
+ | { kind: 'refuse'; sites: readonly string[]; reason: string }
34
+
35
+ export const RELEASED_VALUE_POLICY: readonly ReleasedValuePolicy[] = [
36
+ {
37
+ kind: 'map',
38
+ sites: ['repositoryReadFacts:$.sandboxes[].state', 'sandboxStates:$[].state'],
39
+ map: { provisioning: 'stopped', failed: 'stopped' },
40
+ reason:
41
+ 'Every supported release knows released, stopped and live. A provisioning or failed sandbox has no usable live environment, which older readers spell stopped: their repository status shows it as stopped, dispatcher idle settlement acts only on live, and an operator open of a stopped environment ensures it again, which is what a failed or unfinished one needs.',
42
+ },
43
+ {
44
+ kind: 'refuse',
45
+ sites: [
46
+ 'leafRestack:$.active.trigger',
47
+ 'leafRestack:$.gates[*].trigger',
48
+ 'leafRestack:$.intent.trigger',
49
+ 'leafRestack:$.completed.trigger',
50
+ 'buildStreamSeed:$.restack.active.trigger',
51
+ 'buildStreamSeed:$.restack.gates[*].trigger',
52
+ 'buildStreamSeed:$.restack.intent.trigger',
53
+ 'buildStreamSeed:$.restack.completed.trigger',
54
+ 'buildReadFacts:$.log.restack.active.trigger',
55
+ 'buildReadFacts:$.log.restack.gates[*].trigger',
56
+ 'buildReadFacts:$.log.restack.intent.trigger',
57
+ 'buildReadFacts:$.log.restack.completed.trigger',
58
+ ],
59
+ reason:
60
+ 'Restack triggers drive engine decisions. The current engine recognizes and resumes a wait-resume restack by its trigger (engine wait restacks, log-index reverification, ticket-wait), so an older engine continuing it as verify-entry would write restack facts a newer kernel reads differently. Releases before 1.8 that predate wait-resume refuse.',
61
+ },
62
+ {
63
+ kind: 'map',
64
+ sites: [
65
+ 'build:$.answeredEscalations[].resolution',
66
+ 'buildReadFacts:$.state.answeredEscalations[].resolution',
67
+ 'buildStreamSeed:$.build.answeredEscalations[].resolution',
68
+ 'buildReadFacts:$.publication.retries[].payload.resolution',
69
+ ],
70
+ map: { 'accept-target': 'retry' },
71
+ reason:
72
+ 'Released readers (engine, ab context, build control, dashboard) act only on guidance, dismiss-finding and revise-spec answers; retry and accept-target both fall through every one of those checks, so they behave identically. Mapping to guidance would make older ab context surface the answer as phase guidance.',
73
+ },
74
+ {
75
+ kind: 'omit',
76
+ sites: [
77
+ 'build:$.verify.results[].skipCause',
78
+ 'buildReadFacts:$.state.verify.results[].skipCause',
79
+ 'buildStreamSeed:$.build.verify.results[].skipCause',
80
+ 'buildReadFacts:$.summaryHistory[].result.skipCause',
81
+ 'buildReadFacts:$.log.verifyCompleted[].skipCause',
82
+ ],
83
+ values: ['clean-restack-policy'],
84
+ reason:
85
+ 'Released readers decide on a skipped result by its outcome alone: their engine counts any skipped step as satisfied, and only the dashboard reads skipCause, to pick a post-reconcile skip reason for display. A clean-restack skip without its cause is still a satisfied skipped step with its reason, so dropping the cause changes no decision.',
86
+ },
87
+ {
88
+ kind: 'refuse',
89
+ sites: [
90
+ 'build:$.openEscalations[].policyCause',
91
+ 'buildReadFacts:$.state.openEscalations[].policyCause',
92
+ 'buildStreamSeed:$.build.openEscalations[].policyCause',
93
+ 'build:$.answeredEscalations[].policyCause',
94
+ 'buildReadFacts:$.state.answeredEscalations[].policyCause',
95
+ 'buildStreamSeed:$.build.answeredEscalations[].policyCause',
96
+ 'build:$.verifyStage.superseded[].escalation.policyCause',
97
+ 'buildReadFacts:$.state.verifyStage.superseded[].escalation.policyCause',
98
+ 'buildStreamSeed:$.build.verifyStage.superseded[].escalation.policyCause',
99
+ ],
100
+ reason:
101
+ 'policyCause drives engine decisions, so a release that predates a cause refuses rather than losing it: released engines read an absent cause with no round on a reconcile policy escalation as the legacy reconcile-no-progress marker, and the current engine keeps target-rewritten escalations out of deduplication history. Omitting or substituting the cause would change those decisions.',
102
+ },
103
+ {
104
+ kind: 'refuse',
105
+ sites: ['buildReadFacts:$.terminalEvent', 'buildStreamSeed:$.terminalEvent'],
106
+ reason:
107
+ 'The schema types the slot as any build event, but the fold stores only build.completed or build.aborted, which every release knows; any other value is not one this service writes.',
108
+ },
109
+ {
110
+ kind: 'refuse',
111
+ sites: ['runtime', 'start', 'latestStart', 'stop', 'tick', 'completed'].flatMap((slot) => [
112
+ `dispatcherRunFacts:$.${slot}`,
113
+ `repositoryReadFacts:$.recentRuns[][].${slot}`,
114
+ ]),
115
+ reason:
116
+ 'The schema types each dispatcher run slot as any repository event, but the fold stores only the dispatcher run, runtime, stop and tick events every release knows; any other value is not one this service writes.',
117
+ },
118
+ {
119
+ kind: 'refuse',
120
+ sites: [
121
+ 'buildReadFacts:$.workspacePreservation',
122
+ 'buildReadFacts:$.latestWorkspace',
123
+ 'buildReadFacts:$.restackHistory[]',
124
+ 'buildReadFacts:$.reconcileHistory[]',
125
+ 'buildReadFacts:$.publication.ledger[]',
126
+ ],
127
+ reason:
128
+ 'Decisive workspace, restack, reconcile and publication history: an event or ledger variant the release predates has no older equivalent, so the client must refuse rather than misread it.',
129
+ },
130
+ ]
131
+
132
+ export function policyBySite(
133
+ policy: readonly ReleasedValuePolicy[],
134
+ ): ReadonlyMap<string, ReleasedValuePolicy> {
135
+ const bySite = new Map<string, ReleasedValuePolicy>()
136
+ for (const entry of policy)
137
+ for (const site of entry.sites) {
138
+ if (bySite.has(site)) throw new Error(`released-value policy declares ${site} twice`)
139
+ bySite.set(site, entry)
140
+ }
141
+ return bySite
142
+ }
143
+
144
+ export const RELEASED_VALUE_POLICY_BY_SITE = policyBySite(RELEASED_VALUE_POLICY)
@@ -0,0 +1,406 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { errorBodySchema } from './protocol'
3
+
4
+ /**
5
+ * Transient-failure retries for the hosted clients (SPEC "Transient remote
6
+ * retries"). The happy path is one request: no timer, clone, buffer or probe.
7
+ * Only a failure that could be retried creates the retry bound — the earlier
8
+ * of `retryWindowMs` after that failure and the scoped invocation deadline —
9
+ * and every later piece of retry work (sleeps, retry requests, async safety
10
+ * checks, response-body buffering) is tied to it.
11
+ */
12
+
13
+ /** `idempotent` retries any transient status or transport failure; `unsafe`
14
+ * retries only a `429` or a transport failure proven to precede delivery. */
15
+ export type RetrySafety = 'idempotent' | 'unsafe'
16
+
17
+ export interface RemoteRetryPolicy {
18
+ /** The first attempt plus retries. */
19
+ maxAttempts: number
20
+ baseDelayMs: number
21
+ maxDelayMs: number
22
+ /** A `Retry-After` longer than this is not retried. */
23
+ maxRetryAfterMs: number
24
+ /** Retry work ends this long after the first retryable failure. */
25
+ retryWindowMs: number
26
+ now(): number
27
+ /** Resolves after `ms`, or early when `signal` aborts. */
28
+ sleep(ms: number, signal: AbortSignal): Promise<void>
29
+ random(): number
30
+ /** A cancellable timeout signal; the helper always cancels it before returning. */
31
+ timeout(ms: number): { signal: AbortSignal; cancel(): void }
32
+ }
33
+
34
+ /** `false` is a single attempt; a partial merges over the defaults. */
35
+ export type RemoteRetryOptions = Partial<RemoteRetryPolicy> | false
36
+
37
+ export const DEFAULT_REMOTE_RETRY: RemoteRetryPolicy = {
38
+ maxAttempts: 3,
39
+ baseDelayMs: 500,
40
+ maxDelayMs: 2000,
41
+ maxRetryAfterMs: 5000,
42
+ retryWindowMs: 10_000,
43
+ now: () => Date.now(),
44
+ sleep: (ms, signal) =>
45
+ new Promise<void>((resolve) => {
46
+ if (signal.aborted) return resolve()
47
+ const done = () => {
48
+ clearTimeout(timer)
49
+ signal.removeEventListener('abort', done)
50
+ resolve()
51
+ }
52
+ const timer = setTimeout(done, ms)
53
+ signal.addEventListener('abort', done, { once: true })
54
+ }),
55
+ random: () => Math.random(),
56
+ timeout: (ms) => {
57
+ const controller = new AbortController()
58
+ const timer = setTimeout(
59
+ () => controller.abort(new DOMException('remote retry bound reached', 'TimeoutError')),
60
+ ms,
61
+ )
62
+ return { signal: controller.signal, cancel: () => clearTimeout(timer) }
63
+ },
64
+ }
65
+
66
+ export function resolveRemoteRetry(
67
+ options: RemoteRetryOptions | undefined,
68
+ ): RemoteRetryPolicy | false {
69
+ if (options === false) return false
70
+ return { ...DEFAULT_REMOTE_RETRY, ...options }
71
+ }
72
+
73
+ const deadlineScope = new AsyncLocalStorage<{ deadlineAt: number }>()
74
+
75
+ /** Runs `fn` with an invocation deadline that bounds every retry it causes. */
76
+ export function withRemoteRetryDeadline<T>(deadlineAt: number, fn: () => T): T {
77
+ return deadlineScope.run({ deadlineAt }, fn)
78
+ }
79
+
80
+ /** The exhausted (or bounded) form of a transient remote failure. */
81
+ export class RemoteUnavailableError extends Error {
82
+ override readonly name = 'RemoteUnavailableError'
83
+ readonly status: number | undefined
84
+ readonly attempts: number
85
+
86
+ constructor(
87
+ message: string,
88
+ options: { status?: number; attempts?: number; cause?: unknown } = {},
89
+ ) {
90
+ super(message, options.cause === undefined ? undefined : { cause: options.cause })
91
+ this.status = options.status
92
+ this.attempts = options.attempts ?? 1
93
+ }
94
+ }
95
+
96
+ export const isTransientRemoteFailure = (error: unknown): error is RemoteUnavailableError =>
97
+ error instanceof RemoteUnavailableError
98
+
99
+ /** Milliseconds a `Retry-After` header asks for (delta-seconds or HTTP-date). */
100
+ export function retryAfterMs(header: string | null, now: number): number | undefined {
101
+ if (header === null) return undefined
102
+ const value = header.trim()
103
+ if (/^\d+$/.test(value)) return Number(value) * 1000
104
+ const at = Date.parse(value)
105
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now)
106
+ }
107
+
108
+ const PRE_DELIVERY_CODES = new Set([
109
+ 'ConnectionRefused',
110
+ 'ECONNREFUSED',
111
+ 'FailedToOpenSocket',
112
+ 'ENOTFOUND',
113
+ 'EAI_AGAIN',
114
+ 'UND_ERR_CONNECT_TIMEOUT',
115
+ ])
116
+
117
+ const codeOf = (error: unknown): unknown =>
118
+ error !== null && typeof error === 'object' ? (error as { code?: unknown }).code : undefined
119
+
120
+ /** A transport failure that provably happened before the request was delivered. */
121
+ export function isPreDeliveryFailure(error: unknown): boolean {
122
+ const cause =
123
+ error !== null && typeof error === 'object' ? (error as { cause?: unknown }).cause : undefined
124
+ return [codeOf(error), codeOf(cause)].some(
125
+ (code) => typeof code === 'string' && PRE_DELIVERY_CODES.has(code),
126
+ )
127
+ }
128
+
129
+ function isAbortError(error: unknown): boolean {
130
+ const name =
131
+ error !== null && typeof error === 'object' ? (error as { name?: unknown }).name : undefined
132
+ return name === 'AbortError' || name === 'TimeoutError'
133
+ }
134
+
135
+ const RETRY_STATUSES = new Set([429, 500, 502, 503, 504])
136
+
137
+ /** Whether a final status is transient. A `500` is transient unless its body
138
+ * is a protocol error of a kind other than `internal` (`checkpoint-integrity`,
139
+ * say). `body` is the parsed JSON body, or `undefined` when it had none. */
140
+ export function isTransientStatus(status: number, body: unknown): boolean {
141
+ if (status !== 500) return RETRY_STATUSES.has(status)
142
+ const parsed = errorBodySchema.safeParse(body)
143
+ return !parsed.success || parsed.data.kind === 'internal'
144
+ }
145
+
146
+ function parseJson(bytes: Uint8Array): unknown {
147
+ try {
148
+ return JSON.parse(new TextDecoder().decode(bytes))
149
+ } catch {
150
+ return undefined
151
+ }
152
+ }
153
+
154
+ /** How many attempts produced a response the helper returned. */
155
+ const attemptsByResponse = new WeakMap<Response, number>()
156
+ export const responseAttempts = (response: Response): number =>
157
+ attemptsByResponse.get(response) ?? 1
158
+
159
+ class BoundAborted extends Error {}
160
+
161
+ /** Settles with `promise`, or rejects with `BoundAborted` when `signal` aborts. */
162
+ function raceAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {
163
+ promise.catch(() => {})
164
+ if (signal.aborted) return Promise.reject(new BoundAborted())
165
+ return new Promise<T>((resolve, reject) => {
166
+ const onAbort = () => reject(new BoundAborted())
167
+ signal.addEventListener('abort', onAbort, { once: true })
168
+ promise.then(
169
+ (value) => {
170
+ signal.removeEventListener('abort', onAbort)
171
+ resolve(value)
172
+ },
173
+ (error) => {
174
+ signal.removeEventListener('abort', onAbort)
175
+ reject(error)
176
+ },
177
+ )
178
+ })
179
+ }
180
+
181
+ /** Reads a whole body through an owned reader. When `bound` aborts the reader
182
+ * is cancelled without awaiting cleanup, which also ends a network body whose
183
+ * `fetch` never saw `bound`. */
184
+ async function readAllUnderBound(
185
+ response: Response,
186
+ bound: AbortSignal,
187
+ ): Promise<Uint8Array<ArrayBuffer>> {
188
+ if (!response.body) return new Uint8Array()
189
+ const reader = response.body.getReader()
190
+ const chunks: Uint8Array[] = []
191
+ let size = 0
192
+ try {
193
+ for (;;) {
194
+ const result = await raceAbort(reader.read(), bound)
195
+ if (result.done) break
196
+ chunks.push(result.value)
197
+ size += result.value.byteLength
198
+ }
199
+ } catch (error) {
200
+ if (bound.aborted) {
201
+ void reader.cancel(bound.reason).catch(() => {})
202
+ throw new BoundAborted()
203
+ }
204
+ throw error
205
+ }
206
+ reader.releaseLock()
207
+ const bytes = new Uint8Array(size)
208
+ let offset = 0
209
+ for (const chunk of chunks) {
210
+ bytes.set(chunk, offset)
211
+ offset += chunk.byteLength
212
+ }
213
+ return bytes
214
+ }
215
+
216
+ const NULL_BODY_STATUSES = new Set([204, 205, 304])
217
+
218
+ function rebuild(response: Response, bytes: Uint8Array<ArrayBuffer>, attempts: number): Response {
219
+ const rebuilt = new Response(NULL_BODY_STATUSES.has(response.status) ? null : bytes, {
220
+ status: response.status,
221
+ statusText: response.statusText,
222
+ headers: response.headers,
223
+ })
224
+ attemptsByResponse.set(rebuilt, attempts)
225
+ return rebuilt
226
+ }
227
+
228
+ type Failure =
229
+ | { kind: 'status'; response: Response; bytes: Uint8Array<ArrayBuffer> }
230
+ | { kind: 'transport'; error: unknown }
231
+
232
+ function describe(failure: Failure, label: string): string {
233
+ if (failure.kind === 'transport')
234
+ return failure.error instanceof Error ? failure.error.message : String(failure.error)
235
+ const body = parseJson(failure.bytes)
236
+ const error =
237
+ body !== null && typeof body === 'object' ? (body as { error?: unknown }).error : undefined
238
+ return typeof error === 'string' ? error : `${label} responded ${failure.response.status}`
239
+ }
240
+
241
+ /** A transport failure the client surfaces once retries end: an abort is the
242
+ * caller's own and rethrows unchanged; anything else is transient. */
243
+ function transportOutcome(error: unknown, attempts: number): unknown {
244
+ if (isAbortError(error)) return error
245
+ return new RemoteUnavailableError(error instanceof Error ? error.message : String(error), {
246
+ attempts,
247
+ cause: error,
248
+ })
249
+ }
250
+
251
+ /**
252
+ * One logical request: `attempt(signal)` issues it. The first call passes the
253
+ * caller's signal unchanged; each retry passes the bound. Returns the final
254
+ * response (live when no retry bound was ever created, otherwise rebuilt from
255
+ * bytes buffered under the bound), or throws `RemoteUnavailableError` for an
256
+ * exhausted transport failure or a bound cut-off, or the caller's abort reason.
257
+ */
258
+ export async function fetchWithRetry(
259
+ attempt: (signal: AbortSignal | undefined) => Promise<Response>,
260
+ opts: {
261
+ safety: RetrySafety | (() => Promise<RetrySafety>)
262
+ signal?: AbortSignal
263
+ policy: RemoteRetryPolicy | false
264
+ /** Names the server in a status-only failure description. */
265
+ label?: string
266
+ /** After a retry ends in a non-transient answer, an alternative request
267
+ * issued on the retry bound; its body is read under the bound, and an ok
268
+ * answer replaces the final one. */
269
+ recover?: (final: Response, bound: AbortSignal) => Promise<Response> | undefined
270
+ },
271
+ ): Promise<Response> {
272
+ const { policy, signal: caller } = opts
273
+ const label = opts.label ?? 'store server'
274
+ let response: Response | undefined
275
+ let error: unknown
276
+ try {
277
+ response = await attempt(caller)
278
+ } catch (thrown) {
279
+ error = thrown
280
+ }
281
+ const staticUnsafe = opts.safety === 'unsafe'
282
+ if (response !== undefined) {
283
+ if (
284
+ policy === false ||
285
+ !RETRY_STATUSES.has(response.status) ||
286
+ (staticUnsafe && response.status !== 429)
287
+ )
288
+ return response
289
+ } else if (
290
+ policy === false ||
291
+ isAbortError(error) ||
292
+ caller?.aborted ||
293
+ (staticUnsafe && !isPreDeliveryFailure(error))
294
+ ) {
295
+ // The caller's own abort rethrows exactly as fetch raised it.
296
+ throw caller?.aborted ? error : transportOutcome(error, 1)
297
+ }
298
+
299
+ // A retryable failure: everything from here on is bounded.
300
+ const scoped = deadlineScope.getStore()?.deadlineAt
301
+ const start = policy.now()
302
+ const boundAt = Math.min(start + policy.retryWindowMs, scoped ?? Infinity)
303
+ const timer = policy.timeout(Math.max(0, boundAt - start))
304
+ const bound = caller ? AbortSignal.any([caller, timer.signal]) : timer.signal
305
+ let attempts = 1
306
+ let failure: Failure | undefined
307
+ let safety: RetrySafety | undefined = typeof opts.safety === 'string' ? opts.safety : undefined
308
+
309
+ const boundOutcome = (): unknown => {
310
+ if (caller?.aborted) return caller.reason
311
+ const last = failure
312
+ return new RemoteUnavailableError(
313
+ `${last ? describe(last, label) : `${label} unavailable`} (retries stopped at the retry bound)`,
314
+ {
315
+ ...(last?.kind === 'status' ? { status: last.response.status } : {}),
316
+ attempts,
317
+ cause: last?.kind === 'transport' ? last.error : undefined,
318
+ },
319
+ )
320
+ }
321
+ const giveUp = (): Response => {
322
+ if (failure === undefined) throw boundOutcome()
323
+ if (failure.kind === 'status') return rebuild(failure.response, failure.bytes, attempts)
324
+ throw transportOutcome(failure.error, attempts)
325
+ }
326
+
327
+ const recovered = async (final: Response): Promise<Response> => {
328
+ let alternative: Response | undefined
329
+ try {
330
+ const pending = opts.recover!(final, bound)
331
+ if (pending === undefined) return final
332
+ alternative = await raceAbort(pending, bound)
333
+ const bytes = await readAllUnderBound(alternative, bound)
334
+ return alternative.ok ? rebuild(alternative, bytes, attempts) : final
335
+ } catch (thrown) {
336
+ if (thrown instanceof BoundAborted || bound.aborted) throw boundOutcome()
337
+ throw transportOutcome(thrown, attempts)
338
+ }
339
+ }
340
+
341
+ try {
342
+ for (;;) {
343
+ if (response !== undefined) {
344
+ let bytes: Uint8Array<ArrayBuffer>
345
+ try {
346
+ bytes = await readAllUnderBound(response, bound)
347
+ } catch (thrown) {
348
+ if (thrown instanceof BoundAborted) throw boundOutcome()
349
+ // The body failed mid-stream: a transport failure of this attempt.
350
+ response = undefined
351
+ error = thrown
352
+ continue
353
+ }
354
+ if (!isTransientStatus(response.status, parseJson(bytes))) {
355
+ const final = rebuild(response, bytes, attempts)
356
+ return attempts > 1 && opts.recover ? await recovered(final) : final
357
+ }
358
+ failure = { kind: 'status', response, bytes }
359
+ } else {
360
+ if (caller?.aborted) throw caller.reason
361
+ if (isAbortError(error)) throw error
362
+ failure = { kind: 'transport', error }
363
+ }
364
+
365
+ if (attempts >= policy.maxAttempts) return giveUp()
366
+ if (safety === undefined) {
367
+ try {
368
+ safety = await raceAbort((opts.safety as () => Promise<RetrySafety>)(), bound)
369
+ } catch {
370
+ if (caller?.aborted) throw caller.reason
371
+ safety = 'unsafe'
372
+ }
373
+ }
374
+ const admitted =
375
+ failure.kind === 'status'
376
+ ? safety === 'idempotent' || failure.response.status === 429
377
+ : safety === 'idempotent' || isPreDeliveryFailure(failure.error)
378
+ if (!admitted || bound.aborted) return giveUp()
379
+
380
+ const requested =
381
+ failure.kind === 'status'
382
+ ? retryAfterMs(failure.response.headers.get('retry-after'), policy.now())
383
+ : undefined
384
+ if (requested !== undefined && requested > policy.maxRetryAfterMs) return giveUp()
385
+ const ceiling = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (attempts - 1))
386
+ const delay = Math.max(requested ?? 0, ceiling / 2 + policy.random() * (ceiling / 2))
387
+ if (policy.now() + delay >= boundAt) return giveUp()
388
+
389
+ await policy.sleep(delay, bound)
390
+ if (bound.aborted) throw boundOutcome()
391
+ if (policy.now() >= boundAt) return giveUp()
392
+
393
+ attempts += 1
394
+ try {
395
+ response = await attempt(bound)
396
+ error = undefined
397
+ } catch (thrown) {
398
+ if (bound.aborted) throw boundOutcome()
399
+ response = undefined
400
+ error = thrown
401
+ }
402
+ }
403
+ } finally {
404
+ timer.cancel()
405
+ }
406
+ }
@@ -0,0 +1,41 @@
1
+ /** Rollup serialization primitives, free of the reducer catalog so stores can
2
+ * construct their locks without initializing it. `./rollups` re-exports them. */
3
+
4
+ /** A promise chain per key: serializes same-key work inside one store
5
+ * instance. */
6
+ export class KeyedMutex {
7
+ private readonly tails = new Map<string, Promise<unknown>>()
8
+
9
+ async run<T>(key: string, body: () => Promise<T>): Promise<T> {
10
+ const previous = this.tails.get(key) ?? Promise.resolve()
11
+ const next = previous.catch(() => {}).then(body)
12
+ this.tails.set(key, next)
13
+ try {
14
+ return await next
15
+ } finally {
16
+ if (this.tails.get(key) === next) this.tails.delete(key)
17
+ }
18
+ }
19
+ }
20
+
21
+ /** A store-wide rollup lease (the SQLite adapter's per-key serialization). */
22
+ export const ROLLUP_LEASE_MS = 120_000
23
+ /** How long a reader waits on another holder's lease before giving up. */
24
+ export const ROLLUP_LEASE_WAIT_MS = 600_000
25
+
26
+ /** A reader waited `ROLLUP_LEASE_WAIT_MS` on another holder's lease. */
27
+ export class RollupLeaseTimeoutError extends Error {
28
+ override readonly name = 'RollupLeaseTimeoutError'
29
+ constructor(readonly key: string) {
30
+ super(`timed out waiting for the rollup lease on ${key}`)
31
+ }
32
+ }
33
+
34
+ /** An advance's lease expired and another holder took it over; the advance
35
+ * commits nothing. */
36
+ export class RollupLeaseLostError extends Error {
37
+ override readonly name = 'RollupLeaseLostError'
38
+ constructor(readonly key: string) {
39
+ super(`lost the rollup lease on ${key}`)
40
+ }
41
+ }
@@ -297,41 +297,10 @@ export async function readRollupValue(
297
297
  })
298
298
  }
299
299
 
300
- /** A promise chain per key: serializes same-key work inside one store
301
- * instance. */
302
- export class KeyedMutex {
303
- private readonly tails = new Map<string, Promise<unknown>>()
304
-
305
- async run<T>(key: string, body: () => Promise<T>): Promise<T> {
306
- const previous = this.tails.get(key) ?? Promise.resolve()
307
- const next = previous.catch(() => {}).then(body)
308
- this.tails.set(key, next)
309
- try {
310
- return await next
311
- } finally {
312
- if (this.tails.get(key) === next) this.tails.delete(key)
313
- }
314
- }
315
- }
316
-
317
- /** A store-wide rollup lease (the SQLite adapter's per-key serialization). */
318
- export const ROLLUP_LEASE_MS = 120_000
319
- /** How long a reader waits on another holder's lease before giving up. */
320
- export const ROLLUP_LEASE_WAIT_MS = 600_000
321
-
322
- /** A reader waited `ROLLUP_LEASE_WAIT_MS` on another holder's lease. */
323
- export class RollupLeaseTimeoutError extends Error {
324
- override readonly name = 'RollupLeaseTimeoutError'
325
- constructor(readonly key: string) {
326
- super(`timed out waiting for the rollup lease on ${key}`)
327
- }
328
- }
329
-
330
- /** An advance's lease expired and another holder took it over; the advance
331
- * commits nothing. */
332
- export class RollupLeaseLostError extends Error {
333
- override readonly name = 'RollupLeaseLostError'
334
- constructor(readonly key: string) {
335
- super(`lost the rollup lease on ${key}`)
336
- }
337
- }
300
+ export {
301
+ KeyedMutex,
302
+ ROLLUP_LEASE_MS,
303
+ ROLLUP_LEASE_WAIT_MS,
304
+ RollupLeaseLostError,
305
+ RollupLeaseTimeoutError,
306
+ } from './rollup-lease'