@defrex/autobuild 1.6.0 → 1.8.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 (165) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +423 -57
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +44 -3
  5. package/docs/architecture.md +124 -29
  6. package/docs/cli.md +1 -0
  7. package/docs/configuration-overview.md +11 -1
  8. package/docs/configuration.md +334 -14
  9. package/docs/dispatcher.md +1 -1
  10. package/docs/forges.md +1 -0
  11. package/docs/integration-overview.md +2 -2
  12. package/docs/integration-tree.md +7 -4
  13. package/docs/merge-policy.md +78 -6
  14. package/docs/migration-1.0.md +4 -2
  15. package/docs/operating.md +3 -2
  16. package/docs/operator-api.md +45 -13
  17. package/docs/operator-surfaces.md +16 -3
  18. package/docs/plugin-authoring.md +45 -7
  19. package/docs/remote-store-protocol.md +28 -7
  20. package/docs/restacking.md +35 -11
  21. package/docs/ticket-dependencies.md +9 -4
  22. package/docs/ticket-sources.md +34 -6
  23. package/docs/tickets.md +7 -1
  24. package/docs/troubleshooting.md +1 -1
  25. package/docs/workspaces.md +1 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary-direct.ts +1 -0
  29. package/packages/core/src/cli/build-control.ts +65 -7
  30. package/packages/core/src/cli/context.ts +55 -14
  31. package/packages/core/src/cli/dashboard/actions.ts +13 -4
  32. package/packages/core/src/cli/dashboard/landing-display.ts +32 -8
  33. package/packages/core/src/cli/dashboard/model.ts +61 -8
  34. package/packages/core/src/cli/dashboard/render.ts +28 -3
  35. package/packages/core/src/cli/dashboard/tree.ts +9 -1
  36. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  37. package/packages/core/src/cli/dispatch-preflight.ts +1 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  39. package/packages/core/src/cli/dispatch.ts +9 -3
  40. package/packages/core/src/cli/help.ts +80 -11
  41. package/packages/core/src/cli/init-validation.ts +14 -1
  42. package/packages/core/src/cli/landings.ts +1 -1
  43. package/packages/core/src/cli/main.ts +60 -9
  44. package/packages/core/src/cli/publication-settlement.ts +10 -0
  45. package/packages/core/src/cli/repository-status.ts +37 -2
  46. package/packages/core/src/cli/status.ts +186 -12
  47. package/packages/core/src/cli/terminals.ts +197 -4
  48. package/packages/core/src/cli/ticket.ts +22 -4
  49. package/packages/core/src/cli/wait.ts +1 -0
  50. package/packages/core/src/cli/watch.ts +73 -0
  51. package/packages/core/src/config/landing.ts +12 -0
  52. package/packages/core/src/config/live.ts +4 -0
  53. package/packages/core/src/config/path-selectors.ts +68 -0
  54. package/packages/core/src/config/profiles.ts +96 -0
  55. package/packages/core/src/config/ready-assignee.ts +43 -11
  56. package/packages/core/src/config/roles.ts +33 -10
  57. package/packages/core/src/config/schema.ts +205 -81
  58. package/packages/core/src/events/catalog.ts +17 -3
  59. package/packages/core/src/events/compatibility.ts +4 -1
  60. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  61. package/packages/core/src/events/head-paths-limits.ts +25 -0
  62. package/packages/core/src/events/payloads.ts +323 -20
  63. package/packages/core/src/events/policy.ts +22 -0
  64. package/packages/core/src/events/repository.ts +47 -1
  65. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +320 -130
  66. package/packages/core/src/kernel/build-creation.ts +29 -0
  67. package/packages/core/src/kernel/consent-revocation.ts +72 -0
  68. package/packages/core/src/kernel/dispatch-capacity.ts +19 -8
  69. package/packages/core/src/kernel/engine.ts +48 -8
  70. package/packages/core/src/kernel/forge-health.ts +47 -0
  71. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  72. package/packages/core/src/kernel/head-paths-state.ts +63 -0
  73. package/packages/core/src/kernel/head-paths.ts +401 -0
  74. package/packages/core/src/kernel/landing-policy-identity.ts +20 -0
  75. package/packages/core/src/kernel/landing-policy.ts +55 -2
  76. package/packages/core/src/kernel/landing-readiness.ts +104 -9
  77. package/packages/core/src/kernel/landing-state.ts +44 -4
  78. package/packages/core/src/kernel/leaf-restack-state.ts +50 -2
  79. package/packages/core/src/kernel/log-index.ts +27 -1
  80. package/packages/core/src/kernel/node-parent.ts +2 -0
  81. package/packages/core/src/kernel/node-polling.ts +13 -3
  82. package/packages/core/src/kernel/node-restack-state.ts +8 -1
  83. package/packages/core/src/kernel/node-restack-transaction.ts +45 -0
  84. package/packages/core/src/kernel/read-deferrals.ts +3 -1
  85. package/packages/core/src/kernel/read-facts.ts +37 -2
  86. package/packages/core/src/kernel/reducer-registry.ts +22 -1
  87. package/packages/core/src/kernel/reducer.ts +332 -16
  88. package/packages/core/src/kernel/target-observation.ts +2 -5
  89. package/packages/core/src/kernel/terminal-guard.ts +52 -3
  90. package/packages/core/src/kernel/ticket-handbacks.ts +40 -0
  91. package/packages/core/src/kernel/ticket-preparation.ts +15 -1
  92. package/packages/core/src/kernel/ticket-wait.ts +345 -0
  93. package/packages/core/src/kernel/verify-applicability.ts +9 -19
  94. package/packages/core/src/ontology.ts +1 -0
  95. package/packages/core/src/operator/annotations.ts +6 -0
  96. package/packages/core/src/operator/index.ts +3 -0
  97. package/packages/core/src/operator/protocol.ts +25 -2
  98. package/packages/core/src/operator/query.ts +1 -1
  99. package/packages/core/src/operator/registry.ts +122 -10
  100. package/packages/core/src/operator/repository-events.ts +67 -0
  101. package/packages/core/src/operator/sandbox-host.ts +3 -0
  102. package/packages/core/src/operator/tickets.ts +15 -3
  103. package/packages/core/src/plugin-sdk/index.ts +4 -0
  104. package/packages/core/src/ports/forge/create.ts +6 -0
  105. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  106. package/packages/core/src/ports/forge/github.ts +12 -1
  107. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  108. package/packages/core/src/ports/forge-failure.ts +31 -2
  109. package/packages/core/src/ports/runner/routing.ts +66 -5
  110. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  111. package/packages/core/src/ports/tickets/contract.ts +164 -4
  112. package/packages/core/src/ports/tickets/create.ts +17 -3
  113. package/packages/core/src/ports/tickets/fake.ts +5 -0
  114. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  115. package/packages/core/src/ports/tickets/github.ts +247 -29
  116. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  117. package/packages/core/src/ports/tickets/operations.ts +6 -1
  118. package/packages/core/src/ports/tickets/tree.ts +12 -2
  119. package/packages/core/src/ports/tickets/update.ts +6 -2
  120. package/packages/core/src/ports/types.ts +36 -5
  121. package/packages/core/src/ports/workspace/vercel-sandbox.ts +9 -0
  122. package/packages/core/src/processes/build-child.ts +28 -7
  123. package/packages/core/src/processes/build-execution-state.ts +34 -2
  124. package/packages/core/src/processes/build-runner.ts +165 -19
  125. package/packages/core/src/processes/dispatcher.ts +837 -115
  126. package/packages/core/src/processes/execution-no-progress.ts +22 -2
  127. package/packages/core/src/processes/harvest-child.ts +4 -0
  128. package/packages/core/src/processes/harvest-runner.ts +5 -0
  129. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  130. package/packages/core/src/processes/publication-state.ts +6 -1
  131. package/packages/core/src/processes/repo-view.ts +2 -0
  132. package/packages/core/src/scenarios/harness.ts +15 -1
  133. package/packages/core/src/store/digest.ts +41 -2
  134. package/packages/core/src/store/reduced-reads.ts +4 -1
  135. package/packages/core/src/store/reducer-value-shapes.json +10310 -8441
  136. package/packages/core/src/store/remote/client.ts +49 -10
  137. package/packages/core/src/store/remote/index.ts +4 -0
  138. package/packages/core/src/store/remote/protocol.ts +18 -1
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.8.0.json +29043 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  143. package/packages/core/src/store/repo-state-events.ts +3 -0
  144. package/packages/core/src/store/types.ts +27 -0
  145. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  146. package/packages/core/src/testing/index.ts +2 -0
  147. package/packages/core/src/testing/reduced-read-budget.ts +419 -9
  148. package/skills/code-review/SKILL.md +8 -0
  149. package/skills/finalize/SKILL.md +4 -0
  150. package/skills/guide/SKILL.md +241 -47
  151. package/skills/guide/references/integration-tree.md +7 -4
  152. package/skills/guide/references/merge-policy.md +78 -6
  153. package/skills/guide/references/migration-1.0.md +4 -2
  154. package/skills/guide/references/operator-api.md +45 -13
  155. package/skills/guide/references/plugin-authoring.md +45 -7
  156. package/skills/guide/references/remote-store-protocol.md +28 -7
  157. package/skills/guide/references/restacking.md +35 -11
  158. package/skills/guide/references/ticket-dependencies.md +9 -4
  159. package/skills/implement/SKILL.md +15 -1
  160. package/skills/operate/SKILL.md +133 -16
  161. package/skills/plan/SKILL.md +17 -2
  162. package/skills/plan-review/SKILL.md +8 -0
  163. package/skills/reconcile/SKILL.md +21 -5
  164. package/skills/tickets/SKILL.md +23 -6
  165. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,29 @@
