@defrex/autobuild 1.3.0 → 1.4.1

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 (144) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +307 -27
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +198 -25
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +262 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +187 -53
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/distribution-archive.ts +14 -4
  85. package/packages/core/src/ports/workspace/fake.ts +4 -0
  86. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  87. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  88. package/packages/core/src/processes/build-runner.ts +240 -111
  89. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  90. package/packages/core/src/processes/dispatcher.ts +262 -80
  91. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  92. package/packages/core/src/processes/harvest-runner.ts +6 -7
  93. package/packages/core/src/processes/publication-state.ts +2 -1
  94. package/packages/core/src/processes/repo-view.ts +22 -0
  95. package/packages/core/src/processes/tick-publication.ts +35 -47
  96. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  97. package/packages/core/src/scenarios/harness.ts +7 -0
  98. package/packages/core/src/store/adapter.ts +9 -0
  99. package/packages/core/src/store/build-scope.ts +28 -0
  100. package/packages/core/src/store/contract.ts +125 -0
  101. package/packages/core/src/store/event-reads.ts +156 -0
  102. package/packages/core/src/store/local/schema.ts +11 -0
  103. package/packages/core/src/store/local/store.ts +117 -2
  104. package/packages/core/src/store/memory.ts +237 -0
  105. package/packages/core/src/store/phase-session.ts +47 -0
  106. package/packages/core/src/store/reduced-reads.ts +8 -0
  107. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  108. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  109. package/packages/core/src/store/reducer-values.ts +62 -2
  110. package/packages/core/src/store/remote/client.ts +161 -16
  111. package/packages/core/src/store/remote/compatibility.ts +177 -46
  112. package/packages/core/src/store/remote/errors.ts +16 -0
  113. package/packages/core/src/store/remote/index.ts +11 -0
  114. package/packages/core/src/store/remote/protocol.ts +22 -0
  115. package/packages/core/src/store/remote/released-clients.json +48 -0
  116. package/packages/core/src/store/remote/released-clients.ts +88 -0
  117. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  118. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  119. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  120. package/packages/core/src/store/remote/version.ts +5 -2
  121. package/packages/core/src/store/repo-state-events.ts +4 -3
  122. package/packages/core/src/store/scan-cadence.ts +15 -0
  123. package/packages/core/src/store/session-handle.ts +18 -0
  124. package/packages/core/src/store/types.ts +27 -6
  125. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  126. package/packages/core/src/testing/index.ts +5 -0
  127. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  128. package/skills/guide/SKILL.md +201 -18
  129. package/skills/guide/references/accounts.md +38 -0
  130. package/skills/guide/references/integration-tree.md +8 -0
  131. package/skills/guide/references/operator-api.md +37 -4
  132. package/skills/guide/references/plugin-authoring.md +45 -1
  133. package/skills/guide/references/remote-store-protocol.md +262 -42
  134. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  135. package/skills/guide/references/restacking.md +60 -3
  136. package/skills/guide/references/setup.md +37 -8
  137. package/skills/guide/references/spec-standard.md +37 -3
  138. package/skills/implement/SKILL.md +12 -3
  139. package/skills/operate/SKILL.md +87 -15
  140. package/skills/plan/SKILL.md +27 -4
  141. package/skills/plan-review/SKILL.md +22 -2
  142. package/skills/reconcile/SKILL.md +10 -1
  143. package/skills/spec/SKILL.md +7 -4
  144. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,117 @@
