@defrex/autobuild 1.16.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 (72) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +91 -7
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +15 -1
  5. package/docs/configuration.md +33 -4
  6. package/docs/operator-api.md +15 -5
  7. package/docs/plugin-authoring.md +1 -0
  8. package/docs/remote-store-protocol.md +13 -3
  9. package/docs/remote-ticket-protocol.md +3 -1
  10. package/docs/restacking.md +41 -1
  11. package/docs/setup.md +15 -6
  12. package/docs/troubleshooting.md +39 -2
  13. package/docs/workspaces.md +2 -0
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/accounts.ts +3 -0
  16. package/packages/core/src/cli/binary-direct.ts +14 -1
  17. package/packages/core/src/cli/binary.ts +10 -7
  18. package/packages/core/src/cli/dispatch.ts +503 -334
  19. package/packages/core/src/cli/secrets.ts +2 -0
  20. package/packages/core/src/config/schema.ts +15 -2
  21. package/packages/core/src/events/payloads.ts +8 -5
  22. package/packages/core/src/kernel/engine.ts +118 -0
  23. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  24. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  25. package/packages/core/src/ontology.ts +1 -0
  26. package/packages/core/src/operator/index.ts +10 -0
  27. package/packages/core/src/operator/merged-builds.ts +51 -0
  28. package/packages/core/src/operator/registry.ts +190 -101
  29. package/packages/core/src/operator/repo-argument.ts +43 -0
  30. package/packages/core/src/ports/tickets/grants.ts +2 -0
  31. package/packages/core/src/ports/tickets/remote.ts +2 -0
  32. package/packages/core/src/ports/types.ts +15 -0
  33. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  34. package/packages/core/src/ports/workspace/vercel-sandbox.ts +576 -140
  35. package/packages/core/src/processes/build-child.ts +15 -1
  36. package/packages/core/src/processes/build-runner.ts +349 -20
  37. package/packages/core/src/processes/dispatcher.ts +28 -7
  38. package/packages/core/src/processes/harvest-child.ts +21 -1
  39. package/packages/core/src/processes/harvest-runner.ts +82 -35
  40. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  41. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  42. package/packages/core/src/processes/repo-view.ts +25 -4
  43. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  44. package/packages/core/src/store/adapter.ts +34 -5
  45. package/packages/core/src/store/build-feed.ts +148 -22
  46. package/packages/core/src/store/build-scope.ts +12 -3
  47. package/packages/core/src/store/caller-attribution.ts +170 -0
  48. package/packages/core/src/store/contract.ts +1038 -165
  49. package/packages/core/src/store/local/schema.ts +12 -1
  50. package/packages/core/src/store/local/store.ts +260 -25
  51. package/packages/core/src/store/memory.ts +156 -9
  52. package/packages/core/src/store/phase-session.ts +23 -3
  53. package/packages/core/src/store/reducer-value-shapes.json +3184 -3175
  54. package/packages/core/src/store/remote/client.ts +90 -11
  55. package/packages/core/src/store/remote/credentials.ts +2 -0
  56. package/packages/core/src/store/remote/index.ts +31 -5
  57. package/packages/core/src/store/remote/protocol.ts +45 -8
  58. package/packages/core/src/store/remote/released-clients.json +11 -0
  59. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  60. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  61. package/packages/core/src/store/session-handle.ts +12 -3
  62. package/packages/core/src/store/types.ts +48 -3
  63. package/packages/core/src/testing/reduced-read-budget.ts +222 -4
  64. package/skills/guide/SKILL.md +46 -8
  65. package/skills/guide/references/operator-api.md +15 -5
  66. package/skills/guide/references/plugin-authoring.md +1 -0
  67. package/skills/guide/references/remote-store-protocol.md +13 -3
  68. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  69. package/skills/guide/references/restacking.md +41 -1
  70. package/skills/guide/references/setup.md +15 -6
  71. package/skills/operate/SKILL.md +24 -3
  72. 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,
@@ -1,4 +1,5 @@
1
1
  import { proveTargetLineage } from '../kernel/target-lineage'
