@defrex/autobuild 1.0.0-beta.2 → 1.0.0-beta.4

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 (145) hide show
  1. package/SPEC.md +342 -23
  2. package/bin/ab-dispatch-generation.ts +93 -0
  3. package/docs/answering-blocked-builds.md +21 -3
  4. package/docs/architecture.md +170 -7
  5. package/docs/configuration.md +173 -5
  6. package/docs/integration-tree.md +91 -4
  7. package/docs/integration.md +54 -0
  8. package/docs/operator-api.md +58 -5
  9. package/docs/remote-store-protocol.md +9 -1
  10. package/docs/remote-ticket-protocol.md +5 -0
  11. package/docs/restacking.md +4 -1
  12. package/docs/setup.md +24 -0
  13. package/docs/spec-standard.md +94 -5
  14. package/docs/ticket-migration.md +50 -4
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/artifact.ts +5 -4
  17. package/packages/core/src/cli/attention.ts +2 -0
  18. package/packages/core/src/cli/binary-direct.ts +190 -0
  19. package/packages/core/src/cli/binary-lifecycle.ts +46 -0
  20. package/packages/core/src/cli/binary.ts +24 -210
  21. package/packages/core/src/cli/build-control.ts +108 -5
  22. package/packages/core/src/cli/context.ts +41 -1
  23. package/packages/core/src/cli/dashboard/hand-pushed.ts +24 -0
  24. package/packages/core/src/cli/dashboard/handoff.ts +64 -0
  25. package/packages/core/src/cli/dashboard/integration-detail.ts +11 -6
  26. package/packages/core/src/cli/dashboard/integration-row.ts +15 -8
  27. package/packages/core/src/cli/dashboard/model.ts +41 -10
  28. package/packages/core/src/cli/dashboard/render.ts +24 -2
  29. package/packages/core/src/cli/dashboard/rollback.ts +30 -0
  30. package/packages/core/src/cli/dispatch-args.ts +53 -0
  31. package/packages/core/src/cli/dispatch-crash-budget.ts +15 -0
  32. package/packages/core/src/cli/dispatch-frontend.ts +57 -5
  33. package/packages/core/src/cli/dispatch-handoff.ts +276 -0
  34. package/packages/core/src/cli/dispatch-launch-contract.ts +170 -0
  35. package/packages/core/src/cli/dispatch-launcher.ts +580 -0
  36. package/packages/core/src/cli/dispatch-parent-watch.ts +44 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +272 -0
  38. package/packages/core/src/cli/dispatch-presentation-job.ts +46 -0
  39. package/packages/core/src/cli/dispatch-presentation-ownership.ts +9 -0
  40. package/packages/core/src/cli/dispatch-process.ts +22 -90
  41. package/packages/core/src/cli/dispatch-readiness.ts +47 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +6 -1
  43. package/packages/core/src/cli/dispatch-runtime-cache.ts +522 -0
  44. package/packages/core/src/cli/dispatch-runtime-dependencies.ts +291 -0
  45. package/packages/core/src/cli/dispatch-runtime-use.ts +336 -0
  46. package/packages/core/src/cli/dispatch-upgrade-controller.ts +221 -0
  47. package/packages/core/src/cli/dispatch-upgrade-install.ts +258 -0
  48. package/packages/core/src/cli/dispatch-upgrade-source.ts +309 -0
  49. package/packages/core/src/cli/dispatch-upgrade-target.ts +190 -0
  50. package/packages/core/src/cli/dispatch.ts +609 -60
  51. package/packages/core/src/cli/dispatcher-liveness.ts +1 -1
  52. package/packages/core/src/cli/harvest.ts +28 -11
  53. package/packages/core/src/cli/help.ts +7 -3
  54. package/packages/core/src/cli/installation.ts +5 -3
  55. package/packages/core/src/cli/main-checkout.ts +59 -0
  56. package/packages/core/src/cli/main.ts +26 -53
  57. package/packages/core/src/cli/node-verification-provenance.ts +97 -0
  58. package/packages/core/src/cli/repo-state.ts +3 -58
  59. package/packages/core/src/cli/repository-status.ts +74 -4
  60. package/packages/core/src/cli/runtime-spawn.ts +16 -0
  61. package/packages/core/src/cli/status.ts +57 -3
  62. package/packages/core/src/cli/ticket.ts +35 -11
  63. package/packages/core/src/cli/upgrade-followup.ts +25 -0
  64. package/packages/core/src/cli/wait.ts +3 -0
  65. package/packages/core/src/cli/watch.ts +7 -0
  66. package/packages/core/src/config/live.ts +1 -0
  67. package/packages/core/src/config/schema.ts +8 -4
  68. package/packages/core/src/distribution-packaging.ts +116 -0
  69. package/packages/core/src/events/catalog.ts +6 -0
  70. package/packages/core/src/events/payloads.ts +55 -9
  71. package/packages/core/src/events/policy.ts +26 -0
  72. package/packages/core/src/events/repository.ts +205 -4
  73. package/packages/core/src/events/runtime.ts +16 -0
  74. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +6537 -4053
  75. package/packages/core/src/kernel/change-presence.ts +7 -1
  76. package/packages/core/src/kernel/dispatch-capacity.ts +12 -4
  77. package/packages/core/src/kernel/dispatch-drain-recovery.ts +121 -0
  78. package/packages/core/src/kernel/dispatch-status.ts +4 -2
  79. package/packages/core/src/kernel/dispatch-upgrade.ts +171 -0
  80. package/packages/core/src/kernel/dispatcher-liveness.ts +7 -0
  81. package/packages/core/src/kernel/generators/repository-journals.ts +82 -0
  82. package/packages/core/src/kernel/guarded-forge.ts +1 -1
  83. package/packages/core/src/kernel/harvest.ts +98 -4
  84. package/packages/core/src/kernel/integration-attention.ts +20 -0
  85. package/packages/core/src/kernel/integration-completeness.ts +54 -16
  86. package/packages/core/src/kernel/integration-state.ts +80 -11
  87. package/packages/core/src/kernel/landing-readiness.ts +6 -1
  88. package/packages/core/src/kernel/mixed-version.ts +34 -0
  89. package/packages/core/src/kernel/node-parent.ts +35 -10
  90. package/packages/core/src/kernel/node-polling.ts +160 -0
  91. package/packages/core/src/kernel/read-facts.ts +47 -5
  92. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  93. package/packages/core/src/kernel/reducer.ts +75 -14
  94. package/packages/core/src/kernel/service-facts.ts +11 -4
  95. package/packages/core/src/kernel/ticket-migrations.ts +139 -0
  96. package/packages/core/src/operator/presentation.ts +7 -0
  97. package/packages/core/src/operator/query.ts +13 -3
  98. package/packages/core/src/operator/registry.ts +1 -1
  99. package/packages/core/src/operator/tickets.ts +30 -26
  100. package/packages/core/src/plugins/load.ts +4 -1
  101. package/packages/core/src/plugins/runtime-snapshot.ts +128 -0
  102. package/packages/core/src/ports/forge/contract.ts +29 -0
  103. package/packages/core/src/ports/forge/github.ts +189 -61
  104. package/packages/core/src/ports/forge-failure.ts +1 -0
  105. package/packages/core/src/ports/forge-telemetry.ts +3 -0
  106. package/packages/core/src/ports/runner/session-env.ts +1 -0
  107. package/packages/core/src/ports/tickets/linear.ts +180 -12
  108. package/packages/core/src/ports/tickets/migration.ts +92 -9
  109. package/packages/core/src/ports/types.ts +17 -0
  110. package/packages/core/src/ports/workspace/distribution-archive.ts +22 -149
  111. package/packages/core/src/ports/workspace/distribution-release.ts +56 -0
  112. package/packages/core/src/ports/workspace/git-worktree.ts +2 -1
  113. package/packages/core/src/ports/workspace/local-build-execution.ts +37 -17
  114. package/packages/core/src/processes/build-child-exit.ts +5 -26
  115. package/packages/core/src/processes/build-runner.ts +81 -11
  116. package/packages/core/src/processes/dispatcher.ts +418 -59
  117. package/packages/core/src/processes/execution-no-progress.ts +6 -0
  118. package/packages/core/src/processes/execution-relaunch.ts +30 -0
  119. package/packages/core/src/processes/execution-settlement.ts +16 -7
  120. package/packages/core/src/processes/harvest-runner.ts +328 -292
  121. package/packages/core/src/processes/process-group-reaper.ts +17 -10
  122. package/packages/core/src/runtime-identity.ts +22 -3
  123. package/packages/core/src/store/contract.ts +183 -0
  124. package/packages/core/src/store/local/store.ts +197 -72
  125. package/packages/core/src/store/reduced-reads.ts +8 -0
  126. package/packages/core/src/store/reducer-value-shapes.json +8915 -6344
  127. package/packages/core/src/store/remote/client.ts +43 -0
  128. package/packages/core/src/store/repo-state-events.ts +21 -3
  129. package/packages/core/src/store/types.ts +7 -0
  130. package/packages/core/src/testing/dispatch-read-budget.ts +3 -2
  131. package/skills/guide/SKILL.md +234 -24
  132. package/skills/guide/references/integration-tree.md +91 -4
  133. package/skills/guide/references/operator-api.md +53 -4
  134. package/skills/guide/references/plugin-authoring.md +45 -4
  135. package/skills/guide/references/remote-store-protocol.md +9 -1
  136. package/skills/guide/references/remote-ticket-protocol.md +5 -0
  137. package/skills/guide/references/restacking.md +4 -1
  138. package/skills/guide/references/setup.md +24 -0
  139. package/skills/guide/references/spec-standard.md +94 -5
  140. package/skills/guide/references/ticket-migration.md +50 -4
  141. package/skills/harvest/SKILL.md +4 -0
  142. package/skills/harvest-review/SKILL.md +4 -0
  143. package/skills/operate/SKILL.md +78 -8
  144. package/skills/spec/SKILL.md +35 -5
  145. package/skills/tickets/SKILL.md +19 -0
