@defrex/autobuild 1.10.0 → 1.11.1

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 (255) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +745 -69
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +165 -29
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +64 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +111 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +179 -76
  41. package/packages/core/src/cli/dashboard/render.ts +159 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +40 -40
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +202 -38
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +105 -49
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +381 -30
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  95. package/packages/core/src/kernel/build-roster.ts +230 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  97. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  98. package/packages/core/src/kernel/engine.ts +43 -5
  99. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  100. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  101. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  102. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  103. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  104. package/packages/core/src/kernel/log-index.ts +19 -0
  105. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  106. package/packages/core/src/kernel/optimization.ts +183 -4
  107. package/packages/core/src/kernel/phase-failures.ts +121 -0
  108. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  109. package/packages/core/src/kernel/read-facts.ts +15 -13
  110. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  111. package/packages/core/src/kernel/reducer-revisions.ts +27 -0
  112. package/packages/core/src/kernel/reducer.ts +63 -4
  113. package/packages/core/src/kernel/rollup.ts +61 -0
  114. package/packages/core/src/kernel/setup-streak.ts +38 -0
  115. package/packages/core/src/kernel/step-durations.ts +257 -0
  116. package/packages/core/src/kernel/target-observation.ts +6 -1
  117. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  118. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  119. package/packages/core/src/kernel/verify-stages.ts +13 -3
  120. package/packages/core/src/ontology.ts +5 -0
  121. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  122. package/packages/core/src/operator/annotations.ts +75 -5
  123. package/packages/core/src/operator/attention.ts +470 -0
  124. package/packages/core/src/operator/canonical-skills.ts +35 -0
  125. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  126. package/packages/core/src/operator/context-prompts.ts +61 -0
  127. package/packages/core/src/operator/index.ts +49 -1
  128. package/packages/core/src/operator/landings.ts +28 -19
  129. package/packages/core/src/operator/optimization.ts +7 -0
  130. package/packages/core/src/operator/protocol.ts +3 -0
  131. package/packages/core/src/operator/query.ts +129 -74
  132. package/packages/core/src/operator/read-view.ts +5 -2
  133. package/packages/core/src/operator/registry.ts +406 -46
  134. package/packages/core/src/operator/requests.ts +20 -18
  135. package/packages/core/src/operator/sandbox-host.ts +107 -11
  136. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  137. package/packages/core/src/operator/sandbox.ts +778 -82
  138. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  139. package/packages/core/src/operator/ticket-assets.ts +167 -0
  140. package/packages/core/src/operator/tickets.ts +33 -2
  141. package/packages/core/src/plugin-sdk/index.ts +22 -0
  142. package/packages/core/src/plugins/manifest.ts +1 -1
  143. package/packages/core/src/ports/forge/fake.ts +92 -1
  144. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  145. package/packages/core/src/ports/forge/github.ts +82 -0
  146. package/packages/core/src/ports/forge/local-git.ts +61 -1
  147. package/packages/core/src/ports/forge-failure.ts +24 -0
  148. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  149. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  150. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  151. package/packages/core/src/ports/tickets/contract.ts +71 -0
  152. package/packages/core/src/ports/tickets/fake.ts +11 -0
  153. package/packages/core/src/ports/tickets/file.ts +18 -0
  154. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  155. package/packages/core/src/ports/tickets/github.ts +387 -30
  156. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  157. package/packages/core/src/ports/tickets/linear.ts +130 -0
  158. package/packages/core/src/ports/tickets/priority.ts +9 -0
  159. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  160. package/packages/core/src/ports/tickets/remote.ts +70 -6
  161. package/packages/core/src/ports/tickets/search.ts +139 -0
  162. package/packages/core/src/ports/types.ts +104 -2
  163. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  164. package/packages/core/src/ports/workspace/create.ts +15 -1
  165. package/packages/core/src/ports/workspace/fake.ts +340 -12
  166. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  167. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  168. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  169. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  170. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  171. package/packages/core/src/processes/agent-context.ts +469 -0
  172. package/packages/core/src/processes/build-runner.ts +387 -236
  173. package/packages/core/src/processes/dispatcher.ts +211 -55
  174. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  175. package/packages/core/src/processes/optimization-activity.ts +120 -0
  176. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  177. package/packages/core/src/processes/repo-view.ts +78 -2
  178. package/packages/core/src/processes/sandbox-state.ts +53 -6
  179. package/packages/core/src/processes/tick-publication.ts +2 -0
  180. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  181. package/packages/core/src/scenarios/harness.ts +0 -5
  182. package/packages/core/src/store/account-redaction.ts +1 -0
  183. package/packages/core/src/store/adapter.ts +52 -1
  184. package/packages/core/src/store/agent-context.ts +432 -0
  185. package/packages/core/src/store/build-feed.ts +291 -0
  186. package/packages/core/src/store/build-scope.ts +19 -1
  187. package/packages/core/src/store/contract.ts +911 -14
  188. package/packages/core/src/store/digest.ts +19 -6
  189. package/packages/core/src/store/histogram.ts +113 -0
  190. package/packages/core/src/store/local/schema.ts +62 -0
  191. package/packages/core/src/store/local/store.ts +628 -22
  192. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  193. package/packages/core/src/store/memory.ts +461 -69
  194. package/packages/core/src/store/open-builds.ts +19 -0
  195. package/packages/core/src/store/phase-session.ts +32 -4
  196. package/packages/core/src/store/reduced-reads.ts +14 -4
  197. package/packages/core/src/store/reducer-value-shapes.json +7027 -5751
  198. package/packages/core/src/store/reducer-values.ts +6 -1
  199. package/packages/core/src/store/remote/client.ts +208 -2
  200. package/packages/core/src/store/remote/compatibility.ts +1 -1
  201. package/packages/core/src/store/remote/index.ts +33 -0
  202. package/packages/core/src/store/remote/protocol.ts +69 -0
  203. package/packages/core/src/store/remote/released-clients.json +22 -0
  204. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  205. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  206. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  207. package/packages/core/src/store/retention.ts +23 -1
  208. package/packages/core/src/store/rollups.ts +337 -0
  209. package/packages/core/src/store/session-handle.ts +20 -2
  210. package/packages/core/src/store/snapshots.ts +10 -0
  211. package/packages/core/src/store/types.ts +108 -9
  212. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  213. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  214. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  215. package/packages/core/src/testing/index.ts +27 -0
  216. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  217. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  218. package/packages/core/src/web/analytics-source.ts +303 -0
  219. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  220. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  221. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  222. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  223. package/packages/core/src/web/assets/app.css +1 -0
  224. package/packages/core/src/web/assets/app.js +9 -0
  225. package/packages/core/src/web/assets/manifest.json +31 -0
  226. package/packages/core/src/web/assets/theme.js +1 -0
  227. package/packages/core/src/web/bounded.ts +31 -0
  228. package/packages/core/src/web/http.ts +315 -0
  229. package/packages/core/src/web/hub.ts +160 -0
  230. package/packages/core/src/web/options.ts +38 -0
  231. package/packages/core/src/web/overview-source.ts +322 -0
  232. package/packages/core/src/web/page.ts +56 -0
  233. package/packages/core/src/web/protocol.ts +151 -0
  234. package/packages/core/src/web/read-only.ts +23 -0
  235. package/packages/core/src/web/repository-source.ts +39 -0
  236. package/packages/core/src/web/server.ts +97 -0
  237. package/skills/code-review/SKILL.md +10 -2
  238. package/skills/guide/SKILL.md +376 -54
  239. package/skills/guide/references/accounts.md +2 -1
  240. package/skills/guide/references/integration-tree.md +2 -2
  241. package/skills/guide/references/operator-api.md +134 -6
  242. package/skills/guide/references/optimization-nodes.md +69 -11
  243. package/skills/guide/references/plugin-authoring.md +37 -1
  244. package/skills/guide/references/remote-store-protocol.md +94 -13
  245. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  246. package/skills/guide/references/restacking.md +20 -4
  247. package/skills/guide/references/setup.md +14 -2
  248. package/skills/guide/references/ticket-dependencies.md +10 -3
  249. package/skills/implement/SKILL.md +23 -4
  250. package/skills/operate/SKILL.md +134 -32
  251. package/skills/plan/SKILL.md +10 -4
  252. package/skills/plan-review/SKILL.md +9 -2
  253. package/skills/spec/SKILL.md +34 -8
  254. package/skills/tickets/SKILL.md +51 -5
  255. package/templates/hosted-service/package.json +2 -2