1
+ import type { TargetLineage } from './target-lineage'
2
+ import type { BuildStore } from '../store/types'
3
+ import type { Forge } from '../ports/types'
4
+ import type { EventWrite } from '../events/catalog'
5
+ import { readBuildFacts } from '../store/reduced-reads'
6
+ import { gitOid } from '../events/payloads'
7
+
8
+ export function assertTargetOid(sha: string): void {
9
+ if (!gitOid.safeParse(sha).success) throw new Error('invalid target commit OID')
10
+ }
11
+
12
+ /** Admit only immutable forward destinations. CAS loss requires reclassification
13
+ * against the winning accepted observation, never a blind append. Reads consume
14
+ * reduced values only; idle polls read no event rows. */
15
+ export async function observeTarget(input: {
16
+ store: BuildStore
17
+ forge: Forge
18
+ slug: string
19
+ branch: string
20
+ sha: string
21
+ recordAccepted?: boolean
22
+ enforceUsedBaseline?: boolean
23
+ /** Supplied only by the repository-scoped dispatcher. */
24
+ proveRewrite?: (node: string, from: string) => Promise<TargetLineage | undefined>
25
+ actor: EventWrite['actor']
26
+ }): Promise<'moved' | 'unchanged' | 'rejected' | 'cleared'> {
27
+ const { store, forge, slug, branch, sha, actor } = input
28
+ assertTargetOid(sha)
29
+ for (;;) {
30
+ const facts = await readBuildFacts(store, slug)
31
+ const { state, log } = facts.value
32
+ const restack = log.restack
33
+ const node = state.nodeRestack
34
+ const accepted = restack.target?.branch === branch ? restack.target.sha : undefined
35
+ // Reparent acceptance establishes a new branch scope. Until its replay
36
+ // settles the old parent's contribution boundary is not a baseline here.
37
+ const reconcile = log.lastReconcileCompleted
38
+ const leafBase =
39
+ reconcile && reconcile.completedSeq > (restack.completedAt ?? 0)
40
+ ? reconcile.baseSha
41
+ : (restack.completed?.targetBase ?? restack.initialBase)
42
+ const used =
43
+ state.kind === 'node'
44
+ ? node?.parentChange && node.parentReplay !== node.parentChange.id
45
+ ? undefined
46
+ : node?.contributionBase
47
+ : leafBase
48
+ const baselines = [...new Set([accepted, used].filter((s): s is string => !!s))]
49
+ const rejected = restack.targetRewrite
50
+ if (accepted === sha && !rejected && !input.enforceUsedBaseline) return 'unchanged'
51
+ if (
52
+ !input.proveRewrite &&
53
+ rejected?.branch === branch &&
54
+ rejected.sha === sha &&
55
+ baselines.includes(rejected.previousSha)
56
+ )
57
+ return 'rejected'
58
+ let previousSha: string | undefined
59
+ const lineage: TargetLineage[] = []
60
+ for (const baseline of baselines) {
61
+ assertTargetOid(baseline)
62
+ if (baseline === sha) continue
63
+ if (!forge.isCommitAncestor) throw new Error('forge ancestry proof capability unavailable')
64
+ if (!(await forge.isCommitAncestor(baseline, sha))) {
65
+ // Scoped runners trust only the dispatcher-deposited proof for this
66
+ // exact accepted target, never read a parent's build or receipt index.
67
+ const prior =
68
+ restack.target?.branch === branch
69
+ ? restack.target.lineage?.find((proof) => proof.from === baseline)
70
+ : undefined
71
+ const recorded =
72
+ prior &&
73
+ (accepted === sha ||
74
+ (!input.proveRewrite && accepted && (await forge.isCommitAncestor(accepted, sha))))
75
+ ? prior
76
+ : undefined
77
+ const proof =
78
+ recorded ??
79
+ (state.target?.build && input.proveRewrite
80
+ ? await input.proveRewrite(state.target.build, baseline)
81
+ : undefined)
82
+ if (proof) {
83
+ lineage.push(proof)
84
+ continue
85
+ }
86
+ previousSha = baseline
87
+ break
88
+ }
89
+ }
90
+ if (
91
+ previousSha &&
92
+ rejected?.branch === branch &&
93
+ rejected.previousSha === previousSha &&
94
+ rejected.sha === sha
95
+ )
96
+ return 'rejected'
97
+ if (!previousSha && input.recordAccepted === false && !rejected) return 'unchanged'
98
+ const write: EventWrite | undefined = previousSha
99
+ ? { actor, type: 'target.rewritten', payload: { branch, previousSha, sha } }
100
+ : accepted !== sha
101
+ ? {
102
+ actor,
103
+ type: 'target.moved',
104
+ payload: { branch, sha, ...(lineage.length ? { lineage } : {}) },
105
+ }
106
+ : rejected
107
+ ? {
108
+ actor,
109
+ type: 'target.rewrite-cleared',
110
+ payload: { branch, sha, ...(lineage.length ? { lineage } : {}) },
111
+ }
112
+ : undefined
113
+ if (!write) return 'unchanged'
114
+ if (!(await store.appendIfCurrent(slug, facts.cursor, write))) continue
115
+ return previousSha ? 'rejected' : accepted === sha ? 'cleared' : 'moved'
116
+ }
117
+ }
@@ -1,3 +1,4 @@
1
+ import { readBuildPage } from '../store/event-reads'
1
2
  import { requestNodeRestack } from './restack'