@@ -1,3 +1,4 @@
1
+ import { readTicketMigrations, resolveTicketRef, type TicketMigrations } from './ticket-migrations'
1
2
  import type { BuildState } from './reducer'
2
3
  import type { TicketSource, TicketListing } from '../ports/types'
3
4
  import type { BuildStore, BuildRecord } from '../store/types'
@@ -8,6 +9,7 @@ import type { EventPayload } from '../events/payloads'
8
9
  /** One exhaustive source sample shared by every node in a dispatcher pass.
9
10
  * Scheduling may be cached; publication always requests a sample from this pass. */
10
11
  export interface IntegrationObservationInputs {
12
+ migrations?: TicketMigrations
11
13
  listing: TicketListing
12
14
  builds: { record: BuildRecord; state: BuildState }[]
13
15
  }
@@ -22,7 +24,7 @@ export async function integrationObservationInputs(
22
24
  const builds = []
23
25
  for (const record of await store.listBuildsForRepo(repo))
24
26
  builds.push({ record, state: (await readBuildFacts(store, record.slug)).value.state })
25
- return { listing, builds }
27
+ return { listing, builds, migrations: await readTicketMigrations(store, repo) }
26
28
  }
27
29
 
28
30
  /** A failed or partial enumeration cannot authorize verification or publication. */
