@defrex/autobuild 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto'
1
2
  import type { TicketRef } from '../ontology'
2
3
  import type { BuildRecord, BuildDigest } from '../store/types'
3
4
  import type { CurrentBuildFacts } from '../store/reduced-reads'
@@ -102,24 +103,83 @@ export async function observePresence(
102
103
  aliases = new Map<string, string>(),
103
104
  includeForeign = false,
104
105
  ): Promise<ChangeIdentity[]> {
106
+ return projectPresence(await presenceWitness(git, head), landings, aliases, includeForeign)
107
+ }
108
+
109
+ export interface PresenceWitness {
110
+ version: 1
111
+ commits: string[]
112
+ identities: `build:${string}`[]
113
+ }
114
+
115
+ export async function presenceWitness(git: NodeGit, head: string): Promise<PresenceWitness> {
105
116
  const commits = await history(git, [head])
117
+ return {
118
+ version: 1,
119
+ commits: [...new Set(commits.map((commit) => commit.sha))].sort(),
120
+ identities: [
121
+ ...new Set(
122
+ commits.flatMap((commit) =>
123
+ buildTrailers(commit.message).map((slug) => `build:${slug}` as const),
124
+ ),
125
+ ),
126
+ ].sort(),
127
+ }
128
+ }
129
+
130
+ export function presenceEvidence(witness: PresenceWitness, identities: ChangeIdentity[]): string {
131
+ return `presence-v3:${createHash('sha256')
132
+ .update(
133
+ JSON.stringify([
134
+ witness.version,
135
+ [...new Set(witness.commits)].sort(),
136
+ normalizeIdentities(witness.identities),
137
+ normalizeIdentities(identities),
138
+ ]),
139
+ )
140
+ .digest('hex')}`
141
+ }
142
+
143
+ export function projectPresence(
144
+ witness: PresenceWitness,
145
+ landings: LandingEvidence[],
146
+ aliases = new Map<string, string>(),
147
+ includeForeign = false,
148
+ ): ChangeIdentity[] {
106
149
  const proofs: ChangeIdentity[] = []
107
- const result: ChangeIdentity[] = []
150
+ const result: ChangeIdentity[] = [...witness.identities]
108
151
  const relevantForeign = new Set(
109
152
  landings
110
153
  .flatMap((landing) => landing.contribution ?? [])
111
154
  .filter((id) => id.startsWith('foreign:')),
112
155
  )
113
- for (const commit of commits) {
114
- for (const build of buildTrailers(commit.message)) result.push(`build:${build}`)
115
- const foreign: ChangeIdentity = `foreign:${originalForeign(commit.sha, aliases)}`
116
- proofs.push(foreign, `foreign:${commit.sha}`)
117
- if (includeForeign || aliases.has(commit.sha) || relevantForeign.has(foreign))
118
- result.push(foreign)
156
+ for (const sha of witness.commits) {
157
+ const foreign: ChangeIdentity = `foreign:${originalForeign(sha, aliases)}`
158
+ proofs.push(foreign, `foreign:${sha}`)
159
+ if (includeForeign || aliases.has(sha) || relevantForeign.has(foreign)) result.push(foreign)
119
160
  }
120
161
  return expandLandings(result, proofs, landings)
121
162
  }
122
163
 
164
+ /** Only aliases belonging to this destination's accepted ancestry are relevant. */
165
+ export function destinationAliases(
166
+ inputs: PresenceInputs,
167
+ destination?: string,
168
+ ): Map<string, string> {
169
+ const aliases = new Map<string, string>()
170
+ const seen = new Set<string>()
171
+ while (destination) {
172
+ if (seen.has(destination)) throw new Error('cyclic destination ancestry')
173
+ seen.add(destination)
174
+ const state = inputs.states.get(destination)
175
+ if (!state) throw new Error('missing destination ancestry')
176
+ for (const [sha, original] of Object.entries(state.nodeRestack?.foreignAliases ?? {}))
177
+ aliases.set(sha, original)
178
+ destination = state.target?.build
179
+ }
180
+ return aliases
181
+ }
182
+
123
183
  /** Reconstruct a historical node contribution only from its retained source
124
184
  * range. The caller must establish the source head and confirmed landing. */
125
185
  export async function ownedContribution(
@@ -158,6 +218,7 @@ export async function presenceInputs(
158
218
  store: { buildFacts(slug: string): Promise<CurrentBuildFacts> },
159
219
  entries: PresenceBuild[],
160
220
  destinations: Iterable<string> = [],
221
+ landings = confirmedLandings(entries),
161
222
  ): Promise<PresenceInputs> {
162
223
  const states = new Map<string, BuildState>()
163
224
  const aliases = new Map<string, string>()
@@ -171,6 +232,11 @@ export async function presenceInputs(
171
232
  aliases.set(sha, original)
172
233
  if (state.target) pending.push(state.target.build)
173
234
  }
235
+ return { entries, states, aliases, landings }
236
+ }
237
+
238
+ /** Shared once per dispatcher tick from the existing batched digest read. */
239
+ export function confirmedLandings(entries: PresenceBuild[]): LandingEvidence[] {
174
240
  const landings: LandingEvidence[] = []
175
241
  for (const { record, digest } of entries) {
176
242
  if (!digest.mergedSha || digest.terminal === 'aborted' || digest.prClosed) continue
@@ -183,5 +249,5 @@ export async function presenceInputs(
183
249
  })
184
250
  } else landings.push({ slug: record.slug, sha: digest.mergedSha })
185
251
  }
186
- return { entries, states, aliases, landings }
252
+ return landings
187
253
  }