1
+ import { createHash } from 'node:crypto'
2
+
3
+ /** The grammar of a build-creation key: a preparation attempt id. */
4
+ export const CREATION_KEY = /^[A-Za-z0-9_-]{1,128}$/
5
+
6
+ /** The slug base an allocating store suffixes: the requested slug's first 60
7
+ * characters without trailing hyphens. */
8
+ export function projectBuildSlugBase(requestedSlug: string): string {
9
+ return requestedSlug.slice(0, 60).replace(/-+$/, '')
10
+ }
11
+
12
+ /**
13
+ * The canonical slug an allocating store gives a keyed creation. Client and
14
+ * server share this derivation, so a client that lost the create response can
15
+ * point-read the build its own key created and no other. Two keys collide only
16
+ * with the same repository, requested slug and 96-bit digest prefix; a store
17
+ * answers such a repeat with a conflict and never allocates a second identity.
18
+ */
19
+ export function creationBuildSlug(
20
+ repo: string,
21
+ requestedSlug: string,
22
+ creationKey: string,
23
+ ): string {
24
+ const digest = createHash('sha256')
25
+ .update(`autobuild-build-creation\0${repo}\0${requestedSlug}\0${creationKey}`)
26
+ .digest('hex')
27
+ .slice(0, 24)
28
+ return `${projectBuildSlugBase(requestedSlug)}-${digest}`
29
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Revoking protected merge consent.
3
+ *
4
+ * Consent given under a `[[merge]]` rule with `paths` or `within` predicates
5
+ * approved the protected change the operator read. When a reconcile's own
6
+ * edits (its recorded resolution) touch a file those predicates match, the
7
+ * change that would merge is no longer the reviewed one: the kernel appends
8
+ * `landing.consent-revoked` where the reconcile records its head, never on a
9
+ * poll. Clean restacks record no resolution and never revoke.
10
+ */
11
+ import { compilePathSelectors } from '../config/path-selectors'
12
+ import type { EventPayload } from '../events/payloads'
13
+ import { LANDING_MATCHED_PATHS_PREVIEW } from '../events/head-paths-limits'
14
+ import { readHeadPaths, type RecordedHeadPaths } from './head-paths'
15
+ import type { LandingState } from './landing-state'
16
+ import type { BuildStore } from '../store/types'
17
+
18
+ export type ConsentRevocation = EventPayload<'landing.consent-revoked'>
19
+
20
+ /** Cheap guard: whether any reconcile edit could revoke the current consent. */
21
+ export function revocableConsent(landing: LandingState | undefined): boolean {
22
+ const command = landing?.command
23
+ return command?.kind === 'land' && !command.legacy && command.rule !== undefined
24
+ }
25
+
26
+ /** The revocation a reconcile's resolution causes, or undefined. Each
27
+ * resolution path is matched against the union of the consent rule's `paths`
28
+ * and `within` selectors; `within`'s every-path condition does not apply. */
29
+ export function consentRevocation(
30
+ landing: LandingState | undefined,
31
+ input: {
32
+ source: ConsentRevocation['source']
33
+ previousHead: string
34
+ head: string
35
+ resolution: readonly string[]
36
+ },
37
+ ): ConsentRevocation | undefined {
38
+ const command = landing?.command
39
+ if (!revocableConsent(landing) || command?.rule === undefined) return undefined
40
+ const { paths, within } = command.rule.snapshot
41
+ const protectedPath = compilePathSelectors(
42
+ [...(paths ?? []), ...(within ?? [])],
43
+ (selector, error) =>
44
+ `invalid [[merge]] path selector ${JSON.stringify(selector)} in consent rule ${command.rule!.index}: ${error}`,
45
+ )
46
+ const matched = [...new Set(input.resolution)].sort().filter(protectedPath)
47
+ if (matched.length === 0) return undefined
48
+ return {
49
+ commandSeq: command.seq,
50
+ source: input.source,
51
+ rule: { index: command.rule.index, snapshot: { ...command.rule.snapshot } },
52
+ previousHead: input.previousHead,
53
+ head: input.head,
54
+ ...(command.head === undefined ? {} : { consentedHead: command.head }),
55
+ paths: { total: matched.length, preview: matched.slice(0, LANDING_MATCHED_PATHS_PREVIEW) },
56
+ }
57
+ }
58
+
59
+ /** The complete resolution paths behind a recorded head, without git: the
60
+ * facts just deposited, else a complete summary preview, else one artifact
61
+ * read (a retried terminal recording a resolution beyond the preview). */
62
+ export async function resolutionPathsFor(
63
+ store: Pick<BuildStore, 'getArtifact'>,
64
+ slug: string,
65
+ recorded: RecordedHeadPaths,
66
+ ): Promise<string[]> {
67
+ if (recorded.recorded === 'appended') return recorded.facts.resolution?.paths ?? []
68
+ const resolution = recorded.record.resolution
69
+ if (resolution === undefined) return []
70
+ if (resolution.total === resolution.preview.length) return [...resolution.preview]
71
+ return (await readHeadPaths(store, slug, recorded.record)).resolution?.paths ?? []
72
+ }
@@ -2,14 +2,16 @@ import type { TicketRef } from '../ontology'
2
2
  import type { BuildRecord } from '../store/types'
3
3
  import type { BuildState } from './reducer'
4
4
  import { integrationAdmissible, integrationNeedsRunner } from './integration-state'
5
+ import { waitParked, waitResumeDue } from './ticket-wait'
5
6
 
6
7
  /** Repository-scoped, reduced facts. Provisioning reserves a slot before a workspace exists.
7
8
  *
8
- * `capacity` counts builds running work. A leaf that has finished its pipeline
9
- * (settled, see `epilogueLeaf`) and holds no runner is parked: it waits for a
10
- * merge decision, merge gates or the forge and holds no slot, though it keeps
9
+ * `capacity` counts builds running work. A leaf that holds no runner is
10
+ * parked when it has finished its pipeline (settled, see `epilogueLeaf`) and
11
+ * waits for a merge decision, merge gates or the forge, or when it waits on
12
+ * other tickets (`waitParked`). A parked leaf holds no slot, though it keeps
11
13
  * its workspace. Every other unfinished leaf holds a slot, paused or blocked
12
- * included. Nodes hold a slot only while they need a runner. */
14
+ * on a question included. Nodes hold a slot only while they need a runner. */
13
15
  export interface CapacityBuild {
14
16
  record: BuildRecord
15
17
  state: BuildState
@@ -19,8 +21,9 @@ export interface CapacityBuild {
19
21
  restackDue?: boolean
20
22
  }
21
23
 
22
- /** The runner a node or parked leaf has durably requested and does not yet hold. */
23
- export type SlotRequest = 'verification' | 'reconcile'
24
+ /** The runner a node or parked leaf has durably requested and does not yet
25
+ * hold. `resume` is a leaf whose ticket wait ended. */
26
+ export type SlotRequest = 'verification' | 'reconcile' | 'resume'
24
27
 
25
28
  export interface DispatchCapacity {
26
29
  configured: number
@@ -74,9 +77,14 @@ function executionOpen(state: BuildState): boolean {
74
77
  return state.openExecution?.commandId !== undefined
75
78
  }
76
79
 
77
- /** A finished leaf with no runner working. It holds no slot; its workspace does not count. */
80
+ /** A finished or ticket-waiting leaf with no runner working. It holds no
81
+ * slot; its workspace does not count. */
78
82
  export function parkedLeaf(build: CapacityBuild, now: Date): boolean {
79
- return epilogueLeaf(build.state) && !runnerAllocated(build, now) && !executionOpen(build.state)
83
+ return (
84
+ (epilogueLeaf(build.state) || waitParked(build.state)) &&
85
+ !runnerAllocated(build, now) &&
86
+ !executionOpen(build.state)
87
+ )
80
88
  }
81
89
 
82
90
  /** A finished leaf whose latest verify cycle or finalize has not been settled
@@ -114,6 +122,9 @@ function leafSlotRequest(build: CapacityBuild, now: Date): SlotRequest | undefin
114
122
  state.targetRewrite !== undefined
115
123
  )
116
124
  return undefined
125
+ // A ticket wait parks a leaf mid-pipeline: it asks for a slot only once the
126
+ // wait has ended, to resume the phase that declared it.
127
+ if (waitParked(state)) return waitResumeDue(state) ? 'resume' : undefined
117
128
  if (state.prState === 'conflicted') return 'reconcile'
118
129
  if (build.restackDue || epilogueUnsettled(state)) return 'verification'
119
130
  return undefined
@@ -43,6 +43,8 @@ import {
43
43
  import { indexLog, type LogIndex, type LoopIndex } from './log-index'
44
44
  import { reduceBuild, type AnsweredEscalation, type BuildState } from './reducer'
45
45
  import { stalledChains, type FindingChain } from './stall'
46
+ import { pendingWaitRequest, waitGuidance, waitResumeRestackCycle } from './ticket-wait'
47
+ import { leafRestackedBase } from './leaf-restack-state'
46
48
 
47
49
  // ── The decision contract ────────────────────────────────────────────────────
48
50
 
@@ -51,6 +53,7 @@ export type WaitReason =
51
53
  | 'publication-retry'
52
54
  | 'verify-stage'
53
55
  | 'mixed-version'
56
+ | 'ticket-wait'
54
57
  | 'blocked'
55
58
  | 'paused'
56
59
  | 'awaiting-spec'
@@ -96,7 +99,11 @@ export type Decision =
96
99
  failure: import('../events/payloads').EventPayload<'verify.stage-failed'>
97
100
  }
98
101
  | ({ kind: 'raise-read-deferral' } & import('./read-deferrals').ReadDeferral)
99
- | { kind: 'restack'; trigger: 'verify-entry' | 'awaiting-landing'; cycle: number }
102
+ | {
103
+ kind: 'restack'
104
+ trigger: 'verify-entry' | 'awaiting-landing' | 'wait-resume'
105
+ cycle: number
106
+ }
100
107
  | { kind: 'capture-reconcile-policy'; reconcileSeq: number }
101
108
  | { kind: 'wait'; reason: WaitReason }
102
109
  | { kind: 'acknowledge'; command: 'pause' | 'resume' | 'abort' }
@@ -230,6 +237,11 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
230
237
  return { kind: 'acknowledge', command: 'pause' }
231
238
  }
232
239
 
240
+ // A declared ticket wait parks the build until the dispatcher validates it
241
+ // (SPEC §11 "Ticket waits"): accepted, it becomes an open escalation below;
242
+ // refused, the declaring phase re-runs with the refusal as guidance.
243
+ if (pendingWaitRequest(state)) return { kind: 'wait', reason: 'ticket-wait' }
244
+
233
245
  // Frozen transactions retain their original destination and may recover.
234
246
  if (state.targetRewrite && !log.restack.active && !state.nodeRestack?.active)
235
247
  return { kind: 'wait', reason: 'target-rewritten' }
@@ -273,6 +285,7 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
273
285
  (e) =>
274
286
  !(
275
287
  stage &&
288
+ e.wait === undefined &&
276
289
  e.source === 'agent' &&
277
290
  e.session !== undefined &&
278
291
  stage.stage.some(
@@ -450,10 +463,13 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
450
463
  // same-destination answers, so consuming the winner cannot reveal one of them
451
464
  // later. An answer appended after that delivery becomes the new winner and
452
465
  // remains eligible.
466
+ // A refused ticket wait is guidance for the phase that declared it, keyed by
467
+ // the wait request id and delivered by the same rule.
453
468
  const guidanceFeedback = (destination: GuidanceDestination): Feedback | undefined => {
454
- let latest: AnsweredEscalation | undefined
455
- for (const e of state.answeredEscalations) {
456
- if (e.resolution !== 'guidance' || guidanceDestination(e) !== destination) continue
469
+ let latest: Pick<AnsweredEscalation, 'id' | 'answer' | 'answeredSeq'> | undefined
470
+ for (const e of [...state.answeredEscalations, ...waitGuidance(state)]) {
471
+ if ('resolution' in e && e.resolution !== 'guidance') continue
472
+ if (guidanceDestination(e) !== destination) continue
457
473
  if (latest === undefined || e.answeredSeq > latest.answeredSeq) latest = e
458
474
  }
459
475
  if (
@@ -496,6 +512,22 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
496
512
  ? undefined
497
513
  : { verify: { step: pendingFail.step, report: pendingFail.report } }
498
514
 
515
+ // ── Wait resume (SPEC §11 "Ticket waits"): a build leaving a ticket wait
516
+ // first restacks onto its target's current head, so the declaring phase
517
+ // sees the merged blockers. Supersession of a reconcile-declared wait or a
518
+ // fresh wait-resume restack outranks every open transaction, including an
519
+ // earlier wait-resume conflict. Never-waited builds have no `state.wait`.
520
+ const waitCycle = waitResumeRestackCycle(state, log)
521
+ if (waitCycle !== undefined) return { kind: 'restack', trigger: 'wait-resume', cycle: waitCycle }
522
+ const waitRestack = log.restack.active?.trigger === 'wait-resume' ? log.restack.active : undefined
523
+ if (waitRestack) {
524
+ if (log.restack.replay?.conflicted) {
525
+ const round = log.restack.reconcileAttempt ?? state.reconcileAttempts + 1
526
+ return { kind: 'run-phase', phase: 'reconcile', round, reconcile: { attempt: round } }
527
+ }
528
+ return { kind: 'restack', trigger: 'wait-resume', cycle: waitRestack.cycle }
529
+ }
530
+
499
531
  // ── 5. Plan loop (§5, §10): rounds pair plan ⇄ plan-review ─────────────────
500
532
  const planDecision = decideLoop({
501
533
  loop: log.plan,
@@ -842,7 +874,7 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
842
874
  export function landingRestackDue(state: BuildState, log: Pick<LogIndex, 'restack'>): boolean {
843
875
  return (
844
876
  log.restack.target !== undefined &&
845
- (log.restack.target.sha !== (log.restack.completed?.targetBase ?? log.restack.initialBase) ||
877
+ (log.restack.target.sha !== leafRestackedBase(log.restack) ||
846
878
  (state.target !== undefined &&
847
879
  (log.restack.postStepAt ?? 0) > (log.restack.completedAt ?? 0)))
848
880
  )
@@ -986,17 +1018,25 @@ type GuidanceDestination = 'plan' | 'code' | `verify:${string}` | 'other'
986
1018
  * feeds implement. Finalize/reconcile guidance travels through `ab context`.
987
1019
  */
988
1020
  function guidanceDestination(
989
- escalation: Pick<AnsweredEscalation, 'phase' | 'source' | 'deferral'>,
1021
+ escalation: Pick<AnsweredEscalation, 'phase' | 'source' | 'deferral' | 'wait'>,
990
1022
  ): GuidanceDestination {
991
1023
  const { phase, source } = escalation
1024
+ // A reviewer's own-build-read deferral or ticket wait re-runs that same
1025
+ // review round, which reads its guidance through `ab context`.
992
1026
  if (
993
- escalation.deferral === 'own-build-read' &&
1027
+ (escalation.deferral === 'own-build-read' || escalation.wait !== undefined) &&
994
1028
  (phase === 'plan-review' || phase === 'code-review')
995
1029
  )
996
1030
  return 'other'
997
1031
  if (phase === 'plan' || phase === 'plan-review') return 'plan'
998
1032
  if (phase === 'implement' || phase === 'code-review') return 'code'
1033
+ // A ticket wait's escalations, including the dispatcher's unresolvable
1034
+ // raise that ended one, resume the verify step that declared it.
999
1035
  if (isVerifyPhase(phase))
1000
- return source === 'agent' || escalation.deferral === 'own-build-read' ? phase : 'code'
1036
+ return source === 'agent' ||
1037
+ escalation.deferral === 'own-build-read' ||
1038
+ escalation.wait !== undefined
1039
+ ? phase
1040
+ : 'code'
1001
1041
  return 'other'
1002
1042
  }
@@ -17,3 +17,50 @@ export const forgeHealthReducer = defineReducer<
17
17
  },
18
18
  finish: (acc) => acc.active,
19
19
  })
