@defrex/autobuild 1.2.0 → 1.4.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 (164) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +416 -36
  3. package/docs/accounts.md +50 -1
  4. package/docs/answering-blocked-builds.md +4 -1
  5. package/docs/architecture.md +298 -17
  6. package/docs/build-store.md +18 -0
  7. package/docs/builds.md +7 -1
  8. package/docs/cli.md +1 -1
  9. package/docs/configuration-overview.md +6 -0
  10. package/docs/configuration.md +44 -19
  11. package/docs/dispatcher-hosting.md +42 -0
  12. package/docs/dispatcher.md +41 -0
  13. package/docs/forges.md +5 -0
  14. package/docs/integration-tree.md +24 -5
  15. package/docs/operating.md +11 -3
  16. package/docs/operator-api.md +81 -10
  17. package/docs/operator-surfaces.md +29 -0
  18. package/docs/plugin-authoring.md +51 -2
  19. package/docs/remote-store-protocol.md +321 -46
  20. package/docs/remote-ticket-protocol.md +12 -10
  21. package/docs/restacking.md +105 -3
  22. package/docs/setup.md +37 -8
  23. package/docs/skills.md +1 -1
  24. package/docs/spec-standard.md +41 -5
  25. package/docs/ticket-dependencies.md +8 -0
  26. package/docs/troubleshooting.md +9 -0
  27. package/docs/workspaces.md +1 -1
  28. package/package.json +4 -3
  29. package/packages/core/src/accounts/availability.ts +96 -0
  30. package/packages/core/src/accounts/local-owner.ts +49 -2
  31. package/packages/core/src/cli/attention.ts +2 -0
  32. package/packages/core/src/cli/binary.ts +17 -1
  33. package/packages/core/src/cli/context.ts +62 -0
  34. package/packages/core/src/cli/dashboard/model.ts +12 -3
  35. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  36. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  37. package/packages/core/src/cli/dashboard/render.ts +46 -5
  38. package/packages/core/src/cli/dispatch-args.ts +27 -3
  39. package/packages/core/src/cli/dispatch-frontend.ts +179 -52
  40. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  41. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  42. package/packages/core/src/cli/dispatch-repository-feed.ts +150 -33
  43. package/packages/core/src/cli/dispatch.ts +209 -36
  44. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  45. package/packages/core/src/cli/forge-clear.ts +30 -0
  46. package/packages/core/src/cli/harvest.ts +2 -1
  47. package/packages/core/src/cli/help.ts +17 -3
  48. package/packages/core/src/cli/historical-build-state.ts +6 -0
  49. package/packages/core/src/cli/main.ts +43 -2
  50. package/packages/core/src/cli/publication-settlement.ts +17 -0
  51. package/packages/core/src/cli/remote-poll.ts +11 -1
  52. package/packages/core/src/cli/repository-status.ts +11 -0
  53. package/packages/core/src/cli/status.ts +7 -1
  54. package/packages/core/src/cli/wait.ts +9 -2
  55. package/packages/core/src/cli/watch.ts +47 -16
  56. package/packages/core/src/config/roles.ts +16 -1
  57. package/packages/core/src/events/catalog.ts +8 -0
  58. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  59. package/packages/core/src/events/payloads.ts +95 -2
  60. package/packages/core/src/events/policy.ts +19 -0
  61. package/packages/core/src/events/repository.ts +108 -2
  62. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +464 -0
  63. package/packages/core/src/kernel/change-presence.ts +74 -8
  64. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  65. package/packages/core/src/kernel/engine.ts +27 -12
  66. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  67. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  68. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  69. package/packages/core/src/kernel/log-index.ts +1 -1
  70. package/packages/core/src/kernel/node-landing.ts +27 -10
  71. package/packages/core/src/kernel/node-polling.ts +40 -7
  72. package/packages/core/src/kernel/node-restack-demand.ts +75 -0
  73. package/packages/core/src/kernel/node-restack-state.ts +20 -1
  74. package/packages/core/src/kernel/node-restack-transaction.ts +47 -1
  75. package/packages/core/src/kernel/read-facts.ts +120 -9
  76. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  77. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  78. package/packages/core/src/kernel/reducer-registry.ts +6 -0
  79. package/packages/core/src/kernel/reducer.ts +20 -2
  80. package/packages/core/src/kernel/replay-retention.ts +176 -0
  81. package/packages/core/src/kernel/target-lineage.ts +65 -0
  82. package/packages/core/src/kernel/target-observation.ts +117 -0
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +2 -0
  87. package/packages/core/src/operator/registry.ts +25 -13
  88. package/packages/core/src/operator/tickets.ts +8 -2
  89. package/packages/core/src/plugin-sdk/index.ts +1 -0
  90. package/packages/core/src/ports/forge/fake.ts +22 -0
  91. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  92. package/packages/core/src/ports/forge/github.ts +42 -10
  93. package/packages/core/src/ports/forge/local-git.ts +16 -1
  94. package/packages/core/src/ports/runner/account-env.ts +60 -9
  95. package/packages/core/src/ports/runner/claude.ts +49 -45
  96. package/packages/core/src/ports/types.ts +58 -4
  97. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  98. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  99. package/packages/core/src/ports/workspace/create.ts +2 -0
  100. package/packages/core/src/ports/workspace/fake.ts +4 -0
  101. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  102. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  103. package/packages/core/src/processes/build-runner.ts +240 -111
  104. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  105. package/packages/core/src/processes/dispatcher.ts +732 -201
  106. package/packages/core/src/processes/execution-no-progress.ts +8 -0
  107. package/packages/core/src/processes/harvest-runner.ts +6 -7
  108. package/packages/core/src/processes/harvest.ts +11 -16
  109. package/packages/core/src/processes/publication-state.ts +2 -1
  110. package/packages/core/src/processes/repo-view.ts +25 -0
  111. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  112. package/packages/core/src/scenarios/harness.ts +7 -0
  113. package/packages/core/src/store/adapter.ts +9 -0
  114. package/packages/core/src/store/artifact-meta.ts +7 -0
  115. package/packages/core/src/store/build-scope.ts +28 -0
  116. package/packages/core/src/store/contract.ts +182 -0
  117. package/packages/core/src/store/event-reads.ts +156 -0
  118. package/packages/core/src/store/local/schema.ts +11 -0
  119. package/packages/core/src/store/local/store.ts +117 -2
  120. package/packages/core/src/store/memory.ts +241 -0
  121. package/packages/core/src/store/phase-session.ts +47 -0
  122. package/packages/core/src/store/reduced-reads.ts +8 -0
  123. package/packages/core/src/store/reducer-value-shapes.json +10546 -8877
  124. package/packages/core/src/store/reducer-value-validation.ts +109 -6
  125. package/packages/core/src/store/reducer-values.ts +62 -2
  126. package/packages/core/src/store/remote/client.ts +208 -23
  127. package/packages/core/src/store/remote/compatibility.ts +195 -25
  128. package/packages/core/src/store/remote/errors.ts +16 -0
  129. package/packages/core/src/store/remote/index.ts +17 -0
  130. package/packages/core/src/store/remote/protocol.ts +30 -1
  131. package/packages/core/src/store/remote/released-clients.json +37 -0
  132. package/packages/core/src/store/remote/released-clients.ts +88 -0
  133. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  134. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  135. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  136. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  137. package/packages/core/src/store/remote/version.ts +8 -1
  138. package/packages/core/src/store/repo-state-events.ts +6 -3
  139. package/packages/core/src/store/scan-cadence.ts +15 -0
  140. package/packages/core/src/store/session-handle.ts +18 -0
  141. package/packages/core/src/store/snapshots.ts +16 -3
  142. package/packages/core/src/store/types.ts +29 -6
  143. package/packages/core/src/testing/dispatch-read-budget.ts +457 -7
  144. package/packages/core/src/testing/index.ts +6 -1
  145. package/packages/core/src/testing/reduced-read-budget.ts +1240 -9
  146. package/skills/guide/SKILL.md +220 -22
  147. package/skills/guide/references/accounts.md +50 -1
  148. package/skills/guide/references/integration-tree.md +24 -5
  149. package/skills/guide/references/operator-api.md +81 -10
  150. package/skills/guide/references/plugin-authoring.md +51 -2
  151. package/skills/guide/references/remote-store-protocol.md +321 -46
  152. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  153. package/skills/guide/references/restacking.md +105 -3
  154. package/skills/guide/references/setup.md +37 -8
  155. package/skills/guide/references/spec-standard.md +41 -5
  156. package/skills/guide/references/ticket-dependencies.md +8 -0
  157. package/skills/implement/SKILL.md +12 -3
  158. package/skills/operate/SKILL.md +85 -12
  159. package/skills/plan/SKILL.md +27 -4
  160. package/skills/plan-review/SKILL.md +22 -2
  161. package/skills/reconcile/SKILL.md +16 -1
  162. package/skills/spec/SKILL.md +7 -4
  163. package/skills/tickets/SKILL.md +7 -3
  164. package/templates/hosted-service/package.json +2 -2
