@defrex/autobuild 1.10.0 → 1.11.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 (250) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +738 -68
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +155 -25
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +63 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +101 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +178 -76
  41. package/packages/core/src/cli/dashboard/render.ts +129 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +29 -38
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +200 -34
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +97 -43
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +316 -0
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  94. package/packages/core/src/kernel/build-roster.ts +230 -0
  95. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  96. package/packages/core/src/kernel/engine.ts +43 -5
  97. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  98. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  99. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  100. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  101. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  102. package/packages/core/src/kernel/log-index.ts +19 -0
  103. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  104. package/packages/core/src/kernel/optimization.ts +183 -4
  105. package/packages/core/src/kernel/phase-failures.ts +121 -0
  106. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  107. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  108. package/packages/core/src/kernel/reducer-revisions.ts +25 -0
  109. package/packages/core/src/kernel/reducer.ts +63 -4
  110. package/packages/core/src/kernel/rollup.ts +61 -0
  111. package/packages/core/src/kernel/setup-streak.ts +38 -0
  112. package/packages/core/src/kernel/step-durations.ts +257 -0
  113. package/packages/core/src/kernel/target-observation.ts +6 -1
  114. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  115. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  116. package/packages/core/src/kernel/verify-stages.ts +13 -3
  117. package/packages/core/src/ontology.ts +5 -0
  118. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  119. package/packages/core/src/operator/annotations.ts +75 -5
  120. package/packages/core/src/operator/attention.ts +470 -0
  121. package/packages/core/src/operator/canonical-skills.ts +35 -0
  122. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  123. package/packages/core/src/operator/context-prompts.ts +61 -0
  124. package/packages/core/src/operator/index.ts +49 -1
  125. package/packages/core/src/operator/landings.ts +28 -19
  126. package/packages/core/src/operator/optimization.ts +7 -0
  127. package/packages/core/src/operator/protocol.ts +3 -0
  128. package/packages/core/src/operator/query.ts +122 -72
  129. package/packages/core/src/operator/read-view.ts +5 -2
  130. package/packages/core/src/operator/registry.ts +406 -46
  131. package/packages/core/src/operator/requests.ts +20 -18
  132. package/packages/core/src/operator/sandbox-host.ts +107 -11
  133. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  134. package/packages/core/src/operator/sandbox.ts +778 -82
  135. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  136. package/packages/core/src/operator/ticket-assets.ts +167 -0
  137. package/packages/core/src/operator/tickets.ts +33 -2
  138. package/packages/core/src/plugin-sdk/index.ts +22 -0
  139. package/packages/core/src/plugins/manifest.ts +1 -1
  140. package/packages/core/src/ports/forge/fake.ts +92 -1
  141. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  142. package/packages/core/src/ports/forge/github.ts +82 -0
  143. package/packages/core/src/ports/forge/local-git.ts +61 -1
  144. package/packages/core/src/ports/forge-failure.ts +24 -0
  145. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  146. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  147. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  148. package/packages/core/src/ports/tickets/contract.ts +71 -0
  149. package/packages/core/src/ports/tickets/fake.ts +11 -0
  150. package/packages/core/src/ports/tickets/file.ts +18 -0
  151. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  152. package/packages/core/src/ports/tickets/github.ts +387 -30
  153. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  154. package/packages/core/src/ports/tickets/linear.ts +130 -0
  155. package/packages/core/src/ports/tickets/priority.ts +9 -0
  156. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  157. package/packages/core/src/ports/tickets/remote.ts +70 -6
  158. package/packages/core/src/ports/tickets/search.ts +139 -0
  159. package/packages/core/src/ports/types.ts +104 -2
  160. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  161. package/packages/core/src/ports/workspace/create.ts +15 -1
  162. package/packages/core/src/ports/workspace/fake.ts +340 -12
  163. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  164. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  165. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  166. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  167. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  168. package/packages/core/src/processes/agent-context.ts +469 -0
  169. package/packages/core/src/processes/build-runner.ts +387 -236
  170. package/packages/core/src/processes/dispatcher.ts +211 -55
  171. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  172. package/packages/core/src/processes/optimization-activity.ts +120 -0
  173. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  174. package/packages/core/src/processes/repo-view.ts +78 -2
  175. package/packages/core/src/processes/sandbox-state.ts +53 -6
  176. package/packages/core/src/processes/tick-publication.ts +2 -0
  177. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  178. package/packages/core/src/scenarios/harness.ts +0 -5
  179. package/packages/core/src/store/account-redaction.ts +1 -0
  180. package/packages/core/src/store/adapter.ts +52 -1
  181. package/packages/core/src/store/agent-context.ts +432 -0
  182. package/packages/core/src/store/build-feed.ts +291 -0
  183. package/packages/core/src/store/build-scope.ts +19 -1
  184. package/packages/core/src/store/contract.ts +911 -14
  185. package/packages/core/src/store/digest.ts +19 -6
  186. package/packages/core/src/store/histogram.ts +113 -0
  187. package/packages/core/src/store/local/schema.ts +62 -0
  188. package/packages/core/src/store/local/store.ts +628 -22
  189. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  190. package/packages/core/src/store/memory.ts +461 -69
  191. package/packages/core/src/store/open-builds.ts +19 -0
  192. package/packages/core/src/store/phase-session.ts +32 -4
  193. package/packages/core/src/store/reduced-reads.ts +14 -4
  194. package/packages/core/src/store/reducer-value-shapes.json +6987 -5749
  195. package/packages/core/src/store/reducer-values.ts +6 -1
  196. package/packages/core/src/store/remote/client.ts +208 -2
  197. package/packages/core/src/store/remote/compatibility.ts +1 -1
  198. package/packages/core/src/store/remote/index.ts +33 -0
  199. package/packages/core/src/store/remote/protocol.ts +69 -0
  200. package/packages/core/src/store/remote/released-clients.json +11 -0
  201. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  202. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  203. package/packages/core/src/store/retention.ts +23 -1
  204. package/packages/core/src/store/rollups.ts +337 -0
  205. package/packages/core/src/store/session-handle.ts +20 -2
  206. package/packages/core/src/store/snapshots.ts +10 -0
  207. package/packages/core/src/store/types.ts +108 -9
  208. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  209. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  210. package/packages/core/src/testing/index.ts +27 -0
  211. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  212. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  213. package/packages/core/src/web/analytics-source.ts +303 -0
  214. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  215. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  216. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  217. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  218. package/packages/core/src/web/assets/app.css +1 -0
  219. package/packages/core/src/web/assets/app.js +9 -0
  220. package/packages/core/src/web/assets/manifest.json +31 -0
  221. package/packages/core/src/web/assets/theme.js +1 -0
  222. package/packages/core/src/web/bounded.ts +31 -0
  223. package/packages/core/src/web/http.ts +315 -0
  224. package/packages/core/src/web/hub.ts +160 -0
  225. package/packages/core/src/web/options.ts +38 -0
  226. package/packages/core/src/web/overview-source.ts +322 -0
  227. package/packages/core/src/web/page.ts +56 -0
  228. package/packages/core/src/web/protocol.ts +151 -0
  229. package/packages/core/src/web/read-only.ts +23 -0
  230. package/packages/core/src/web/repository-source.ts +35 -0
  231. package/packages/core/src/web/server.ts +97 -0
  232. package/skills/code-review/SKILL.md +10 -2
  233. package/skills/guide/SKILL.md +366 -52
  234. package/skills/guide/references/accounts.md +2 -1
  235. package/skills/guide/references/integration-tree.md +2 -2
  236. package/skills/guide/references/operator-api.md +134 -6
  237. package/skills/guide/references/optimization-nodes.md +69 -11
  238. package/skills/guide/references/plugin-authoring.md +37 -1
  239. package/skills/guide/references/remote-store-protocol.md +94 -13
  240. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  241. package/skills/guide/references/restacking.md +20 -4
  242. package/skills/guide/references/setup.md +14 -2
  243. package/skills/guide/references/ticket-dependencies.md +10 -3
  244. package/skills/implement/SKILL.md +23 -4
  245. package/skills/operate/SKILL.md +134 -32
  246. package/skills/plan/SKILL.md +10 -4
  247. package/skills/plan-review/SKILL.md +9 -2
  248. package/skills/spec/SKILL.md +34 -8
  249. package/skills/tickets/SKILL.md +51 -5
  250. package/templates/hosted-service/package.json +2 -2