2
+ import { withCallerStage } from '../store/caller-attribution'
2
3
  import {
3
4
  recordRetention,
4
5
  restoreRetainedHead,
@@ -407,6 +408,7 @@ import {
407
408
  } from '../objective'
408
409
  export { specConformance, type SpecConformance } from '../spec-standard'
409
410
  import { recordInfrastructureFailure as appendInfrastructureFailure } from './infrastructure-failure-budget'
411
+ import { describeProvisionProgress, provisioningAbandonmentMessage } from './provisioning-progress'
410
412
  import { settleOpenExecution } from './execution-settlement'
411
413
  import { isWorkDigest, RepoViewStore } from './repo-view'
412
414
  import type { OpenBuildWorkspace, ProvisionMarker } from './dispatcher-selectors'
@@ -878,6 +880,11 @@ interface ProvisionContinuation {
878
880
  readonly instance: string
879
881
  readonly controller: AbortController
880
882
  promise: Promise<void>
883
+ /** The provider's latest reported stage and when it began (clock ms);
884
+ * teardown names it in the abandonment fact. */
885
+ progress?: { label: string; since: number }
886
+ /** When teardown signalled this continuation (clock ms). */
887
+ abortedAt?: number
881
888
  }
882
889
 
883
890
  export interface DispatcherOpts {
@@ -1928,9 +1935,11 @@ export class Dispatcher {
1928
1935
  opts: TickOpts,
1929
1936
  run: (stageOpts: TickOpts) => Promise<void>,
1930
1937
  ): Promise<void> {
1938
+ // Hosted requests made inside the stage, and work it starts, name it.
1931
1939
  // Unbounded: the helpers' own promise, scheduled exactly as before.
1932
- if (opts.deadlineAt === undefined) return run(opts)
1933
- return this.runBoundedStage(stage, opts, opts.deadlineAt, run)
1940
+ const deadlineAt = opts.deadlineAt
1941
+ if (deadlineAt === undefined) return withCallerStage(stage, () => run(opts))
1942
+ return withCallerStage(stage, () => this.runBoundedStage(stage, opts, deadlineAt, run))
1934
1943
  }
1935
1944
 
1936
1945
  private async runBoundedStage(
@@ -3612,12 +3621,21 @@ export class Dispatcher {
3612
3621
  }
3613
3622
  : {}),
3614
3623
  ...(input.adoptAbandoned ? { adoptAbandoned: true } : {}),
3624
+ signal: entry.controller.signal,
3625
+ onProgress: (progress) => {
3626
+ if (entry.controller.signal.aborted) return
3627
+ entry.progress = {
3628
+ label: describeProvisionProgress(progress),
3629
+ since: this.deps.clock().getTime(),
3630
+ }
3631
+ },
3615
3632
  },
3616
3633
  entry.controller.signal,
3617
3634
  )
3618
- // The provisioned fact is true and welcome even when a teardown signal
3619
- // landed mid-call; the token check below still prevents a superseded
3620
- // supervisor from launching.
3635
+ // Providers receive the teardown signal and usually reject promptly, but
3636
+ // one that ignores it may still complete: the provisioned fact is then
3637
+ // true and welcome even though the signal landed mid-call. The token
3638
+ // check below still prevents a superseded supervisor from launching.
3621
3639
  await store.append(slug, {
3622
3640
  actor: DISPATCHER,
3623
3641
  type: 'workspace.provisioned',
@@ -3754,8 +3772,10 @@ export class Dispatcher {
3754
3772
  payload: {
3755
3773
  stage: 'workspace',
3756
3774
  attempt,
3757
- error:
3758
- 'provisioning abandoned at dispatcher teardown; the next supervisor adopts the open marker',
3775
+ error: provisioningAbandonmentMessage(
3776
+ entry.progress,
3777
+ entry.abortedAt ?? this.deps.clock().getTime(),
3778
+ ),
3759
3779
  abandoned: 'teardown',
3760
3780
  },
3761
3781
  })
@@ -3779,6 +3799,7 @@ export class Dispatcher {
3779
3799
  abortProvisioning(): void {
3780
3800
  for (const entry of this.continuations.values()) {
3781
3801
  this.abortedContinuations.set(entry.instance, entry)
3802
+ entry.abortedAt ??= this.deps.clock().getTime()
3782
3803
  entry.controller.abort()
3783
3804
  }
3784
3805
  }
@@ -5,6 +5,7 @@ import { ticketGrantRequest } from '../ports/tickets/grants'
5
5
  * durable boundary lives in the repository journal, so a replacement process
6
6
  * resumes the claimed snapshot rather than starting a duplicate run.
7
7
  */
8
+ import { withStoreCaller } from '../store/caller-attribution'
8
9
  import { join } from 'node:path'
9
10
  import { loadConfig } from '../config/load'
10
11
  import type { HarvestExecutionEnvironment } from '../ports/workspace/harvest-execution'
@@ -50,12 +51,31 @@ export function guestTicketSourceArgs(
50
51
  * composition likewise matches a local harvest in this checkout: a relative
51
52
  * or defaulted `[tickets].dir` resolves against the guest checkout and the
52
53
  * selected local state root (see `guestTicketSourceArgs`). */
53
- export async function runHarvestChild(
54
+ export function runHarvestChild(
54
55
  input: HarvestRunnerLaunch,
55
56
  env: Record<string, string | undefined> = process.env,
56
57
  openStore: StoreOpener = openProductionStore,
57
58
  /** Guest checkout root. The provider launches the runner with this as cwd. */
58
59
  workspacePath: string = process.cwd(),
60
+ ): Promise<void> {
61
+ // Every hosted request this runner makes, its ticket-grant renewals
62
+ // included, is attributed to its harvest execution.
63
+ return withStoreCaller(
64
+ {
65
+ kind: 'runner',
66
+ runner: 'harvest',
67
+ execution: input.instance,
68
+ ...(input.preparedRun ? { harvest: input.preparedRun.run } : {}),
69
+ },
70
+ () => runHarvestChildInScope(input, env, openStore, workspacePath),
71
+ )
72
+ }
73
+
74
+ async function runHarvestChildInScope(
75
+ input: HarvestRunnerLaunch,
76
+ env: Record<string, string | undefined>,
77
+ openStore: StoreOpener,
78
+ workspacePath: string,
59
79
  ): Promise<void> {
60
80
  const fullStore: BuildStore = openStore(input.storeRef, env.AB_TOKEN)
61
81
  const ticketAuthority =