@@ -35,6 +37,7 @@ export async function observeIntegration(
35
37
  const record = await store.getBuild(slug)
36
38
  const state = (await readBuildFacts(store, slug)).value.state
37
39
  const observation: EventPayload<'integration.observed'> = {
40
+ membershipSource: state.integration?.observation?.membershipSource,
38
41
  openChildren: [],
39
42
  diagnostics: [],
40
43
  contributions: [...(state.integration?.observation?.contributions ?? [])],
@@ -45,24 +48,31 @@ export async function observeIntegration(
45
48
  try {
46
49
  if (!record?.ticket || !tickets.integrationTree || !tickets.listAll)
47
50
  throw new Error('ticket source cannot establish exhaustive integration completeness')
48
- if (record.ticket.source !== tickets.name)
49
- throw new Error('configured ticket source differs from the frozen node source')
50
- const { listing, builds } = await (inputs
51
- ? inputs()
52
- : integrationObservationInputs(store, tickets, record.repo))
51
+ const {
52
+ listing,
53
+ builds,
54
+ migrations: supplied,
55
+ } = await (inputs ? inputs() : integrationObservationInputs(store, tickets, record.repo))
56
+ const migrations = supplied ?? (await readTicketMigrations(store, record.repo))
57
+ const nodeRef = resolveTicketRef(migrations, record.ticket, tickets.name, slug)
58
+ observation.membershipSource = tickets.name
59
+ const current = (build: BuildRecord) =>
60
+ build.ticket
61
+ ? resolveTicketRef(migrations, build.ticket, tickets.name, build.slug)
62
+ : undefined
53
63
  observation.diagnostics.push(...listing.diagnostics)
54
64
  for (const ticket of listing.tickets)
55
- if (ticket.target === record.ticket.id && !ticket.resolved) children.add(ticket.ref.id)
65
+ if (ticket.target === nodeRef.id && !ticket.resolved) children.add(ticket.ref.id)
56
66
  // Frozen claims survive edits to the source ticket's target.
57
67
  for (const { record: build, state: child } of builds) {
58
68
  if (child.target?.build === slug && child.status !== 'done' && child.status !== 'aborted')
59
- children.add(build.ticket?.id ?? build.slug)
69
+ children.add(current(build)?.id ?? build.slug)
60
70
  if (
61
71
  [child.nodeRestack?.parentRequest, child.nodeRestack?.parentChange].some(
62
72
  (move) => move && (move.old.target?.build === slug || move.next.target?.build === slug),
63
73
  )
64
74
  )
65
- children.add(build.ticket?.id ?? build.slug)
75
+ children.add(current(build)?.id ?? build.slug)
66
76
  if (child.target?.build === slug && child.prState === 'merged')
67
77
  observation.contributions.push(build.slug)
68
78
  }
@@ -99,26 +109,54 @@ export async function observeIntegration(
99
109
  for (const contribution of [...new Set(observation.contributions)].sort()) {
100
110
  const build = builds.find((b) => b.record.slug === contribution)?.record
101
111
  put(
102
- build?.ticket?.source ?? record.ticket.source,
103
- build?.ticket?.id ?? contribution,
112
+ build ? (current(build)?.source ?? tickets.name) : tickets.name,
113
+ build ? (current(build)?.id ?? contribution) : contribution,
104
114
  build?.ticket?.title,
105
115
  contribution,
106
116
  )
107
117
  }
108
118
  for (const { record: build } of builds)
109
- if (children.has(build.ticket?.id ?? build.slug))
119
+ if (
120
+ (build.ticket?.source === tickets.name ||
121
+ builds.some(
122
+ (entry) =>
123
+ entry.record.slug === build.slug &&
124
+ (entry.state.target?.build === slug ||
125
+ observation.contributions.includes(build.slug)),
126
+ )) &&
127
+ children.has(current(build)?.id ?? build.slug)
128
+ )
110
129
  put(
111
- build.ticket?.source ?? record.ticket.source,
112
- build.ticket?.id ?? build.slug,
130
+ current(build)?.source ?? tickets.name,
131
+ current(build)?.id ?? build.slug,
113
132
  build.ticket?.title,
114
133
  )
134
+ for (const { record: build, state: child } of builds) {
135
+ if (
136
+ !build.ticket ||
137
+ child.target?.build !== slug ||
138
+ child.status === 'done' ||
139
+ child.status === 'aborted'
140
+ )
141
+ continue
142
+ const ref = current(build)!
143
+ if (
144
+ ref.source === build.ticket.source &&
145
+ ref.id === build.ticket.id &&
146
+ nodeRef.source === record.ticket.source &&
147
+ nodeRef.id === record.ticket.id
148
+ )
149
+ continue
150
+ const entry = display.get(JSON.stringify([ref.source, ref.id]))
151
+ if (entry) entry.claims = [...new Set([...(entry.claims ?? []), build.slug])].sort()
152
+ }
115
153
  for (const ticket of listing.tickets)
116
154
  if (
117
- (ticket.ref.source === record.ticket.source && children.has(ticket.ref.id)) ||
155
+ (ticket.ref.source === tickets.name && children.has(ticket.ref.id)) ||
118
156
  display.has(JSON.stringify([ticket.ref.source, ticket.ref.id]))
119
157
  )
120
158
  put(ticket.ref.source, ticket.ref.id, ticket.title, undefined, true)
121
- for (const id of children) put(record.ticket.source, id)
159
+ for (const id of children) put(tickets.name, id)
122
160
  if (observation.diagnostics.length)
123
161
  for (const previous of state.integration?.observation?.children ?? [])
124
162
  if (!display.has(JSON.stringify([previous.source, previous.id])))
@@ -5,6 +5,7 @@ import type { BuildState } from './reducer'
5
5
  /** Exact immutable inputs, retained independently of disposable execution. */
6
6
  export interface IntegrationState {
7
7
  cycles?: (EventPayload<'integration.prepared'> & { seq: number })[]
8
+ failures?: (EventPayload<'integration.verification-failed'> & { seq: number })[]
8
9
  observation?: EventPayload<'integration.observed'>
9
10
  cycle?: EventPayload<'integration.prepared'> & { seq: number }
10
11
  intent?: EventPayload<'integration.landing-intended'>
@@ -13,6 +14,10 @@ export interface IntegrationState {
13
14
  }
14
15
  export function advanceIntegration(state: IntegrationState, event: AbEvent): void {
15
16
  switch (event.type) {
17
+ case 'integration.verification-failed':
18
+ state.failures ??= []
19
+ state.failures.push({ ...event.payload, seq: event.seq })
20
+ break
16
21
  case 'integration.observed':
17
22
  state.observation = event.payload
18
23
  break
@@ -44,30 +49,40 @@ export function integrationComplete(state: Pick<BuildState, 'integration'>): boo
44
49
  observation.contributions.length > 0
45
50
  )
46
51
  }
52
+ type CycleState = Pick<BuildState, 'integration' | 'restartSince' | 'nodeComparison' | 'verify'>
53
+
54
+ /** A spec revision invalidates execution eligibility, never historical receipts. */
55
+ export function integrationCycleCurrent(
56
+ state: Pick<CycleState, 'integration' | 'restartSince'>,
57
+ ): boolean {
58
+ return !!state.integration?.cycle && state.integration.cycle.seq > state.restartSince
59
+ }
60
+
47
61
  export function integrationCurrent(state: BuildState): boolean {
48
62
  const cycle = state.integration?.cycle
49
63
  return (
50
- !!cycle &&
64
+ integrationCycleCurrent(state) &&
51
65
  integrationComplete(state) &&
52
66
  !state.nodeRestack?.parentRequest &&
53
67
  !state.nodeRestack?.parentChange &&
54
68
  !state.nodeRestack?.active &&
55
- state.nodeComparison?.headSha === cycle.head &&
56
- state.nodeComparison?.parentSha === cycle.parent &&
57
- (!state.nodeRestack?.observedParent || state.nodeRestack.observedParent.sha === cycle.parent) &&
58
- state.nodeRestack?.contributionBase === cycle.parent
69
+ state.nodeComparison?.headSha === cycle!.head &&
70
+ state.nodeComparison?.parentSha === cycle!.parent &&
71
+ (!state.nodeRestack?.observedParent ||
72
+ state.nodeRestack.observedParent.sha === cycle!.parent) &&
73
+ state.nodeRestack?.contributionBase === cycle!.parent
59
74
  )
60
75
  }
61
76
 
62
77
  export function integrationConfig(config: import('../config/schema').Config): string {
63
78
  return JSON.stringify({ verify: config.verify, commands: config.commands })
64
79
  }
65
- export function integrationFailed(state: BuildState): boolean {
80
+ export function integrationFailed(state: CycleState): boolean {
66
81
  const cycle = state.integration?.cycle
67
82
  return (
68
- !!cycle &&
69
- state.nodeComparison?.headSha === cycle.head &&
70
- state.nodeComparison?.parentSha === cycle.parent &&
83
+ integrationCycleCurrent(state) &&
84
+ state.nodeComparison?.headSha === cycle!.head &&
85
+ state.nodeComparison?.parentSha === cycle!.parent &&
71
86
  state.verify.results.some(
72
87
  (result) =>
73
88
  result.seq > cycle!.seq && result.restackId === cycle!.id && result.outcome === 'fail',
@@ -123,9 +138,16 @@ export function integrationHeadVerified(state: BuildState, head: string): boolea
123
138
  * remains available to landing audits, but cannot authorize a new parent. */
124
139
  export function integrationCycleVerified(state: BuildState): boolean {
125
140
  const cycle = state.integration?.cycle
126
- if (!cycle) return false
141
+ if (!cycle || !integrationCycleCurrent(state)) return false
127
142
  return integrationHeadVerified(
128
- { ...state, integration: { ...state.integration, cycles: [cycle] } },
143
+ {
144
+ ...state,
145
+ verify: {
146
+ ...state.verify,
147
+ results: state.verify.results.filter((result) => result.seq > cycle.seq),
148
+ },
149
+ integration: { ...state.integration, cycles: [cycle] },
150
+ },
129
151
  cycle.head,
130
152
  )
131
153
  }
@@ -133,3 +155,50 @@ export function integrationCycleVerified(state: BuildState): boolean {
133
155
  export function integrationNeedsRunner(state: BuildState): boolean {
134
156
  return integrationCurrent(state) && !integrationFailed(state) && !integrationCycleVerified(state)
135
157
  }
158
+
159
+ /** Only the current failed cycle can still require a repair child. */
160
+ export function missingIntegrationFailures(
161
+ state: BuildState,
162
+ slug: string,
163
+ ): EventPayload<'integration.verification-failed'>[] {
164
+ if (
165
+ state.kind !== 'node' ||
166
+ state.status === 'done' ||
167
+ state.status === 'aborted' ||
168
+ !integrationCycleCurrent(state)
169
+ )
170
+ return []
171
+ const cycle = state.integration?.cycle
172
+ if (
173
+ !cycle ||
174
+ state.nodeComparison?.headSha !== cycle.head ||
175
+ state.nodeComparison?.parentSha !== cycle.parent
176
+ )
177
+ return []
178
+ if (state.integration?.failures?.some((failure) => failure.id === cycle.id)) return []
179
+ const steps = [
180
+ ...new Set(
181
+ state.verify.results
182
+ .filter(
183
+ (result) =>
184
+ result.seq > cycle.seq &&
185
+ result.restackId === cycle.id &&
186
+ result.headSha === cycle.head &&
187
+ result.baseSha === cycle.parent &&
188
+ result.outcome === 'fail',
189
+ )
190
+ .map((result) => result.step),
191
+ ),
192
+ ]
193
+ return steps.length
194
+ ? [
195
+ {
196
+ id: cycle.id,
197
+ head: cycle.head,
198
+ parent: cycle.parent,
199
+ steps,
200
+ guidance: `file a repair child targeting this node: ${slug}`,
201
+ },
202
+ ]
203
+ : []
204
+ }
@@ -1,13 +1,18 @@
1
1
  import type { BuildState } from './reducer'
2
2
  import { discardInFlight } from './reducer'
3
3
  import type { LeafRestackState } from './leaf-restack-state'
4
- import { integrationCurrent, integrationCycleVerified } from './integration-state'
4
+ import {
5
+ integrationCurrent,
6
+ integrationCycleVerified,
7
+ integrationCycleCurrent,
8
+ } from './integration-state'
5
9
 
6
10
  /** The deterministic part of land's guard. Live completeness and CAS remain at the write boundary. */
7
11
  export function landPreconditions(state: BuildState, restack: LeafRestackState): boolean {
8
12
  const decision = state.landing?.decision
9
13
  return (
10
14
  !!decision &&
15
+ (state.kind !== 'node' || integrationCycleCurrent(state)) &&
11
16
  state.status !== 'paused' &&
12
17
  !state.currentPhase &&
13
18
  !state.openEscalations.length &&
@@ -1,9 +1,42 @@
1
+ import type { RuntimeIdentity } from '../events/runtime'
1
2
  import type { CompatibilityState } from '../events/compatibility'
2
3
  import type { BuildState } from './reducer'
3
4
  import type { BuildStore } from '../store/types'
4
5
  import type { Actor } from '../events/envelope'
5
6
  import { readBuildFacts } from '../store/reduced-reads'
6
7
 
8
+ const drainingExecutions = new WeakMap<BuildStore, { instance: string; runtime: RuntimeIdentity }>()
9
+ /** Carry the caller's own immutable execution identity through nested kernel
10
+ * helpers without adding repository authority to a build-scoped store. */
11
+ export function withDrainingExecution<T extends BuildStore>(
12
+ store: T,
13
+ instance: string,
14
+ runtime: RuntimeIdentity,
15
+ ): T {
16
+ const scoped = new Proxy(store, {
17
+ get(target, key) {
18
+ const value = Reflect.get(target, key, target)
19
+ return typeof value === 'function' ? value.bind(target) : value
20
+ },
21
+ })
22
+ drainingExecutions.set(scoped, { instance, runtime })
23
+ return scoped
24
+ }
25
+ async function authorizedDrainingExecution(store: BuildStore, slug: string): Promise<boolean> {
26
+ const execution = drainingExecutions.get(store)
27
+ if (!execution) return false
28
+ const authorization = (await readBuildFacts(store, slug)).value.state.drainingExecutions?.[
29
+ execution.instance
30
+ ]?.authorization
31
+ return (
32
+ !!authorization &&
33
+ authorization.runtime.version === execution.runtime.version &&
34
+ authorization.runtime.commit === execution.runtime.commit &&
35
+ authorization.runtime.source.kind === execution.runtime.source.kind &&
36
+ authorization.runtime.source.location === execution.runtime.source.location
37
+ )
38
+ }
39
+
7
40
  export function compatibilityDiagnostic(facts: CompatibilityState): string | undefined {
8
41
  if (facts.decisiveFacts === 0) return undefined
9
42
  const versions = facts.decisiveWriterVersions.length
@@ -28,6 +61,7 @@ export async function deferMixedVersion(
28
61
  const { state } = (await readBuildFacts(store, slug)).value
29
62
  const diagnostic = compatibilityDiagnostic(state.compatibility)
30
63
  if (!diagnostic) return false
64
+ if (await authorizedDrainingExecution(store, slug)) return true
31
65
  const facts = state.compatibility
32
66
  if (state.compatibilityDeferredBoundary === facts.decisiveBoundary) return true
33
67
  const written = await store.appendIfCurrent(slug, state.lastSeq, {
@@ -1,3 +1,4 @@
1
+ import { currentTicketRef, readTicketMigrations, resolveTicketRef } from './ticket-migrations'
1
2
  import { randomUUID } from 'node:crypto'
2
3
  import { DISPATCHER } from '../events/envelope'
3
4
  import type { EventPayload } from '../events/payloads'
@@ -26,17 +27,29 @@ function refuse(message: string): never {
26
27
  throw new TicketOperationError('refusal', message)
27
28
  }
28
29
  export async function newestTicketBuild(ctx: ParentContext, ticket: Ticket) {
29
- const namespace = (source: string) =>
30
- source === 'database' && ctx.configuredSource === 'hosted' ? 'hosted' : source
31
- const candidates = (await ctx.store.listBuildsForRepo(ctx.repo)).filter(
32
- (b) => b.ticket && namespace(b.ticket.source) === namespace(ticket.ref.source),
33
- )
30
+ const candidates = await ctx.store.listBuildsForRepo(ctx.repo)
31
+ if (!candidates.length) return undefined
32
+ const migrations = await readTicketMigrations(ctx.store, ctx.repo)
34
33
  const matches: BuildRecord[] = []
35
34
  for (const build of candidates) {
36
- if (build.ticket!.id === ticket.ref.id) matches.push(build)
37
- else if (
38
- ctx.configuredSource === 'hosted' &&
39
- (await ctx.source.get(build.ticket!.id))?.ref.id === ticket.ref.id
35
+ if (!build.ticket) continue
36
+ let ref = build.ticket
37
+ try {
38
+ ref = resolveTicketRef(
39
+ migrations,
40
+ build.ticket,
41
+ ctx.source.name === 'database' && ctx.configuredSource === 'hosted'
42
+ ? 'hosted'
43
+ : ctx.source.name,
44
+ build.slug,
45
+ )
46
+ } catch {
47
+ continue
48
+ }
49
+ if (
50
+ ref.id === ticket.ref.id ||
51
+ (ctx.configuredSource === 'hosted' &&
52
+ (await ctx.source.get(ref.id))?.ref.id === ticket.ref.id)
40
53
  )
41
54
  matches.push(build)
42
55
  }
@@ -124,7 +137,19 @@ export async function updateTicketTarget(
124
137
  if (!record) return updateTicket(ctx.source, id, canonicalPatch, true, expectedRevision)
125
138
  let state = (await readBuildFacts(ctx.store, record.slug)).value.state
126
139
  const active = state.status !== 'done' && state.status !== 'aborted'
127
- const frozenId = state.target?.ticket.id
140
+ const frozenId = state.target
141
+ ? (
142
+ await currentTicketRef(
143
+ ctx.store,
144
+ ctx.repo,
145
+ ctx.source.name === 'database' && ctx.configuredSource === 'hosted'
146
+ ? 'hosted'
147
+ : ctx.source.name,
148
+ state.target.ticket,
149
+ record.slug,
150
+ )
151
+ ).id
152
+ : undefined
128
153
  const effective =
129
154
  frozenId === undefined ? undefined : ((await ctx.source.get(frozenId))?.ref.id ?? frozenId)
130
155
  if (state.kind !== 'node') {
@@ -0,0 +1,160 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { AbEvent } from '../events/catalog'
3
+ import type { BuildState } from './reducer'
4
+
5
+ export interface NodePollingPolicy {
6
+ nodeIdleAfterSeconds: number
7
+ nodeIdlePollSeconds: number
8
+ }
9
+
10
+ /** Canonical serialization also survives JSONB key reordering. */
11
+ function canonical(value: unknown): string {
12
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
13
+ if (value !== null && typeof value === 'object')
14
+ return `{${Object.entries(value)
15
+ .sort(([a], [b]) => a.localeCompare(b))
16
+ .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)
17
+ .join(',')}}`
18
+ return JSON.stringify(value) ?? 'null'
19
+ }
20
+
21
+ const observations = new Set([
22
+ 'node.compared',
23
+ 'node.parent-distance',
24
+ 'integration.observed',
25
+ 'target.moved',
26
+ 'node.inventory',
27
+ 'landing.decided',
28
+ 'node.parent-rejected',
29
+ ])
30
+
31
+ /** Commands retain identity, even repeated holds. Observations retain meaning.
32
+ * The bounded map has at most one entry per event type, never per log entry. */
33
+ export function advancePollingActivity(activity: Record<string, string>, event: AbEvent): void {
34
+ if (
35
+ event.type === 'node.poll-checked' ||
36
+ event.type === 'observation.recorded' ||
37
+ event.type.startsWith('session.') ||
38
+ event.type.startsWith('runner.') ||
39
+ event.type.startsWith('workspace.') ||
40
+ event.type.startsWith('build.janitor-')
41
+ )
42
+ return
43
+ activity[event.type] = observations.has(event.type) ? canonical(event.payload) : String(event.seq)
44
+ }
45
+
46
+ export function nodeActivityKey(
47
+ state: Pick<BuildState, 'pollingActivity'>,
48
+ children: readonly { slug: string; state: Pick<BuildState, 'pollingActivity'> }[],
49
+ ): string {
50
+ return createHash('sha256')
51
+ .update(
52
+ canonical({
53
+ own: state.pollingActivity,
54
+ children: children
55
+ .map(({ slug, state: child }) => ({ slug, activity: child.pollingActivity }))
56
+ .sort((a, b) => a.slug.localeCompare(b.slug)),
57
+ }),
58
+ )
59
+ .digest('hex')
60
+ }
61
+
62
+ /** Ticket membership needs claims, PR lifecycle and operator demand, not each
63
+ * plan/review/verification event that keeps GitHub observation active. */
64
+ export function nodeTicketObservationKey(
65
+ state: Pick<BuildState, 'pollingActivity'>,
66
+ children: readonly { slug: string; state: Pick<BuildState, 'pollingActivity'> }[],
67
+ ): string {
68
+ const select = (activity: BuildState['pollingActivity'], types: readonly string[]) =>
69
+ Object.fromEntries(
70
+ types.flatMap((type) => (activity?.[type] === undefined ? [] : [[type, activity[type]]])),
71
+ )
72
+ return nodeActivityKey(
73
+ {
74
+ pollingActivity: select(state.pollingActivity, [
75
+ 'build.land-requested',
76
+ 'build.hold-requested',
77
+ 'node.restack-requested',
78
+ 'escalation.answered',
79
+ 'node.parent-requested',
80
+ 'node.parent-accepted',
81
+ ]),
82
+ },
83
+ children.map((child) => ({
84
+ slug: child.slug,
85
+ state: {
86
+ pollingActivity: select(child.state.pollingActivity, [
87
+ 'build.created',
88
+ 'pr.opened',
89
+ 'finalize.completed',
90
+ 'pr.merged',
91
+ 'pr.closed',
92
+ 'build.completed',
93
+ 'build.aborted',
94
+ 'node.contribution-recorded',
95
+ 'integration.landed',
96
+ ]),
97
+ },
98
+ })),
99
+ )
100
+ }
101
+
102
+ /** Pending operations always bypass cadence; hold and absent consent do not. */
103
+ export function nodePollingUnsettled(state: BuildState): boolean {
104
+ return (
105
+ !state.nodeOpened ||
106
+ !state.nodeComparison ||
107
+ state.nodeRestack?.distance?.count === null ||
108
+ !!state.currentPhase ||
109
+ state.status === 'done' ||
110
+ state.status === 'aborted' ||
111
+ state.prState === 'closed' ||
112
+ state.prState === 'merged' ||
113
+ state.pendingCommands.length > 0 ||
114
+ state.sessions.open.length > 0 ||
115
+ !!state.landing?.native?.operation ||
116
+ !!state.landing?.native?.enabled ||
117
+ !!state.landing?.nativeEnablePending ||
118
+ !!state.landing?.applicationFailure ||
119
+ !!(
120
+ state.pr &&
121
+ state.landing?.command &&
122
+ state.landing.command.seq !== state.landing.acknowledgedSeq
123
+ ) ||
124
+ !!state.nodeRestack?.active ||
125
+ !!state.nodeRestack?.parentRequest ||
126
+ !!state.nodeRestack?.parentChange ||
127
+ Object.keys(state.nodeRestack?.requests ?? {}).length > 0 ||
128
+ !!state.integration?.intent
129
+ )
130
+ }
131
+
132
+ export function nodePollingSchedule(
133
+ state: BuildState,
134
+ activityKey: string,
135
+ policy: NodePollingPolicy,
136
+ now: Date,
137
+ unsettled = nodePollingUnsettled(state),
138
+ ) {
139
+ const check = state.nodePolling
140
+ const time = now.getTime()
141
+ const checked = Date.parse(check?.checkedAt ?? '')
142
+ const unchanged = Date.parse(check?.unchangedSince ?? '')
143
+ const idle =
144
+ !unsettled &&
145
+ check?.activityKey === activityKey &&
146
+ check.nodeIdleAfterSeconds === policy.nodeIdleAfterSeconds &&
147
+ check.nodeIdlePollSeconds === policy.nodeIdlePollSeconds &&
148
+ Number.isFinite(time) &&
149
+ Number.isFinite(checked) &&
150
+ Number.isFinite(unchanged) &&
151
+ unchanged <= checked &&
152
+ checked <= time &&
153
+ time - unchanged >= policy.nodeIdleAfterSeconds * 1000
154
+ return {
155
+ mode: idle ? ('idle' as const) : ('active' as const),
156
+ due: !idle || time - checked >= policy.nodeIdlePollSeconds * 1000,
157
+ intervalSeconds: policy.nodeIdlePollSeconds,
158
+ lastChecked: check?.checkedAt,
159
+ }
160
+ }