@@ -4,6 +4,7 @@
4
4
  * `import type`) and run these same contracts against their adapters.
5
5
  */
6
6
  export type * from '../ports/types'
7
+ export { WorkspaceCleanupRequired } from '../ports/types'
7
8
  export type * from '../ports/workspace/build-execution'
8
9
  export type * from '../ports/workspace/harvest-execution'
9
10
  export type * from '../store/types'
@@ -450,6 +450,28 @@ export class FakeForge implements Forge {
450
450
  this.files.set(`${ref}\0${path}`, content)
451
451
  }
452
452
 
453
+ private readonly commitParents = new Map<string, string[]>()
454
+
455
+ seedCommit(sha: string, parents: string[] = []): void {
456
+ this.commitParents.set(sha, parents)
457
+ }
458
+
459
+ async isCommitAncestor(ancestor: string, descendant: string): Promise<boolean> {
460
+ if (ancestor === descendant) return true
461
+ const pending = [descendant]
462
+ const seen = new Set<string>()
463
+ while (pending.length) {
464
+ const sha = pending.pop()!
465
+ if (sha === ancestor) return true
466
+ if (seen.has(sha)) continue
467
+ seen.add(sha)
468
+ const parents = this.commitParents.get(sha)
469
+ if (!parents) throw new Error(`FakeForge: unknown ancestry for ${sha}`)
470
+ pending.push(...parents)
471
+ }
472
+ return false
473
+ }
474
+
453
475
  async remoteBranchSha(branch: string): Promise<string> {
454
476
  const sha = this.remoteBranches.get(branch)
455
477
  if (sha === undefined) throw new Error(`FakeForge: unknown remote branch ${branch}`)
@@ -1,4 +1,5 @@
1
- import { classifyGitNetworkFailure } from '../forge-failure'
1
+ import { ForgeRequestDeferred } from '../forge-request-context'
2
+ import { classifyGitNetworkFailure, isForgeFailure } from '../forge-failure'
2
3
  import type { ForgeRewrite, RewriteResult } from '../types'
3
4
  import type { Exec } from '../workspace/git-worktree'
4
5
  import { isValidGitBranchName } from '../../kernel/origin'
@@ -15,7 +16,11 @@ function branchRef(branch: string): string {
15
16
 
16
17
  /** Git transport and shared-database implementations share validation, but local-git
17
18
  * never consults a remote, even when the repository happens to have one. */
18
- export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
19
+ export function gitRewrite(
20
+ exec: Exec,
21
+ local: boolean,
22
+ createArchive?: (ref: string, sha: string) => Promise<void>,
23
+ ): ForgeRewrite {
19
24
  async function git(cwd: string, args: string[], allowFailure = false) {
20
25
  const network = !local && ['push', 'fetch', 'ls-remote'].includes(args[0] ?? '')
21
26
  let result: Awaited<ReturnType<Exec>>
@@ -130,24 +135,56 @@ export function gitRewrite(exec: Exec, local: boolean): ForgeRewrite {
130
135
  const existing = await read(input.workspacePath, input.ref)
131
136
  if (existing !== null && existing !== input.sha)
132
137
  throw new Error(`immutable archive ${input.ref} names ${existing}, expected ${input.sha}`)
138
+ const missing =
139
+ !local &&
140
+ (await git(input.workspacePath, ['cat-file', '-e', `${input.sha}^{commit}`], true))
141
+ .exitCode !== 0
133
142
  if (existing === null) {
134
- const result = await git(
135
- input.workspacePath,
136
- local
137
- ? ['update-ref', input.ref, input.sha, '0'.repeat(input.sha.length)]
138
- : ['push', `--force-with-lease=${input.ref}:`, 'origin', `${input.sha}:${input.ref}`],
139
- true,
140
- )
141
- // An uncertain acknowledgement is adopted only after an exact readback.
142
- if ((await read(input.workspacePath, input.ref)) !== input.sha)
143
+ let failure: unknown
144
+ try {
145
+ if (missing) {
146
+ if (!createArchive)
147
+ throw new Error('remote archive creation is unavailable in this adapter')
148
+ await createArchive(input.ref, input.sha)
149
+ } else {
150
+ const result = await git(
151
+ input.workspacePath,
152
+ local
153
+ ? ['update-ref', input.ref, input.sha, '0'.repeat(input.sha.length)]
154
+ : [
155
+ 'push',
156
+ `--force-with-lease=${input.ref}:`,
157
+ 'origin',
158
+ `${input.sha}:${input.ref}`,
159
+ ],
160
+ true,
161
+ )
162
+ if (result.exitCode !== 0) throw new Error(result.stderr || result.stdout)
163
+ }
164
+ } catch (error) {
165
+ failure = error
166
+ }
167
+ // Mutation acknowledgement alone is never proof, including API races.
168
+ let confirmed: string | null
169
+ try {
170
+ confirmed = await read(input.workspacePath, input.ref)
171
+ } catch (error) {
172
+ if (isForgeFailure(failure) || failure instanceof ForgeRequestDeferred) throw failure
173
+ throw error
174
+ }
175
+ if (confirmed !== input.sha) {
176
+ if (isForgeFailure(failure) || failure instanceof ForgeRequestDeferred) throw failure
143
177
  throw new Error(
144
- `archive publication rejected for ${input.ref}: ${result.stderr}; enable refs/autobuild/archive/ publication before branch rewrites`,
178
+ `archive publication rejected for ${input.ref} at ${input.sha}: ${String(failure ?? 'exact readback did not confirm publication')}; enable refs/autobuild/archive/ publication before branch rewrites`,
179
+ { cause: failure },
145
180
  )
181
+ }
146
182
  }
147
183
  if (!local) {
148
184
  // Fetch by the exact archive ref, never by an unadvertised object id.
149
185
  await git(input.workspacePath, [
150
186
  'fetch',
187
+ ...(missing ? ['--depth=1', '--refmap='] : []),
151
188
  '--no-tags',
152
189
  '--no-write-fetch-head',
153
190
  'origin',
@@ -1,3 +1,4 @@
1
+ import { gitOid } from '../../events/payloads'
1
2
  import { AsyncLocalStorage } from 'node:async_hooks'
2
3
  import {
3
4
  classifyGitNetworkFailure,
@@ -582,13 +583,17 @@ const REPRESENTATION_CACHE_CAP = 512
582
583
 
583
584
  export class GitHubForge implements Forge {
584
585
  get rewrite() {
585
- return gitRewrite(async (cmd, opts) => {
586
- if (cmd.includes('push')) this.invalidateReads()
587
- return this.exec(cmd, opts)
588
- }, false)
586
+ return gitRewrite(
587
+ async (cmd, opts) => {
588
+ if (cmd.includes('push')) this.invalidateReads()
589
+ return this.exec(cmd, opts)
590
+ },
591
+ false,
592
+ (ref, sha) => this.createArchive(ref, sha),
593
+ )
589
594
  }
590
595
  get kernelRewrite() {
591
- return gitRewrite(this.kernelExec, false)
596
+ return gitRewrite(this.kernelExec, false, (ref, sha) => this.createArchive(ref, sha))
592
597
  }
593
598
  /** Credentials exist only in the trusted subprocess environment, never in
594
599
  * argv, repository config, remote URLs, or the resolving agent's environment. */
@@ -1891,14 +1896,41 @@ export class GitHubForge implements Forge {
1891
1896
  }
1892
1897
 
1893
1898
  private async compareShas(parentSha: string, headSha: string) {
1899
+ return this.memo(`comparison:${parentSha}:${headSha}`, async () => {
1900
+ const { owner, name } = await this.requireCoordinates()
1901
+ return this.revalidate(
1902
+ z.object({
1903
+ ahead_by: z.number().int().nonnegative(),
1904
+ behind_by: z.number().int().nonnegative(),
1905
+ status: z.enum(['ahead', 'behind', 'diverged', 'identical']).optional(),
1906
+ }),
1907
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/compare/${encodeURIComponent(parentSha)}...${encodeURIComponent(headSha)}`,
1908
+ 'commit comparison',
1909
+ )
1910
+ })
1911
+ }
1912
+
1913
+ async isCommitAncestor(ancestor: string, descendant: string): Promise<boolean> {
1914
+ if (!gitOid.safeParse(ancestor).success || !gitOid.safeParse(descendant).success)
1915
+ throw new Error('invalid ancestry OID')
1916
+ const result = await this.compareShas(ancestor, descendant)
1917
+ if (result.status === undefined) throw new Error('commit comparison omitted ancestry status')
1918
+ return result.status === 'ahead' || result.status === 'identical'
1919
+ }
1920
+
1921
+ private async createArchive(ref: string, sha: string): Promise<void> {
1894
1922
  const { owner, name } = await this.requireCoordinates()
1895
- return this.revalidate(
1923
+ this.parse(
1896
1924
  z.object({
1897
- ahead_by: z.number().int().nonnegative(),
1898
- behind_by: z.number().int().nonnegative(),
1925
+ ref: z.literal(ref),
1926
+ object: z.object({ sha: z.literal(sha), type: z.literal('commit') }),
1899
1927
  }),
1900
- `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/compare/${encodeURIComponent(parentSha)}...${encodeURIComponent(headSha)}`,
1901
- 'node comparison',
1928
+ await this.request(
1929
+ 'POST',
1930
+ `repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}/git/refs`,
1931
+ { body: { ref, sha } },
1932
+ ),
1933
+ 'archive create',
1902
1934
  )
1903
1935
  }
1904
1936
 
@@ -1,3 +1,4 @@
1
+ import { gitOid } from '../../events/payloads'
1
2
  import { readinessChecks, type ForgeReadinessCheck } from './readiness'
2
3
  import { gitRewrite } from './git-rewrite'
3
4
  import { historyContainsBuild, withBuildTrailer } from '../../kernel/build-identity'
@@ -57,7 +58,7 @@ export class LocalGitForge implements Forge {
57
58
  private readonly exec: Exec
58
59
  /** The repository the optional checkout-less read seam reads from. The
59
60
  * factory passes the served checkout; without it the capability is absent
60
- * and callers retain their checkout/git fallbacks. */
61
+ * and callers defer authoritative reads. */
61
62
  private readonly repoRoot?: string
62
63
 
63
64
  constructor(opts: { exec?: Exec; repoRoot?: string } = {}) {
@@ -80,6 +81,20 @@ export class LocalGitForge implements Forge {
80
81
  return result.stdout.trim()
81
82
  }
82
83
 
84
+ async isCommitAncestor(ancestor: string, descendant: string): Promise<boolean> {
85
+ if (!this.repoRoot) throw new Error('local-git ancestry requires repoRoot')
86
+ if (!gitOid.safeParse(ancestor).success || !gitOid.safeParse(descendant).success)
87
+ throw new Error('invalid ancestry OID')
88
+ const result = await this.command(
89
+ ['merge-base', '--is-ancestor', ancestor, descendant],
90
+ this.repoRoot,
91
+ true,
92
+ )
93
+ if (result.exitCode === 0) return true
94
+ if (result.exitCode === 1) return false
95
+ throw new Error(`local-git ancestry proof failed: ${result.stderr.trim()}`)
96
+ }
97
+
83
98
  async createNodeBranch(branch: string, sha: string): Promise<string> {
84
99
  if (!this.repoRoot) throw new Error('local-git node branches require repoRoot')
85
100
  const ref = `refs/heads/${branch}`
@@ -1,3 +1,6 @@
1
+ import { mkdtemp, writeFile, rm } from 'node:fs/promises'
2
+ import { tmpdir } from 'node:os'
3
+ import { join, resolve } from 'node:path'
1
4
  import {
2
5
  accountRemedy,
3
6
  accountPlaceholder,
@@ -76,13 +79,61 @@ export function accountEnvironment(
76
79
 
77
80
  /** CLI settings outrank user/project settings.env. Empty competing values also
78
81
  * override saved values, without editing the user's files. */
79
- export function accountSettings(env: Record<string, string>, account?: SelectedAccount): string[] {
80
- if (account === undefined) return []
81
- return [
82
- '--settings',
83
- JSON.stringify({
84
- apiKeyHelper: '',
85
- env: Object.fromEntries(ROUTING_KEYS.map((key) => [key, env[key] ?? ''])),
86
- }),
87
- ]
82
+ export async function withAccountSettings<T>(
83
+ env: Record<string, string>,
84
+ account: SelectedAccount | undefined,
85
+ invoke: (args: string[]) => Promise<T>,
86
+ files: {
87
+ mkdtemp: (prefix: string) => Promise<string>
88
+ writeFile: typeof writeFile
89
+ rm: typeof rm
90
+ } = { mkdtemp, writeFile, rm },
91
+ ): Promise<T> {
92
+ if (account === undefined) return await invoke([])
93
+ let directory: string | undefined
94
+ try {
95
+ // mkdtemp creates the directory with mode 0700 from the outset.
96
+ directory = await files.mkdtemp(join(resolve(tmpdir()), 'autobuild-account-'))
97
+ const path = join(directory, 'settings.json')
98
+ await files.writeFile(
99
+ path,
100
+ JSON.stringify({
101
+ apiKeyHelper: '',
102
+ env: Object.fromEntries(ROUTING_KEYS.map((key) => [key, env[key] ?? ''])),
103
+ }),
104
+ { flag: 'wx', mode: 0o600 },
105
+ )
106
+ } catch {
107
+ if (directory !== undefined) {
108
+ try {
109
+ await files.rm(directory, { recursive: true, force: true })
110
+ } catch {
111
+ throw new Error('Account settings setup and cleanup failed')
112
+ }
113
+ }
114
+ throw new Error('Account settings setup failed')
115
+ }
116
+ let outcome: { value: T } | { error: unknown }
117
+ let cleanupFailed = false
118
+ try {
119
+ outcome = { value: await invoke(['--settings', join(directory, 'settings.json')]) }
120
+ } catch (error) {
121
+ outcome = { error }
122
+ } finally {
123
+ try {
124
+ await files.rm(directory, { recursive: true, force: true })
125
+ } catch {
126
+ cleanupFailed = true
127
+ }
128
+ }
129
+ if (cleanupFailed) {
130
+ throw new Error(
131
+ 'error' in outcome
132
+ ? 'Account invocation failed and settings cleanup failed'
133
+ : 'Account settings cleanup failed',
134
+ 'error' in outcome ? { cause: outcome.error } : undefined,
135
+ )
136
+ }
137
+ if ('error' in outcome) throw outcome.error
138
+ return outcome.value
88
139
  }
@@ -1,5 +1,5 @@
1
1
  import { accountRemedy } from '../../config/accounts'
2
- import { accountEnvironment, accountSettings } from './account-env'
2
+ import { accountEnvironment, withAccountSettings } from './account-env'
3
3
  import { hostname } from 'node:os'
4
4
  import {
5
5
  guardNativeHandle,
@@ -232,19 +232,21 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
232
232
  async complete(input: OneShotCompletionInput): Promise<OneShotCompletionResult> {
233
233
  const env = accountEnvironment(sessionEnv(input.env), input.account, input.model)
234
234
  const args = this.baseArgs()
235
- args.push(...accountSettings(env, input.account))
236
- args.push('--tools', '', '--disallowedTools', 'mcp__*', '--no-session-persistence')
237
- if (input.model !== undefined) args.push(CLAUDE_MODEL_ARG, input.model)
238
- args.push(...(input.args ?? []), CLAUDE_PROMPT_BOUNDARY, input.prompt)
239
-
240
- const turn = await this.runPrompt({
241
- args,
242
- cwd: input.cwd,
243
- env,
244
- ...(input.signal !== undefined ? { signal: input.signal } : {}),
235
+ return await withAccountSettings(env, input.account, async (settingsArgs) => {
236
+ args.push(...settingsArgs)
237
+ args.push('--tools', '', '--disallowedTools', 'mcp__*', '--no-session-persistence')
238
+ if (input.model !== undefined) args.push(CLAUDE_MODEL_ARG, input.model)
239
+ args.push(...(input.args ?? []), CLAUDE_PROMPT_BOUNDARY, input.prompt)
240
+
241
+ const turn = await this.runPrompt({
242
+ args,
243
+ cwd: input.cwd,
244
+ env,
245
+ ...(input.signal !== undefined ? { signal: input.signal } : {}),
246
+ })
247
+ if (turn.failure !== undefined) throw new Error(turn.failure.message)
248
+ return { text: turn.text }
245
249
  })
246
- if (turn.failure !== undefined) throw new Error(turn.failure.message)
247
- return { text: turn.text }
248
250
  }
249
251
 
250
252
  async start(
@@ -441,38 +443,40 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
441
443
  args.push(...(opts.args ?? []), CLAUDE_PROMPT_BOUNDARY, prompt)
442
444
 
443
445
  const env = accountEnvironment(sessionEnv(opts.env), opts.account, opts.model)
444
- args.unshift(...accountSettings(env, opts.account))
445
- const invocation: ClaudeCliInvocation = {
446
- args,
447
- cwd: opts.workspacePath,
448
- env,
449
- ...(signal !== undefined ? { signal } : {}),
450
- }
451
- if (opts.stream === undefined && opts.onNativeSession === undefined)
452
- return this.runPrompt(invocation)
453
- if (opts.stream === undefined) {
454
- if (this.runCliStream !== undefined)
455
- return this.runStreamingPrompt(invocation, undefined, observe)
456
- const turn = await this.runPrompt(invocation)
457
- for (const event of turn.events) await observeEvent(event)
458
- return turn
459
- }
446
+ return await withAccountSettings(env, opts.account, async (settingsArgs) => {
447
+ args.unshift(...settingsArgs)
448
+ const invocation: ClaudeCliInvocation = {
449
+ args,
450
+ cwd: opts.workspacePath,
451
+ env,
452
+ ...(signal !== undefined ? { signal } : {}),
453
+ }
454
+ if (opts.stream === undefined && opts.onNativeSession === undefined)
455
+ return this.runPrompt(invocation)
456
+ if (opts.stream === undefined) {
457
+ if (this.runCliStream !== undefined)
458
+ return this.runStreamingPrompt(invocation, undefined, observe)
459
+ const turn = await this.runPrompt(invocation)
460
+ for (const event of turn.events) await observeEvent(event)
461
+ return turn
462
+ }
460
463
 
461
- // Streaming turn: translate while the CLI runs. Without an injected
462
- // streaming boundary (offline fakes), the buffered path still translates
463
- // after completion — degraded latency, same content.
464
- const emitter = opts.stream
465
- emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
466
- let turn: ClaudeTurn
467
- if (this.runCliStream !== undefined) {
468
- turn = await this.runStreamingPrompt(invocation, emitter, observe)
469
- } else {
470
- turn = await this.runPrompt(invocation)
471
- for (const event of turn.events) await observeEvent(event)
472
- translateBufferedClaudeTurn(turn, (parts) => emitter?.append(parts))
473
- }
474
- this.emitTurnEnd(turn, emitter, signal)
475
- return turn
464
+ // Streaming turn: translate while the CLI runs. Without an injected
465
+ // streaming boundary (offline fakes), the buffered path still translates
466
+ // after completion — degraded latency, same content.
467
+ const emitter = opts.stream
468
+ emitter.append([promptPart(prompt), startPart(crypto.randomUUID())])
469
+ let turn: ClaudeTurn
470
+ if (this.runCliStream !== undefined) {
471
+ turn = await this.runStreamingPrompt(invocation, emitter, observe)
472
+ } else {
473
+ turn = await this.runPrompt(invocation)
474
+ for (const event of turn.events) await observeEvent(event)
475
+ translateBufferedClaudeTurn(turn, (parts) => emitter?.append(parts))
476
+ }
477
+ this.emitTurnEnd(turn, emitter, signal)
478
+ return turn
479
+ })
476
480
  }
477
481
 
478
482
  /** Completed-turn, failed-turn, and cancelled-turn closing parts. */
@@ -559,7 +563,7 @@ export class ClaudeAgentRunner implements AgentRunner, OneShotCompletion {
559
563
  } catch (error) {
560
564
  if (error instanceof NativeObservationError) {
561
565
  controller.abort(error)
562
- void handle.result.catch(() => {})
566
+ await handle.result.catch(() => {})
563
567
  throw error
564
568
  }
565
569
  // The result promise below still carries the CLI's exit and stderr.
@@ -304,7 +304,50 @@ export interface WorkspaceProvisionResult extends WorkspaceHandle {
304
304
  base: WorkspaceBase
305
305
  }
306
306
 
307
+ /** A provider refused to destroy a checkout during provision/start. The
308
+ * dispatcher must record its identity before fencing and preservation. */
309
+ export class WorkspaceCleanupRequired extends Error {
310
+ constructor(
311
+ readonly workspace: WorkspaceHandle & { base?: WorkspaceBase },
312
+ cause: unknown,
313
+ ) {
314
+ super(
315
+ `workspace ${workspace.ref} requires dispatcher-authorized cleanup: ${cause instanceof Error ? cause.message : String(cause)}`,
316
+ { cause },
317
+ )
318
+ this.name = 'WorkspaceCleanupRequired'
319
+ }
320
+ }
321
+
322
+ export interface WorkspacePreservationHead {
323
+ sha: string
324
+ remoteRef: string
325
+ role: 'branch' | 'producer'
326
+ commits: string[]
327
+ }
328
+ export type WorkspaceFenceOutcome =
329
+ | { outcome: 'confirmed' | 'absent' }
330
+ | { outcome: 'unknown'; error: string }
331
+
307
332
  export interface WorkspacePublication {
333
+ recoverCandidate?(input: {
334
+ ref: string
335
+ slug: string
336
+ branch: string
337
+ sha: string
338
+ replayPack?: string
339
+ }): Promise<boolean>
340
+
341
+ /** Dispatcher-only, after a durable non-destructive fence. Errors never
342
+ * constitute proof that an environment or its unpublished work is absent. */
343
+ preserve?(input: {
344
+ ref: string
345
+ slug: string
346
+ branch: string
347
+ base: string
348
+ candidates: string[]
349
+ }): Promise<{ outcome: 'preserved'; heads: WorkspacePreservationHead[] } | { outcome: 'absent' }>
350
+
308
351
  /** Trusted after-teardown path; never route a restack through plain publish. */
309
352
  rewrite?(input: {
310
353
  ref: string
@@ -342,12 +385,19 @@ export interface WorkspaceReapOutcome {
342
385
  }
343
386
 
344
387
  export interface WorkspaceRecovery {
388
+ /** Stops execution without deleting the workspace or its snapshots. */
389
+ fence?(handle: WorkspaceHandle): Promise<WorkspaceFenceOutcome>
390
+
345
391
  /** Fence an unavailable environment. Unknown outcomes must reject so the
346
392
  * dispatcher retains the lease/workspace fact and retries after its fence. */
347
393
  reap(handle: WorkspaceHandle): Promise<WorkspaceReapOutcome>
348
394
  }
349
395
 
350
396
  export interface WorkspaceProvider {
397
+ /** Local adapters may provide the same boundary capability without becoming
398
+ * a remote-publication provider. */
399
+ readonly preservation?: NonNullable<WorkspacePublication['preserve']>
400
+
351
401
  readonly name: string
352
402
  /** Optional workspace-adjacent executor. Remote providers substitute here;
353
403
  * locally reachable providers use the shipped subprocess capability. */
@@ -381,6 +431,7 @@ export interface WorkspaceProvider {
381
431
  /** Confirmed publication and known stale cache tips, from durable facts.
382
432
  * Providers must preserve unknown unpublished work during ordinary resume. */
383
433
  publication?: { sha: string; cacheHeads: string[] }
434
+ restoration?: WorkspacePreservationHead[]
384
435
  /** Immutable recovery checkpoint, never a moved base branch. */
385
436
  revision?: string
386
437
  /** Monotonic environment generation used in provider idempotency keys. */
@@ -521,6 +572,7 @@ export interface ForgeRewrite {
521
572
  branch: string
522
573
  destinationRef: string
523
574
  }): Promise<string>
575
+ /** Remote archives recover remote-present objects by exact ref and return a verified local commit. */
524
576
  archive(input: { workspacePath: string; ref: string; sha: string }): Promise<void>
525
577
  replace(input: {
526
578
  workspacePath: string
@@ -654,11 +706,13 @@ export interface Forge {
654
706
  containsBuild?(workspacePath: string, branch: string, buildSlug: string): Promise<boolean>
655
707
  /** Post the build's summary comment (§7.5). */
656
708
  commentOnPr(workspacePath: string, number: number, body: string): Promise<void>
657
- /** Optional checkout-less capability: the current tip of a remote branch.
658
- * Throws when the branch does not exist (including 404); callers decide
659
- * whether absence is an error or an `undefined`. Its absence retains the
660
- * legacy host `git ls-remote` base resolution. */
709
+ /** Authoritative forge branch tip. Absence or failure must defer target
710
+ * observation; callers must never substitute dispatcher-host refs. */
661
711
  remoteBranchSha?(branch: string): Promise<string>
712
+ /** Prove ancestry of immutable commit OIDs in the authoritative repository.
713
+ * False means a proven non-descendant; absent capability or unknown objects
714
+ * must fail closed, never authorize replay. */
715
+ isCommitAncestor?(ancestor: string, descendant: string): Promise<boolean>
662
716
  /** Optional checkout-less capability: raw file bytes from the repository.
663
717
  * Ref omitted → the repository's default branch. Throws when the path does
664
718
  * not exist. Its absence retains reading configuration from a checkout. */
@@ -12,6 +12,7 @@ export function accountPolicy(
12
12
  base: NetworkPolicy,
13
13
  accounts: Accounts,
14
14
  env: Readonly<Record<string, string | undefined>>,
15
+ requiredAccounts: Accounts = accounts,
15
16
  ): { policy: NetworkPolicy; missing: string[] } {
16
17
  if (Object.keys(accounts).length === 0) return { policy: base, missing: [] }
17
18
  if (base === 'deny-all' || (typeof base === 'object' && Array.isArray(base.allow)))
@@ -24,7 +25,7 @@ export function accountPolicy(
24
25
  for (const [name, descriptor] of Object.entries(accounts)) {
25
26
  const credential = env[descriptor.credentialEnv]
26
27
  if (!credential) {
27
- missing.push(accountRemedy({ name, descriptor }))
28
+ if (Object.hasOwn(requiredAccounts, name)) missing.push(accountRemedy({ name, descriptor }))
28
29
  continue
29
30
  }
30
31
  const claude = descriptor.kind !== 'kimi-code'