@@ -27,6 +27,8 @@ import {
27
27
 
28
28
  import { preserveWorkspaceBeforeRelease, supersedeRestorationHeads } from './workspace-preservation'
29
29
  import { WorkspaceCleanupRequired } from '../ports/types'
30
+ import type { AgentContextCapture } from './agent-context'
31
+ import type { AgentContextDiagnostic } from '../store/agent-context'
30
32
  import type { OpenHarvestExecution } from './harvest-execution-state'
31
33
  import { ArtifactMetaUnsupportedError } from '../store/artifact-meta'
32
34
  import {
@@ -124,6 +126,7 @@ import {
124
126
  } from '../kernel/dispatch-capacity'
125
127
  import { attemptCreationKey } from '../kernel/attempt-creation-key'
126
128
  import {
129
+ ExecutionFactsMissingError,
127
130
  exhaustedStopDue,
128
131
  optimizationElapsedHours,
129
132
  proposalWithdrawalDue,
@@ -232,12 +235,13 @@ import { hasBuildTrailer } from '../kernel/build-identity'
232
235
  import { BuildDigestCapabilityError, digestNodeTargets, digestOptimization } from '../store/digest'
233
236
  import { readBuildDigests, readForgeHealth } from '../store/reduced-reads'
234
237
  import { enforceOptimizationStop } from './optimization-stop'
238
+ import { recordOptimizationActivity } from './optimization-activity'
235
239
  import { reconcileMergedAttempts } from './optimization-merges'
236
240
  import { readBuildSelector, readBuildFacts, type CurrentBuildFacts } from '../store/reduced-reads'
237
241
  import { ensureExecutionProgress } from './execution-no-progress'
238
242
  import { ticketIdentity } from '../ports/tickets/identity'
239
243
  import { holdsState, ticketLifecycle } from '../ports/tickets/lifecycle'
240
- import { ticketPriority, urgentFirst } from '../ports/tickets/priority'
244
+ import { ticketPriority, urgentFirstBy } from '../ports/tickets/priority'
241
245
  import { ensureDispatchBudget } from './dispatch-failure-budget'
242
246
  import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
243
247
  /**
@@ -279,7 +283,7 @@ import type { TicketSourceDegradation } from '../kernel/ticket-source-health'
279
283
  * execution lease before launch; the child renews that same-holder lease.
280
284
  */
281
285
  import { createHash } from 'node:crypto'
282
- import type { Config } from '../config/schema'
286
+ import { orchestratorEnabled, type Config, type OrchestratorHost } from '../config/schema'
283
287
  import { DISPATCHER, KERNEL, agentActor } from '../events/envelope'
284
288
  import { isRemoteWorkspace } from '../events/workspace-remote'
285
289
  import type { AbEvent, EventWrite } from '../events/catalog'
@@ -326,6 +330,7 @@ import type {
326
330
  import {
327
331
  isForgeMergeQueueRejection,
328
332
  NoCommitsBetweenBranchesError,
333
+ TicketClaimBlockedError,
329
334
  TicketSourceRateLimitError,
330
335
  } from '../ports/types'
331
336
  import { issueLinksForForge } from '../kernel/issue-keywords'
@@ -680,6 +685,9 @@ export interface TickReport {
680
685
  sandboxIdleStops: number
681
686
  /** Contained idle-settlement failures this tick; retried next tick. */
682
687
  sandboxSettleFailures: number
688
+ /** Agent-context stage (`processes/agent-context.ts`): typed problems this
689
+ * tick found capturing the base branch's skills and agent instructions. */
690
+ agentContextDiagnostics: AgentContextDiagnostic[]
683
691
  }
684
692
 
685
693
  export function emptyTickReport(): TickReport {
@@ -718,6 +726,7 @@ export function emptyTickReport(): TickReport {
718
726
  harvestFailed: 0,
719
727
  sandboxIdleStops: 0,
720
728
  sandboxSettleFailures: 0,
729
+ agentContextDiagnostics: [],
721
730
  }
722
731
  }
723
732
 
@@ -880,6 +889,9 @@ export interface TickOpts {
880
889
  export type LaunchRunnerResult = 'scheduled' | 'already-active'
881
890
 
882
891
  export interface DispatcherDeps {
892
+ /** Where `[orchestrator].enabled` is resolved for idle settlement
893
+ * (`orchestratorEnabled`). Default `local`. */
894
+ orchestratorHost?: OrchestratorHost
883
895
  /** Whether this process currently holds repository authority (SPEC §12).
884
896
  * Synchronous and without I/O. Absent means always true. When false, the
885
897
  * tick starts no further unit of work, and its durable new-work writes are
@@ -952,6 +964,9 @@ export interface DispatcherDeps {
952
964
  * harvest settlement stage skips them: their completion chain owns the
953
965
  * durable facts. */
954
966
  activeHarvestExecutions?: () => ReadonlySet<string>
967
+ /** The agent-context stage, run last on every tick that still has budget
968
+ * and repository authority. Absent: the tick captures nothing. */
969
+ agentContext?: Pick<AgentContextCapture, 'run'>
955
970
  ids: IdSource
956
971
  clock: Clock
957
972
  opts?: DispatcherOpts
@@ -1624,9 +1639,32 @@ export class Dispatcher {
1624
1639
  // launch. Pending control commands still launch the runner so the kernel
1625
1640
  // can settle them under the repository lease.
1626
1641
  await this.triggerHarvest()
1642
+ await this.captureAgentContext(report, opts)
1627
1643
  return report
1628
1644
  }
1629
1645
 
1646
+ /** Agent-context stage: contained, so a capture failure never fails the
1647
+ * tick; only an authority lapse escapes. */
1648
+ private async captureAgentContext(report: TickReport, opts: TickOpts): Promise<void> {
1649
+ const stage = this.deps.agentContext
1650
+ if (stage === undefined || this.outOfBudget(opts)) return
1651
+ try {
1652
+ report.agentContextDiagnostics.push(
1653
+ ...(await stage.run({
1654
+ baseBranch: this.deps.config.baseBranch,
1655
+ ...(opts.deadlineAt !== undefined ? { deadlineAt: opts.deadlineAt } : {}),
1656
+ holdsAuthority: () => this.deps.holdsRepoAuthority?.() !== false,
1657
+ })),
1658
+ )
1659
+ } catch (error) {
1660
+ rethrowAuthorityLapse(error)
1661
+ report.agentContextDiagnostics.push({
1662
+ kind: 'capture-failed',
1663
+ message: error instanceof Error ? error.message : String(error),
1664
+ })
1665
+ }
1666
+ }
1667
+
1630
1668
  /** The repository-wide quiescence flag, from durable state. Guarded like
1631
1669
  * `triggerHarvest`: `getRepoEvents` throws for a repository row no tick has
1632
1670
  * created yet, and an unpaused repository is the correct reading of one that
@@ -2689,17 +2727,21 @@ export class Dispatcher {
2689
2727
  * provider no longer matches the wired provider is likewise dispositioned
2690
2728
  * once idle: its trail is closed with an unconfirmed release fact (AUT-377)
2691
2729
  * — never a stop, since this dispatcher cannot reach a provider it is not
2692
- * wired to — and if the old provider returns, the next operator ensure()
2730
+ * wired to — and if the old provider returns, the next sandbox.open
2693
2731
  * re-provisions and re-brackets the environment, so the disposition is
2694
- * reachable again. The stage is a no-op unless `[orchestrator]` is
2695
- * enabled and the wired provider hosts the capability; `unsupported`
2732
+ * reachable again. The stage is a no-op unless `[orchestrator]` resolves
2733
+ * enabled for this dispatcher's host (`orchestratorEnabled` with
2734
+ * `orchestratorHost`) and the wired provider hosts the capability; `unsupported`
2696
2735
  * providers (local worktrees) are skipped silently. */
2697
2736
  private async settleOrchestratorSandboxes(
2698
2737
  report: TickReport,
2699
2738
  opts: TickOpts = {},
2700
2739
  ): Promise<void> {
2701
2740
  const config = this.deps.config
2702
- if (config.orchestrator?.enabled !== true) return
2741
+ // Test configs may omit the table entirely; production configs always
2742
+ // carry it after parsing.
2743
+ if (config.orchestrator === undefined) return
2744
+ if (!orchestratorEnabled(config, this.deps.orchestratorHost ?? 'local')) return
2703
2745
  const capability = this.deps.workspaces.orchestratorSandbox
2704
2746
  if (capability === undefined) return
2705
2747
  const providerName = this.deps.workspaces.name
@@ -2741,7 +2783,7 @@ export class Dispatcher {
2741
2783
  // every tick forever. Close the trail with an unconfirmed release —
2742
2784
  // never a stop: nothing was stopped through a provider this
2743
2785
  // dispatcher no longer owns. If the provider returns, the next
2744
- // operator ensure() re-provisions and re-brackets the environment.
2786
+ // sandbox.open re-provisions and re-brackets the environment.
2745
2787
  await this.store.appendRepo(this.deps.repo, {
2746
2788
  actor: DISPATCHER,
2747
2789
  type: 'orchestrator.sandbox.released',
@@ -3221,6 +3263,21 @@ export class Dispatcher {
3221
3263
  // node's enforcer and completion see them as they are.
3222
3264
  if (await reconcileMergedAttempts(deps, record, state, builds))
3223
3265
  state = (await this.store.buildFacts(record.slug)).state
3266
+ // The active-hours clock: attempt runs since the last pass, and a
3267
+ // stopped node's one settlement, ahead of every early return.
3268
+ try {
3269
+ if (await recordOptimizationActivity(deps, record, state, builds))
3270
+ state = (await this.store.buildFacts(record.slug)).state
3271
+ } catch (error) {
3272
+ if (
3273
+ !(error instanceof BuildDigestCapabilityError) &&
3274
+ !(error instanceof ExecutionFactsMissingError)
3275
+ )
3276
+ throw error
3277
+ report.janitorDiagnostics.push(
3278
+ `build ${record.slug}: optimization activity not recorded — ${error.message}`,
3279
+ )
3280
+ }
3224
3281
  if (await enforceOptimizationStop(deps, record, state, builds))
3225
3282
  state = (await this.store.buildFacts(record.slug)).state
3226
3283
  }
@@ -6803,9 +6860,29 @@ export class Dispatcher {
6803
6860
  facts.replacedHeads,
6804
6861
  )
6805
6862
  const local = this.deps.forge.name === 'local-git'
6863
+ // A leaf's first provision never adopts a pre-existing branch (#1261).
6864
+ // A node is exempt: the kernel opens its branch before any provision and
6865
+ // children merge into it, so that branch is the node's own work.
6866
+ // `owner` is unique to this build (an earlier same-slug build in another
6867
+ // store has another creation time) and stable across its retries.
6868
+ const fresh =
6869
+ facts.state.kind !== 'node' &&
6870
+ facts.workspaceGenerations === 0 &&
6871
+ input.revision === undefined &&
6872
+ input.generation === undefined &&
6873
+ input.baseBranch !== input.branch &&
6874
+ facts.created !== undefined
6875
+ ? {
6876
+ owner: createHash('sha256')
6877
+ .update(`${slug}\0${facts.created.ts}`)
6878
+ .digest('hex')
6879
+ .slice(0, 32),
6880
+ }
6881
+ : undefined
6806
6882
  try {
6807
6883
  const handle = await this.deps.workspaces.provision({
6808
6884
  ...input,
6885
+ ...(fresh !== undefined ? { fresh } : {}),
6809
6886
  restoration,
6810
6887
  ...(facts.replacedHeads.length ? { restorationReplaced: facts.replacedHeads } : {}),
6811
6888
  // Store reads happen only while provisioning a build whose receipt
@@ -8557,13 +8634,16 @@ export class Dispatcher {
8557
8634
  .flatMap(({ record }) => (record.ticket ? [record.ticket] : []))
8558
8635
  const adjust = { settled: this.parkedSettled, denied: this.slotWaiters }
8559
8636
  let capacity = intakeCapacity(projection, adjust)
8560
- let urgentCapacity = tickets.priority ? intakeCapacity(projection, adjust, 'urgent') : capacity
8637
+ let urgentCapacity = intakeCapacity(projection, adjust, 'urgent')
8561
8638
  let urgentWaiting = 0
8639
+ // Each ready ticket's claim tier: an optimization attempt claims at its
8640
+ // node's current build priority, any other ticket at its own priority
8641
+ // when the source stores one. Filled once the claimable set is known.
8642
+ let attemptTiers = new Map<string, TicketPriority>()
8643
+ const tierOf = (ticket: Ticket): TicketPriority =>
8644
+ attemptTiers.get(ticket.ref.id) ?? (tickets.priority ? ticketPriority(ticket) : 'normal')
8562
8645
  const urgentClaim = (ticket: Ticket) =>
8563
- !targeted &&
8564
- !!tickets.priority &&
8565
- ticket.kind !== 'node' &&
8566
- ticketPriority(ticket) === 'urgent'
8646
+ !targeted && ticket.kind !== 'node' && tierOf(ticket) === 'urgent'
8567
8647
  // A targeted ticket's tier is its request's, never its ticket's priority.
8568
8648
  const startTier = (ticket: Ticket): TicketStartPriority =>
8569
8649
  targeted?.requests.get(ticket.ref.id)?.priority ?? 'manual'
@@ -8607,8 +8687,9 @@ export class Dispatcher {
8607
8687
  for (const [index, ticket] of [...conflicts.tickets].entries())
8608
8688
  settle(ticket, { outcome: 'invalid', detail: conflicts.diagnostics[index]! })
8609
8689
  const claimable = eligible.filter((ticket) => !conflicts.tickets.has(ticket))
8690
+ if (!targeted) attemptTiers = await this.attemptClaimTiers(claimable)
8610
8691
  // A targeted pass keeps its tier-then-request order.
8611
- const ready = !targeted && this.deps.tickets.priority ? urgentFirst(claimable) : claimable
8692
+ const ready = targeted ? claimable : urgentFirstBy(claimable, tierOf)
8612
8693
  report.invalidTickets += listing.diagnostics.length + conflicts.diagnostics.length
8613
8694
  report.ticketDiagnostics.push(...listing.diagnostics, ...conflicts.diagnostics)
8614
8695
  if (!targeted && normalPaused)
@@ -8658,13 +8739,11 @@ export class Dispatcher {
8658
8739
  paused ||
8659
8740
  (!targeted &&
8660
8741
  normalPaused &&
8661
- !ready.some(
8662
- (ticket) => ticketPriority(ticket) === 'urgent' && !withheld.has(ticket.ref.id),
8663
- )) ||
8742
+ !ready.some((ticket) => tierOf(ticket) === 'urgent' && !withheld.has(ticket.ref.id))) ||
8664
8743
  (noBudget &&
8665
8744
  !ready.some(
8666
8745
  (ticket) =>
8667
- (targeted || !normalPaused || ticketPriority(ticket) === 'urgent') &&
8746
+ (targeted || !normalPaused || tierOf(ticket) === 'urgent') &&
8668
8747
  (ticket.kind === 'node' ||
8669
8748
  (ticket.target !== undefined && (ticket.blockedBy?.length ?? 0) > 0)),
8670
8749
  ))
@@ -8873,7 +8952,7 @@ export class Dispatcher {
8873
8952
  claimLoopCompleted = false
8874
8953
  break
8875
8954
  }
8876
- if (!targeted && normalPaused && ticketPriority(ticket) !== 'urgent') continue
8955
+ if (!targeted && normalPaused && tierOf(ticket) !== 'urgent') continue
8877
8956
  const urgent = urgentClaim(ticket)
8878
8957
  const budget = targeted
8879
8958
  ? targeted.budgets[startTier(ticket)]
@@ -8953,7 +9032,21 @@ export class Dispatcher {
8953
9032
  let authoredSession: string | undefined
8954
9033
  let createdSeed: Parameters<Dispatcher['buildCreatedPayload']>[2]
8955
9034
  try {
8956
- if (!(await tickets.claim(ticket.ref.id))) {
9035
+ let claimed: boolean
9036
+ try {
9037
+ claimed = await tickets.claim(ticket.ref.id, { blockedBy: ticket.blockedBy ?? [] })
9038
+ } catch (error) {
9039
+ if (!(error instanceof TicketClaimBlockedError)) throw error
9040
+ // A blocker recorded after the dependency check (GitHub's summary
9041
+ // lags its edges): still ready, so the next scan sees the blocker.
9042
+ const detail = `ticket ${ticket.ref.id}: blockers ${error.blockers.join(', ')} were recorded after the dependency check; waiting for the next scan`
9043
+ await this.preparationResolved(attempt, 'lost-claim', error.message)
9044
+ report.dependencyBlocked += 1
9045
+ report.dependencyDiagnostics.push(detail)
9046
+ settle(ticket, { outcome: 'blocked', detail })
9047
+ continue
9048
+ }
9049
+ if (!claimed) {
8957
9050
  await this.preparationResolved(attempt, 'lost-claim')
8958
9051
  settle(ticket, {
8959
9052
  outcome: 'claim-refused',
@@ -9070,7 +9163,9 @@ export class Dispatcher {
9070
9163
  // `manual` is admission-only; an explicit urgent start is urgent.
9071
9164
  ...(startTier(ticket) === 'urgent' && targeted
9072
9165
  ? { priority: 'urgent' as const }
9073
- : this.claimedPriority(ticket)),
9166
+ : tierOf(ticket) === 'urgent'
9167
+ ? { priority: 'urgent' as const }
9168
+ : {}),
9074
9169
  }
9075
9170
  // `build.created` rides with the record so the pinned assets and the
9076
9171
  // record exist together or not at all.
@@ -9165,6 +9260,88 @@ export class Dispatcher {
9165
9260
  }
9166
9261
  }
9167
9262
 
9263
+ /** Builds whose ticket resolves to `target` under the repository's
9264
+ * ticket migrations, newest first. A pure scan of the tick's listing. */
9265
+ private targetBuilds(
9266
+ target: string,
9267
+ source: string,
9268
+ all: readonly { record: BuildRecord; digest: BuildDigest }[],
9269
+ ): { record: BuildRecord; digest: BuildDigest }[] {
9270
+ const migrations = this.store.repositoryFacts().ticketMigrations
9271
+ return all
9272
+ .filter(({ record }) => {
9273
+ if (!record.ticket) return false
9274
+ try {
9275
+ return resolveTicketRef(migrations, record.ticket, source, record.slug).id === target
9276
+ } catch {
9277
+ return false
9278
+ }
9279
+ })
9280
+ .sort(
9281
+ (a, b) =>
9282
+ b.record.createdAt.localeCompare(a.record.createdAt) ||
9283
+ b.record.slug.localeCompare(a.record.slug),
9284
+ )
9285
+ }
9286
+
9287
+ /** The ticket identity the attempt claim gate and claim tier match
9288
+ * attempts under: the configured source after recorded migrations. */
9289
+ private attemptIdentity(): (ref: TicketRef) => string {
9290
+ const migrations = this.store.repositoryFacts().ticketMigrations
9291
+ return (ref) => {
9292
+ try {
9293
+ const resolved = resolveTicketRef(migrations, ref, this.deps.tickets.name)
9294
+ return `${resolved.source}\u0000${resolved.id}`
9295
+ } catch {
9296
+ return `${ref.source}\u0000${ref.id}`
9297
+ }
9298
+ }
9299
+ }
9300
+
9301
+ /**
9302
+ * The claim tier of each ready optimization attempt: its node's current
9303
+ * build priority (`ab priority <node>`), decided at claim, whatever the
9304
+ * ticket says or whether its source stores priority. Nothing is reserved;
9305
+ * other tickets keep their own tier. Costs one served node state per open,
9306
+ * unstopped optimization node a ready ticket targets, and none otherwise.
9307
+ */
9308
+ private async attemptClaimTiers(
9309
+ tickets: readonly Ticket[],
9310
+ ): Promise<Map<string, TicketPriority>> {
9311
+ const tiers = new Map<string, TicketPriority>()
9312
+ const candidates = tickets.filter(
9313
+ (ticket) => ticket.target !== undefined && ticket.kind !== 'node',
9314
+ )
9315
+ if (candidates.length === 0) return tiers
9316
+ const all = await this.repoBuildDigests()
9317
+ const nodes = new Map<string, BuildState>()
9318
+ const key = this.attemptIdentity()
9319
+ for (const ticket of candidates) {
9320
+ const [latest, tied] = this.targetBuilds(ticket.target!, ticket.ref.source, all)
9321
+ if (latest === undefined || tied?.record.createdAt === latest.record.createdAt) continue
9322
+ const { record, digest } = latest
9323
+ if (digest.terminal !== undefined || !digest.nodeOpened) continue
9324
+ let signal: ReturnType<typeof digestOptimization>
9325
+ try {
9326
+ signal = digestOptimization(digest)
9327
+ } catch (error) {
9328
+ // An older store's digest: the ticket keeps its own tier.
9329
+ if (error instanceof BuildDigestCapabilityError) continue
9330
+ throw error
9331
+ }
9332
+ if (!signal || signal.stopped) continue
9333
+ let state = nodes.get(record.slug)
9334
+ if (state === undefined) {
9335
+ state = (await this.store.buildFacts(record.slug)).state
9336
+ nodes.set(record.slug, state)
9337
+ }
9338
+ if (state.optimization === undefined || state.optimization.stopped !== undefined) continue
9339
+ if (optimizationAttempt(state.optimization, ticket.ref, key) !== undefined)
9340
+ tiers.set(ticket.ref.id, buildPriority(state))
9341
+ }
9342
+ return tiers
9343
+ }
9344
+
9168
9345
  /**
9169
9346
  * Walk unresolved branches in provider order. Listing facts and dependency
9170
9347
  * reads share a tick-local cache; traversal visits are local to this root.
@@ -9189,29 +9366,7 @@ export class Dispatcher {
9189
9366
  if (ticket.target === undefined) return undefined
9190
9367
  const migrations = this.store.repositoryFacts().ticketMigrations
9191
9368
  const all = await this.repoBuildDigests()
9192
- const entries = all
9193
- .filter(
9194
- ({ record }) =>
9195
- record.ticket &&
9196
- (() => {
9197
- try {
9198
- const ref = resolveTicketRef(
9199
- migrations,
9200
- record.ticket,
9201
- ticket.ref.source,
9202
- record.slug,
9203
- )
9204
- return ref.id === ticket.target
9205
- } catch {
9206
- return false
9207
- }
9208
- })(),
9209
- )
9210
- .sort(
9211
- (a, b) =>
9212
- b.record.createdAt.localeCompare(a.record.createdAt) ||
9213
- b.record.slug.localeCompare(a.record.slug),
9214
- )
9369
+ const entries = this.targetBuilds(ticket.target, ticket.ref.source, all)
9215
9370
  const latest = entries[0]
9216
9371
  if (latest && entries[1]?.record.createdAt === latest.record.createdAt)
9217
9372
  return `target node ${ticket.target} has ambiguous build generations at ${latest.record.createdAt}`
@@ -9231,14 +9386,7 @@ export class Dispatcher {
9231
9386
  if (state.pendingCommands.some((c) => c.command === 'abort'))
9232
9387
  return `target node ${ticket.target} is closing`
9233
9388
  if (state.optimization?.stopped !== undefined) {
9234
- const key = (ref: TicketRef) => {
9235
- try {
9236
- const resolved = resolveTicketRef(migrations, ref, this.deps.tickets.name)
9237
- return `${resolved.source}\u0000${resolved.id}`
9238
- } catch {
9239
- return `${ref.source}\u0000${ref.id}`
9240
- }
9241
- }
9389
+ const key = this.attemptIdentity()
9242
9390
  const wanted = key(ticket.ref)
9243
9391
  if (
9244
9392
  optimizationAttempt(state.optimization, ticket.ref, key) !== undefined ||
@@ -10703,17 +10851,25 @@ export class Dispatcher {
10703
10851
  return verdict
10704
10852
  }
10705
10853
 
10706
- /** Valid bounded base, deduped with -2/-3/… against this store's builds and,
10854
+ /** Valid bounded base, deduped with -2/-3/… against this store's builds,
10707
10855
  * when the forge can answer, against build branches already on the remote
10708
- * (another store's builds, AUT-1106). Claim-time only; a forge failure fails
10709
- * the naming stage and the claim is handed back. */
10856
+ * (another store's builds, AUT-1106), and, when the workspace provider
10857
+ * creates branches in a local checkout, against local branches there: a
10858
+ * stale local `ab/<slug>` must never become a new build's branch (#1261).
10859
+ * Claim-time only; a probe failure fails the naming stage and the claim is
10860
+ * handed back. */
10710
10861
  private async uniqueSlug(base: string, prefix: 'ab' | 'ab-node'): Promise<string> {
10711
10862
  const forge = this.deps.forge
10712
10863
  const exists = forge.remoteBranchExists
10864
+ const workspaces = this.deps.workspaces
10865
+ const local = workspaces.localBranchExists
10866
+ const checkout = this.deps.checkout ?? this.deps.repo
10713
10867
  for (let n = 1; n <= MAX_SLUG_CANDIDATES; n += 1) {
10714
10868
  const slug = n === 1 ? base : `${base}-${n}`
10715
10869
  if ((await this.store.getBuild(slug)) !== null) continue
10716
- if (exists !== undefined && (await exists.call(forge, `${prefix}/${slug}`))) continue
10870
+ const branch = `${prefix}/${slug}`
10871
+ if (exists !== undefined && (await exists.call(forge, branch))) continue
10872
+ if (local !== undefined && (await local.call(workspaces, checkout, branch))) continue
10717
10873
  return slug
10718
10874
  }
10719
10875
  throw new Error(`no free slug for ${base} after ${MAX_SLUG_CANDIDATES} candidates`)
@@ -12,6 +12,7 @@ export const executionProgress = {
12
12
  'execution.relaunch-requested': 'bookkeeping',
13
13
  'execution.drain-authorized': 'bookkeeping',
14
14
  'execution.drain-settled': 'bookkeeping',
15
+ 'execution.accounted': 'bookkeeping',
15
16
  'build.compatibility-deferred': 'bookkeeping',
16
17
  'build.janitor-attempt-failed': 'bookkeeping',
17
18
  'build.janitor-failing': 'bookkeeping',
@@ -36,6 +37,8 @@ export const executionProgress = {
36
37
  'target.rewritten': 'bookkeeping',
37
38
  'target.rewrite-cleared': 'bookkeeping',
38
39
  'target.moved': 'bookkeeping',
40
+ 'target.rewrite-reprovision-prepared': 'bookkeeping',
41
+ 'target.rewrite-recovered': 'progress',
39
42
  'head.paths-recorded': 'bookkeeping',
40
43
  'restack.prepared': 'progress',
41
44
  'restack.replayed': 'progress',
@@ -86,6 +89,7 @@ export const executionProgress = {
86
89
  'optimization.proposal-deferred': 'bookkeeping',
87
90
  'optimization.proposal-withdrawn': 'bookkeeping',
88
91
  'optimization.attempts-proposed': 'bookkeeping',
92
+ 'optimization.activity-recorded': 'bookkeeping',
89
93
  'attempt.measurement-requested': 'bookkeeping',
90
94
  'attempt.sampled': 'progress',
91
95
  'attempt.measured': 'progress',
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The dispatcher's optimization activity pass (SPEC §13.1.1): copy attempt
3
+ * execution facts into the node's active-hours clock, and settle a stopped
4
+ * node's clock once.
5
+ *
6
+ * An unchanged tick reads nothing: which builds have new facts is decided
7
+ * from the node's reduced state and the build digests the tick already
8
+ * holds. A build whose digest `executionFacts` grew costs one served
9
+ * `executionIntervals` value, which holds only unacknowledged execution
10
+ * facts. A stop costs one such value per relevant build, once. No path ever
11
+ * reads events.
12
+ */
13
+ import { DISPATCHER } from '../events/envelope'
14
+ import type { EventWrite } from '../events/catalog'
15
+ import {
16
+ chunkActivityBatch,
17
+ optimizationActivityBatch,
18
+ type ActivityBuildInput,
19
+ } from '../kernel/optimization'
20
+ import type { BuildState } from '../kernel/reducer'
21
+ import { BuildDigestCapabilityError } from '../store/digest'
22
+ import { readExecutionIntervals } from '../store/reduced-reads'
23
+ import type { BuildDigest, BuildRecord } from '../store/types'
24
+ import { newestAttemptBuild, type OptimizationStopDeps } from './optimization-stop'
25
+
26
+ /** Whether the node keeps an active-hours clock the pass still advances. */
27
+ function activityApplies(state: BuildState): boolean {
28
+ const optimization = state.optimization
29
+ return (
30
+ state.kind === 'node' &&
31
+ state.nodeOpened !== undefined &&
32
+ optimization !== undefined &&
33
+ optimization.clock.settled !== true &&
34
+ state.status !== 'done' &&
35
+ state.status !== 'aborted' &&
36
+ state.prState !== 'merged' &&
37
+ state.prState !== 'closed'
38
+ )
39
+ }
40
+
41
+ /**
42
+ * One tick of the activity pass for a node. `builds` is the repository's
43
+ * unfiltered build listing. Returns whether the node's log was written; the
44
+ * caller rereads its facts. Throws `BuildDigestCapabilityError` when an older
45
+ * store's digest lacks `executionFacts`.
46
+ */
47
+ export async function recordOptimizationActivity(
48
+ deps: Pick<OptimizationStopDeps, 'store' | 'migrations' | 'ticketSource'>,
49
+ record: BuildRecord,
50
+ state: BuildState,
51
+ builds: readonly { record: BuildRecord; digest: BuildDigest }[],
52
+ ): Promise<boolean> {
53
+ if (!activityApplies(state)) return false
54
+ const optimization = state.optimization!
55
+ const clock = optimization.clock
56
+ // A stopped node settles; reading after the state that holds the stop, so
57
+ // every fact at or before the stop is in what the reads return.
58
+ const settling = clock.stoppedAt !== undefined
59
+ const newest = new Set<string>()
60
+ for (const attempt of optimization.inFlight) {
61
+ const entry = newestAttemptBuild(deps, record.slug, attempt, builds)
62
+ if (entry !== undefined) newest.add(entry.record.slug)
63
+ }
64
+ const relevant = [...new Set([...Object.keys(clock.builds), ...newest])].sort()
65
+ // A clock the dispatcher has not started gets its first batch even with
66
+ // nothing to account, so every later settlement is tracked.
67
+ if (relevant.length === 0 && !settling && clock.watermark !== undefined) return false
68
+ const listing = new Map(builds.map((entry) => [entry.record.slug, entry.digest]))
69
+ const inputs: ActivityBuildInput[] = []
70
+ for (const build of relevant) {
71
+ const digest = listing.get(build)
72
+ const inFlightNewest = newest.has(build)
73
+ if (digest === undefined) {
74
+ inputs.push({ build, inFlightNewest, missing: true })
75
+ continue
76
+ }
77
+ if (digest.executionFacts === undefined)
78
+ throw new BuildDigestCapabilityError(build, 'execution')
79
+ const input: ActivityBuildInput = {
80
+ build,
81
+ inFlightNewest,
82
+ digestCount: digest.executionFacts,
83
+ digestOpen: digest.executionOpen === true,
84
+ }
85
+ if (settling || digest.executionFacts > (clock.builds[build] ?? 0))
86
+ input.value = (await readExecutionIntervals(deps.store, build)).value
87
+ inputs.push(input)
88
+ }
89
+ const batch = optimizationActivityBatch(clock, inputs, optimization.openedAt)
90
+ if (batch === undefined) return false
91
+ let expected = state.lastSeq
92
+ for (const payload of chunkActivityBatch(batch)) {
93
+ const written = await deps.store.appendIfCurrent(record.slug, expected, {
94
+ actor: DISPATCHER,
95
+ type: 'optimization.activity-recorded',
96
+ payload,
97
+ } satisfies EventWrite<'optimization.activity-recorded'>)
98
+ // A concurrent writer moved the node: the next tick starts over from
99
+ // what the node then holds, and skips what it already accounted by `n`.
100
+ if (written === null) return expected !== state.lastSeq
101
+ expected = written.seq
102
+ }
103
+ // Advisory and after the node record only: a build's value drops facts
104
+ // the node has durably accounted. A refusal leaves them for a later read.
105
+ const values = new Map(inputs.map((input) => [input.build, input.value]))
106
+ for (const [build, count] of Object.entries(batch.accounted)) {
107
+ if (count < 1 || count <= (values.get(build)?.acknowledged ?? 0)) continue
108
+ try {
109
+ await deps.store.append(build, {
110
+ actor: DISPATCHER,
111
+ type: 'execution.accounted',
112
+ payload: { count },
113
+ } satisfies EventWrite<'execution.accounted'>)
114
+ } catch {
115
+ // A terminal or refused build keeps its facts; nobody reads them once
116
+ // the node releases it.
117
+ }
118
+ }
119
+ return true
120
+ }
@@ -20,6 +20,7 @@ export const POLICY_PHASE_FAILURE_RESET_SCOPES = {
20
20
  'non-retryable-phase-failure': 'matching-round',
21
21
  'wait-unresolvable': 'none',
22
22
  'measurement-failed': 'none',
23
+ 'target-rewritten': 'none',
23
24
  } as const satisfies Record<PolicyEscalationCause, PhaseFailureBudgetResetScope>
24
25
 
25
26
  export interface PhaseFailureResetEscalation {