@@ -394,6 +394,14 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
394
394
  // ── 4. Spec (§6.3: dispatch owns the import; `spec` is not a phase §5) ─────
395
395
  if (state.specRev === undefined) return { kind: 'wait', reason: 'awaiting-spec' }
396
396
 
397
+ // A revised contract invalidates approvals, but an unfinished replay still
398
+ // belongs to its reconcile occurrence. Publish it before opening the new
399
+ // plan loop so no other phase inherits its detached/conflicted workspace.
400
+ if (state.currentPhase?.phase === 'reconcile' && state.currentPhase.seq < log.restartSeq) {
401
+ const attempt = state.currentPhase.attempt ?? state.reconcileAttempts
402
+ return { kind: 'run-phase', phase: 'reconcile', round: attempt, reconcile: { attempt } }
403
+ }
404
+
397
405
  // ── Shared routing inputs ──────────────────────────────────────────────────
398
406
 
399
407
  // dismiss-finding contributes the raised escalation's refs to the dismissed
@@ -19,6 +19,20 @@ export function nodeRestackLog(): AbEvent[] {
19
19
  },
20
20
  },
21
21
  { actor: DISPATCHER, type: 'node.opened', payload: { sha: 'd'.repeat(40) } },
22
+ {
23
+ actor: KERNEL,
24
+ type: 'node.restack-availability-observed',
25
+ payload: {
26
+ version: 1,
27
+ fingerprint: 'assessment',
28
+ branch: 'ab-node/node',
29
+ parentBranch: 'main',
30
+ head: expected,
31
+ parent,
32
+ base: 'd'.repeat(40),
33
+ available: [],
34
+ },
35
+ },
22
36
  {
23
37
  actor: KERNEL,
24
38
  type: 'node.writer-reserved',
@@ -129,27 +129,60 @@ export function nodePollingUnsettled(state: BuildState): boolean {
129
129
  )
130
130
  }
131
131
 