20
+
21
+ /** One process's latest rate limit outside the dispatcher's credential. */
22
+ export type ForgeCredentialLimit = RepositoryEventPayload<'forge.credential-limited'> & {
23
+ at: string
24
+ }
25
+
26
+ /** Retained credential-limit entries; the newest resets win. */
27
+ export const FORGE_CREDENTIAL_LIMIT_CAP = 16
28
+
29
+ /** Latest `forge.credential-limited` per (forge, process), bounded. Expiry
30
+ * is a read-time projection: callers keep only entries whose reset is ahead. */
31
+ export const forgeCredentialLimitsReducer = defineReducer<
32
+ { limits: Record<string, ForgeCredentialLimit> },
33
+ RepositoryEvent,
34
+ ForgeCredentialLimit[]
35
+ >({
36
+ version: 1,
37
+ initial: () => ({ limits: {} }),
38
+ fold(acc, events) {
39
+ for (const event of events) {
40
+ if (event.type !== 'forge.credential-limited') continue
41
+ acc.limits[`${event.payload.forge}\u0000${event.payload.process}`] = {
42
+ ...event.payload,
43
+ at: event.ts,
44
+ }
45
+ }
46
+ const entries = Object.entries(acc.limits)
47
+ if (entries.length > FORGE_CREDENTIAL_LIMIT_CAP)
48
+ acc.limits = Object.fromEntries(
49
+ entries
50
+ .sort(([, a], [, b]) => Date.parse(b.resetAt) - Date.parse(a.resetAt))
51
+ .slice(0, FORGE_CREDENTIAL_LIMIT_CAP),
52
+ )
53
+ },
54
+ finish: (acc) =>
55
+ Object.values(acc.limits)
56
+ .map((limit) => ({ ...limit }))
57
+ .sort((a, b) => a.resetAt.localeCompare(b.resetAt)),
58
+ })
59
+
60
+ /** Entries whose reset is still ahead of `now`. */
61
+ export function activeForgeCredentialLimits(
62
+ limits: readonly ForgeCredentialLimit[],
63
+ now: Date,
64
+ ): ForgeCredentialLimit[] {
65
+ return limits.filter((limit) => Date.parse(limit.resetAt) > now.getTime())
66
+ }
@@ -12,21 +12,33 @@ import { KERNEL } from '../events/envelope'
12
12
  /** Scheduling signal, never a failed attempt. */
