@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,3 +1,4 @@
1
+ import { storeCallerHeaders } from '../store/caller-attribution'
1
2
  import { SECRET_NAME_EXPLANATION } from '../secret-name'
2
3
  import { connectedProject } from './connect'
3
4
  import { ProjectCredentials } from './project-credentials'
@@ -128,6 +129,7 @@ export async function abSecrets(
128
129
  headers: {
129
130
  'content-type': 'application/json',
130
131
  authorization: `Bearer ${credential.token}`,
132
+ ...storeCallerHeaders(),
131
133
  [AUTOBUILD_VERSION_HEADER]: AUTOBUILD_VERSION,
132
134
  [REMOTE_STORE_PROTOCOL_VERSION_HEADER]: REMOTE_STORE_PROTOCOL_VERSION,
133
135
  },
@@ -192,15 +192,28 @@ const envNameSchema = z
192
192
  const nonblankProvisioningString = (field: string) =>
193
193
  z.string().refine((value) => value.trim().length > 0, `${field} must be nonblank`)
194
194
 
195
+ /** Default and ceiling for one declared Vercel provisioning step's timeout.
196
+ * The ceiling stays under the ~15-minute request timeout Bun's native fetch
197
+ * puts on the SDK's command long-poll. */
198
+ export const VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS = 600
199
+ export const VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS = 840
200
+
195
201
  export const vercelProvisioningStepSchema = z.strictObject({
196
202
  name: nonblankProvisioningString('provisioning step name'),
197
203
  command: nonblankProvisioningString('provisioning step command'),
204
+ timeoutSeconds: z
205
+ .number()
206
+ .int()
207
+ .min(1)
208
+ .max(VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS)
209
+ .optional(),
198
210
  })
199
211
 
200
212
  documentFields(vercelProvisioningStepSchema, {
201
213
  name: 'Unique provisioning step name. Must contain a non-whitespace character.',
202
214
  command:
203
215
  'Shell command executed in declaration order during provisioning. Must contain a non-whitespace character.',
216
+ timeoutSeconds: `Optional per-step timeout in seconds (default ${VERCEL_PROVISIONING_STEP_TIMEOUT_DEFAULT_SECONDS}, at most ${VERCEL_PROVISIONING_STEP_TIMEOUT_MAX_SECONDS}). The sandbox kills the step when it elapses, and provisioning fails with the step name, command, elapsed time, and output so far.`,
204
217
  })
205
218
  export type VercelProvisioningStep = z.infer<typeof vercelProvisioningStepSchema>
206
219
 
@@ -342,7 +355,7 @@ documentFields(vercelSandboxConfigSchema, {
342
355
  environmentVariables:
343
356
  'unique API-credential variable names copied into runtime and agent/check commands',
344
357
  provisioning:
345
- 'ordered strict inline tables `{ name, command }`; names and commands are nonblank and names are unique',
358
+ 'ordered strict inline tables `{ name, command, timeoutSeconds? }`; names and commands are nonblank and names are unique',
346
359
  runtimeProvisioning:
347
360
  'open map keyed by every effective role/alternate runtime; each entry requires `install` and `preflight`',
348
361
  gitUsernameEnv:
@@ -1488,7 +1501,7 @@ documentFields(configRootSchema, {
1488
1501
  workspace: 'Workspace provider selector and provider-specific configuration.',
1489
1502
  commands: 'Named shell commands used by setup and deterministic checks.',
1490
1503
  generated:
1491
- 'Generated files that a declared command rebuilds. Restack replays that conflict only in these files are regenerated instead of reconciled by an agent.',
1504
+ 'Generated files that a declared command rebuilds. Restack replays that conflict only in these files are regenerated instead of reconciled by an agent, and uncommitted changes to them are discarded before a replay.',
1492
1505
  verify:
1493
1506
  'Ordered verification steps and applicability rules. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1494
1507
  finalize:
@@ -2282,14 +2282,17 @@ export const eventPayloadSchemas = {
2282
2282
  conflicted: z.boolean(),
2283
2283
  archives: z.array(archiveEntry),
2284
2284
  }),
2285
- /** The kernel abandoned an open reconcile occurrence with no publish
2286
- * intent because its session declared a ticket wait and the target moved
2287
- * before the build resumed. The workspace operation was aborted and nothing
2288
- * was published; `restackId` names the automatic restack it also closes. */
2285
+ /** The kernel abandoned an open reconcile occurrence (or frozen automatic
2286
+ * restack) with no publish intent. `wait-resume`: its session declared a
2287
+ * ticket wait and the target moved before the build resumed; the workspace
2288
+ * operation was aborted. `dirty-worktree`: an operator answered a
2289
+ * dirty-worktree escalation, so the preparation is abandoned and the
2290
+ * dirt kept, on the build branch, for the recovery implement round. Nothing was
2291
+ * published; `restackId` names the automatic restack it also closes. */
2289
2292
  'reconcile.superseded': z.strictObject({
2290
2293
  attempt,
2291
2294
  cycle: z.number().int().nonnegative(),
2292
- cause: z.literal('wait-resume'),
2295
+ cause: z.enum(['wait-resume', 'dirty-worktree']),
2293
2296
  restackId: z.string().min(1).optional(),
2294
2297
  }),
2295
2298
  'propose.started': z.strictObject({
@@ -152,7 +152,9 @@ const tickCountersSchema = z.strictObject({
152
152
  * provisioning estimate. Optional so historical tick facts replay. */
153
153
  provisioningDeferred: z.number().int().nonnegative().optional(),
154
154
  /** Builds whose stopped-sandbox recovery (or a launch waiting on one) the
155
- * invocation budget deferred. Optional so historical tick facts replay. */
155
+ * invocation budget deferred, or whose launch the work deadline cut after
156
+ * its execution lease was claimed. Optional so historical tick facts
157
+ * replay. */
156
158
  recoveryDeferred: z.number().int().nonnegative().optional(),
157
159
  /** Operator sandboxes idly stopped this tick. Added with the operator
158
160
  * sandbox; optional so historical tick facts replay. */
@@ -570,16 +572,20 @@ export const orchestratorSandboxEventPayloadSchemas = {
570
572
 
571
573
  export const dispatcherStatusEventPayloadSchemas = {
572
574
  /** A latest-only scheduling hint: the builds whose deadline-gated work
573
- * (a provision or a stopped-sandbox recovery step) a bounded invocation
574
- * deferred for budget. The next tick sweeps these builds first, re-deriving
575
- * every decision from fresh build state; it is never authority. An empty
576
- * list clears it. */
575
+ * (a provision, a runner launch the work deadline cut, or a stopped-sandbox
576
+ * recovery step) a bounded invocation deferred for budget. The next tick
577
+ * serves these builds first, re-deriving every decision from fresh build
578
+ * state; it is never authority. An empty list clears it. `instance` names a
579
+ * deadline-cut execution whose exact-holder lease teardown could not
580
+ * settle: the next tick fences it first (step `fence`) or only releases it
581
+ * (step `launch`), and only while that instance still holds the lease. */
577
582
  'dispatcher.work-deferred': z.strictObject({
578
583
  builds: z
579
584
  .array(
580
585
  z.strictObject({
581
586
  slug: z.string().min(1),
582
- step: z.enum(['provision', 'resume', 'fence', 'preserve', 'cleanup']),
587
+ step: z.enum(['provision', 'launch', 'resume', 'fence', 'preserve', 'cleanup']),
588
+ instance: z.string().min(1).optional(),
583
589
  }),
584
590
  )
585
591
  .max(64),
@@ -0,0 +1,108 @@
1
+ {
2
+ "records": [
3
+ {
4
+ "name": "repositoryReadFacts",
5
+ "identity": "repositoryReadFacts",
6
+ "revisions": [
7
+ "repositoryAttention/fold/u6bhzf2af0",
8
+ "repositoryReadFacts/fold/0xl1c98cpy",
9
+ "repositoryReadFacts/fold/4gnmhbji3n",
10
+ "repositoryReadFacts/fold/5porrk9y1h",
11
+ "repositoryReadFacts/fold/fk3ka9gb3z",
12
+ "repositoryReadFacts/fold/vvcfmd23zp",
13
+ "repositoryReadFacts/shape/5yo149tiqz",
14
+ "repositoryReadFacts/shape/70jpyc3nd3",
15
+ "repositoryReadFacts/shape/7hbgb52kw8",
16
+ "repositoryReadFacts/shape/e2u2pgiup3",
17
+ "repositoryReadFacts/shape/ez3eddcdoo",
18
+ "repositoryReadFacts/shape/hgw4spz5c0",
19
+ "repositoryReadFacts/shape/mggr8x6l5z",
20
+ "repositoryReadFacts/shape/o7791nz2gt",
21
+ "repositoryReadFacts/shape/se5kk44boc",
22
+ "repositoryReadFacts/shape/xyn7875cxw",
23
+ "sandboxStates/fold/hjdgop7xoh",
24
+ "sandboxStates/shape/gbrf8k4qxq",
25
+ "ticketStarts/fold/8fp156vze2",
26
+ "ticketStarts/fold/eglrhnb0ta",
27
+ "ticketStarts/shape/dzxrbuuq7e",
28
+ "ticketStarts/shape/eecofz22vy"
29
+ ],
30
+ "entries": {
31
+ "017d8dd5bb6dd80b": "9b19c8eb254d503fbe74d8de7039566f",
32
+ "10a4657408d4e121": "218f9c92364c4b9176b70c9bee8a29f8",
33
+ "1411d1cdbdd9911e": "a5b60fa55d3c1d3999e4ee947878bd23",
34
+ "1444fe1fa7fc802c": "81c89822174d63012aa06ad744fae9e6",
35
+ "178e12f1759b7552": "61197c43eb41d8451ce5182402f23373",
36
+ "1921f86f752428c9": "abf8d370c9d94b6a50ab70d52d33454b",
37
+ "1972c1d66008ef6b": "56c634f6d1a0076256c385b2a9feab7c",
38
+ "19e8e43e7f3f1a06": "b18b2ccd2d11b39684f2fc991526b0d6",
39
+ "21ce2c0bf58318e1": "8eedb8f516b89cb65230c9cedb1bd903",
40
+ "293dcb3a94fb3470": "203e641af713b42a0e5369f9486f2301",
41
+ "2ab7436356267118": "fc4031327a07006ccdc946bf07aba04f",
42
+ "2d084641735caaff": "1061299214f493d5d51f9c11afae68ab",
43
+ "3237bcecf68e5db9": "79f6d09249036fd77dc5d3400e18124a",
44
+ "33d0cc593610e56f": "bd88ed40c1ada79d8657af1b339a6a9f",
45
+ "35cf9ccc4478b2d2": "5a2279bc99403d0f7d40cede4c8bb573",
46
+ "3649e7bd1203f154": "9d3742c0e29c7a3e999c9c9a8c6eac27",
47
+ "38c75099d9191471": "203e641af713b42a0e5369f9486f2301",
48
+ "431c9bb2ee8838e0": "0715d441ad523323105867bf09108797",
49
+ "49064fc079964a5c": "844ca8b44174ab640ce17a713b580d7d",
50
+ "4932c70a2af97faf": "0c732c6ead43fcb8d5f34159ac5e0e0b",
51
+ "4f00c0f2c8afd159": "9688f560966f37d57b4177bf5aa4b7f0",
52
+ "516a5a7aadf97587": "e63f56f546ed51d4e04df1e86c9fc476",
53
+ "536085773daf6b58": "57901f1d28ee614272cc8915a80e38ff",
54
+ "59ffaa6974094c72": "d1757ea5344f9164aca22e3ca6ca165a",
55
+ "5f0ca42af862c4ee": "840d8a2c1947ef0941e1ab8bf3afd42e",
56
+ "6118031132db9bfc": "8c44d3ef5b8a0241b5c712f994d56907",
57
+ "643d70429ce03dad": "c2b7bfc98da1427b6a3858d814d3f57b",
58
+ "677ea92572c29082": "4067b95ee98f33bc298d71c7489fabba",
59
+ "6ae5bf60504d6467": "58975765e668c4f361659977261d56ed",
60
+ "6bd6275061aaffa5": "c84c2528779e3ecc21e549e0ef2adedd",
61
+ "6efdc8defc75fccb": "d5b512d4f4c16b9d4bcadbee8f8206ad",
62
+ "7833e42d16301424": "b32c86839cd9044a4d7757d51b62db14",
63
+ "7d4edad0614adaf1": "54a48a0b441082d54a07d786c217153e",
64
+ "837365898d04f45a": "54a48a0b441082d54a07d786c217153e",
65
+ "85f9f0c921b8b5bb": "0926918433e11ebd637e34dae2a2d615",
66
+ "8879f57a24733897": "58975765e668c4f361659977261d56ed",
67
+ "88cb9e71bdec972d": "3f7ed5a476e6457efedb7cdf6412fd23",
68
+ "89625654b02e9ac1": "bac4fc52c015d8cb7b9f833dda540b85",
69
+ "8cc15eb1807c0157": "10c221f0b9db3782b1dca2ed6eb1f5c9",
70
+ "8ced97c44bc0af3a": "d998291081ba51e1bef3205aae7595ef",
71
+ "8d4144004720b9f8": "ef6389a96f072b54e91a0e0f19c827b8",
72
+ "8db633ead1807f8b": "c4fe43ef3276b5877db1b08a38d607cb",
73
+ "8e42cdbd0994ab0c": "e12aa5b2f6373eceb51f303a929e8d5a",
74
+ "9539b995af5c54a9": "1061299214f493d5d51f9c11afae68ab",
75
+ "9ee3919fbd4f9458": "a553618f38080bfcb814cb4a5416cfb1",
76
+ "a0b32c12e4e6edb6": "d323237478cd65b159eda1faab172bcf",
77
+ "a55218252707bdd3": "54a48a0b441082d54a07d786c217153e",
78
+ "a98af134be2da8a9": "9a0830cc47de7a66b3c2f1a85a7eb852",
79
+ "af953392d81911da": "58975765e668c4f361659977261d56ed",
80
+ "b0d877c44810ecb0": "64a155224f6c8526212f92f64e7ef575",
81
+ "be211f0e31a65006": "64a155224f6c8526212f92f64e7ef575",
82
+ "c68b7ee2e2610f30": "05034ebd16ae9bf93b398663b30aea92",
83
+ "c7f7e0378aeea237": "1061299214f493d5d51f9c11afae68ab",
84
+ "c98cb1659eb142b6": "64a155224f6c8526212f92f64e7ef575",
85
+ "ca830adf06ed55a1": "54a48a0b441082d54a07d786c217153e",
86
+ "cb3a219f33e437ca": "feab7b027da5be2ecf041dd93fb55f1d",
87
+ "cf1e0c0d82567e0c": "cac9aba9f25adeb55568e902396839a4",
88
+ "d1432a819d8e48c5": "203e641af713b42a0e5369f9486f2301",
89
+ "d185ed6aa9192aff": "235467b1c87a46b383a7fa8550d8a2f8",
90
+ "d5d5ccca80a893d8": "0fdfd82c7426fd151bbb7544cd415187",
91
+ "d873fad29d6c7e55": "3f7ed5a476e6457efedb7cdf6412fd23",
92
+ "e2f18fa32fe1f6d0": "e5878dff98f5f30c5f82c1656fa82737",
93
+ "e37393fed29e84c5": "b32c86839cd9044a4d7757d51b62db14",
94
+ "e6a8585e2a054ff6": "ed2947f48b407a9a4f3bbfd151d8bc63",
95
+ "eb7ddd5319d09e27": "e7fa56dec140a7688e4a7d470b419aba",
96
+ "eca4959b2b87ae15": "5d66240a5fdec0ca59deafae16615bc5",
97
+ "ee10d7959ec4843c": "7a0b8bf4fb7a11ea26c5431bc205f96d",
98
+ "ef1b68347966ab26": "3f7ed5a476e6457efedb7cdf6412fd23",
99
+ "f3e55425cc41f230": "54a48a0b441082d54a07d786c217153e",
100
+ "f5b9ace9b59351e7": "3f7ed5a476e6457efedb7cdf6412fd23",
101
+ "f8155387eb5f375c": "5c119a1b47ade210ed5517f68b3babfc",
102
+ "fa8f1475a55be935": "8ecd3e416726e4af9b75f8eaa983f171",
103
+ "fb21116a15d0b1f1": "22c5ba7ef2445e8d6a9e7bbeb1b06d52",
104
+ "fe95444fbeabe592": "4b033ccb2ce1d4edc32bb44601049293"
105
+ }
106
+ }
107
+ ]
108
+ }
@@ -10,6 +10,11 @@ import { mixedVersionDeferred } from './mixed-version'
10
10
  import { integrationCurrent, integrationConfig, integrationFailed } from './integration-state'
11
11
  import { proposeRunDue, proposeStarted } from './optimization'
12
12
  import { reopenSpecPending, reviseSpecPending } from './reopen-state'
13
+ import {
14
+ dirtyWorktreeArtifact,
15
+ dirtyWorktreeGuidance,
16
+ dirtyWorktreeSetAsideObservation,
17
+ } from './tracked-dirt'
13
18
  /**
14
19
  * The kernel pipeline engine (SPEC §8): "read the event log, decide the next
15
20
  * phase per the transition table, invoke the AgentRunner with `/{skill}
@@ -136,6 +141,20 @@ export type Decision =
136
141
  reconcile?: { attempt: number }
137
142
  /** Present iff phase === 'propose': the open request it answers. */
138
143
  propose?: { request: string; head: string }
144
+ /** The answered `policy/dirty-worktree` escalation this implement round
145
+ * recovers from. Engine-derived, never persisted: the runner skips the
146
+ * setup dirt check for it, since this round's agent handles the dirt. */
147
+ dirtyRecovery?: string
148
+ }
149
+ /** An answered dirty-worktree escalation abandons a frozen preparation that
150
+ * has no publish intent. The worktree keeps the dirt; HEAD returns to the
151
+ * build branch if a replay detached it. */
152
+ | {
153
+ kind: 'supersede-dirty-preparation'
154
+ escalation: string
155
+ attempt: number
156
+ cycle: number
157
+ restackId?: string
139
158
  }
140
159
  | VerifyAction
141
160
  | {
@@ -510,6 +529,41 @@ function decideNextInternal(state: BuildState, log: LogIndex, config: Config): D
510
529
  // ── 4. Spec (§6.3: dispatch owns the import; `spec` is not a phase §5) ─────
511
530
  if (state.specRev === undefined) return { kind: 'wait', reason: 'awaiting-spec' }
512
531
 
532
+ // An answered dirty-worktree escalation returns the build to implement
533
+ // (SPEC §11): a frozen preparation with no publish intent is superseded
534
+ // first; one with an intent falls through so its candidate settles (the
535
+ // runner sets the dirt aside); with nothing frozen, the recovery round runs.
536
+ const dirtyRecovery = dirtyWorktreeRecovery(state, log)
537
+ if (dirtyRecovery) {
538
+ const { escalation, round } = dirtyRecovery
539
+ const frozen = frozenPreparation(state, log)
540
+ if (frozen && !frozen.intended) {
541
+ const { intended: _intended, ...target } = frozen
542
+ return { kind: 'supersede-dirty-preparation', escalation: escalation.id, ...target }
543
+ }
544
+ if (!frozen)
545
+ return {
546
+ kind: 'run-phase',
547
+ phase: 'implement',
548
+ round,
549
+ dirtyRecovery: escalation.id,
550
+ feedback: {
551
+ guidance: {
552
+ escalation: escalation.id,
553
+ answer: dirtyWorktreeGuidance({
554
+ question: escalation.question,
555
+ ...(escalation.resolution === 'guidance' ? { answer: escalation.answer } : {}),
556
+ ...(state.observations.some(
557
+ (o) => o.id === dirtyWorktreeSetAsideObservation(escalation.id),
558
+ )
559
+ ? { setAside: dirtyWorktreeArtifact(escalation.id) }
560
+ : {}),
561
+ }),
562
+ },
563
+ },
564
+ }
565
+ }
566
+
513
567
  // A revised contract invalidates approvals, but an unfinished replay still
514
568
  // belongs to its reconcile occurrence. Publish it before opening the new
515
569
  // plan loop so no other phase inherits its detached/conflicted workspace.
@@ -1040,6 +1094,70 @@ interface LoopArgs {
1040
1094
  producerFeedback: () => Feedback | undefined
1041
1095
  }
1042
1096
 
1097
+ /**
1098
+ * The recovery an answered `policy/dirty-worktree` escalation selects: the
1099
+ * latest such guidance or retry answer after both restart boundaries, while
1100
+ * the plan loop is approved. The recovery round is the first implement round
1101
+ * started after the answer; until it completes, every rerun is that round.
1102
+ * Once it completes the ordinary loop owns the build.
1103
+ */
1104
+ export function dirtyWorktreeRecovery(
1105
+ state: BuildState,
1106
+ log: LogIndex,
1107
+ ): { escalation: AnsweredEscalation; round: number } | undefined {
1108
+ const escalation = state.answeredEscalations.findLast(
1109
+ (e) => e.source === 'policy' && e.policyCause === 'dirty-worktree',
1110
+ )
1111
+ if (
1112
+ escalation === undefined ||
1113
+ (escalation.resolution !== 'guidance' && escalation.resolution !== 'retry') ||
1114
+ escalation.answeredSeq <= Math.max(log.restartSeq, log.codeRestartSeq)
1115
+ )
1116
+ return undefined
1117
+ if (log.plan.rounds.get(log.plan.maxRound)?.verdict?.verdict !== 'approve') return undefined
1118
+ let designated: number | undefined
1119
+ for (const [round, record] of log.code.rounds)
1120
+ if (
1121
+ record.startedSeq !== undefined &&
1122
+ record.startedSeq > escalation.answeredSeq &&
1123
+ (designated === undefined || round < designated)
1124
+ )
1125
+ designated = round
1126
+ if (designated === undefined)
1127
+ return { escalation, round: (log.code.maxRound || log.code.maxRoundEver) + 1 }
1128
+ if (log.code.rounds.get(designated)?.completedSeq !== undefined) return undefined
1129
+ return { escalation, round: designated }
1130
+ }
1131
+
1132
+ /** A preparation already frozen in durable state: an active automatic
1133
+ * restack, or an open reconcile occurrence. `intended` when its candidate
1134
+ * recorded a publish intent and must settle rather than be superseded. */
1135
+ export function frozenPreparation(
1136
+ state: BuildState,
1137
+ log: LogIndex,
1138
+ ): { attempt: number; cycle: number; restackId?: string; intended: boolean } | undefined {
1139
+ const active = log.restack.active
1140
+ if (active !== undefined)
1141
+ return {
1142
+ // An unadopted automatic transaction never started a reconcile, so the
1143
+ // next attempt cannot match a completed occurrence's transaction.
1144
+ attempt: log.restack.reconcileAttempt ?? state.reconcileAttempts + 1,
1145
+ cycle: active.cycle,
1146
+ restackId: active.id,
1147
+ intended: log.restack.intent !== undefined || log.openReconcile?.intended === true,
1148
+ }
1149
+ if (state.currentPhase?.phase === 'reconcile' || log.openReconcile !== undefined)
1150
+ return {
1151
+ attempt:
1152
+ (state.currentPhase?.phase === 'reconcile' ? state.currentPhase.attempt : undefined) ??
1153
+ log.openReconcile?.attempt ??
1154
+ state.reconcileAttempts,
1155
+ cycle: log.lastConflict?.seq ?? 0,
1156
+ intended: log.openReconcile?.intended === true,
1157
+ }
1158
+ return undefined
1159
+ }
1160
+
1043
1161
  function decideLoop(args: LoopArgs): Decision | 'approved' {
1044
1162
  const {
1045
1163
  loop,
@@ -25,6 +25,13 @@ import {
25
25
  type RetentionOutcome,
26
26
  } from './history-retention'
27
27
  import { readRetainedPack, RetainedCopyInvalid } from './replay-retention'
28
+ import {
29
+ classifyTrackedDirt,
30
+ formatPathList,
31
+ listTrackedDirt,
32
+ restoreTrackedPaths,
33
+ TrackedDirtRefusal,
34
+ } from './tracked-dirt'
28
35
 
29
36
  export type ReconcileTransaction = EventPayload<'reconcile.prepared'>
30
37
  export interface RestackDeps {
@@ -36,6 +43,9 @@ export interface RestackDeps {
36
43
  instance?: string
37
44
  clock?: import('../store/types').Clock
38
45
  beforeRewrite?: () => Promise<void>
46
+ /** Declared `[[generated]]` entries: their tracked dirt is discarded before
47
+ * a replay instead of refusing preparation. */
48
+ generated?: readonly GeneratedEntry[]
39
49
  probeCandidate?: (input: {
40
50
  ref: string
41
51
  slug: string
@@ -578,11 +588,15 @@ async function continuePreparation(
578
588
  (e) => e.type === 'reconcile.publish-intended' && e.payload.id === transaction.id,
579
589
  )
580
590
  if (intent?.type === 'reconcile.publish-intended') {
591
+ // The frozen candidate publishes exactly as recorded, so dirt is
592
+ // classified even when the workspace already holds it (a same-workspace
593
+ // relaunch): generated dirt is discarded, undeclared dirt refuses.
594
+ await settleTrackedDirt(deps, {
595
+ operation: deps.automatic ? 'restack' : 'reconcile',
596
+ id: transaction.id,
597
+ prefix: 'cannot publish an intended replay over local changes',
598
+ })
581
599
  if (currentHead === intent.payload.headSha && parent === transaction.targetBase) return
582
- if ((await output(deps, ['status', '--porcelain', '--untracked-files=no'])) !== '')
583
- throw new Error(
584
- 'cannot restore an intended replay over local changes; preserve and inspect them',
585
- )
586
600
  const candidate = intent.payload.headSha
587
601
  await restoreOrRedo(ctx, candidate)
588
602
  await deps.beforeRewrite?.()
@@ -593,8 +607,17 @@ async function continuePreparation(
593
607
  parent === transaction.targetBase &&
594
608
  currentHead !== transaction.workspaceHead &&
595
609
  buildTrailers(await output(deps, ['show', '-s', '--format=%B', 'HEAD'])).join() === deps.slug
596
- )
610
+ ) {
611
+ // A completed automatic replay is about to record its intent: classify
612
+ // dirt now. A resolver's uncommitted work is left to its session.
613
+ if (deps.automatic !== undefined)
614
+ await settleTrackedDirt(deps, {
615
+ operation: 'restack',
616
+ id: transaction.id,
617
+ prefix: 'cannot publish a replay over local changes',
618
+ })
597
619
  return
620
+ }
598
621
  // A replacement workspace without a resolved intent replays the same durable
599
622
  // change; no resolver-authored result is discarded.
600
623
  }
@@ -626,10 +649,11 @@ async function continuePreparation(
626
649
  head !== transaction.workspaceHead
627
650
  )
628
651
  ) {
629
- if ((await output(deps, ['status', '--porcelain', '--untracked-files=no'])) !== '')
630
- throw new Error(
631
- 'reconcile preparation requires a clean tracked worktree; preserve and inspect local work',
632
- )
652
+ await settleTrackedDirt(deps, {
653
+ operation: deps.automatic ? 'restack' : 'reconcile',
654
+ id: transaction.id,
655
+ prefix: 'reconcile preparation requires a clean tracked worktree',
656
+ })
633
657
  await deps.beforeRewrite?.()
634
658
  await git(deps, ['checkout', '--detach', transaction.targetBase])
635
659
  const result = await commitGit(
@@ -676,6 +700,45 @@ async function continuePreparation(
676
700
  })
677
701
  }
678
702
 
703
+ /**
704
+ * The pre-replay clean-tree gate. A clean tree passes. Dirt confined to
705
+ * declared `[[generated]]` paths is restored to HEAD and recorded once as an
706
+ * observation. Any undeclared dirt refuses with `TrackedDirtRefusal` naming
707
+ * those paths, and nothing is touched, not even generated paths in the set.
708
+ */
709
+ export async function settleTrackedDirt(
710
+ deps: Pick<RestackDeps, 'store' | 'slug' | 'exec' | 'workspacePath' | 'generated'> &
711
+ Partial<Pick<RestackDeps, 'beforeRewrite'>>,
712
+ input: { operation: 'restack' | 'reconcile'; id: string; prefix?: string },
713
+ ): Promise<void> {
714
+ const dirt = await listTrackedDirt(deps.exec, deps.workspacePath)
715
+ if (dirt.length === 0) return
716
+ const { undeclared } = classifyTrackedDirt(dirt, deps.generated ?? [])
717
+ if (undeclared.length > 0)
718
+ throw new TrackedDirtRefusal(
719
+ input.prefix ?? `${input.operation} preparation requires a clean tracked worktree`,
720
+ undeclared,
721
+ )
722
+ await deps.beforeRewrite?.()
723
+ await restoreTrackedPaths(deps.exec, deps.workspacePath, dirt)
724
+ const id = `${input.operation}:${input.id}:generated-dirt:${createHash('sha256')
725
+ .update(JSON.stringify(dirt))
726
+ .digest('hex')}`
727
+ const { observations } = (await readBuildFacts(deps.store, deps.slug)).value
728
+ if (observations.some((entry) => entry.id === id)) return
729
+ await deps.store.append(deps.slug, {
730
+ actor: KERNEL,
731
+ type: 'observation.recorded',
732
+ payload: {
733
+ id,
734
+ kind: 'followup',
735
+ summary: `Discarded uncommitted [[generated]] changes before ${input.operation} preparation: ${formatPathList(dirt)}`,
736
+ files: dirt,
737
+ refs: [`${input.operation}:${input.id}`],
738
+ },
739
+ })
740
+ }
741
+
679
742
  /** `git clean` pathspecs for every declared generated selector. */
680
743
  export function generatedCleanPathspecs(declarations: readonly GeneratedEntry[]): string[] {
681
744
  return generatedSelectors(declarations).map((selector) => `:(glob)${selector}`)
@@ -98,4 +98,5 @@ export const REDUCER_REVISIONS: Readonly<Record<string, string>> = {
98
98
  'repositoryReadFacts/fold/5porrk9y1h': '#1406 latest dispatcher.work-deferred is carried forward',
99
99
  'repositoryReadFacts/shape/ez3eddcdoo': '#1409 pass cursors and stage timings',
100
100
  'repositoryReadFacts/fold/0xl1c98cpy': '#1409 latest dispatcher.pass-cursors is carried forward',
101
+ 'repositoryReadFacts/shape/70jpyc3nd3': '#1415 launch step, cut instance in deferred hint',
101
102
  }