@defrex/autobuild 1.0.1 → 1.2.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 (247) hide show
  1. package/README.md +10 -18
  2. package/SPEC.md +499 -238
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +2 -2
  7. package/docs/architecture.md +262 -53
  8. package/docs/assets/headline-wide.png +0 -0
  9. package/docs/build-store.md +3 -41
  10. package/docs/builds.md +4 -4
  11. package/docs/cli.md +18 -4
  12. package/docs/configuration-overview.md +115 -4
  13. package/docs/configuration.md +488 -334
  14. package/docs/dispatcher-hosting.md +19 -34
  15. package/docs/dispatcher.md +1 -1
  16. package/docs/forges.md +5 -5
  17. package/docs/getting-started.md +2 -2
  18. package/docs/glossary.md +6 -6
  19. package/docs/intake.md +2 -0
  20. package/docs/integration-overview.md +15 -15
  21. package/docs/integration-tree.md +45 -38
  22. package/docs/integration.md +6 -6
  23. package/{skills/guide/references/landing-policy.md → docs/merge-policy.md} +40 -24
  24. package/docs/migration-1.0.md +17 -13
  25. package/docs/operating.md +41 -19
  26. package/docs/operator-api.md +180 -51
  27. package/docs/operator-surfaces.md +5 -18
  28. package/docs/overview.md +3 -3
  29. package/docs/plugin-authoring.md +21 -0
  30. package/docs/remote-store-protocol.md +242 -68
  31. package/docs/remote-ticket-protocol.md +30 -50
  32. package/docs/restacking.md +54 -15
  33. package/docs/seams.md +8 -8
  34. package/docs/setup.md +59 -119
  35. package/docs/skills.md +1 -1
  36. package/docs/spec-standard.md +6 -6
  37. package/docs/ticket-dependencies.md +7 -7
  38. package/docs/ticket-sources.md +18 -0
  39. package/docs/tickets.md +8 -2
  40. package/docs/troubleshooting.md +8 -12
  41. package/docs/upgrading.md +9 -4
  42. package/docs/verification.md +60 -14
  43. package/docs/workspaces.md +4 -4
  44. package/package.json +17 -6
  45. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  46. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  47. package/packages/core/src/accounts/local-credentials.ts +194 -0
  48. package/packages/core/src/accounts/local-inference.ts +106 -0
  49. package/packages/core/src/accounts/local-owner.ts +123 -0
  50. package/packages/core/src/accounts/sensitive.ts +2 -0
  51. package/packages/core/src/cli/accounts.ts +147 -0
  52. package/packages/core/src/cli/binary-direct.ts +13 -1
  53. package/packages/core/src/cli/binary-lifecycle.ts +65 -2
  54. package/packages/core/src/cli/binary.ts +3 -1
  55. package/packages/core/src/cli/build-control.ts +83 -28
  56. package/packages/core/src/cli/connect.ts +3 -3
  57. package/packages/core/src/cli/context.ts +81 -38
  58. package/packages/core/src/cli/dashboard/facts.ts +2 -1
  59. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
  60. package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
  61. package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
  62. package/packages/core/src/cli/dashboard/model.ts +56 -33
  63. package/packages/core/src/cli/dashboard/poll.ts +9 -3
  64. package/packages/core/src/cli/dashboard/render.ts +59 -37
  65. package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
  66. package/packages/core/src/cli/dashboard/tree.ts +3 -2
  67. package/packages/core/src/cli/dispatch-args.ts +1 -1
  68. package/packages/core/src/cli/dispatch-frontend.ts +6 -3
  69. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  70. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  71. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  72. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  73. package/packages/core/src/cli/dispatch.ts +106 -11
  74. package/packages/core/src/cli/env.ts +4 -0
  75. package/packages/core/src/cli/help.ts +46 -23
  76. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  77. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  78. package/packages/core/src/cli/init-validation.ts +160 -18
  79. package/packages/core/src/cli/main.ts +68 -8
  80. package/packages/core/src/cli/node-verification-provenance.ts +1 -97
  81. package/packages/core/src/cli/publication-settlement.ts +47 -21
  82. package/packages/core/src/cli/repository-status.ts +20 -9
  83. package/packages/core/src/cli/secrets.ts +173 -0
  84. package/packages/core/src/cli/status.ts +42 -5
  85. package/packages/core/src/cli/store-opening.ts +17 -2
  86. package/packages/core/src/cli/terminal.ts +22 -1
  87. package/packages/core/src/cli/terminals.ts +14 -10
  88. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  89. package/packages/core/src/cli/upgrade-landing.ts +70 -30
  90. package/packages/core/src/cli/upgrade.ts +3 -1
  91. package/packages/core/src/cli/wait.ts +15 -7
  92. package/packages/core/src/cli/watch-lifetime.ts +111 -0
  93. package/packages/core/src/cli/watch.ts +635 -510
  94. package/packages/core/src/config/accounts.ts +101 -0
  95. package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
  96. package/packages/core/src/config/effective-artifact.ts +13 -0
  97. package/packages/core/src/config/landing.ts +1 -1
  98. package/packages/core/src/config/live.ts +14 -1
  99. package/packages/core/src/config/load.ts +21 -1
  100. package/packages/core/src/config/pipeline-source.ts +28 -0
  101. package/packages/core/src/config/reference-metadata.ts +2 -0
  102. package/packages/core/src/config/reference.ts +22 -7
  103. package/packages/core/src/config/roles.ts +54 -3
  104. package/packages/core/src/config/schema.ts +146 -162
  105. package/packages/core/src/context-directory.ts +26 -0
  106. package/packages/core/src/distribution-packaging.ts +26 -5
  107. package/packages/core/src/events/catalog.ts +10 -2
  108. package/packages/core/src/events/compatibility.ts +2 -1
  109. package/packages/core/src/events/globs.ts +1 -1
  110. package/packages/core/src/events/payloads.ts +73 -1
  111. package/packages/core/src/events/policy.ts +7 -0
  112. package/packages/core/src/events/repository.ts +4 -4
  113. package/packages/core/src/events/sessions.ts +6 -6
  114. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +574 -0
  115. package/packages/core/src/kernel/auto-merge.ts +2 -2
  116. package/packages/core/src/kernel/engine.ts +255 -26
  117. package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
  118. package/packages/core/src/kernel/integration-landing.ts +3 -3
  119. package/packages/core/src/kernel/integration-state.ts +27 -4
  120. package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
  121. package/packages/core/src/kernel/log-index.ts +13 -1
  122. package/packages/core/src/kernel/node-landing.ts +8 -8
  123. package/packages/core/src/kernel/node-parent.ts +2 -2
  124. package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
  125. package/packages/core/src/kernel/node-verification-context.ts +216 -0
  126. package/packages/core/src/kernel/phases.ts +1 -1
  127. package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
  128. package/packages/core/src/kernel/publication-retry.ts +168 -0
  129. package/packages/core/src/kernel/reconcile-restack.ts +29 -1
  130. package/packages/core/src/kernel/reducer.ts +85 -5
  131. package/packages/core/src/kernel/target-distance.ts +45 -0
  132. package/packages/core/src/kernel/terminal-guard.ts +10 -1
  133. package/packages/core/src/kernel/verify-stage-state.ts +123 -0
  134. package/packages/core/src/kernel/verify-stages.ts +39 -0
  135. package/packages/core/src/ontology.ts +1 -0
  136. package/packages/core/src/operator/annotations.ts +6 -0
  137. package/packages/core/src/operator/control.ts +1 -1
  138. package/packages/core/src/operator/index.ts +3 -7
  139. package/packages/core/src/operator/landings.ts +5 -1
  140. package/packages/core/src/operator/presentation.ts +6 -1
  141. package/packages/core/src/operator/protocol.ts +6 -0
  142. package/packages/core/src/operator/query.ts +14 -18
  143. package/packages/core/src/operator/registry.ts +39 -7
  144. package/packages/core/src/operator/sandbox-host.ts +64 -40
  145. package/packages/core/src/operator/sandbox.ts +3 -0
  146. package/packages/core/src/operator/ticket-source-backend.ts +3 -12
  147. package/packages/core/src/operator/tickets.ts +25 -4
  148. package/packages/core/src/plugins/manifest.ts +2 -1
  149. package/packages/core/src/ports/forge/contract.ts +2 -2
  150. package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
  151. package/packages/core/src/ports/forge/github-readiness.ts +2 -2
  152. package/packages/core/src/ports/forge/github.ts +26 -7
  153. package/packages/core/src/ports/forge/local-git.ts +4 -4
  154. package/packages/core/src/ports/forge/readiness.ts +1 -1
  155. package/packages/core/src/ports/forge-failure.ts +24 -0
  156. package/packages/core/src/ports/runner/account-env.ts +88 -0
  157. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  158. package/packages/core/src/ports/runner/claude.ts +26 -2
  159. package/packages/core/src/ports/runner/codex.ts +63 -31
  160. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  161. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  162. package/packages/core/src/ports/runner/routing.ts +35 -4
  163. package/packages/core/src/ports/tickets/contract.ts +58 -0
  164. package/packages/core/src/ports/tickets/tree.ts +1 -1
  165. package/packages/core/src/ports/types.ts +28 -7
  166. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  167. package/packages/core/src/ports/workspace/build-execution.ts +9 -2
  168. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  169. package/packages/core/src/ports/workspace/create.ts +2 -0
  170. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  171. package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
  172. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  173. package/packages/core/src/ports/workspace/vercel-sandbox.ts +182 -72
  174. package/packages/core/src/processes/build-child.ts +6 -8
  175. package/packages/core/src/processes/build-execution-state.ts +8 -5
  176. package/packages/core/src/processes/build-runner.ts +554 -99
  177. package/packages/core/src/processes/dispatcher.ts +209 -101
  178. package/packages/core/src/processes/execution-no-progress.ts +8 -1
  179. package/packages/core/src/processes/execution-settlement.ts +21 -3
  180. package/packages/core/src/processes/harvest-runner.ts +68 -8
  181. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  182. package/packages/core/src/processes/publication-loss.ts +8 -2
  183. package/packages/core/src/processes/publication-state.ts +42 -4
  184. package/packages/core/src/processes/repo-view.ts +14 -0
  185. package/packages/core/src/processes/verify-cycle-config.ts +96 -0
  186. package/packages/core/src/project-secrets.ts +105 -0
  187. package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
  188. package/packages/core/src/secret-name.ts +41 -0
  189. package/packages/core/src/store/account-redaction.ts +156 -0
  190. package/packages/core/src/store/adapter.ts +1 -0
  191. package/packages/core/src/store/build-scope.ts +9 -0
  192. package/packages/core/src/store/contract.ts +116 -2
  193. package/packages/core/src/store/local/schema.ts +13 -0
  194. package/packages/core/src/store/local/store.ts +42 -0
  195. package/packages/core/src/store/memory.ts +47 -0
  196. package/packages/core/src/store/operator-presence.ts +21 -0
  197. package/packages/core/src/store/phase-session.ts +10 -0
  198. package/packages/core/src/store/reducer-value-shapes.json +5185 -4156
  199. package/packages/core/src/store/remote/client.ts +89 -48
  200. package/packages/core/src/store/remote/compatibility.ts +20 -0
  201. package/packages/core/src/store/remote/protocol.ts +4 -0
  202. package/packages/core/src/store/remote/version.ts +3 -1
  203. package/packages/core/src/store/retention.ts +2 -3
  204. package/packages/core/src/store/session-handle.ts +9 -0
  205. package/packages/core/src/store/streams/session-writer.ts +1 -1
  206. package/packages/core/src/store/types.ts +12 -2
  207. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  208. package/packages/core/src/testing/index.ts +12 -1
  209. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  210. package/packages/core/src/testing/temp-directories.ts +58 -0
  211. package/skills/code-review/SKILL.md +23 -9
  212. package/skills/finalize/SKILL.md +15 -7
  213. package/skills/guide/SKILL.md +373 -148
  214. package/skills/guide/references/accounts.md +119 -0
  215. package/skills/guide/references/integration-tree.md +45 -38
  216. package/{docs/landing-policy.md → skills/guide/references/merge-policy.md} +40 -24
  217. package/skills/guide/references/migration-1.0.md +17 -13
  218. package/skills/guide/references/operator-api.md +180 -51
  219. package/skills/guide/references/plugin-authoring.md +21 -0
  220. package/skills/guide/references/remote-store-protocol.md +242 -68
  221. package/skills/guide/references/remote-ticket-protocol.md +30 -50
  222. package/skills/guide/references/restacking.md +54 -15
  223. package/skills/guide/references/setup.md +59 -119
  224. package/skills/guide/references/spec-standard.md +6 -6
  225. package/skills/guide/references/ticket-dependencies.md +7 -7
  226. package/skills/harvest/SKILL.md +3 -1
  227. package/skills/harvest-review/SKILL.md +3 -1
  228. package/skills/implement/SKILL.md +43 -17
  229. package/skills/operate/SKILL.md +118 -118
  230. package/skills/plan/SKILL.md +39 -13
  231. package/skills/plan-review/SKILL.md +15 -10
  232. package/skills/reconcile/SKILL.md +22 -3
  233. package/skills/spec/SKILL.md +20 -20
  234. package/skills/tickets/SKILL.md +12 -9
  235. package/templates/autobuild.toml +1 -1
  236. package/templates/hosted-service/package.json +2 -2
  237. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  238. package/docs/hosted-dispatcher.md +0 -275
  239. package/docs/hosted-service.md +0 -293
  240. package/docs/mcp.md +0 -149
  241. package/packages/core/src/orchestrator/approvals.ts +0 -115
  242. package/packages/core/src/orchestrator/conversation.ts +0 -167
  243. package/packages/core/src/orchestrator/model.ts +0 -86
  244. package/packages/core/src/orchestrator/prompt.ts +0 -63
  245. package/packages/core/src/orchestrator/tools.ts +0 -117
  246. package/packages/core/src/orchestrator/turn-runner.ts +0 -457
  247. package/packages/core/src/processes/orchestrator-tick.ts +0 -360