2
3
  import { listOperatorLandings } from './landings'
3
4
  import { getOperatorTicketTree } from './tickets'
@@ -237,8 +238,9 @@ const buildEventsInput = z.strictObject({
237
238
  .number()
238
239
  .int()
239
240
  .min(0)
241
+ .safe()
240
242
  .describe(
241
- 'Event sequence cursor: return build events with seq strictly greater than this (0 = the whole log).',
243
+ 'Event sequence cursor: return build events with seq strictly greater than this (0 = the first page).',
242
244
  ),
243
245
  waitSeconds: z
244
246
  .number()
@@ -551,21 +553,11 @@ export const TOOLS: readonly ToolEntry[] = [
551
553
  'builds.events',
552
554
  'Read one build’s event log after a cursor, optionally waiting (bounded, ≤30s) for new events — the polling companion to builds.get.',
553
555
  buildEventsInput,
554
- '{events, cursor}: the new events in sequence order (each with seq, ts, actor, type, payload) and the cursor to pass next time — the last returned event’s seq, or the requested cursor when the page is empty.',
556
+ '{events, cursor, hasMore}: at most 256 new events in sequence order (each with seq, ts, actor, type, payload) and the cursor to pass next time — the last returned event’s seq, or the requested cursor when the page is empty.',
555
557
  async (raw, ctx) => {
556
558
  const input = raw as z.infer<typeof buildEventsInput>
557
559
  await requireRouteBuild(ctx.store, input.repo, input.slug)
558
- let events = await ctx.store.getEvents(input.slug, input.cursor)
559
- if (events.length === 0 && input.waitSeconds > 0) {
560
- // The store interface offers subscribe but no bounded wait; polling
561
- // keeps the handler finite. The schema caps waitSeconds at 30.
562
- const deadline = Date.now() + input.waitSeconds * 1000
563
- while (events.length === 0 && Date.now() < deadline) {
564
- await new Promise((resolve) => setTimeout(resolve, 500))
565
- events = await ctx.store.getEvents(input.slug, input.cursor)
566
- }
567
- }
568
- return { events, cursor: events.length > 0 ? events.at(-1)!.seq : input.cursor }
560
+ return readBuildPage(ctx.store, input.slug, input.cursor, { waitSeconds: input.waitSeconds })
569
561
  },
570
562
  ),
571
563
  defineTool(
@@ -163,9 +163,15 @@ async function matchingBuild(
163
163
  }
164
164
  const matches = normalized.filter(({ ref }) => ref.id === id).map(({ record }) => record)
165
165
  if (!matches.length && source.name === 'hosted') {
166
+ // Readable refs already identify tickets; only legacy local-store refs need aliases.
167
+ const aliases = new Map<string, string | null>()
166
168
  try {
167
- for (const { record, ref } of normalized)
168
- if ((await source.get(ref.id))?.ref.id === id) matches.push(record)
169
+ for (const { record, ref } of normalized) {
170
+ if (!/^ticket-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(ref.id))
171
+ continue
172
+ if (!aliases.has(ref.id)) aliases.set(ref.id, (await source.get(ref.id))?.ref.id ?? null)
173
+ if (aliases.get(ref.id) === id) matches.push(record)
174
+ }
169
175
  } catch {
170
176
  /* optional alias association must not undo a successful mutation */
171
177
  }
@@ -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}`
@@ -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'