132
- export function nodePollingSchedule(
132
+ /** Valid scheduling evidence may be reused across processes, never across activity epochs. */
133
+ export function nodePollingEvidenceValid(
133
134
  state: BuildState,
134
135
  activityKey: string,
135
136
  policy: NodePollingPolicy,
136
137
  now: Date,
137
- unsettled = nodePollingUnsettled(state),
138
- ) {
138
+ ): boolean {
139
139
  const check = state.nodePolling
140
140
  const time = now.getTime()
141
141
  const checked = Date.parse(check?.checkedAt ?? '')
142
142
  const unchanged = Date.parse(check?.unchangedSince ?? '')
143
- const idle =
144
- !unsettled &&
143
+ return (
145
144
  check?.activityKey === activityKey &&
146
145
  check.nodeIdleAfterSeconds === policy.nodeIdleAfterSeconds &&
147
146
  check.nodeIdlePollSeconds === policy.nodeIdlePollSeconds &&
148
147
  Number.isFinite(time) &&
149
148
  Number.isFinite(checked) &&
150
149
  Number.isFinite(unchanged) &&
151
- unchanged <= checked &&
152
- checked <= time &&
150
+ // The anchor uses the dispatcher clock; checkedAt uses the store clock.
151
+ // Validate each against now without imposing an order across clocks.
152
+ unchanged <= time &&
153
+ checked <= time
154
+ )
155
+ }
156
+
157
+ /** Successful unchanged active observations need no additional durable record. */
158
+ export function nodePollingCheckpointRequired(
159
+ state: BuildState,
160
+ activityKey: string,
161
+ policy: NodePollingPolicy,
162
+ now: Date,
163
+ ): boolean {
164
+ if (!nodePollingEvidenceValid(state, activityKey, policy, now)) return true
165
+ const check = state.nodePolling!
166
+ return (
167
+ now.getTime() - Date.parse(check.unchangedSince) >= policy.nodeIdleAfterSeconds * 1000 &&
168
+ now.getTime() - Date.parse(check.checkedAt) >= policy.nodeIdlePollSeconds * 1000
169
+ )
170
+ }
171
+
172
+ export function nodePollingSchedule(
173
+ state: BuildState,
174
+ activityKey: string,
175
+ policy: NodePollingPolicy,
176
+ now: Date,
177
+ unsettled = nodePollingUnsettled(state),
178
+ ) {
179
+ const check = state.nodePolling
180
+ const time = now.getTime()
181
+ const checked = Date.parse(check?.checkedAt ?? '')
182
+ const unchanged = Date.parse(check?.unchangedSince ?? '')
183
+ const idle =
184
+ !unsettled &&
185
+ nodePollingEvidenceValid(state, activityKey, policy, now) &&
153
186
  time - unchanged >= policy.nodeIdleAfterSeconds * 1000
154
187
  return {
155
188
  mode: idle ? ('idle' as const) : ('active' as const),
@@ -1,3 +1,5 @@
1
+ import { createHash } from 'node:crypto'
2
+ import type { PresenceInputs } from './change-presence'
1
3
  import type { BuildState } from './reducer'
2
4
  import { integrationComplete, integrationFailed } from './integration-state'
3
5
 
@@ -27,3 +29,75 @@ export function presenceRestackPath(
27
29
  .flatMap((entry) => (entry.slug && requested.has(entry.slug) ? [entry.slug] : []))
28
30
  .reverse()
29
31
  }
32
+
33
+ /** Canonical semantic evidence only: polling facts and journal positions do not
34
+ * invalidate an assessment, but unchanged-head landing proofs do. */
35
+ export function restackAvailabilityFingerprint(
36
+ state: BuildState,
37
+ branch: string,
38
+ parentBranch: string,
39
+ head: string,
40
+ parent: string,
41
+ evidence: PresenceInputs,
42
+ landingKey = restackLandingKey(evidence.landings),
43
+ ): string {
44
+ const requests = Object.values(state.nodeRestack?.requests ?? {})
45
+ .map((r) => [
46
+ r.id,
47
+ r.reason,
48
+ r.branch,
49
+ r.parent,
50
+ r.dependent?.source,
51
+ r.dependent?.id,
52
+ [...new Set(r.identities ?? [])].sort(),
53
+ ])
54
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])))
55
+ const ancestry = [...evidence.states]
56
+ .map(([slug, s]) => [
57
+ slug,
58
+ s.target?.build,
59
+ s.baseBranch,
60
+ Object.entries(s.nodeRestack?.foreignAliases ?? {}).sort(([a], [b]) => a.localeCompare(b)),
61
+ ])
62
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])))
63
+ return createHash('sha256')
64
+ .update(
65
+ JSON.stringify([
66
+ 1,
67
+ branch,
68
+ parentBranch,
69
+ head,
70
+ parent,
71
+ state.nodeRestack?.contributionBase,
72
+ requests,
73
+ ancestry,
74
+ landingKey,
75
+ ]),
76
+ )
77
+ .digest('hex')
78
+ }
79
+
80
+ export function actionableRestackDemand(state: BuildState, fingerprint: string): boolean {
81
+ const observation = state.nodeRestack?.availability
82
+ if (observation?.version !== 1 || observation.fingerprint !== fingerprint)
83
+ return nodeRestackDemand(state)
84
+ return nodeRestackDemand({
85
+ ...state,
86
+ nodeRestack: {
87
+ ...state.nodeRestack!,
88
+ requests: Object.fromEntries(
89
+ Object.entries(state.nodeRestack?.requests ?? {}).filter(
90
+ ([id, request]) => request.reason === 'operator' || observation.available.includes(id),
91
+ ),
92
+ ),
93
+ },
94
+ })
95
+ }
96
+
97
+ /** Hash shared landing evidence once, not once per considered node. */
98
+ export function restackLandingKey(landings: PresenceInputs['landings']): string {
99
+ const canonical = landings
100
+ .map((l) => [l.slug, l.sha, [...new Set(l.contribution ?? [])].sort()])
101
+ .sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)))
102
+ return createHash('sha256').update(JSON.stringify(canonical)).digest('hex')
103
+ }
@@ -19,6 +19,7 @@ export function sameParentRejection(
19
19
  * holder resumes these immutable inputs before admitting another operation. */
20
20
  export interface NodeRestackState {
21
21
  requests?: Record<string, EventPayload<'node.restack-requested'>>
22
+ availability?: EventPayload<'node.restack-availability-observed'>
22
23
  distance?: EventPayload<'node.parent-distance'>
23
24
  parentRequest?: EventPayload<'node.parent-requested'>
24
25
  parentChange?: EventPayload<'node.parent-accepted'>
@@ -50,6 +51,9 @@ export function advanceNodeRestack(state: NodeRestackState, events: readonly AbE
50
51
  case 'node.restack-satisfied':
51
52
  if (state.requests) delete state.requests[event.payload.id]
52
53
  break
54
+ case 'node.restack-availability-observed':
55
+ state.availability = event.payload
56
+ break
53
57
  case 'node.parent-distance':
54
58
  state.distance = event.payload
55
59
  break
@@ -214,7 +218,7 @@ export function advanceNodeRestack(state: NodeRestackState, events: readonly AbE
214
218
  }
215
219
  }
216
220
  export const nodeRestackReducer = defineReducer<NodeRestackState, AbEvent, NodeRestackState>({
217
- version: 7,
221
+ version: 8,
218
222
  initial: () => ({ items: [] }),
219
223
  fold: advanceNodeRestack,
220
224
  finish: (state) => structuredClone(state),
@@ -1,4 +1,4 @@
1
- import { nodeRestackDemand } from './node-restack-demand'
1
+ import { nodeRestackDemand, restackAvailabilityFingerprint } from './node-restack-demand'
2
2
  import { deferMixedVersion, MixedVersionDeferral } from './mixed-version'
3
3
  import { suspendNativeLanding } from './landing-publication'
4
4
  import { observePresence, presenceInputs } from './change-presence'
@@ -18,6 +18,9 @@ import {
18
18
  } from './node-restack'
19
19
 
20
20
  export interface NodeTransactionDeps extends RestackDeps {
21
+ /** Confirm targeting-leaf native landing suspension before reservation and
22
+ * again when recovering a frozen replay. Operation identities survive restart. */
23
+ beforeReplay?: (operation: string) => Promise<void>
21
24
  holder: string
22
25
  /** Lifecycle and writer authority are rechecked at each effect boundary. */
23
26
  canWrite: () => Promise<boolean>
@@ -162,6 +165,29 @@ export async function runNodeTransaction(
162
165
  request.branch === input.parentBranch &&
163
166
  (request.identities ?? []).every((id) => new Set<string>(upstream).has(id)),
164
167
  )
168
+ const fingerprint = restackAvailabilityFingerprint(
169
+ state,
170
+ input.branch,
171
+ input.parentBranch,
172
+ expected,
173
+ parent,
174
+ evidence,
175
+ )
176
+ if (node?.availability?.fingerprint !== fingerprint)
177
+ await append({
178
+ actor: KERNEL,
179
+ type: 'node.restack-availability-observed',
180
+ payload: {
181
+ version: 1,
182
+ fingerprint,
183
+ branch: input.branch,
184
+ parentBranch: input.parentBranch,
185
+ head: expected,
186
+ parent,
187
+ base,
188
+ available: availableRequests.map((r) => r.id).sort(),
189
+ },
190
+ })
165
191
  const demanded = nodeRestackDemand({
166
192
  ...state,
167
193
  nodeRestack: {
@@ -183,6 +209,10 @@ export async function runNodeTransaction(
183
209
  })
184
210
  return 'idle'
185
211
  }
212
+ await deps.beforeReplay?.(input.id)
213
+ await authority(deps)
214
+ if ((await current(deps.store, deps.slug)).lastSeq !== revision)
215
+ throw new Error('node inputs changed during native cancellation')
186
216
  const frozen = await prepareNodeReplay(deps, { oldBase, oldHead: expected, parent }, evidence)
187
217
  // Preserve frozen source objects before the reservation can survive a
188
218
  // workspace loss. Archives also retain the previous boundary's history.
@@ -236,6 +266,8 @@ export async function runNodeTransaction(
236
266
  })
237
267
  return runNodeTransaction(deps, input)
238
268
  }
269
+ await deps.beforeReplay?.(active.id)
270
+ await authority(deps)
239
271
  const frozen = { ...active, oldHead: active.expected }
240
272
  assertSafeNodeReplay(frozen)
241
273
  const replayEvidence = {
@@ -1,3 +1,4 @@
1
+ import { ticketPreparationReducer } from './ticket-preparation'
1
2
  import { ticketMigrationsReducer } from './ticket-migrations'
2
3
  import { dispatchUpgradeReducer } from './dispatch-upgrade'
3
4
  import {
@@ -481,6 +482,7 @@ import { dispatchStatusReducer } from './dispatch-status'
481
482
  * correlations outside it use the explicitly parameterized cache. */
482
483
  export const RECENT_DISPATCH_RUN_LIMIT = 16
483
484
  export interface RepositoryReadAcc {
485
+ preparation: ReturnType<typeof ticketPreparationReducer.initial>
484
486
  compatibility: CompatibilityState
485
487
  presence: Record<
486
488
  string,
@@ -534,6 +536,7 @@ export const repositoryReadFactsReducer = defineReducer({
534
536
  4 +
535
537
  ticketMigrationsReducer.version +
536
538
  dispatchUpgradeReducer.version +
539
+ ticketPreparationReducer.version +
537
540
  dispatcherRunFactsReducer('version').version +
538
541
  openHarvestExecutionsReducer.version +
539
542
  forgeHealthReducer.version +
@@ -548,6 +551,7 @@ export const repositoryReadFactsReducer = defineReducer({
548
551
  initial: (): RepositoryReadAcc => ({
549
552
  compatibility: initialCompatibility(),
550
553
  presence: {},
554
+ preparation: ticketPreparationReducer.initial(),
551
555
  upgrades: dispatchUpgradeReducer.initial(),
552
556
  recentRuns: [],
553
557
  openHarvest: openHarvestExecutionsReducer.initial(),
@@ -573,6 +577,7 @@ export const repositoryReadFactsReducer = defineReducer({
573
577
  publications: [],
574
578
  }),
575
579
  fold(acc: RepositoryReadAcc, events: readonly RepositoryEvent[]) {
580
+ acc.preparation = ticketPreparationReducer.advance(acc.preparation, events)
576
581
  advanceCompatibility(acc.compatibility, events)
577
582
  acc.upgrades = dispatchUpgradeReducer.advance(acc.upgrades, events)
578
583
  acc.attention = repositoryAttentionReducer.advance(acc.attention, events)
@@ -683,6 +688,7 @@ export const repositoryReadFactsReducer = defineReducer({
683
688
  finish: (acc: RepositoryReadAcc) => ({
684
689
  compatibility: structuredClone(acc.compatibility),
685
690
  presence: structuredClone(acc.presence),
691
+ preparation: ticketPreparationReducer.finish(acc.preparation),
686
692
  upgrades: dispatchUpgradeReducer.finish(acc.upgrades),
687
693
  harvestFailures: structuredClone(acc.harvestFailures),
688
694
  harvestVerdicts: structuredClone(acc.harvestVerdicts),
@@ -1,3 +1,4 @@
1
+ import { ticketPreparationReducer } from './ticket-preparation'
1
2
  import { ticketMigrationsReducer } from './ticket-migrations'
2
3
  import { dispatchUpgradeReducer } from './dispatch-upgrade'
3
4
  import { forgeHealthReducer } from './forge-health'
@@ -87,6 +88,7 @@ export interface RegisteredReducer {
87
88
  /** Parameterized reducers are registered with representative arguments; the
88
89
  * accumulator shape does not depend on them. */
89
90
  const REGISTERED: Record<string, Omit<RegisteredReducer, 'valueRead'>> = {
91
+ ticketPreparation: { reducer: ticketPreparationReducer, covers: [] },
90
92
  ticketMigrations: { reducer: ticketMigrationsReducer, covers: [] },
91
93
  nodeRestack: { reducer: nodeRestackReducer, covers: ['advanceNodeRestack'] },
92
94
  leafRestack: { reducer: leafRestackReducer, covers: ['advanceLeafRestack'] },
@@ -215,6 +217,7 @@ const valueExclusions: Record<string, string> = {
215
217
  ),
216
218
  }
217
219
  const repositoryValues = new Set([
220
+ 'ticketPreparation',
218
221
  'ticketMigrations',
219
222
  'forgeHealthValue',
220
223
  'repositoryReadFacts',
@@ -1,3 +1,4 @@
1
+ import type { SelectedAccount } from '../config/accounts'
1
2
  import {
2
3
  advanceVerifyStage,
3
4
  initialVerifyStageState,
@@ -118,6 +119,7 @@ export interface OpenSession {
118
119
  nativeHandle?: NativeSessionHandle
119
120
  continuation?: EventPayload<'session.started'>['continuation']
120
121
  budgetMs?: number
122
+ account?: SelectedAccount
121
123
  args?: string[]
122
124
  startedAt: string
123
125
  nativeResumeFallback?: boolean
@@ -463,7 +465,7 @@ export interface BuildAcc {
463
465
  }
464
466
 
465
467
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
466
- export const BUILD_REDUCER_VERSION = 24
468
+ export const BUILD_REDUCER_VERSION = 26
467
469
 
468
470
  function initialBuildAcc(): BuildAcc {
469
471
  return {
@@ -865,6 +867,7 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
865
867
  continuation: event.payload.continuation,
866
868
  budgetMs: event.payload.budgetMs,
867
869
  args: event.payload.args,
870
+ account: event.payload.account,
868
871
  startedAt: event.ts,
869
872
  nativeHandle: event.payload.continuation?.handle,
870
873
  session: event.payload.session,
@@ -0,0 +1,66 @@
1
+ import type { RepositoryEvent } from '../events/repository'
2
+ import type { TicketRef } from '../ontology'
3
+ import { defineReducer } from './incremental'
4
+
5
+ export interface TicketPreparation {
6
+ attempt: string
7
+ ticket: TicketRef
8
+ readyState: string
9
+ claimedState: string
10
+ claimed: boolean
11
+ slug?: string
12
+ handback?: string
13
+ stage?: string
14
+ error?: string
15
+ recoveryError?: string
16
+ retryAt?: string
17
+ }
18
+ /** Completed attempts leave no historical entries in the canonical value. */
19
+ export const ticketPreparationReducer = defineReducer<
20
+ Record<string, TicketPreparation>,
21
+ RepositoryEvent,
22
+ Record<string, TicketPreparation>
23
+ >({
24
+ version: 1,
25
+ initial: () => ({}),
26
+ fold(acc, events) {
27
+ for (const event of events) {
28
+ if (event.type === 'ticket-preparation.intended') {
29
+ acc[event.payload.attempt] = { ...event.payload, claimed: false }
30
+ continue
31
+ }
32
+ if (!event.type.startsWith('ticket-preparation.')) continue
33
+ if (!('attempt' in event.payload)) continue
34
+ const held = acc[event.payload.attempt]
35
+ if (!held) continue
36
+ switch (event.type) {
37
+ case 'ticket-preparation.claimed':
38
+ held.claimed = true
39
+ break
40
+ case 'ticket-preparation.creation-selected':
41
+ held.slug = event.payload.slug
42
+ break
43
+ case 'ticket-preparation.handback-selected':
44
+ held.handback = event.payload.state
45
+ break
46
+ case 'ticket-preparation.failed':
47
+ held.claimed = event.payload.claimed
48
+ held.error ??= event.payload.error
49
+ held.stage = event.payload.stage
50
+ held.handback = event.payload.handback
51
+ break
52
+ case 'ticket-preparation.recovery-failed':
53
+ held.claimed ||= event.payload.claimed ?? false
54
+ if (event.payload.handback) held.handback = event.payload.handback
55
+ if (event.payload.preparationError) held.error ??= event.payload.preparationError
56
+ held.recoveryError = event.payload.error
57
+ held.retryAt = event.payload.retryAt
58
+ break
59
+ case 'ticket-preparation.resolved':
60
+ delete acc[event.payload.attempt]
61
+ break
62
+ }
63
+ }
64
+ },
65
+ finish: (acc) => structuredClone(acc),
66
+ })
@@ -86,6 +86,12 @@ export const OPERATOR_TOOL_ANNOTATIONS = {
86
86
  idempotentHint: false,
87
87
  approval: 'default',
88
88
  },
89
+ 'repository.forge_clear': {
90
+ readOnlyHint: false,
91
+ destructiveHint: false,
92
+ idempotentHint: false,
93
+ approval: 'default',
94
+ },
89
95
  'repository.status': {
90
96
  readOnlyHint: true,
91
97
  destructiveHint: false,
@@ -134,3 +134,23 @@ export async function controlHarvestRun(opts: {
134
134
  })
135
135
  return { action: projected.action, event }
136
136
  }
137
+
138
+ /** Explicit operator override. No history lookup or provider-success claim. */
139
+ export async function clearForgeDegradation(opts: {
140
+ store: BuildStore
141
+ repo: string
142
+ user: string
143
+ via?: Via
144
+ forge: string
145
+ reason: string
146
+ }): Promise<{ event: RepositoryEventEnvelope }> {
147
+ const forge = opts.forge.trim()
148
+ const reason = opts.reason.trim()
149
+ if (!forge || !reason || !opts.user.trim()) throw new Error('forge, reason and user are required')
150
+ const event = await opts.store.appendRepo(opts.repo, {
151
+ actor: humanActor(opts.user, opts.via),
152
+ type: 'dispatcher.forge-recovered',
153
+ payload: { forge, reason },
154
+ })
155
+ return { event }
156
+ }
@@ -17,6 +17,7 @@ export {
17
17
  ticketBlockerRequestSchema,
18
18
  ticketCreateRequestSchema,
19
19
  ticketMoveRequestSchema,
20
+ ticketPageSchema,
20
21
  ticketUpdateRequestSchema,
21
22
  } from './protocol'
22
23
  export type {
@@ -83,6 +84,7 @@ export type {
83
84
  OperatorTicketBuild,
84
85
  OperatorTicketContext,
85
86
  OperatorTicketDetail,
87
+ OperatorTicketPage,
86
88
  OperatorTicketQueue,
87
89
  } from './tickets'
88
90
  export {
@@ -139,3 +141,5 @@ export { listOperatorLandings } from './landings'
139
141
  export { readTicketTree, getOperatorTicketTree } from './tickets'
140
142
 
141
143
  export { requestNodeRestack } from './restack'
144
+
145
+ export { clearForgeDegradation } from './control'
@@ -79,6 +79,12 @@ export const ticketUpdateRequestSchema = z
79
79
  value.target !== undefined,
80
80
  'update must name at least one field',
81
81
  )
82
+ /** A window over a ticket listing; see `OperatorTicketPage`. */
83
+ export const ticketPageSchema = z.strictObject({
84
+ limit: z.number().int().min(0).max(200),
85
+ offset: z.number().int().min(0).optional(),
86
+ order: z.enum(['oldest', 'newest']).optional(),
87
+ })
82
88
  export const ticketMoveRequestSchema = z.strictObject({
83
89
  expectedRevision: expectedRevisionSchema,
84
90
  state: z.string().min(1),