13
13
  export class ForgeCooldown extends ForgeRequestDeferred {}
14
14
 
15
+ /** Whose rate limits a guard may record. `'repository'` is the dispatcher's
16
+ * own forge: its classified limits pause forge work repository-wide. A
17
+ * process scope (build runner, phase session) only obeys that cooldown; its
18
+ * own limits, like any unauthenticated limit, stay local to the guard and are
19
+ * reported as attention, because they say nothing about the dispatcher's
20
+ * credential. */
21
+ export type ForgeGuardScope = 'repository' | { process: string }
22
+
15
23
  /** Receiver bindings and optional plugin capabilities survive the wrapper.
16
24
  * Only trusted kernel composition receives the repository Store authority. */
17
- type GuardDeps = { store: BuildStore; repo: string; name: string; now?: () => Date; wait?: boolean }
25
+ type GuardDeps = {
26
+ store: BuildStore
27
+ repo: string
28
+ name: string
29
+ now?: () => Date
30
+ wait?: boolean
31
+ scope?: ForgeGuardScope
32
+ /** Test seam for cooldown waits. */
33
+ sleep?: (ms: number) => Promise<void>
34
+ }
18
35
  const guarded = new WeakMap<Forge, { raw: Forge; deps: GuardDeps }>()
19
36
 
