@defrex/autobuild 1.15.0 → 1.17.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 (80) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +110 -10
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +41 -7
  5. package/docs/configuration.md +41 -7
  6. package/docs/dispatcher-hosting.md +3 -0
  7. package/docs/operator-api.md +15 -5
  8. package/docs/plugin-authoring.md +1 -0
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +3 -1
  11. package/docs/restacking.md +41 -1
  12. package/docs/setup.md +15 -6
  13. package/docs/troubleshooting.md +51 -3
  14. package/docs/workspaces.md +4 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/accounts.ts +3 -0
  17. package/packages/core/src/cli/binary-direct.ts +14 -1
  18. package/packages/core/src/cli/binary.ts +10 -7
  19. package/packages/core/src/cli/dispatch.ts +610 -356
  20. package/packages/core/src/cli/secrets.ts +2 -0
  21. package/packages/core/src/config/schema.ts +15 -2
  22. package/packages/core/src/events/payloads.ts +8 -5
  23. package/packages/core/src/events/repository.ts +12 -6
  24. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  25. package/packages/core/src/kernel/engine.ts +118 -0
  26. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  27. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  28. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  29. package/packages/core/src/ontology.ts +1 -0
  30. package/packages/core/src/operator/index.ts +10 -0
  31. package/packages/core/src/operator/merged-builds.ts +51 -0
  32. package/packages/core/src/operator/registry.ts +190 -101
  33. package/packages/core/src/operator/repo-argument.ts +43 -0
  34. package/packages/core/src/ports/tickets/grants.ts +2 -0
  35. package/packages/core/src/ports/tickets/remote.ts +2 -0
  36. package/packages/core/src/ports/types.ts +25 -4
  37. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +811 -169
  39. package/packages/core/src/processes/build-child.ts +15 -1
  40. package/packages/core/src/processes/build-runner.ts +349 -20
  41. package/packages/core/src/processes/dispatcher.ts +509 -104
  42. package/packages/core/src/processes/harvest-child.ts +21 -1
  43. package/packages/core/src/processes/harvest-runner.ts +82 -35
  44. package/packages/core/src/processes/invocation-budget.ts +6 -0
  45. package/packages/core/src/processes/launch-cut.ts +37 -0
  46. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  47. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  48. package/packages/core/src/processes/repo-view.ts +25 -4
  49. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  50. package/packages/core/src/store/adapter.ts +34 -5
  51. package/packages/core/src/store/build-feed.ts +148 -22
  52. package/packages/core/src/store/build-scope.ts +12 -3
  53. package/packages/core/src/store/caller-attribution.ts +170 -0
  54. package/packages/core/src/store/contract.ts +1038 -165
  55. package/packages/core/src/store/local/schema.ts +12 -1
  56. package/packages/core/src/store/local/store.ts +260 -25
  57. package/packages/core/src/store/memory.ts +156 -9
  58. package/packages/core/src/store/phase-session.ts +23 -3
  59. package/packages/core/src/store/reducer-value-shapes.json +5351 -5338
  60. package/packages/core/src/store/remote/client.ts +90 -11
  61. package/packages/core/src/store/remote/credentials.ts +2 -0
  62. package/packages/core/src/store/remote/index.ts +31 -5
  63. package/packages/core/src/store/remote/protocol.ts +45 -8
  64. package/packages/core/src/store/remote/released-clients.json +22 -0
  65. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  66. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  67. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  68. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  69. package/packages/core/src/store/session-handle.ts +12 -3
  70. package/packages/core/src/store/types.ts +48 -3
  71. package/packages/core/src/testing/reduced-read-budget.ts +310 -12
  72. package/skills/guide/SKILL.md +58 -9
  73. package/skills/guide/references/operator-api.md +15 -5
  74. package/skills/guide/references/plugin-authoring.md +1 -0
  75. package/skills/guide/references/remote-store-protocol.md +13 -3
  76. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  77. package/skills/guide/references/restacking.md +41 -1
  78. package/skills/guide/references/setup.md +15 -6
  79. package/skills/operate/SKILL.md +31 -7
  80. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,5 @@
1
1
  import { composeBuildConfig } from '../config/live'
2
+ import { withStoreCaller } from '../store/caller-attribution'
2
3
  import { readVerifyPipeline } from '../config/pipeline-source'
3
4
  import { guardForge } from '../kernel/guarded-forge'