@@ -1,3 +1,8 @@
1
+ import { LocalCredentials } from '../accounts/local-credentials'
2
+ import { LocalAccountOwner } from '../accounts/local-owner'
3
+ import { abSecrets } from './secrets'
4
+ import type { ProjectSecretMetadata } from '../project-secrets'
5
+ import { accountRemedy } from '../config/accounts'
1
6
  import { createForge } from '../ports/forge/create'
2
7
  import {
3
8
  inspectForgeReadiness,
@@ -73,15 +78,17 @@ function effectiveTargets(
73
78
  ): Array<{ runtime: string; models: string[] }> {
74
79
  // Preserve eager registry/model/argument validation, but probe only routes
75
80
  // the pipeline can consume rather than every declared role table.
76
- createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds)
77
- return effectiveRuntimeReferences(config).map((group) => {
81
+ createRuntimeResolver(runtimes, config.roles, config.policy.sessionBudgetSeconds, config.accounts)
82
+ return effectiveRuntimeReferences(config).flatMap((group) => {
83
+ const selected = Object.keys(config.accounts).length ? group.legacyAuthentication : group
84
+ if (selected === undefined) return []
78
85
  const defaultModel = runtimes[group.runtime]?.defaultModel
79
86
  return {
80
87
  runtime: group.runtime,
81
88
  models: [
82
89
  ...new Set([
83
- ...group.models,
84
- ...(group.usesRuntimeDefaultModel && defaultModel !== undefined ? [defaultModel] : []),
90
+ ...selected.models,
91
+ ...(selected.usesRuntimeDefaultModel && defaultModel !== undefined ? [defaultModel] : []),
85
92
  ]),
86
93
  ].sort(),
87
94
  }
@@ -124,10 +131,10 @@ export async function runGuestReadinessProbe(opts: {
124
131
  // check detail now see `[REDACTED]` there. Providers without a
125
132
  // `guestEnvNames`/`configSchema` declaration fall back to the name-heuristic
126
133
  // redaction only.
127
- const redact = createReadinessRedactor(
128
- opts.env,
129
- providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : [],
130
- )
134
+ const redact = createReadinessRedactor(opts.env, [
135
+ ...(providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : []),
136
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
137
+ ])
131
138
  try {
132
139
  const setup = config.commands.setup
133
140
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
@@ -221,6 +228,57 @@ export async function runGuestReadinessProbe(opts: {
221
228
  : `fix workspace.config.runtimeProvisioning.${runtime}${preflightOnly ? '.preflight' : ''} and expose API credential names in workspace.config.environmentVariables`
222
229
 
223
230
  try {
231
+ for (const [name, descriptor] of Object.entries(config.accounts)) {
232
+ checks.push({
233
+ name: `credential ${JSON.stringify(name)}`,
234
+ status: opts.env[descriptor.credentialEnv] ? 'pass' : 'warning',
235
+ detail: `${descriptor.credentialEnv} is ${opts.env[descriptor.credentialEnv] ? 'present' : 'absent'}${!opts.env[descriptor.credentialEnv] && descriptor.kind === 'claude-subscription' ? '; run claude setup-token for remote use' : ''}`,
236
+ })
237
+ const account = { name, descriptor }
238
+ const runtime = descriptor.kind === 'chatgpt-subscription' ? 'codex' : 'claude'
239
+ if (
240
+ descriptor.kind === 'chatgpt-subscription' &&
241
+ (JSON.parse(opts.env.AB_CHATGPT_HOSTED_READINESS ?? '[]') as string[]).includes(name)
242
+ ) {
243
+ checks.push({
244
+ name: `account ${JSON.stringify(name)}`,
245
+ status: 'pass',
246
+ detail: 'Hosted metadata readiness only; the first hosted build is the live check',
247
+ })
248
+ continue
249
+ }
250
+ const completion = runtimes[runtime]?.oneShot
251
+ try {
252
+ if (!completion) throw new Error(`${runtime} runtime has no model probe capability`)
253
+ await completion.complete({
254
+ prompt: 'Reply only OK.',
255
+ cwd: opts.repo,
256
+ env: Object.fromEntries(
257
+ Object.entries(opts.env).filter(
258
+ (entry): entry is [string, string] => entry[1] !== undefined,
259
+ ),
260
+ ),
261
+ account,
262
+ model:
263
+ descriptor.kind === 'kimi-code' ? 'kimi-for-coding' : runtimes[runtime]?.defaultModel,
264
+ signal: AbortSignal.any([
265
+ AbortSignal.timeout(30_000),
266
+ ...(opts.signal ? [opts.signal] : []),
267
+ ]),
268
+ })
269
+ checks.push({
270
+ name: `account ${JSON.stringify(name)}`,
271
+ status: 'pass',
272
+ detail: `minimal ${runtime} model request succeeded`,
273
+ })
274
+ } catch (error) {
275
+ checks.push({
276
+ name: `account ${JSON.stringify(name)}`,
277
+ status: 'fail',
278
+ detail: `${redact(error)}; ${accountRemedy(account)}`,
279
+ })
280
+ }
281
+ }
224
282
  for (const target of effectiveTargets(config, runtimes)) {
225
283
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
226
284
  const probe = runtimes[target.runtime]?.initUsable
@@ -378,7 +436,8 @@ function hostPreflight(config: Config, env: Record<string, string | undefined>):
378
436
  throw new Error('ticket source "linear" requires LINEAR_API_KEY')
379
437
  }
380
438
 
381
- export async function validateInitReadiness(opts: {
439
+ async function validateInitReadinessInner(opts: {
440
+ resolvedRepo?: string
382
441
  targetRepo: string
383
442
  env: Record<string, string | undefined>
384
443
  /** The raw launcher process environment, alongside the dotenv-augmented
@@ -396,7 +455,7 @@ export async function validateInitReadiness(opts: {
396
455
  }): Promise<InitValidationReport> {
397
456
  const exec = opts.exec ?? spawnExec
398
457
  if (opts.signal?.aborted) throw opts.signal.reason ?? new Error('validation cancelled')
399
- const repo = await resolveMainRepo(opts.targetRepo, exec)
458
+ const repo = opts.resolvedRepo ?? (await resolveMainRepo(opts.targetRepo, exec))
400
459
  const configPath = join(repo, 'autobuild.toml')
401
460
  const configBytes = await readFile(configPath, 'utf8')
402
461
  const config = await loadConfig(configPath)
@@ -432,10 +491,10 @@ export async function validateInitReadiness(opts: {
432
491
  builtinCaps?.configSchema !== undefined
433
492
  ? builtinCaps.configSchema.parse(config.workspace.config)
434
493
  : undefined
435
- let redact = createReadinessRedactor(
436
- opts.env,
437
- providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : [],
438
- )
494
+ let redact = createReadinessRedactor(opts.env, [
495
+ ...(providerConfig !== undefined ? (builtinCaps?.guestEnvNames?.(providerConfig) ?? []) : []),
496
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
497
+ ])
439
498
  let caps: WorkspaceProviderCapabilities | undefined
440
499
  let assigneeLine: string | undefined
441
500
  let forgeChecks: ForgeReadinessCheck[] = readinessChecks(
@@ -480,10 +539,12 @@ export async function validateInitReadiness(opts: {
480
539
  if (caps?.configSchema !== undefined)
481
540
  providerConfig = caps.configSchema.parse(config.workspace.config)
482
541
  if (caps?.guestEnvNames !== undefined)
483
- redact = createReadinessRedactor(
484
- opts.env,
485
- caps.guestEnvNames(providerConfig !== undefined ? providerConfig : config.workspace.config),
486
- )
542
+ redact = createReadinessRedactor(opts.env, [
543
+ ...caps.guestEnvNames(
544
+ providerConfig !== undefined ? providerConfig : config.workspace.config,
545
+ ),
546
+ ...Object.values(config.accounts).map((account) => account.credentialEnv),
547
+ ])
487
548
  // Registry-aware process-env-only check: a declared name present in the
488
549
  // dotenv-augmented `env` but absent from the raw launcher map fails here,
489
550
  // so plugin-declared requirements and non-CLI callers are covered too
@@ -635,6 +696,7 @@ export async function validateInitReadiness(opts: {
635
696
  exec,
636
697
  redact,
637
698
  runtimeReferences: effectiveRuntimeReferences(config),
699
+ accounts: config.accounts,
638
700
  stdout: opts.stdout ?? (() => {}),
639
701
  ...(opts.signal !== undefined ? { signal: opts.signal } : {}),
640
702
  ...(opts.vercelFacade !== undefined ? { facade: opts.vercelFacade } : {}),
@@ -691,3 +753,83 @@ export async function validateInitReadiness(opts: {
691
753
  })),
692
754
  }
693
755
  }
756
+
757
+ /** Validation consumes the current owner's access value, never its refresh token. */
758
+ export async function validateInitReadiness(
759
+ opts: Parameters<typeof validateInitReadinessInner>[0],
760
+ ): Promise<InitValidationReport> {
761
+ const exec = opts.exec ?? spawnExec
762
+ const repo = await resolveMainRepo(opts.targetRepo, exec)
763
+ const config = await loadConfig(join(repo, 'autobuild.toml'))
764
+ const accounts = Object.entries(config.accounts).filter(
765
+ ([, a]) => a.kind === 'chatgpt-subscription',
766
+ )
767
+ if (!accounts.length) return validateInitReadinessInner({ ...opts, resolvedRepo: repo })
768
+ const credentials = new LocalCredentials(join(repo, '.autobuild'))
769
+ const owner = new LocalAccountOwner(credentials)
770
+ const claimed: string[] = []
771
+ const env = { ...opts.env }
772
+ const checks: InitValidationReport['checks'] = []
773
+ try {
774
+ const service = opts.env.AB_STORE?.trim() || config.store?.url
775
+ let metadata: ProjectSecretMetadata[] | undefined
776
+ if (
777
+ service &&
778
+ isRemoteStoreRef(service) &&
779
+ accounts.some(([name]) => !credentials.load(name))
780
+ ) {
781
+ await abSecrets('list', undefined, {
782
+ cwd: repo,
783
+ env: opts.env,
784
+ exec,
785
+ json: true,
786
+ print: (text) => {
787
+ metadata = JSON.parse(text).secrets
788
+ },
789
+ })
790
+ }
791
+ for (const [name, descriptor] of accounts) {
792
+ const record = credentials.load(name)
793
+ if (record) {
794
+ if (!record.owner) {
795
+ owner.claim(name)
796
+ claimed.push(name)
797
+ await owner.tick({ [name]: descriptor })
798
+ }
799
+ const current = credentials.load(name)!
800
+ if (current.status !== 'ready' || current.state.expiresAt <= Date.now())
801
+ throw new Error(`account ${JSON.stringify(name)}: sign in again with ab accounts login`)
802
+ env[descriptor.credentialEnv] = current.state.accessToken
803
+ } else {
804
+ const entry = metadata?.find(
805
+ (s) => s.name === descriptor.credentialEnv && s.kind === 'chatgpt-subscription',
806
+ )
807
+ const ready = entry?.status === 'ready' && entry.failureCode === null
808
+ checks.push({
809
+ name: `account ${JSON.stringify(name)}`,
810
+ status: ready ? 'pass' : 'fail',
811
+ detail: entry
812
+ ? `Hosted credential ${entry.status}; owner ${entry.owner}; set ${entry.setAt}; ${entry.warnings?.join(', ') || 'no refresh-window warning'}. The first hosted build is the live check.`
813
+ : `Credential absent; run ab accounts login ${JSON.stringify(name)} ${service && isRemoteStoreRef(service) ? '--project' : '--local'}`,
814
+ })
815
+ if (!ready)
816
+ return {
817
+ provider: config.workspace.provider,
818
+ context:
819
+ config.workspace.provider === 'git-worktree' ? 'local worktree' : 'Vercel Sandbox',
820
+ checks,
821
+ exitCode: 1,
822
+ }
823
+ env.AB_CHATGPT_HOSTED_READINESS = JSON.stringify([
824
+ ...(JSON.parse(env.AB_CHATGPT_HOSTED_READINESS ?? '[]') as string[]),
825
+ name,
826
+ ])
827
+ env[descriptor.credentialEnv] = 'autobuild-hosted-metadata-only'
828
+ }
829
+ }
830
+ const report = await validateInitReadinessInner({ ...opts, env, resolvedRepo: repo })
831
+ return { ...report, checks: [...checks, ...report.checks] }
832
+ } finally {
833
+ for (const name of claimed) owner.release(name)
834
+ }
835
+ }
@@ -1,3 +1,5 @@
1
+ import { abAccountsLogin } from './accounts'
2
+ import { abSecrets } from './secrets'
1
3
  import { currentTicketRef } from '../kernel/ticket-migrations'
2
4
  import { upgradeFollowup } from './upgrade-followup'
3
5
  import { parseDispatchArgs } from './dispatch-args'
@@ -106,12 +108,16 @@ export const SESSIONLESS_COMMANDS = new Set([
106
108
  'init',
107
109
  'connect',
108
110
  'disconnect',
111
+ 'secrets',
112
+ 'accounts',
109
113
  'upgrade',
110
114
  'update',
111
115
  'ticket',
112
116
  'dispatch',
113
117
  'builds',
114
118
  'landings',
119
+ 'merges',
120
+ 'merge',
115
121
  'build',
116
122
  'watch',
117
123
  'wait',
@@ -173,6 +179,8 @@ export interface SessionlessCliDeps {
173
179
  /** For init/upgrade this is just the cwd — the default target repo. */
174
180
  workspacePath: string
175
181
  stdout: (line: string) => void
182
+ /** Drain watch output while termination cleanup still owns the store. */
183
+ flushStdout?: () => Promise<void>
176
184
  stderr: (line: string) => void
177
185
  /** Raw process environment for sessionless store selection, operator
178
186
  * provenance/self-control checks, and adapter secrets; distinct from `env`,
@@ -248,7 +256,7 @@ function requireSession(command: string, deps: SessionlessCliDeps): CliDeps {
248
256
  ) {
249
257
  throw new Error(
250
258
  `'ab ${command}' runs inside a build session — the runner sets AB_STORE, ` +
251
- 'AB_BUILD, AB_PHASE, AB_SESSION for every session (SPEC §8.1, D8). ' +
259
+ 'AB_BUILD, AB_PHASE, AB_SESSION, AB_CONTEXT_DIR for every session (SPEC §8.1, D8). ' +
252
260
  'Use `ab help` for commands that run sessionless.',
253
261
  )
254
262
  }
@@ -263,8 +271,8 @@ export function buildControlConfirmation(result: BuildControlResult): string {
263
271
  resume: 'resume requested',
264
272
  abort: 'abort requested',
265
273
  discard: 'discard requested',
266
- hold: 'landing hold requested',
267
- land: 'landing consent requested',
274
+ hold: 'merge hold requested',
275
+ land: 'merge consent requested',
268
276
  'auto-merge-on': 'auto-merge requested',
269
277
  'auto-merge-off': 'auto-merge cancelled',
270
278
  }
@@ -408,6 +416,7 @@ function renderManifest(manifest: ContextManifest): string[] {
408
416
  `context materialized for ${manifest.build} — ${manifest.phase}@${manifest.round}`,
409
417
  `required deposits: ${manifest.required.join(', ') || '(none)'}`,
410
418
  `allowed terminals: ${manifest.allowedTerminals.join(', ')}`,
419
+ `directory: ${manifest.contextDir}`,
411
420
  `manifest: ${manifest.manifestPath}`,
412
421
  ]
413
422
  if (manifest.notesPath !== undefined) lines.push(`notes path: ${manifest.notesPath}`)
@@ -420,7 +429,7 @@ function renderManifest(manifest: ContextManifest): string[] {
420
429
  if (manifest.step !== undefined) {
421
430
  lines.push(`verify step: ${manifest.step.name} (kind ${manifest.step.config.kind})`)
422
431
  }
423
- lines.push('.ab/ files:')
432
+ lines.push(`${manifest.contextDir}/ files:`)
424
433
  const entries = Object.entries(manifest.materialized)
425
434
  if (entries.length === 0) {
426
435
  lines.push(' (none)')
@@ -455,6 +464,10 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
455
464
  return 0
456
465
  }
457
466
  if (helpRequest?.kind === 'command') {
467
+ if (helpRequest.command === 'land' || helpRequest.command === 'landings')
468
+ stderr(
469
+ `ab ${helpRequest.command} is deprecated; use ab ${helpRequest.command === 'land' ? 'merge' : 'merges'}`,
470
+ )
458
471
  stdout(renderCommandHelp(helpRequest.command))
459
472
  return 0
460
473
  }
@@ -479,6 +492,46 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
479
492
 
480
493
  // init and upgrade run OUTSIDE build sessions (§16.3): they operate on a
481
494
  // repo, not a build, so they route before any store/env requirement.
495
+ case 'accounts': {
496
+ const usage = 'usage: ab accounts login NAME [--local|--project]'
497
+ const parsed = parseArgs(rest, { local: 'boolean', project: 'boolean' }, usage)
498
+ if (
499
+ parsed.positionals.length !== 2 ||
500
+ parsed.positionals[0] !== 'login' ||
501
+ (parsed.flags.get('local') && parsed.flags.get('project'))
502
+ )
503
+ throw new Error(usage)
504
+ await abAccountsLogin(parsed.positionals[1]!, {
505
+ cwd: deps.workspacePath,
506
+ env: deps.processEnv ?? process.env,
507
+ exec: deps.exec ?? spawnExec,
508
+ print: stdout,
509
+ ...(deps.signal ? { signal: deps.signal } : {}),
510
+ ...(parsed.flags.get('local')
511
+ ? { destination: 'local' as const }
512
+ : parsed.flags.get('project')
513
+ ? { destination: 'project' as const }
514
+ : {}),
515
+ })
516
+ return 0
517
+ }
518
+ case 'secrets': {
519
+ const parsed = parseArgs(
520
+ rest,
521
+ { json: 'boolean' },
522
+ 'usage: ab secrets list [--json] | set NAME | remove NAME',
523
+ )
524
+ if (parsed.positionals.length > 2)
525
+ throw new Error('Secrets values must be supplied through stdin')
526
+ await abSecrets(parsed.positionals[0], parsed.positionals[1], {
527
+ cwd: deps.workspacePath,
528
+ env: deps.processEnv ?? process.env,
529
+ exec: deps.exec ?? spawnExec,
530
+ print: stdout,
531
+ json: parsed.flags.get('json') === true,
532
+ })
533
+ return 0
534
+ }
482
535
  case 'connect':
483
536
  case 'disconnect': {
484
537
  const usage = command === 'connect' ? 'usage: ab connect [url]' : 'usage: ab disconnect'
@@ -780,11 +833,13 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
780
833
  return 0
781
834
  }
782
835
 
836
+ case 'merges':
783
837
  case 'landings': {
784
- const usage = 'usage: ab landings [--json] [--store <ref>]'
838
+ if (command === 'landings') stderr('ab landings is deprecated; use ab merges')
839
+ const usage = 'usage: ab merges [--json] [--store <ref>]'
785
840
  const parsed = parseArgs(rest, { json: 'boolean', store: 'value' }, usage)
786
841
  if (parsed.positionals.length) throw new Error(usage)
787
- if (!deps.exec) throw new Error('ab landings needs an exec seam')
842
+ if (!deps.exec) throw new Error('ab merges needs an exec seam')
788
843
  await abLandings({
789
844
  targetRepo: deps.workspacePath,
790
845
  env: deps.processEnv ?? {},
@@ -928,6 +983,7 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
928
983
  rest,
929
984
  {
930
985
  repository: 'boolean',
986
+ operator: 'boolean',
931
987
  event: 'multi',
932
988
  since: 'value',
933
989
  timeout: 'value',
@@ -958,9 +1014,11 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
958
1014
  env: deps.processEnv ?? {},
959
1015
  exec: deps.exec,
960
1016
  stdout,
1017
+ ...(deps.flushStdout ? { flushStdout: deps.flushStdout } : {}),
961
1018
  stderr,
962
1019
  slugs: parsed.positionals,
963
1020
  repository: parsed.flags.has('repository'),
1021
+ operator: parsed.flags.has('operator'),
964
1022
  events: multiFlag(parsed, 'event'),
965
1023
  since: stringFlag(parsed, 'since'),
966
1024
  timeout: stringFlag(parsed, 'timeout'),
@@ -1090,20 +1148,22 @@ async function dispatch(argv: string[], deps: SessionlessCliDeps): Promise<numbe
1090
1148
  }
1091
1149
 
1092
1150
  case 'hold':
1151
+ case 'merge':
1093
1152
  case 'land': {
1153
+ if (command === 'land') stderr('ab land is deprecated; use ab merge')
1094
1154
  const usage = `usage: ab ${command} <slug> [--store <ref>]`
1095
1155
  const parsed = parseArgs(rest, { store: 'value' }, usage)
1096
1156
  if (parsed.positionals.length !== 1) throw new Error(usage)
1097
1157
  await runBuildControl(
1098
1158
  deps,
1099
1159
  parsed.positionals[0]!,
1100
- { kind: command },
1160
+ { kind: command === 'merge' ? 'land' : command },
1101
1161
  stringFlag(parsed, 'store'),
1102
1162
  )
1103
1163
  return 0
1104
1164
  }
1105
1165
  case 'auto-merge':
1106
- throw new Error('ab auto-merge is retired; use ab hold, ab land, and [[landing]] policy')
1166
+ throw new Error('ab auto-merge is retired; use ab hold, ab merge, and [[merge]] policy')
1107
1167
 
1108
1168
  case 'answer': {
1109
1169
  const usage =
@@ -1,97 +1 @@
1
- import { buildTrailers, validateBuildSlug } from '../kernel/build-identity'
2
- import { originalForeign } from '../kernel/change-presence'
3
- import { history, nodeInventory, type NodeGit } from '../kernel/node-restack'
4
- import type { CommitRange, TicketRef } from '../ontology'
5
- import { readBuildFacts } from '../store/reduced-reads'
6
- import type { BuildStore } from '../store/types'
7
-
8
- export interface NodeContribution {
9
- build: string
10
- ticket: TicketRef
11
- spec: { kind: 'spec'; rev: number }
12
- specPath: string
13
- commits: string[]
14
- }
15
- export interface NodeVerificationIndex {
16
- range: CommitRange
17
- handPushedCommits: { sha: string; originalSha: string; message: string }[]
18
- contributions: NodeContribution[]
19
- unattributedCommits: string[]
20
- commits: { sha: string; build?: string }[]
21
- }
22
-
23
- /** Reachability, rather than the current child inventory, establishes membership. */
24
- export async function collectNodeVerificationProvenance(
25
- store: BuildStore,
26
- repo: string,
27
- range: CommitRange,
28
- git: NodeGit,
29
- ownership: { contributionBase: string; foreignAliases?: Record<string, string> },
30
- ): Promise<{ index: NodeVerificationIndex; specs: Map<string, string> }> {
31
- const index: NodeVerificationIndex = {
32
- range,
33
- handPushedCommits: [],
34
- contributions: [],
35
- unattributedCommits: [],
36
- commits: [],
37
- }
38
- const owned = new Set((await nodeInventory(git, range.head, ownership.contributionBase)).foreign)
39
- const aliases = new Map(Object.entries(ownership.foreignAliases ?? {}))
40
- const specs = new Map<string, string>()
41
- const byBuild = new Map<string, NodeContribution>()
42
- for (const commit of await history(
43
- git,
44
- [`${range.base}..${range.head}`],
45
- ['--reverse', '--topo-order'],
46
- )) {
47
- if (owned.has(commit.sha))
48
- index.handPushedCommits.push({
49
- sha: commit.sha,
50
- originalSha: originalForeign(commit.sha, aliases),
51
- message: commit.message,
52
- })
53
- const trailers = buildTrailers(commit.message)
54
- if (trailers.length > 1) throw new Error(`ambiguous build identity on ${commit.sha}`)
55
- const build = trailers[0]
56
- if (build === undefined) {
57
- index.commits.push({ sha: commit.sha })
58
- index.unattributedCommits.push(commit.sha)
59
- continue
60
- }
61
- try {
62
- validateBuildSlug(build)
63
- } catch {
64
- throw new Error(`invalid build identity on ${commit.sha}: ${JSON.stringify(build)}`)
65
- }
66
- let contribution = byBuild.get(build)
67
- if (contribution === undefined) {
68
- try {
69
- const record = await store.getBuild(build)
70
- if (!record) throw new Error('unknown build')
71
- if (record.repo !== repo) throw new Error('build belongs to a different repository')
72
- if (!record.ticket) throw new Error('missing ticket identity')
73
- const { state } = (await readBuildFacts(store, build)).value
74
- if (state.specRev === undefined) throw new Error('missing authoritative spec revision')
75
- const artifact = await store.getArtifact(build, 'spec', state.specRev)
76
- if (!artifact) throw new Error(`missing spec@${state.specRev}`)
77
- contribution = {
78
- build,
79
- ticket: record.ticket,
80
- spec: { kind: 'spec', rev: state.specRev },
81
- specPath: '',
82
- commits: [],
83
- }
84
- byBuild.set(build, contribution)
85
- index.contributions.push(contribution)
86
- specs.set(build, new TextDecoder().decode(artifact.content))
87
- } catch (error) {
88
- throw new Error(
89
- `node verification contribution ${build} at ${commit.sha}: ${error instanceof Error ? error.message : String(error)}`,
90
- )
91
- }
92
- }
93
- contribution.commits.push(commit.sha)
94
- index.commits.push({ sha: commit.sha, build })
95
- }
96
- return { index, specs }
97
- }
1
+ export * from '../kernel/node-verification-context'
@@ -1,3 +1,4 @@
1
+ import { publicationRetryGate, retryPublicationEffect } from '../kernel/publication-retry'
1
2
  import { ForgeRequestDeferred } from '../ports/forge-request-context'
2
3
  import { stat } from 'node:fs/promises'
3
4
  import { deferMixedVersion, MixedVersionDeferral } from '../kernel/mixed-version'
@@ -17,6 +18,9 @@ export interface PublicationSettlementDeps {
17
18
  publication?: WorkspacePublication
18
19
  forge: Forge
19
20
  workspacePath: string
21
+ /** Origin-mode dispatchers have no checkout, and possibly no host git:
22
+ * their `workspacePath` is a scratch root, never a ref cache to confirm. */
23
+ checkoutless?: boolean
20
24
  exec: Exec
21
25
  ids: IdSource
22
26
  runId: string
@@ -33,7 +37,7 @@ async function confirmDispatcherCache(
33
37
  branch: string,
34
38
  sha: string,
35
39
  ) {
36
- if (!deps.forge.confirmPublication) return
40
+ if (deps.checkoutless || !deps.forge.confirmPublication) return
37
41
  try {
38
42
  if (!(await stat(deps.workspacePath)).isDirectory()) return
39
43
  } catch (error) {
@@ -93,21 +97,35 @@ export async function settlePendingPublication(
93
97
  intended.branch !== request.payload.branch
94
98
  )
95
99
  throw new Error('restack publication request does not match its durable intent')
100
+ const retryDeps = { ...deps, slug, clock: deps.clock ?? systemClock, actor: DISPATCHER }
101
+ await publicationRetryGate(retryDeps, 'restack', transaction.id)
96
102
  const archives = [...new Set([...events.gitTips, request.payload.sha])].map((sha) => ({
97
103
  ref: `refs/autobuild/archive/${slug}/${sha}`,
98
104
  sha,
99
105
  }))
100
- await suspendNativeLanding({ ...deps, slug }, `publication:${request.seq}`)
101
- const result = await publication.rewrite({
102
- ref,
103
- sha: request.payload.sha,
104
- branch: transaction.branch,
105
- expected: transaction.oldHead,
106
- localExpected: transaction.localBranchHead,
107
- archives,
108
- })
106
+ const external = <T>(effect: () => Promise<T>) =>
107
+ retryPublicationEffect(
108
+ retryDeps,
109
+ 'restack',
110
+ transaction.id,
111
+ events.state.reconcileAttempts + 1,
112
+ effect,
113
+ )
114
+ await external(() => suspendNativeLanding({ ...deps, slug }, `publication:${request.seq}`))
115
+ const result = await external(() =>
116
+ publication.rewrite!({
117
+ ref,
118
+ sha: request.payload.sha,
119
+ branch: transaction.branch,
120
+ expected: transaction.oldHead,
121
+ localExpected: transaction.localBranchHead,
122
+ archives,
123
+ }),
124
+ )
109
125
  if (result.kind === 'published')
110
- await confirmDispatcherCache(deps, request.payload.branch, request.payload.sha)
126
+ await external(() =>
127
+ confirmDispatcherCache(deps, request.payload.branch, request.payload.sha),
128
+ )
111
129
  const latest = (await readBuildFacts(deps.store, slug)).value
112
130
  if (
113
131
  (result.kind === 'published' || result.rewritten === true) &&
@@ -170,19 +188,27 @@ export async function settlePendingPublication(
170
188
  throw new Error('reconcile request does not match its durable resolved intent')
171
189
  if (events.reconcileBases[String(transaction.attempt)] !== transaction.targetBase)
172
190
  throw new Error('reconcile publication target differs from the recorded start')
191
+ const retryDeps = { ...deps, slug, clock: deps.clock ?? systemClock, actor: DISPATCHER }
192
+ await publicationRetryGate(retryDeps, 'reconcile', transaction.id)
173
193
  const tips = new Set([...events.gitTips, request.payload.sha])
174
194
  const archives = [...tips].map((sha) => ({ ref: `refs/autobuild/archive/${slug}/${sha}`, sha }))
175
- await suspendNativeLanding({ ...deps, slug }, `publication:${request.seq}`)
176
- const result = await publication.rewrite({
177
- ref,
178
- sha: request.payload.sha,
179
- branch: request.payload.branch,
180
- expected: transaction.oldHead,
181
- localExpected: transaction.localBranchHead,
182
- archives,
183
- })
195
+ const external = <T>(effect: () => Promise<T>) =>
196
+ retryPublicationEffect(retryDeps, 'reconcile', transaction.id, transaction.attempt, effect)
197
+ await external(() => suspendNativeLanding({ ...deps, slug }, `publication:${request.seq}`))
198
+ const result = await external(() =>
199
+ publication.rewrite!({
200
+ ref,
201
+ sha: request.payload.sha,
202
+ branch: request.payload.branch,
203
+ expected: transaction.oldHead,
204
+ localExpected: transaction.localBranchHead,
205
+ archives,
206
+ }),
207
+ )
184
208
  if (result.kind === 'published')
185
- await confirmDispatcherCache(deps, request.payload.branch, request.payload.sha)
209
+ await external(() =>
210
+ confirmDispatcherCache(deps, request.payload.branch, request.payload.sha),
211
+ )
186
212
  const history = (await readBuildFacts(deps.store, slug)).value.reconcileHistory
187
213
  if (
188
214
  (result.kind === 'published' || result.rewritten === true) &&