20
- export function guardForge(
21
- forge: Forge,
22
- deps: {
23
- store: BuildStore
24
- repo: string
25
- name: string
26
- now?: () => Date
27
- wait?: boolean
28
- },
29
- ): Forge {
37
+ function scopeKey(scope: ForgeGuardScope | undefined): string {
38
+ return scope === undefined || scope === 'repository' ? 'repository' : `process:${scope.process}`
39
+ }
40
+
41
+ export function guardForge(forge: Forge, deps: GuardDeps): Forge {
30
42
  const previous = guarded.get(forge)
31
43
  if (previous) {
32
44
  if (
@@ -34,29 +46,75 @@ export function guardForge(
34
46
  previous.deps.repo === deps.repo &&
35
47
  previous.deps.name === deps.name &&
36
48
  previous.deps.wait === deps.wait &&
37
- previous.deps.now === deps.now
49
+ previous.deps.now === deps.now &&
50
+ previous.deps.sleep === deps.sleep &&
51
+ scopeKey(previous.deps.scope) === scopeKey(deps.scope)
38
52
  )
39
53
  return forge
40
54
  return guardForge(previous.raw, deps)
41
55
  }
42
56
  if (deps.name === 'local-git') return forge
43
57
  const now = deps.now ?? (() => new Date())
58
+ const sleep =
59
+ deps.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
60
+ const scope = deps.scope ?? 'repository'
44
61
  const health = () => readForgeHealth(deps.store, deps.repo)
62
+ const pause = (resetAt: string) =>
63
+ sleep(Math.max(1000, Math.min(30_000, Date.parse(resetAt) - now().getTime())))
64
+ /** This guard's own cooldown from a limit that is not repository-wide, and
65
+ * the latest reset it has already reported (one fact per episode). */
66
+ let local: { resetAt: string } | undefined
67
+ let reported: string | undefined
45
68
  const before = async () => {
69
+ while (local) {
70
+ if (Date.parse(local.resetAt) <= now().getTime()) {
71
+ local = undefined
72
+ break
73
+ }
74
+ if (!deps.wait) throw new ForgeCooldown(`Forge cooldown until ${local.resetAt}`)
75
+ await pause(local.resetAt)
76
+ }
46
77
  let active = await health()
47
78
  while (active && (deps.wait || Date.parse(active.resetAt) > now().getTime())) {
48
79
  if (!deps.wait) throw new ForgeCooldown(`Forge cooldown until ${active.resetAt}`)
49
- await new Promise((resolve) =>
50
- setTimeout(
51
- resolve,
52
- Math.max(1000, Math.min(30_000, Date.parse(active!.resetAt) - now().getTime())),
53
- ),
54
- )
80
+ await pause(active.resetAt)
55
81
  active = await health()
56
82
  }
57
83
  }
58
84
  const failed = async (error: unknown) => {
59
85
  if (!isForgeFailure(error) || error.details.kind !== 'rate-limited') return
86
+ const details = error.details
87
+ if (scope !== 'repository' || details.unauthenticated) {
88
+ // At least one second, so a stale reset cannot spin a waiting retry.
89
+ const until = Math.max(
90
+ Date.parse(details.resetAt),
91
+ local ? Date.parse(local.resetAt) : 0,
92
+ now().getTime() + 1000,
93
+ )
94
+ local = { resetAt: new Date(until).toISOString() }
95
+ if (reported !== undefined && Date.parse(reported) >= Date.parse(details.resetAt)) return
96
+ reported = details.resetAt
97
+ try {
98
+ await deps.store.appendRepo(deps.repo, {
99
+ actor: KERNEL,
100
+ type: 'forge.credential-limited',
101
+ payload: {
102
+ forge: deps.name,
103
+ process: scope === 'repository' ? 'dispatcher' : scope.process,
104
+ credential: details.unauthenticated ? 'unauthenticated' : 'process',
105
+ ...(details.unauthenticated
106
+ ? { missingCredential: details.unauthenticated.slice(0, 1000) }
107
+ : {}),
108
+ message: error.message.slice(0, 2000),
109
+ resetAt: details.resetAt,
110
+ },
111
+ })
112
+ } catch {
113
+ // Attention only: an older server or a missing repository must not
114
+ // turn the limited request into a different failure.
115
+ }
116
+ return
117
+ }
60
118
  const active = await health()
61
119
  if (active?.resetAt === error.details.resetAt && active.message === error.message) return
62
120
  // Runner/phase credentials cannot administer repositories; their repo
@@ -0,0 +1,63 @@
1
+ /** Pure half of the head path facts (`kernel/head-paths.ts`): the folded
2
+ * summary shape, the reducer step and the selectors. No IO, so the build
3
+ * reducer can import it. */
4
+ import type { EventPayload } from '../events/payloads'
5
+ import { HEAD_PATHS_RECORDS } from '../events/head-paths-limits'
6
+ import type { BuildState } from './reducer'
7
+
8
+ export type HeadPathsPayload = EventPayload<'head.paths-recorded'>
9
+ export type HeadPathsSource = HeadPathsPayload['source']
10
+ /** One folded fact: the event's bounded summary plus its seq. */
11
+ export type HeadPathsSummary = HeadPathsPayload & { seq: number }
12
+
13
+ export type HeadPathsAnswer = { recorded: false } | { recorded: true; record: HeadPathsSummary }
14
+
15
+ // ── Selectors (pure, no IO) ──────────────────────────────────────────────────
16
+
17
+ /** The head a landing decision would judge: a node's integration-cycle head,
18
+ * a leaf's PR head. */
19
+ export function candidateHead(
20
+ state: Pick<BuildState, 'kind' | 'integration' | 'pr'>,
21
+ ): string | undefined {
22
+ return state.kind === 'node' ? state.integration?.cycle?.head : state.pr?.headSha
23
+ }
24
+
25
+ /** "Not recorded" is distinct from "recorded and empty". */
26
+ export function headPathsFor(
27
+ state: Pick<BuildState, 'headPaths'>,
28
+ head: string | undefined,
29
+ ): HeadPathsAnswer {
30
+ const record = head === undefined ? undefined : state.headPaths?.find((r) => r.head === head)
31
+ return record === undefined ? { recorded: false } : { recorded: true, record }
32
+ }
33
+
34
+ export function candidateHeadPaths(
35
+ state: Pick<BuildState, 'kind' | 'integration' | 'pr' | 'headPaths'>,
36
+ ): HeadPathsAnswer {
37
+ return headPathsFor(state, candidateHead(state))
38
+ }
39
+
40
+ /** Reducer step: the first summary per head wins (retries and races record
41
+ * the same head again), and only the newest `HEAD_PATHS_RECORDS` are kept. */
42
+ export function foldHeadPaths(
43
+ current: readonly HeadPathsSummary[] | undefined,
44
+ payload: HeadPathsPayload,
45
+ seq: number,
46
+ ): HeadPathsSummary[] | undefined {
47
+ if (current?.some((record) => record.head === payload.head)) return current as HeadPathsSummary[]
48
+ const { source, head, destination, mergeBase, total, preview, resolution, artifact } = payload
49
+ const record: HeadPathsSummary = {
50
+ source,
51
+ head,
52
+ destination,
53
+ mergeBase,
54
+ total,
55
+ preview: [...preview],
56
+ ...(resolution === undefined
57
+ ? {}
58
+ : { resolution: { total: resolution.total, preview: [...resolution.preview] } }),
59
+ artifact: { kind: artifact.kind, rev: artifact.rev },
60
+ seq,
61
+ }
62
+ return [...(current ?? []), record].slice(-HEAD_PATHS_RECORDS)
63
+ }