4
5
  import { isRemoteWorkspace } from '../events/workspace-remote'
@@ -34,11 +35,24 @@ function message(error: unknown): string {
34
35
  * guest cannot resolve — guests never construct workspace providers, so a
35
36
  * provider plugin configured in autobuild.toml is skipped with a notice
36
37
  * instead of failing the build (AUT-517). */
37
- export async function runBuildChild(
38
+ export function runBuildChild(
38
39
  input: BuildExecutionStart,
39
40
  env: Record<string, string | undefined> = process.env,
40
41
  openStore: (ref: string, token?: string) => BuildStore = openProductionStore,
41
42
  opts: { guest?: boolean; shutdownSignal?: AbortSignal } = {},
43
+ ): Promise<void> {
44
+ // Every hosted request this runner makes is attributed to its build.
45
+ return withStoreCaller(
46
+ { kind: 'runner', runner: 'build', build: input.slug, execution: input.instance },
47
+ () => runBuildChildInScope(input, env, openStore, opts),
48
+ )
49
+ }
50
+
51
+ async function runBuildChildInScope(
52
+ input: BuildExecutionStart,
53
+ env: Record<string, string | undefined>,
54
+ openStore: (ref: string, token?: string) => BuildStore,
55
+ opts: { guest?: boolean; shutdownSignal?: AbortSignal },
42
56
  ): Promise<void> {
43
57
  const fullStore = openStore(input.storeRef, env.AB_TOKEN)
44
58
  const store = fullStore.scopeBuild(input.slug)
@@ -59,6 +59,17 @@ import {
59
59
  revocableConsent,
60
60
  } from '../kernel/consent-revocation'
61
61
  import { classifyGenerated, generatedSelectors } from '../kernel/generated-files'
62
+ import {
63
+ classifyTrackedDirt,
64
+ dirtyWorktreeArtifact,
65
+ dirtyWorktreeQuestion,
66
+ dirtyWorktreeSetAsideObservation,
67
+ listTrackedDirt,
68
+ mergePatches,
69
+ restoreTrackedPaths,
70
+ TrackedDirtRefusal,
71
+ type DirtyWorktreeOrigin,
72
+ } from '../kernel/tracked-dirt'
62
73
  import {
63
74
  regenerateConflict,
64
75
  RegenerationInterrupted,
@@ -75,6 +86,7 @@ import {
75
86
  publishRestack,
76
87
  retainReplay,
77
88
  requireRewrite,
89
+ settleTrackedDirt,
78
90
  } from '../kernel/reconcile-restack'
79
91
  import { RetainedHistoryUnavailable, restoreRetainedHead } from '../kernel/history-retention'
80
92
  import {
@@ -136,7 +148,7 @@ import type { AbEvent, EventEnvelope, EventWrite } from '../events/catalog'
136
148
  import type { EventPayload } from '../events/payloads'
137
149
  import { KERNEL, agentActor, type Actor } from '../events/envelope'
138
150
  import type { IdSource } from '../ids'
139
- import { decideNextFromFacts, type Decision } from '../kernel/engine'
151
+ import { decideNextFromFacts, dirtyWorktreeRecovery, type Decision } from '../kernel/engine'
140
152
  import { continuesVerifyCycle } from '../kernel/pr-summary'
141
153
  import { isPhaseTerminalEvent, PHASE_SPECS } from '../kernel/phases'
142
154
  import type { BuildState } from '../kernel/reducer'
@@ -942,6 +954,227 @@ export class BuildRunner {
942
954
  } satisfies EventWrite<'escalation.raised'>)
943
955
  }
944
956
 
957
+ /** Raise the `policy/dirty-worktree` blocker, unless one is already open. */
958
+ private async raiseDirtyWorktree(
959
+ input: DirtyWorktreeOrigin & { paths: readonly string[] },
960
+ ): Promise<void> {
961
+ const { store, slug } = this.deps
962
+ const state = (await readBuildFacts(store, slug)).value.state
963
+ if (state.openEscalations.some((e) => e.policyCause === 'dirty-worktree')) return
964
+ await store.append(slug, {
965
+ actor: KERNEL,
966
+ type: 'escalation.raised',
967
+ payload: {
968
+ id: this.deps.ids('esc'),
969
+ phase: 'implement',
970
+ source: 'policy',
971
+ policyCause: 'dirty-worktree',
972
+ question: dirtyWorktreeQuestion(input),
973
+ },
974
+ } satisfies EventWrite<'escalation.raised'>)
975
+ }
976
+
977
+ /** Tracked dirt, or undefined when the workspace cannot report it. */
978
+ private async trackedDirt(): Promise<string[] | undefined> {
979
+ try {
980
+ return await listTrackedDirt(this.deps.exec, this.deps.workspacePath)
981
+ } catch {
982
+ return undefined
983
+ }
984
+ }
985
+
986
+ /**
987
+ * After a successful `[commands].setup`: raise `policy/dirty-worktree` when
988
+ * setup newly modified tracked files outside `[[generated]]`. Dirt present
989
+ * before setup is never blamed on it; generated outputs are left for the
990
+ * phase and discarded before any replay. Skipped while an answered
991
+ * dirty-worktree recovery is pending (its implement round handles the
992
+ * dirt) and for a reconcile, whose resolver works on its own replay.
993
+ * Git-only; the facts are those the caller already read.
994
+ */
995
+ private async checkSetupDirt(
996
+ setup: string,
997
+ before: readonly string[] | undefined,
998
+ facts: Awaited<ReturnType<typeof readBuildFacts>>['value'],
999
+ decision: Decision,
1000
+ config: Config,
1001
+ ): Promise<boolean> {
1002
+ if (before === undefined) return false
1003
+ const after = await this.trackedDirt()
1004
+ if (after === undefined) return false
1005
+ const prior = new Set(before)
1006
+ const { undeclared } = classifyTrackedDirt(
1007
+ after.filter((path) => !prior.has(path)),
1008
+ config.generated ?? [],
1009
+ )
1010
+ if (undeclared.length === 0) return false
1011
+ if (
1012
+ (decision.kind === 'run-phase' && decision.phase === 'reconcile') ||
1013
+ dirtyWorktreeRecovery(facts.state, facts.log) !== undefined ||
1014
+ facts.state.openEscalations.some((e) => e.policyCause === 'dirty-worktree')
1015
+ )
1016
+ return false
1017
+ await this.raiseDirtyWorktree({ origin: 'setup', command: setup, paths: undeclared })
1018
+ return true
1019
+ }
1020
+
1021
+ /**
1022
+ * A frozen preparation refused undeclared tracked dirt. When its candidate
1023
+ * already recorded a publish intent and an operator answered a
1024
+ * dirty-worktree escalation after that intent, set the dirt aside and
1025
+ * report true so the caller retries the preparation once. Otherwise raise
1026
+ * the escalation (idempotently) and report false.
1027
+ */
1028
+ private async handleDirtRefusal(
1029
+ error: TrackedDirtRefusal,
1030
+ origin: 'restack' | 'reconcile',
1031
+ intentId: string | undefined,
1032
+ ): Promise<boolean> {
1033
+ const facts = (await readBuildFacts(this.deps.store, this.deps.slug)).value
1034
+ if (intentId !== undefined) {
1035
+ const intent = (
1036
+ origin === 'restack' ? facts.restackHistory : facts.reconcileHistory
1037
+ ).findLast(
1038
+ (event) =>
1039
+ (event.type === 'restack.publish-intended' ||
1040
+ event.type === 'reconcile.publish-intended') &&
1041
+ event.payload.id === intentId,
1042
+ )
1043
+ const answered = facts.state.answeredEscalations.findLast(
1044
+ (e) => e.source === 'policy' && e.policyCause === 'dirty-worktree',
1045
+ )
1046
+ if (
1047
+ intent !== undefined &&
1048
+ answered !== undefined &&
1049
+ (answered.resolution === 'guidance' || answered.resolution === 'retry') &&
1050
+ answered.answeredSeq > intent.seq &&
1051
+ !facts.state.openEscalations.some((e) => e.policyCause === 'dirty-worktree')
1052
+ ) {
1053
+ await this.setAsideDirt(answered.id, error.paths)
1054
+ return true
1055
+ }
1056
+ }
1057
+ await this.raiseDirtyWorktree({ origin, paths: error.paths })
1058
+ return false
1059
+ }
1060
+
1061
+ /**
1062
+ * Preserve operator-authorized dirt durably, then reset it so a frozen
1063
+ * publication can settle exactly as recorded, or a superseded replay can
1064
+ * return to the build branch: a binary patch artifact and a
1065
+ * deterministic observation, written before anything is restored. The
1066
+ * patch is Git's own byte-exact form (no textconv, external diff driver or
1067
+ * color), so `git apply --binary` restores what was reset. A patch too
1068
+ * large to store throws before the tree is touched.
1069
+ *
1070
+ * A retry (a stop before the reset, or a later preparation of the same
1071
+ * recovery) never trusts an earlier capture: the reset is authorized only
1072
+ * for the exact bytes the artifact's latest revision holds. When the tree
1073
+ * now differs, for example because setup rewrote a path on relaunch, a new
1074
+ * revision is stored first, keeping every earlier-captured path the tree no
1075
+ * longer shows.
1076
+ */
1077
+ private async setAsideDirt(
1078
+ escalation: string,
1079
+ paths: readonly string[],
1080
+ reason = 'so a frozen publication could settle',
1081
+ ): Promise<void> {
1082
+ const { store, slug, exec, workspacePath } = this.deps
1083
+ const observation = dirtyWorktreeSetAsideObservation(escalation)
1084
+ const kind = dirtyWorktreeArtifact(escalation)
1085
+ const diff = await exec(
1086
+ [
1087
+ 'git',
1088
+ 'diff',
1089
+ '--binary',
1090
+ '--no-textconv',
1091
+ '--no-ext-diff',
1092
+ '--no-color',
1093
+ '--src-prefix=a/',
1094
+ '--dst-prefix=b/',
1095
+ 'HEAD',
1096
+ '--',
1097
+ ...paths,
1098
+ ],
1099
+ {
1100
+ cwd: workspacePath,
1101
+ },
1102
+ )
1103
+ if (diff.exitCode !== 0) throw new Error(`git diff failed: ${diff.stderr || diff.stdout}`)
1104
+ const captured = await store.getArtifact(slug, kind)
1105
+ const previous = captured === null ? undefined : new TextDecoder().decode(captured.content)
1106
+ const patch = previous === undefined ? diff.stdout : mergePatches(previous, diff.stdout)
1107
+ if (patch !== previous) await store.putArtifact(slug, { kind, content: patch })
1108
+ const facts = (await readBuildFacts(store, slug)).value
1109
+ if (!facts.state.observations.some((entry) => entry.id === observation))
1110
+ await store.append(slug, {
1111
+ actor: KERNEL,
1112
+ type: 'observation.recorded',
1113
+ payload: {
1114
+ id: observation,
1115
+ kind: 'followup',
1116
+ summary: `Set aside uncommitted tracked changes as artifact ${kind} ${reason}: ${paths.join(', ')}`,
1117
+ files: [...paths],
1118
+ refs: [escalation, kind],
1119
+ },
1120
+ })
1121
+ await this.assertAutomaticRewriteOwnership(true)
1122
+ await restoreTrackedPaths(exec, workspacePath, paths)
1123
+ }
1124
+
1125
+ /** Abandon a frozen preparation with no publish intent after its
1126
+ * dirty-worktree escalation was answered. The worktree keeps the dirt for
1127
+ * the recovery implement round. */
1128
+ private async supersedeDirtyPreparation(
1129
+ decision: Extract<Decision, { kind: 'supersede-dirty-preparation' }>,
1130
+ ): Promise<void> {
1131
+ const picking = await this.deps.exec(
1132
+ ['git', 'rev-parse', '-q', '--verify', 'CHERRY_PICK_HEAD'],
1133
+ { cwd: this.deps.workspacePath },
1134
+ )
1135
+ if (picking.exitCode === 0)
1136
+ throw new Error(
1137
+ 'a cherry-pick occupies the workspace; a dirty preparation cannot be superseded',
1138
+ )
1139
+ await this.assertAutomaticRewriteOwnership()
1140
+ // A replay that already ran left HEAD detached on the abandoned candidate.
1141
+ // Return to the unchanged build branch, carrying the dirt for implement.
1142
+ // When Git refuses because the target changed a dirty file, the dirt is
1143
+ // set aside durably first (patch artifact plus observation) and the
1144
+ // recovery round's feedback names it; nothing is lost either way.
1145
+ const { exec, workspacePath, branch } = this.deps
1146
+ const current = await exec(['git', 'symbolic-ref', '-q', 'HEAD'], { cwd: workspacePath })
1147
+ if (current.exitCode !== 0 || current.stdout.trim() !== `refs/heads/${branch}`) {
1148
+ const checkout = () => exec(['git', 'checkout', '-q', branch], { cwd: workspacePath })
1149
+ let result = await checkout()
1150
+ if (result.exitCode !== 0) {
1151
+ const dirt = await listTrackedDirt(exec, workspacePath)
1152
+ if (dirt.length > 0) {
1153
+ await this.setAsideDirt(
1154
+ decision.escalation,
1155
+ dirt,
1156
+ 'so the workspace could return to the build branch',
1157
+ )
1158
+ result = await checkout()
1159
+ }
1160
+ }
1161
+ if (result.exitCode !== 0)
1162
+ throw new Error(
1163
+ `cannot return the workspace to ${branch}: ${result.stderr.trim() || result.stdout.trim()}`,
1164
+ )
1165
+ }
1166
+ await this.deps.store.append(this.deps.slug, {
1167
+ actor: KERNEL,
1168
+ type: 'reconcile.superseded',
1169
+ payload: {
1170
+ attempt: decision.attempt,
1171
+ cycle: decision.cycle,
1172
+ cause: 'dirty-worktree',
1173
+ ...(decision.restackId === undefined ? {} : { restackId: decision.restackId }),
1174
+ },
1175
+ })
1176
+ }
1177
+
945
1178
  /** Close every session open in the captured pre-attachment prefix, then
946
1179
  * announce takeover against that same boundary. If a write is interrupted,
947
1180
  * no attachment lands; the next runner reduces the newer prefix and closes
@@ -1147,8 +1380,16 @@ export class BuildRunner {
1147
1380
  const setup = config.commands.setup
1148
1381
  const preparedBase = verifyDiffBaseFrom(facts)
1149
1382
  if (setup !== undefined) {
1383
+ const before = await this.trackedDirt()
1150
1384
  const failure = await this.executeSetup(setup, streak + 1)
1151
1385
  if (failure !== undefined) await this.failSetup(failure, config)
1386
+ await this.checkSetupDirt(
1387
+ setup,
1388
+ before,
1389
+ facts,
1390
+ decideNextFromFacts(facts.state, facts.log, config),
1391
+ config,
1392
+ )
1152
1393
  }
1153
1394
 
1154
1395
  if (recovering) {
@@ -1224,14 +1465,16 @@ export class BuildRunner {
1224
1465
  facts: Awaited<ReturnType<typeof readBuildFacts>>['value'],
1225
1466
  decision: Decision,
1226
1467
  config: Config,
1227
- ): Promise<void> {
1468
+ ): Promise<boolean> {
1228
1469
  const setup = config.commands.setup
1229
1470
  const base = verifyDiffBaseFrom(facts)
1230
- if (setup === undefined || !preparationStale(this.preparedFor, base, decision)) return
1471
+ if (setup === undefined || !preparationStale(this.preparedFor, base, decision)) return false
1231
1472
  const streak = await readBuildSelector(this.deps.store, this.deps.slug, 'setupStreak')
1473
+ const before = await this.trackedDirt()
1232
1474
  const failure = await this.executeSetup(setup, streak + 1)
1233
1475
  if (failure !== undefined) await this.failSetup(failure, config)
1234
1476
  this.preparedFor = { base }
1477
+ return this.checkSetupDirt(setup, before, facts, decision, config)
1235
1478
  }
1236
1479
 
1237
1480
  /**
@@ -1254,7 +1497,8 @@ export class BuildRunner {
1254
1497
  const config = await this.captureConfig()
1255
1498
  const facts = (await readBuildFacts(store, slug)).value
1256
1499
  const decision = decideNextFromFacts(facts.state, facts.log, config)
1257
- await this.refreshPreparation(facts, decision, config)
1500
+ if (await this.refreshPreparation(facts, decision, config))
1501
+ return { kind: 'wait', reason: 'blocked' }
1258
1502
  // A requested measurement runs where the pipeline is otherwise parked.
1259
1503
  const parked =
1260
1504
  decision.kind === 'run-measurement' ||
@@ -1354,6 +1598,9 @@ export class BuildRunner {
1354
1598
  case 'accept-target-rewrite':
1355
1599
  await this.acceptTargetRewrite(decision)
1356
1600
  return decision
1601
+ case 'supersede-dirty-preparation':
1602
+ await this.supersedeDirtyPreparation(decision)
1603
+ return decision
1357
1604
  case 'capture-reconcile-policy':
1358
1605
  await store.append(slug, {
1359
1606
  actor: KERNEL,
@@ -1783,6 +2030,31 @@ export class BuildRunner {
1783
2030
  if (phase === 'reconcile' && !this.recovery) {
1784
2031
  const facts = (await readBuildFacts(store, slug)).value
1785
2032
  const active = facts.log.restack.active
2033
+ // A fresh epilogue occurrence refuses undeclared dirt before anything
2034
+ // is frozen; declared generated dirt is discarded.
2035
+ if (
2036
+ active === undefined &&
2037
+ facts.reconcileTransaction?.attempt !== round &&
2038
+ !(
2039
+ facts.state.currentPhase?.phase === 'reconcile' &&
2040
+ facts.state.currentPhase.attempt === round
2041
+ )
2042
+ ) {
2043
+ try {
2044
+ await settleTrackedDirt(
2045
+ {
2046
+ ...this.deps,
2047
+ generated: this.boundaryConfig.generated ?? [],
2048
+ beforeRewrite: () => this.assertAutomaticRewriteOwnership(),
2049
+ },
2050
+ { operation: 'reconcile', id: `attempt-${round}` },
2051
+ )
2052
+ } catch (error) {
2053
+ if (!(error instanceof TrackedDirtRefusal)) throw error
2054
+ await this.raiseDirtyWorktree({ origin: 'reconcile', paths: error.paths })
2055
+ return
2056
+ }
2057
+ }
1786
2058
  if (active !== undefined && facts.reconcileTransaction?.restackId !== active.id) {
1787
2059
  await store.append(slug, {
1788
2060
  actor: KERNEL,
@@ -1819,17 +2091,32 @@ export class BuildRunner {
1819
2091
  const oldBase = await readBuildSelector(store, slug, 'verifyDiffBase')
1820
2092
  if (oldBase === undefined || reconcileBaseSha === undefined)
1821
2093
  throw new Error('missing reconcile contribution base')
1822
- await prepareRestack(
1823
- { ...this.deps },
1824
- {
1825
- attempt: round,
1826
- restackId: (await readBuildFacts(store, slug)).value.log.restack.active?.id,
1827
- branch: this.deps.branch,
1828
- oldBase,
1829
- targetBase: reconcileBaseSha,
1830
- id: this.deps.ids('rewrite').replaceAll('_', '-'),
1831
- },
1832
- )
2094
+ const targetBase = reconcileBaseSha
2095
+ const input = {
2096
+ attempt: round,
2097
+ restackId: (await readBuildFacts(store, slug)).value.log.restack.active?.id,
2098
+ branch: this.deps.branch,
2099
+ oldBase,
2100
+ targetBase,
2101
+ id: this.deps.ids('rewrite').replaceAll('_', '-'),
2102
+ }
2103
+ const prepare = () =>
2104
+ prepareRestack({ ...this.deps, generated: this.boundaryConfig.generated ?? [] }, input)
2105
+ try {
2106
+ await prepare()
2107
+ } catch (error) {
2108
+ if (!(error instanceof TrackedDirtRefusal)) throw error
2109
+ const transaction = (await readBuildFacts(store, slug)).value.reconcileTransaction
2110
+ if (
2111
+ !(await this.handleDirtRefusal(
2112
+ error,
2113
+ 'reconcile',
2114
+ transaction?.attempt === round ? transaction.id : undefined,
2115
+ ))
2116
+ )
2117
+ return
2118
+ await prepare()
2119
+ }
1833
2120
  } catch (error) {
1834
2121
  await this.failPhase(
1835
2122
  phase,
@@ -2199,12 +2486,11 @@ export class BuildRunner {
2199
2486
  await publicationRetryGate(retryDeps, 'reconcile', rewriteId)
2200
2487
  const publicationDeps = {
2201
2488
  ...this.deps,
2489
+ generated: this.boundaryConfig.generated ?? [],
2202
2490
  beforeRewrite: () => this.assertAutomaticRewriteOwnership(true),
2203
2491
  }
2204
- // A replacement workspace may still be checked out at the old branch tip.
2205
- // Restore the frozen resolved intent before the guarded branch update.
2206
- try {
2207
- await prepareRestack(publicationDeps, {
2492
+ const restore = () =>
2493
+ prepareRestack(publicationDeps, {
2208
2494
  attempt: intent.payload.attempt,
2209
2495
  branch: intent.payload.branch,
2210
2496
  oldBase: intent.payload.oldBase,
@@ -2212,7 +2498,30 @@ export class BuildRunner {
2212
2498
  id: intent.payload.id,
2213
2499
  restackId: intent.payload.restackId,
2214
2500
  })
2501
+ // A replacement workspace may still be checked out at the old branch tip.
2502
+ // Restore the frozen resolved intent before the guarded branch update.
2503
+ try {
2504
+ try {
2505
+ await restore()
2506
+ } catch (error) {
2507
+ if (!(error instanceof TrackedDirtRefusal)) throw error
2508
+ // Undeclared dirt over an intended candidate: escalate, or set it
2509
+ // aside once an operator answered, then restore the candidate.
2510
+ if (!(await this.handleDirtRefusal(error, 'reconcile', intent.payload.id))) return
2511
+ await restore()
2512
+ }
2215
2513
  } catch (error) {
2514
+ if (error instanceof StoreWriteTooLargeError) {
2515
+ const failures = await readPhaseFailures(store, slug, 'reconcile', intent.payload.attempt)
2516
+ await this.failPhase(
2517
+ 'reconcile',
2518
+ intent.payload.attempt,
2519
+ failures.count,
2520
+ `cannot set aside uncommitted tracked changes: ${errorMessage(error)}`,
2521
+ false,
2522
+ )
2523
+ return
2524
+ }
2216
2525
  if (!(error instanceof RetainedHistoryUnavailable)) throw error
2217
2526
  // The resolved candidate is retained nowhere: retire it, and the
2218
2527
  // reconcile replays from the published branch under its replacement id.
@@ -2250,7 +2559,10 @@ export class BuildRunner {
2250
2559
  await completeAutomaticReconcile(store, slug)
2251
2560
  }
2252
2561
 
2253
- private async restack(decision: Extract<Decision, { kind: 'restack' }>): Promise<void> {
2562
+ private async restack(
2563
+ decision: Extract<Decision, { kind: 'restack' }>,
2564
+ retried = false,
2565
+ ): Promise<void> {
2254
2566
  const { store, slug } = this.deps
2255
2567
  let facts = (await readBuildFacts(store, slug)).value
2256
2568
  if (facts.state.sessions.open.length > 0 || facts.publication.pending())
@@ -2352,9 +2664,12 @@ export class BuildRunner {
2352
2664
  await this.assertAutomaticRewriteOwnership()
2353
2665
  const deps = {
2354
2666
  ...this.deps,
2667
+ generated: this.boundaryConfig.generated ?? [],
2355
2668
  automatic,
2356
2669
  beforeRewrite: () => this.assertAutomaticRewriteOwnership(),
2357
2670
  }
2671
+ // A fresh restack refuses undeclared dirt before anything is frozen.
2672
+ if (transaction === undefined) await settleTrackedDirt(deps, { operation: 'restack', id })
2358
2673
  const prepared = await prepareRestack(deps, {
2359
2674
  attempt: 1,
2360
2675
  branch: this.deps.branch,
@@ -2400,6 +2715,14 @@ export class BuildRunner {
2400
2715
  facts.log.restack.regeneration?.outcome === 'resolved'
2401
2716
  ? facts.log.restack.regeneration
2402
2717
  : undefined
2718
+ // The automatic replay is complete, whichever recovery path reached it
2719
+ // (a fresh replay, a cherry-pick recovered before its replay fact, an
2720
+ // adopted regeneration): tracked dirt is never part of the candidate.
2721
+ await settleTrackedDirt(deps, {
2722
+ operation: 'restack',
2723
+ id: transaction.id,
2724
+ prefix: 'cannot publish a replay over local changes',
2725
+ })
2403
2726
  const result = await this.deps.exec(['git', 'rev-parse', 'HEAD'], {
2404
2727
  cwd: this.deps.workspacePath,
2405
2728
  })
@@ -2521,6 +2844,12 @@ export class BuildRunner {
2521
2844
  throw error
2522
2845
  if (error instanceof AutomaticRewriteDeferred || error instanceof RegenerationInterrupted)
2523
2846
  return
2847
+ if (error instanceof TrackedDirtRefusal) {
2848
+ const intent = (await readBuildFacts(store, slug)).value.log.restack.intent
2849
+ if ((await this.handleDirtRefusal(error, 'restack', intent?.id)) && !retried)
2850
+ await this.restack(decision, true)
2851
+ return
2852
+ }
2524
2853
  await this.failPhase(
2525
2854
  'reconcile',
2526
2855
  round,