@@ -18,6 +18,19 @@ function page(lines: string[]): string {
18
18
  * that are part of the public CLI contract.
19
19
  */
20
20
  export const HELP_CATALOG: readonly HelpEntry[] = [
21
+ {
22
+ name: 'operator',
23
+ audience: 'human',
24
+ summary: 'Read or save the checkout-local dispatcher ownership preference.',
25
+ detail: page([
26
+ 'Usage: ab operator dispatcher [human|agent] [--json]',
27
+ 'Without a value, reads the preference (unset when absent) without creating a file.',
28
+ 'Saving writes only .autobuild/local.toml and may normalize its TOML formatting.',
29
+ 'Other settings are preserved. Writes are refused inside build or harvest sessions.',
30
+ 'This command needs no store or credential and does not start or stop a dispatcher.',
31
+ 'Repository instructions take precedence over this personal preference.',
32
+ ]),
33
+ },
21
34
  {
22
35
  name: 'help',
23
36
  audience: 'human',
@@ -144,7 +157,9 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
144
157
  detail: page([
145
158
  'Usage:',
146
159
  ' ab dispatch [--once] [--interval <s>] [--store <ref>] [--plain] [--intake | --no-intake]',
160
+ ' [--web [--port <n>] [--host <addr>] [--json]]',
147
161
  ' ab dispatch --viewer [--dispatched-by <label>] [--once] [--interval <s>] [--store <ref>] [--plain]',
162
+ ' [--web [--port <n>] [--host <addr>] [--json]]',
148
163
  '',
149
164
  'Run the outer loop for this repository: resume current builds, run the',
150
165
  'janitor and lease sweep, and dispatch ready work (§3.3, §12). This command',
@@ -172,6 +187,20 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
172
187
  'Plain/non-TTY output states the same at startup and prints state changes.',
173
188
  'Viewer keeps the shared-store controls below; Ctrl-C never stops dispatch elsewhere.',
174
189
  '',
190
+ 'Web UI:',
191
+ ' --web Also serve the read-only web UI (see ab help web).',
192
+ ' --port <n>, --host <addr>, --json',
193
+ ' As for ab web; valid only with --web. --json changes',
194
+ ' only the URL announcement line.',
195
+ 'A TTY keeps the terminal dashboard; under --plain or without a TTY the web',
196
+ 'UI is the only presentation. It shows what the dispatcher’s own refresh',
197
+ 'reads, so in plain mode it updates each tick. Dashboard frames add no store',
198
+ 'reads; a plain dispatcher reads one change position per tick while a',
199
+ 'browser is connected. Analytics are explicit reads once the store is open.',
200
+ 'The server binds before the repository lease; a taken port fails dispatch.',
201
+ 'The URL keeps working across automatic runtime upgrades. Ctrl-C closes it.',
202
+ '--web cannot be combined with --once.',
203
+ '',
175
204
  '',
176
205
  'An interactive terminal gets a fixed global/harvest/build dashboard.',
177
206
  'TTY controls:',
@@ -211,6 +240,7 @@ export const HELP_CATALOG: readonly HelpEntry[] = [
211
240
  ' ab ticket block <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
212
241
  ' ab ticket unblock <id> <blocker-id[,blocker-id...]> [--expected-revision <opaque>] [--json]',
213
242
  ' ab ticket list [--state <state>] [--labels a,b] [--json]',
243
+ ' ab ticket search <query> [--state <state>] [--labels a,b] [--limit <n>] [--cursor <cursor>] [--json]',
214
244
  ' ab ticket show <id> [--store <ref>] [--json]',
215
245
  ' ab ticket move <id> (<state> | --role triage|ready|backlog|rejected) [--expected-revision <opaque>] [--json]',
216
246
  ' ab ticket states [--json]',
@@ -259,6 +289,13 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
259
289
  'adds an assets array (kind, name, revision, size, layout, fileCount). Sources',
260
290
  'that store assignees add an assignees array of usernames.',
261
291
  '',
292
+ 'search finds tickets whose title or body contains every word of the query,',
293
+ 'case-insensitively, in any state unless --state is given. Use it to check for',
294
+ 'duplicates before create. --limit (default 20, at most 100) sizes a page, and',
295
+ "--cursor continues from the previous page's cursor. --json emits",
296
+ '{tickets, cursor?, diagnostics}, identical to MCP tickets.search. Sources',
297
+ 'without search exit nonzero, naming the source, and list nothing.',
298
+ '',
262
299
  'Ticket assets are files or folders (a design export, a reference screenshot, a',
263
300
  'sample payload) attached to a ticket and kept in the BuildStore, never in the',
264
301
  'ticket source. attach stores <path> under <kind> and a name (default: the',
@@ -415,7 +452,8 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
415
452
  '',
416
453
  'Default filter — actionable attention only. Builds: escalation.raised, phase.deferral-escalated, integration.landed,',
417
454
  'integration.verification-failed (failed node verification), build.janitor-failing, build.janitor-escalated,',
418
- 'build.compatibility-deferred, node.item-conflicted, target.rewritten, conflicted restack.replayed,',
455
+ 'build.compatibility-deferred, node.item-conflicted, target.rewritten (a node, once per rejected baseline),',
456
+ 'conflicted restack.replayed,',
419
457
  'landing.consent-revoked (protected merge consent revoked by a reconcile),',
420
458
  "pr.checks-failed (failing forge CI on a finished leaf's live PR head),",
421
459
  "optimization.noise-exceeded (an optimization node's ε is below its measured noise), derived build.consent-ready and",
@@ -481,6 +519,45 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
481
519
  'and --repository are rejected, as are malformed or partial identity.',
482
520
  ]),
483
521
  },
522
+ {
523
+ name: 'web',
524
+ audience: 'human',
525
+ summary: "Serve the read-only web UI for this repository's builds.",
526
+ detail: page([
527
+ 'Usage:',
528
+ ' ab web [--port <n>] [--host <addr>] [--json] [--store <ref>]',
529
+ '',
530
+ "Serve a web UI of this repository's builds to a local browser. It reads the",
531
+ 'BuildStore the way ab watch does and runs outside sessions. The page, its',
532
+ 'scripts, styles and fonts all come from this server; nothing loads from',
533
+ 'elsewhere. Every page response carries a strict Content-Security-Policy.',
534
+ '',
535
+ 'Read-only: ab web appends no event, takes no dispatcher lease and registers no',
536
+ 'operator presence. Only GET and HEAD are accepted, and its store refuses writes.',
537
+ '',
538
+ 'One refresh loop serves every open tab over one event stream (/events). While no',
539
+ 'browser is connected, ab web reads nothing from the store.',
540
+ '',
541
+ 'Pages: the overview (/), each build (/builds/<slug>, ending with its timeline)',
542
+ 'and analytics (/analytics): a Gantt of builds and step durations over a window.',
543
+ 'Analytics and timelines are explicit JSON reads (/api/analytics,',
544
+ '/api/builds/<slug>/timeline), fetched again only when the store changes.',
545
+ '',
546
+ 'Options:',
547
+ ' --port <n> Listen on this port. Default: a free port the OS assigns. Fails',
548
+ ' if the port is already in use.',
549
+ ' --host <addr> Bind address. Default 127.0.0.1. A request whose Host header is',
550
+ ' not the bound address, localhost or 127.0.0.1 is refused. Any',
551
+ ' other --host turns that check off and serves beyond loopback',
552
+ ' with no access control: ab web warns on stderr that anyone who',
553
+ " can reach the port can read the repository's builds.",
554
+ ' --json Print exactly one line once listening: {"url":"http://127.0.0.1:<port>/"}.',
555
+ ' Without it, print one human-readable line with the URL.',
556
+ ' --store <ref> Override the BuildStore path or URL.',
557
+ '',
558
+ 'Stop it with Ctrl-C.',
559
+ ]),
560
+ },
484
561
  {
485
562
  name: 'wait',
486
563
  audience: 'human',
@@ -650,6 +727,7 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
650
727
  ' ab answer <slug> [<text>] --dismiss [--store <ref>]',
651
728
  ' ab answer <slug> [<text>] --revise-spec <file> [--store <ref>]',
652
729
  ' ab answer <slug> [<text>] --revise-spec-from-ticket [--store <ref>]',
730
+ ' ab answer <slug> [<text>] --accept-target [--store <ref>]',
653
731
  '',
654
732
  'Nonblank text supplies guidance to the loop producer.',
655
733
  'Omitting text requests a bare retry. --dismiss retires each cited finding chain,',
@@ -674,6 +752,11 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
674
752
  'recorded. Retrying an interrupted revision completes the exact body authorized by',
675
753
  'the earlier recorded answer, not a newly supplied body.',
676
754
  '',
755
+ '--accept-target answers only a target-rewritten escalation: a leaf whose target',
756
+ 'was rewritten while it had work of its own. It waives the rejected base and restacks',
757
+ "the build's own commits onto the current target before any further verification.",
758
+ 'Other answer forms skip that escalation; ab abort is the other way out.',
759
+ '',
677
760
  'If paused and every blocker clears, resume is requested last. --store overrides the',
678
761
  'BuildStore path or URL. This command is sessionless; a phase may not answer its',
679
762
  'own build.',
@@ -778,13 +861,14 @@ These fields describe intent; dispatch and merge behavior are unchanged.`,
778
861
  '',
779
862
  'Without flags, prints the effective objective, marking every field revised since',
780
863
  'it was accepted, and progress: starting, current and best values, attempts filed,',
781
- 'accepted, rejected and running, the plateau counter, elapsed hours and stop',
864
+ 'accepted, rejected and running, the plateau counter, active hours and stop',
782
865
  'eligibility. With flags, records optimization.objective-revised and then prints.',
783
866
  '',
784
867
  ' --threshold n Stop when the node head reaches n.',
785
868
  ' --epsilon n|n% Smallest gain that counts: 2 is absolute, 3% is relative 0.03.',
786
869
  ' --max-attempts n Attempts budget.',
787
- ' --max-hours n Hours budget since the node opened.',
870
+ ' --max-hours n Active-hours budget: hours while an attempt, the proposer',
871
+ ' or a measurement runs.',
788
872
  ' --plateau n Consecutive no-improvement or declined attempts that stop it.',
789
873
  ' --stop-mode m abort or drain.',
790
874
  ' --concurrency n Attempts in flight.',
@@ -23,7 +23,7 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises'
23
23
  import { tmpdir } from 'node:os'
24
24
  import { join, resolve } from 'node:path'
25
25
  import { effectiveRuntimeReferences } from '../config/roles'
26
- import type { Config, TicketsConfig } from '../config/schema'
26
+ import { orchestratorEnabled, type Config, type TicketsConfig } from '../config/schema'
27
27
  import { loadConfig } from '../config/load'
28
28
  import { createRuntimeResolver } from '../ports/runner/routing'
29
29
  import type { RuntimeRegistry } from '../ports/runner/runtime'
@@ -484,7 +484,7 @@ function declaredForgeEnvChecks(
484
484
  * `sandboxForbiddenEnv` extras. Enforced at the registry-aware init seam so a
485
485
  * plugin-declared forbidden name is refused before any infrastructure is
486
486
  * provisioned, mirroring `createWorkspaceProvider`'s construction-site check:
487
- * same gate (`[orchestrator].enabled`), same name union
487
+ * same gate (`[orchestrator].enabled`, resolved for the local host), same name union
488
488
  * (`SANDBOX_FORBIDDEN_ENV` plus the declared extras), same message. A no-op
489
489
  * repeat for builtins — config parse already rejected every shared and
490
490
  * builtin-declared name — and a no-op when the declaration is absent. */
@@ -492,7 +492,7 @@ function declaredSandboxForbiddenEnvCheck(
492
492
  caps: WorkspaceProviderCapabilities | undefined,
493
493
  config: Config,
494
494
  ): void {
495
- if (!config.orchestrator.enabled || caps?.sandboxForbiddenEnv === undefined) return
495
+ if (!orchestratorEnabled(config, 'local') || caps?.sandboxForbiddenEnv === undefined) return
496
496
  for (const name of config.orchestrator.sandbox.environmentVariables) {
497
497
  if (SANDBOX_FORBIDDEN_ENV.includes(name) || caps.sandboxForbiddenEnv.includes(name)) {
498
498
  throw new Error(sandboxForbiddenEnvMessage(name))
@@ -57,6 +57,7 @@ import type { PinnedAsset } from '../events/payloads'
57
57
  * switch makes it unit-testable.
58
58
  */
59
59
  export const SESSIONLESS_COMMANDS = new Set([
60
+ 'operator',
60
61
  'init',
61
62
  'connect',
62
63
  'disconnect',
@@ -73,6 +74,7 @@ export const SESSIONLESS_COMMANDS = new Set([
73
74
  'build',
74
75
  'watch',
75
76
  'wait',
77
+ 'web',
76
78
  'mcp',
77
79
  'repository',
78
80
  'restack',
@@ -277,6 +279,10 @@ export function buildControlConfirmation(result: BuildControlResult): string {
277
279
  result.resumed ? '; resume requested' : ''
278
280
  }`
279
281
  }
282
+ if (result.resolution === 'accept-target')
283
+ return `build ${result.slug}: accepted the rewritten target for ${result.count} escalation${plural}; the build's own commits restack onto it${
284
+ result.resumed ? '; resume requested' : ''
285
+ }`
280
286
  if (result.resolution === 'dismiss-finding' && (result.remainingOpen ?? 0) > 0) {
281
287
  const remaining = result.remainingOpen ?? 0
282
288
  return `build ${result.slug}: dismissed ${result.count} escalation${plural}; ${remaining} blocker${
@@ -552,6 +558,21 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
552
558
 
553
559
  // init and upgrade run OUTSIDE build sessions (§16.3): they operate on a
554
560
  // repo, not a build, so they route before any store/env requirement.
561
+ case 'operator': {
562
+ const usage = 'usage: ab operator dispatcher [human|agent] [--json]'
563
+ const parsed = parseArgs(rest, { json: 'boolean' }, usage)
564
+ if (parsed.positionals[0] !== 'dispatcher' || parsed.positionals.length > 2)
565
+ throw new Error(usage)
566
+ const { abOperatorDispatcher } = await import('./operator-preference')
567
+ await abOperatorDispatcher({
568
+ targetRepo: deps.workspacePath,
569
+ value: parsed.positionals[1],
570
+ json: parsed.flags.get('json') === true,
571
+ env: deps.processEnv ?? process.env,
572
+ stdout,
573
+ })
574
+ return 0
575
+ }
555
576
  case 'accounts': {
556
577
  const { abAccountsLogin } = await import('./accounts')
557
578
  const usage = 'usage: ab accounts login NAME [--local|--project]'
@@ -841,6 +862,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
841
862
  intervalMs,
842
863
  storeRef,
843
864
  repository,
865
+ web,
844
866
  } = parseDispatchArgs(rest, deps.processEnv ?? {})
845
867
  if (deps.exec === undefined) {
846
868
  throw new Error("'ab dispatch' needs an exec seam — this is a wiring bug in the ab binary")
@@ -861,6 +883,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
861
883
  ...(intervalMs !== undefined ? { intervalMs } : {}),
862
884
  ...(storeRef !== undefined ? { storeRef } : {}),
863
885
  ...(repository !== undefined && repository !== '' ? { repository } : {}),
886
+ ...(web !== undefined ? { web } : {}),
864
887
  ...(deps.signal !== undefined ? { signal: deps.signal } : {}),
865
888
  ...(deps.terminal !== undefined ? { terminal: deps.terminal } : {}),
866
889
  ...(deps.input !== undefined ? { input: deps.input } : {}),
@@ -1161,6 +1184,38 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1161
1184
  return 0
1162
1185
  }
1163
1186
 
1187
+ // The read-only web UI: store-only like `ab watch`, it appends nothing,
1188
+ // takes no lease and registers no presence. Serves until SIGINT.
1189
+ case 'web': {
1190
+ const { abWeb, parseWebPort, WEB_USAGE } = await import('./web')
1191
+ const parsed = parseArgs(
1192
+ rest,
1193
+ { port: 'value', host: 'value', json: 'boolean', store: 'value' },
1194
+ WEB_USAGE,
1195
+ )
1196
+ if (parsed.positionals.length > 0) throw new Error(WEB_USAGE)
1197
+ const port = parseWebPort(stringFlag(parsed, 'port'))
1198
+ const host = stringFlag(parsed, 'host')
1199
+ const storeRef = stringFlag(parsed, 'store')
1200
+ if (deps.exec === undefined) {
1201
+ throw new Error("'ab web' needs an exec seam — this is a wiring bug in the ab binary")
1202
+ }
1203
+ await abWeb({
1204
+ targetRepo: deps.workspacePath,
1205
+ env: deps.processEnv ?? {},
1206
+ exec: deps.exec,
1207
+ stdout,
1208
+ stderr,
1209
+ port,
1210
+ ...(host !== undefined ? { host } : {}),
1211
+ json: parsed.flags.has('json'),
1212
+ ...(storeRef !== undefined ? { storeRef } : {}),
1213
+ ...(deps.openStore !== undefined ? { openStore: deps.openStore } : {}),
1214
+ ...(deps.signal !== undefined ? { signal: deps.signal } : {}),
1215
+ })
1216
+ return 0
1217
+ }
1218
+
1164
1219
  // Read-only blocking runs OUTSIDE build sessions (§16.3) exactly like
1165
1220
  // `ab watch`: it resolves its own store and honors a complete ambient
1166
1221
  // identity as a scope restriction. Exit codes 0/2/3/4 are the command's
@@ -1465,12 +1520,13 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1465
1520
 
1466
1521
  case 'answer': {
1467
1522
  const usage =
1468
- 'usage: ab answer <slug> [<text>] [--review-round-ceiling <n> | --dismiss | --revise-spec <file> | --revise-spec-from-ticket] [--store <ref>]'
1523
+ 'usage: ab answer <slug> [<text>] [--review-round-ceiling <n> | --dismiss | --revise-spec <file> | --revise-spec-from-ticket | --accept-target] [--store <ref>]'
1469
1524
  const parsed = parseArgs(
1470
1525
  rest,
1471
1526
  {
1472
1527
  store: 'value',
1473
1528
  dismiss: 'boolean',
1529
+ 'accept-target': 'boolean',
1474
1530
  'revise-spec': 'value',
1475
1531
  'revise-spec-from-ticket': 'boolean',
1476
1532
  'review-round-ceiling': 'value',
@@ -1483,6 +1539,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1483
1539
  parsed.flags.has('dismiss'),
1484
1540
  parsed.flags.has('revise-spec'),
1485
1541
  parsed.flags.has('revise-spec-from-ticket'),
1542
+ parsed.flags.has('accept-target'),
1486
1543
  ].filter(Boolean).length
1487
1544
  if (resolutionFlags > 1) throw new Error(`resolution flags are mutually exclusive — ${usage}`)
1488
1545
  const answer = text.join(' ')
@@ -1507,15 +1564,22 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1507
1564
  'cannot combine --review-round-ceiling with --dismiss; use guidance or a bare retry to answer the review-round-limit escalation',
1508
1565
  )
1509
1566
  }
1567
+ if (parsed.flags.has('accept-target')) {
1568
+ throw new Error(
1569
+ 'cannot combine --review-round-ceiling with --accept-target; it answers only a target-rewritten escalation',
1570
+ )
1571
+ }
1510
1572
  reviewRoundCeiling = parsedCeiling
1511
1573
  }
1512
1574
  const resolve = parsed.flags.has('dismiss')
1513
1575
  ? ({ kind: 'dismiss-finding' } as const)
1514
- : specPath !== undefined
1515
- ? ({ kind: 'revise-spec', body: suppliedSpecBody(specPath) } as const)
1516
- : parsed.flags.has('revise-spec-from-ticket')
1517
- ? ({ kind: 'revise-spec', body: { kind: 'ticket' } } as const)
1518
- : undefined
1576
+ : parsed.flags.has('accept-target')
1577
+ ? ({ kind: 'accept-target' } as const)
1578
+ : specPath !== undefined
1579
+ ? ({ kind: 'revise-spec', body: suppliedSpecBody(specPath) } as const)
1580
+ : parsed.flags.has('revise-spec-from-ticket')
1581
+ ? ({ kind: 'revise-spec', body: { kind: 'ticket' } } as const)
1582
+ : undefined
1519
1583
  const readers =
1520
1584
  resolve?.kind === 'revise-spec' && resolve.body.kind === 'ticket'
1521
1585
  ? ticketSpecReaders(deps, slug, storeRef, 'ab answer --revise-spec-from-ticket')
@@ -22,7 +22,7 @@ import { join } from 'node:path'
22
22
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
23
23
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
24
24
  import { loadConfig } from '../config/load'
25
- import type { Config } from '../config/schema'
25
+ import { orchestratorEnabled, type Config } from '../config/schema'
26
26
  import type { Via } from '../events/envelope'
27
27
  import { defaultTriageState } from '../processes/dispatcher'
28
28
  import { createWorkspaceProvider } from '../ports/workspace/create'
@@ -37,6 +37,13 @@ import type { Exec } from '../ports/workspace/git-worktree'
37
37
  import { openSessionlessStore, type StoreOpener } from './store-opening'
38
38
  import { InvalidAmbientContextError, resolveAmbientReadSession } from './env'
39
39
  import { buildRegistry, RegistryError, type OperatorToolRegistry } from '../operator/registry'
40
+ import {
41
+ contextInstructions,
42
+ type ContextEntry,
43
+ type ContextIndex,
44
+ type ContextReadResult,
45
+ } from '../operator/agent-context-serve'
46
+ import { registerContextPrompts } from '../operator/context-prompts'
40
47
  import { createOperatorSandboxService, type OperatorSandboxService } from '../operator/sandbox'
41
48
  import type { OperatorTicketBackend } from '../operator/tickets'
42
49
 
@@ -51,6 +58,7 @@ const SERVER_INSTRUCTIONS = [
51
58
  'and the operator API routes — every result equals the corresponding route. Prefer the CLI when a command exists;',
52
59
  'use these tools when no shell is available, for dogfooding, and for parity testing of the tool registry.',
53
60
  'Every tool names its repository explicitly via `repo`; mutating tools append durable, human-attributed events.',
61
+ 'Call `context.list` first: it names the skills and agent instructions to load before acting.',
54
62
  ].join(' ')
55
63
 
56
64
  export interface AbMcpOpts {
@@ -238,11 +246,12 @@ export async function abMcp(opts: AbMcpOpts): Promise<number> {
238
246
  }
239
247
  throw error
240
248
  }
241
- if (mcpConfig.orchestrator.enabled) {
249
+ if (orchestratorEnabled(mcpConfig, 'local')) {
242
250
  const plugins = await loadPlugins(mcpConfig.plugins, context.checkout)
243
251
  const provider = await createWorkspaceProvider(mcpConfig.workspace, {
244
252
  registry: plugins,
245
253
  worktreeRoot: context.worktreeRoot,
254
+ isolatedWorktreeRoot: context.isolatedWorktreeRoot,
246
255
  repoRoot: context.checkout,
247
256
  env: opts.env,
248
257
  storeRef: context.storeRef,
@@ -250,6 +259,7 @@ export async function abMcp(opts: AbMcpOpts): Promise<number> {
250
259
  sandboxSetupCommand: mcpConfig.commands.setup,
251
260
  sandboxRoot: join(context.localStateRoot, 'orchestrator-sandboxes'),
252
261
  sandboxEnvironmentVariables: mcpConfig.orchestrator.sandbox.environmentVariables,
262
+ sandboxIdleMinutes: mcpConfig.orchestrator.sandbox.idleMinutes,
253
263
  orchestratorSandboxEnabled: true,
254
264
  })
255
265
  // The forge is needed only for sandbox.publish; a construction
@@ -293,10 +303,32 @@ export async function abMcp(opts: AbMcpOpts): Promise<number> {
293
303
  ...(opts.repo !== undefined ? { allowedRepo: opts.repo } : {}),
294
304
  })
295
305
 
306
+ // The agent context is read once per process start (one latest-revision
307
+ // artifact read): the long-lived stdio server is not a recurring path.
308
+ const repo = context.repo
309
+ let contextEntry: ContextEntry
310
+ try {
311
+ contextEntry = {
312
+ repo,
313
+ index: (await registry.call('context.list', { repo })) as ContextIndex,
314
+ }
315
+ } catch (error) {
316
+ contextEntry = { repo, error: error instanceof Error ? error.message : String(error) }
317
+ }
296
318
  const server = new McpServer(
297
319
  { name: 'autobuild', version: AUTOBUILD_VERSION },
298
- { instructions: SERVER_INSTRUCTIONS },
320
+ {
321
+ instructions: `${SERVER_INSTRUCTIONS}\n${contextInstructions([contextEntry], { scoped: true })}`,
322
+ },
299
323
  )
324
+ registerContextPrompts(server.server, {
325
+ scoped: true,
326
+ indexes: async () => [
327
+ { repo, index: (await registry.call('context.list', { repo })) as ContextIndex },
328
+ ],
329
+ read: async (target, path) =>
330
+ (await registry.call('context.read', { repo: target, path })) as ContextReadResult,
331
+ })
300
332
  serveRegistry(registry, server, {
301
333
  identity: buildControlUser(opts.env),
302
334
  // Unlike the hosted stateless server, the stdio server is long-lived:
@@ -134,7 +134,7 @@ export function renderObjective(view: ObjectiveView): string[] {
134
134
  ...progress.unmeasuredMerges.map((merge) => ` ${unmeasuredMergeText(merge)}`),
135
135
  ...progress.pendingCleanups.map((cleanup) => ` ${pendingCleanupText(cleanup)}`),
136
136
  ` plateau: ${progress.plateau}`,
137
- ` elapsed: ${progress.elapsedHours.toFixed(1)} hours`,
137
+ ` active: ${progress.elapsedHours.toFixed(1)} hours${progress.settling ? ' (settling: attempt runs before the stop are still being accounted)' : ''}`,
138
138
  ` stop eligible: ${
139
139
  eligible.length === 0
140
140
  ? 'none'
@@ -0,0 +1,57 @@
1
+ import { mkdir, rename, rm } from 'node:fs/promises'
2
+ import { dirname, join } from 'node:path'
3
+ import { stringify } from 'smol-toml'
4
+ import { localConfigPath, parseLayeredConfig, readLocalConfig } from '../config/local'
5
+ import { parseConfigTable } from '../config/load'
6
+
7
+ /** Explicit checkout-local preference; never opens a store or commands a dispatcher. */
8
+ export async function abOperatorDispatcher(opts: {
9
+ targetRepo: string
10
+ value?: string
11
+ json?: boolean
12
+ env: Record<string, string | undefined>
13
+ stdout: (line: string) => void
14
+ }): Promise<void> {
15
+ if (opts.value !== undefined && opts.value !== 'human' && opts.value !== 'agent')
16
+ throw new Error('usage: ab operator dispatcher [human|agent] [--json]')
17
+ if (
18
+ opts.value !== undefined &&
19
+ ['AB_BUILD', 'AB_SESSION', 'AB_HARVEST'].some((name) => opts.env[name]?.trim())
20
+ )
21
+ throw new Error(
22
+ 'operator dispatcher writes require an operator outside a build or harvest session',
23
+ )
24
+ const file = localConfigPath(opts.targetRepo)
25
+ const local = await readLocalConfig(opts.targetRepo)
26
+ const table = local ? parseConfigTable(local.text, file) : {}
27
+ // Validate the local input itself, including its allowlist, before updating it.
28
+ const committed = {
29
+ text: await Bun.file(join(opts.targetRepo, 'autobuild.toml')).text(),
30
+ source: join(opts.targetRepo, 'autobuild.toml'),
31
+ }
32
+ const validate = (text: string) =>
33
+ parseLayeredConfig({ committed, local: { text, source: file } }, () => {}).config
34
+ const before = validate(local?.text ?? '')
35
+ let dispatcher = before.operator?.dispatcher ?? null
36
+ if (opts.value !== undefined) {
37
+ table.operator = {
38
+ ...(table.operator as Record<string, unknown> | undefined),
39
+ dispatcher: opts.value,
40
+ }
41
+ const candidate = stringify(table)
42
+ dispatcher = validate(candidate).operator?.dispatcher ?? null
43
+ await mkdir(dirname(file), { recursive: true })
44
+ const temporary = `${file}.${crypto.randomUUID()}.tmp`
45
+ try {
46
+ await Bun.write(temporary, candidate)
47
+ await rename(temporary, file)
48
+ } finally {
49
+ await rm(temporary, { force: true })
50
+ }
51
+ }
52
+ opts.stdout(
53
+ opts.json
54
+ ? JSON.stringify({ dispatcher, file })
55
+ : `Dispatcher preference: ${dispatcher ?? 'unset'} (${file})`,
56
+ )
57
+ }
@@ -154,6 +154,8 @@ export const FORGE_READ_ALLOWLIST: readonly string[] = [
154
154
  'remoteBranchExists',
155
155
  'isCommitAncestor',
156
156
  'readFile',
157
+ 'readTree',
158
+ 'readBlob',
157
159
  ]
158
160
 
159
161
  const FORGE_CAPABILITIES = ['rewrite', 'kernelRewrite', 'prAttachments']
@@ -21,7 +21,9 @@
21
21
  * interpret a relative path from different working directories.
22
22
  */
23
23
  import { configuredStore } from './configured-store'
24
- import { join, resolve } from 'node:path'
24
+ import { createHash } from 'node:crypto'
25
+ import { homedir } from 'node:os'
26
+ import { basename, isAbsolute, join, resolve } from 'node:path'
25
27
  import type { Exec } from '../ports/workspace/git-worktree'
26
28
  import type { BuildRecord } from '../store/types'
27
29
  import { normalizeGitRemoteUrl } from '../kernel/origin'
@@ -52,10 +54,44 @@ export interface RepoStatePaths {
52
54
  defaultLocalRoot: string
53
55
  /** Normalized local path, or an unchanged HTTP(S) URL. */
54
56
  storeRef: string
55
- /** Root for local-only state (tickets and worktrees). */
57
+ /** Root for local-only state (database, blobs, tickets, accounts). */
56
58
  localStateRoot: string
57
- /** Local scratch root used by GitWorktreeProvider. */
59
+ /** The state tree's own worktree directory, `<localStateRoot>/worktrees`.
60
+ * GitWorktreeProvider uses it for build worktrees only when it resolves
61
+ * outside the checkout; otherwise it is the legacy adoption root. */
58
62
  worktreeRoot: string
63
+ /** Per-checkout build worktree root outside the checkout's package
64
+ * ancestry: `<stateHome>/autobuild/worktrees/<checkout-name>-<hash12>`.
65
+ * GitWorktreeProvider chooses between it and `worktreeRoot` on canonical
66
+ * paths and validates the choice before provisioning. */
67
+ isolatedWorktreeRoot: string
68
+ }
69
+
70
+ /**
71
+ * The host's per-user state home: an absolute nonblank `XDG_STATE_HOME`, else
72
+ * `~/.local/state`. A relative value is ignored, as the XDG Base Directory
73
+ * specification requires. Read from the host process, never a command's
74
+ * injected environment.
75
+ */
76
+ export function hostStateHome(
77
+ env: Record<string, string | undefined> = process.env,
78
+ home: string = homedir(),
79
+ ): string {
80
+ const xdg = env.XDG_STATE_HOME
81
+ return xdg !== undefined && xdg.trim() !== '' && isAbsolute(xdg)
82
+ ? resolve(xdg)
83
+ : join(home, '.local', 'state')
84
+ }
85
+
86
+ /** `<sanitized checkout basename>-<sha256(localStateRoot)[:12]>`: two
87
+ * checkouts, or two state trees of one checkout, never share a root. */
88
+ function worktreeKey(checkout: string, localStateRoot: string): string {
89
+ const name =
90
+ basename(checkout)
91
+ .replace(/[^A-Za-z0-9._-]+/g, '-')
92
+ .replace(/^[.-]+/, '') || 'repo'
93
+ const hash = createHash('sha256').update(localStateRoot).digest('hex').slice(0, 12)
94
+ return `${name}-${hash}`
59
95
  }
60
96
 
61
97
  function nonBlank(value: string | undefined): string | undefined {
@@ -66,9 +102,12 @@ function nonBlank(value: string | undefined): string | undefined {
66
102
  * Select state with one precedence rule for every sessionless command:
67
103
  * non-blank explicit `--store` > non-blank `AB_STORE` > `[store] url` > local default.
68
104
  *
69
- * A local selection relocates the whole local tree, including worktrees. A
70
- * remote store has no filesystem root, so its worktrees remain local beneath
71
- * the repository's implicit state root.
105
+ * A local selection relocates the whole local tree. A remote store has no
106
+ * filesystem root, so its local state stays beneath the repository's implicit
107
+ * state root. Build worktrees get two candidates — the state tree's own
108
+ * `worktrees/` and a per-checkout root under the host state home — and
109
+ * GitWorktreeProvider chooses between them on canonical paths, so a worktree
110
+ * never sits inside the checkout's package ancestry.
72
111
  */
73
112
  export function resolveRepoStatePaths(opts: {
74
113
  /** Repository identity: a normalized origin URL, or a local checkout path. */
@@ -79,6 +118,8 @@ export function resolveRepoStatePaths(opts: {
79
118
  storeRef?: string
80
119
  envStore?: string
81
120
  configStore?: string
121
+ /** Test seam: the host state home. Defaults to `hostStateHome()`. */
122
+ stateHome?: string
82
123
  }): RepoStatePaths {
83
124
  const checkout = resolve(opts.checkout ?? opts.repo)
84
125
  const defaultLocalRoot = join(checkout, LOCAL_STATE_DIR)
@@ -98,6 +139,12 @@ export function resolveRepoStatePaths(opts: {
98
139
  storeRef,
99
140
  localStateRoot,
100
141
  worktreeRoot: join(localStateRoot, 'worktrees'),
142
+ isolatedWorktreeRoot: join(
143
+ opts.stateHome ?? hostStateHome(),
144
+ 'autobuild',
145
+ 'worktrees',
146
+ worktreeKey(checkout, localStateRoot),
147
+ ),
101
148
  }
102
149
  }
103
150
 
@@ -178,6 +225,8 @@ export async function resolveRepoState(opts: {
178
225
  storeRef?: string
179
226
  envStore?: string
180
227
  configStore?: string
228
+ /** Test seam: the host state home. Defaults to `hostStateHome()`. */
229
+ stateHome?: string
181
230
  }): Promise<RepoStatePaths> {
182
231
  const checkout = await resolveMainRepo(opts.targetRepo, opts.exec)
183
232
  const origin = await resolveRepoOrigin(checkout, opts.exec)
@@ -189,5 +238,6 @@ export async function resolveRepoState(opts: {
189
238
  checkout,
190
239
  ...(opts.storeRef !== undefined ? { storeRef: opts.storeRef } : {}),
191
240
  ...(opts.envStore !== undefined ? { envStore: opts.envStore } : {}),
241
+ ...(opts.stateHome !== undefined ? { stateHome: opts.stateHome } : {}),
192
242
  })
193
243
  }