@defrex/autobuild 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +91 -7
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +15 -1
  5. package/docs/configuration.md +33 -4
  6. package/docs/operator-api.md +15 -5
  7. package/docs/plugin-authoring.md +1 -0
  8. package/docs/remote-store-protocol.md +13 -3
  9. package/docs/remote-ticket-protocol.md +3 -1
  10. package/docs/restacking.md +41 -1
  11. package/docs/setup.md +15 -6
  12. package/docs/troubleshooting.md +39 -2
  13. package/docs/workspaces.md +2 -0
  14. package/package.json +3 -3
  15. package/packages/core/src/cli/accounts.ts +3 -0
  16. package/packages/core/src/cli/binary-direct.ts +14 -1
  17. package/packages/core/src/cli/binary.ts +10 -7
  18. package/packages/core/src/cli/dispatch.ts +503 -334
  19. package/packages/core/src/cli/secrets.ts +2 -0
  20. package/packages/core/src/config/schema.ts +15 -2
  21. package/packages/core/src/events/payloads.ts +8 -5
  22. package/packages/core/src/kernel/engine.ts +118 -0
  23. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  24. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  25. package/packages/core/src/ontology.ts +1 -0
  26. package/packages/core/src/operator/index.ts +10 -0
  27. package/packages/core/src/operator/merged-builds.ts +51 -0
  28. package/packages/core/src/operator/registry.ts +190 -101
  29. package/packages/core/src/operator/repo-argument.ts +43 -0
  30. package/packages/core/src/ports/tickets/grants.ts +2 -0
  31. package/packages/core/src/ports/tickets/remote.ts +2 -0
  32. package/packages/core/src/ports/types.ts +15 -0
  33. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  34. package/packages/core/src/ports/workspace/vercel-sandbox.ts +576 -140
  35. package/packages/core/src/processes/build-child.ts +15 -1
  36. package/packages/core/src/processes/build-runner.ts +349 -20
  37. package/packages/core/src/processes/dispatcher.ts +28 -7
  38. package/packages/core/src/processes/harvest-child.ts +21 -1
  39. package/packages/core/src/processes/harvest-runner.ts +82 -35
  40. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  41. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  42. package/packages/core/src/processes/repo-view.ts +25 -4
  43. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  44. package/packages/core/src/store/adapter.ts +34 -5
  45. package/packages/core/src/store/build-feed.ts +148 -22
  46. package/packages/core/src/store/build-scope.ts +12 -3
  47. package/packages/core/src/store/caller-attribution.ts +170 -0
  48. package/packages/core/src/store/contract.ts +1038 -165
  49. package/packages/core/src/store/local/schema.ts +12 -1
  50. package/packages/core/src/store/local/store.ts +260 -25
  51. package/packages/core/src/store/memory.ts +156 -9
  52. package/packages/core/src/store/phase-session.ts +23 -3
  53. package/packages/core/src/store/reducer-value-shapes.json +3184 -3175
  54. package/packages/core/src/store/remote/client.ts +90 -11
  55. package/packages/core/src/store/remote/credentials.ts +2 -0
  56. package/packages/core/src/store/remote/index.ts +31 -5
  57. package/packages/core/src/store/remote/protocol.ts +45 -8
  58. package/packages/core/src/store/remote/released-clients.json +11 -0
  59. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  60. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  61. package/packages/core/src/store/session-handle.ts +12 -3
  62. package/packages/core/src/store/types.ts +48 -3
  63. package/packages/core/src/testing/reduced-read-budget.ts +222 -4
  64. package/skills/guide/SKILL.md +46 -8
  65. package/skills/guide/references/operator-api.md +15 -5
  66. package/skills/guide/references/plugin-authoring.md +1 -0
  67. package/skills/guide/references/remote-store-protocol.md +13 -3
  68. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  69. package/skills/guide/references/restacking.md +41 -1
  70. package/skills/guide/references/setup.md +15 -6
  71. package/skills/operate/SKILL.md +24 -3
  72. package/templates/hosted-service/package.json +2 -2
@@ -7,14 +7,15 @@ import release4 from './1.13.0.json'
7
7
  import release5 from './1.14.0.json'
8
8
  import release6 from './1.15.0.json'
9
9
  import release7 from './1.16.0.json'
10
- import release8 from './1.2.0.json'
11
- import release9 from './1.3.0.json'
12
- import release10 from './1.4.0.json'
13
- import release11 from './1.5.0.json'
14
- import release12 from './1.6.0.json'
15
- import release13 from './1.7.0.json'
16
- import release14 from './1.8.0.json'
17
- import release15 from './1.9.0.json'
10
+ import release8 from './1.17.0.json'
11
+ import release9 from './1.2.0.json'
12
+ import release10 from './1.3.0.json'
13
+ import release11 from './1.4.0.json'
14
+ import release12 from './1.5.0.json'
15
+ import release13 from './1.6.0.json'
16
+ import release14 from './1.7.0.json'
17
+ import release15 from './1.8.0.json'
18
+ import release16 from './1.9.0.json'
18
19
  import type { ReducerValueCatalog } from '../../reducer-value-validation'
19
20
  export interface ReleasedReducerValues extends ReducerValueCatalog {
20
21
  versions: Record<string, number>
@@ -28,12 +29,13 @@ export const RELEASED_REDUCER_VALUES: Readonly<Record<string, ReleasedReducerVal
28
29
  '1.14.0.json': release5,
29
30
  '1.15.0.json': release6,
30
31
  '1.16.0.json': release7,
31
- '1.2.0.json': release8,
32
- '1.3.0.json': release9,
33
- '1.4.0.json': release10,
34
- '1.5.0.json': release11,
35
- '1.6.0.json': release12,
36
- '1.7.0.json': release13,
37
- '1.8.0.json': release14,
38
- '1.9.0.json': release15,
32
+ '1.17.0.json': release8,
33
+ '1.2.0.json': release9,
34
+ '1.3.0.json': release10,
35
+ '1.4.0.json': release11,
36
+ '1.5.0.json': release12,
37
+ '1.6.0.json': release13,
38
+ '1.7.0.json': release14,
39
+ '1.8.0.json': release15,
40
+ '1.9.0.json': release16,
39
41
  }
@@ -30,7 +30,7 @@ import type {
30
30
  SubscribeOptions,
31
31
  Unsubscribe,
32
32
  } from './types'
33
- import type { BuildPage, ChangedBuilds } from './types'
33
+ import type { BuildPage, ChangedBuilds, MergedBuildPage } from './types'
34
34
  import type {
35
35
  TicketAsset,
36
36
  TicketAssetInput,
@@ -129,6 +129,9 @@ export function createSessionScopedStore(store: BuildStore, scope: string): Sess
129
129
  listBuildsPage(repo: string): Promise<BuildPage> {
130
130
  return Promise.reject(new SessionScopeError(scope, 'listBuildsPage', repo))
131
131
  },
132
+ listMergedBuildsPage(repo: string): Promise<MergedBuildPage> {
133
+ return Promise.reject(new SessionScopeError(scope, 'listMergedBuildsPage', repo))
134
+ },
132
135
  listBuilds(): Promise<BuildRecord[]> {
133
136
  return Promise.reject(new SessionScopeError(scope, 'listBuilds'))
134
137
  },
@@ -229,7 +232,10 @@ export function createSessionScopedStore(store: BuildStore, scope: string): Sess
229
232
  repo: string,
230
233
  _artifacts: ArtifactInput[],
231
234
  _makeEvent: (deposited: RepositoryArtifactMeta[]) => RepositoryEventWrite<T>,
232
- ): Promise<{ event: RepositoryEventEnvelope<T>; artifacts: RepositoryArtifactMeta[] }> {
235
+ ): Promise<{
236
+ event: RepositoryEventEnvelope<T>
237
+ artifacts: RepositoryArtifactMeta[]
238
+ }> {
233
239
  return Promise.reject(new SessionScopeError(scope, 'appendRepoWithArtifacts', repo))
234
240
  },
235
241
  getRepoEvents(repo: string, _sinceSeq?: number): Promise<RepositoryEvent[]> {
@@ -392,7 +398,10 @@ export function createSessionScopedStore(store: BuildStore, scope: string): Sess
392
398
  id: string,
393
399
  artifacts: ArtifactInput[],
394
400
  makeEvent: (deposited: SessionArtifactMeta[]) => SessionEventWrite<T>,
395
- ): Promise<{ event: SessionEventEnvelope<T>; artifacts: SessionArtifactMeta[] }> {
401
+ ): Promise<{
402
+ event: SessionEventEnvelope<T>
403
+ artifacts: SessionArtifactMeta[]
404
+ }> {
396
405
  own('appendSessionWithArtifacts', id)
397
406
  return store.appendSessionWithArtifacts(id, artifacts, makeEvent)
398
407
  },
@@ -2,7 +2,13 @@ import type { ScanCadence } from './scan-cadence'
2
2
  import type { BoundedEventReads } from './event-reads'
3
3
  import type { OperatorIdentity, OperatorPresence } from './operator-presence'
4
4
  export type { OperatorIdentity, OperatorPresence } from './operator-presence'
5
- import type { BuildPage, BuildPageOptions, ChangedBuilds } from './build-feed'
5
+ import type {
6
+ BuildPage,
7
+ BuildPageOptions,
8
+ ChangedBuilds,
9
+ MergedBuildPage,
10
+ MergedBuildPageOptions,
11
+ } from './build-feed'
6
12
  export type {
7
13
  BuildPage,
8
14
  BuildPageFilters,
@@ -10,6 +16,10 @@ export type {
10
16
  BuildPageOptions,
11
17
  ChangedBuild,
12
18
  ChangedBuilds,
19
+ MergedBuild,
20
+ MergedBuildPage,
21
+ MergedBuildPageOptions,
22
+ MergedBuildTarget,
13
23
  } from './build-feed'
14
24
  import type { ReducerValueRequest, ReducerValue } from './reducer-values'
15
25
  /**
@@ -214,7 +224,11 @@ export interface RepoTickObservation {
214
224
  run: string
215
225
  open?: { startedAt: string }
216
226
  /** Retained across begin, even when the next run has a different holder. */
217
- finished?: RepoTickCompletion & { run: string; startedAt: string; completedAt: string }
227
+ finished?: RepoTickCompletion & {
228
+ run: string
229
+ startedAt: string
230
+ completedAt: string
231
+ }
218
232
  }
219
233
  export interface RepoTickFinish {
220
234
  observation: RepoTickObservation
@@ -418,6 +432,34 @@ export interface BuildStore extends BoundedEventReads {
418
432
  */
419
433
  listBuildsPage(repo: string, opts?: BuildPageOptions): Promise<BuildPage>
420
434
 
435
+ /**
436
+ * One page of `repo`'s merged builds, most recently merged first: merge
437
+ * time descending, then slug descending. Served from the same per-build
438
+ * listing facts as `listBuildsPage`, each written in the same transaction
439
+ * as the event that changes it:
440
+ *
441
+ * - `mergedAt`: the latest `build.completed` envelope `ts` when its outcome
442
+ * is merged; cleared by a non-merged completion or `build.reopened`. Later
443
+ * writes (workspace release, PR-attachment reclaim, escalations) never
444
+ * move it.
445
+ * - `pr`: number and url of the latest `pr.opened` or `finalize.completed`.
446
+ * - `target`: `build.created`'s target, replaced on a node build by each
447
+ * `node.parent-accepted` `next.target` (null clears it).
448
+ * - `kind`: `node` when `build.created` kind is `node`, else `leaf`.
449
+ *
450
+ * `since` is inclusive and `until` exclusive, both on merge time. Records
451
+ * match `listBuildsForRepo` records, including the ticket projection. A
452
+ * cursor is opaque and continues only a request with the same window. A
453
+ * page is one bounded range scan over at most `limit + 1` entries, and reads
454
+ * zero event rows and zero reduced values, whatever the repository's build
455
+ * count, a build's log length, or the writes after its merge. An unknown
456
+ * repository answers `{builds: [], next: null}` and creates no state. An
457
+ * invalid instant, `since` after `until`, a malformed cursor, a cursor of
458
+ * another order or a limit outside 1..100 rejects with
459
+ * `BuildFeedValidationError`. Scoped handles reject.
460
+ */
461
+ listMergedBuildsPage(repo: string, opts?: MergedBuildPageOptions): Promise<MergedBuildPage>
462
+
421
463
  /**
422
464
  * Append one validated event; the store assigns `seq` (per-build,
423
465
  * monotonic, starting at 1) and `ts` (§15.1). Writes must pass
@@ -785,7 +827,10 @@ export interface BuildStore extends BoundedEventReads {
785
827
  id: string,
786
828
  artifacts: ArtifactInput[],
787
829
  makeEvent: (deposited: SessionArtifactMeta[]) => SessionEventWrite<T>,
788
- ): Promise<{ event: SessionEventEnvelope<T>; artifacts: SessionArtifactMeta[] }>
830
+ ): Promise<{
831
+ event: SessionEventEnvelope<T>
832
+ artifacts: SessionArtifactMeta[]
833
+ }>
789
834
  putSessionArtifact(id: string, artifact: ArtifactInput): Promise<SessionArtifactMeta>
790
835
  /** Latest revision when `rev` is omitted; null if kind (or rev) absent. */
791
836
  getSessionArtifact(id: string, kind: string, rev?: number): Promise<SessionArtifact | null>
@@ -9023,7 +9023,8 @@ export async function agentContextReadBudget(): Promise<void> {
9023
9023
 
9024
9024
  /** Count the build records and digest entries callers receive from a memory
9025
9025
  * store: record entries from `listBuilds`, `listBuildsForRepo`, a found
9026
- * `getBuild` and `listOpenBuilds`; digest entries from `getRepoBuildDigests`,
9026
+ * `getBuild`, `listOpenBuilds` and `listMergedBuildsPage` items; digest
9027
+ * entries from `getRepoBuildDigests`,
9027
9028
  * `listOpenBuilds` and outer `buildDigest` reductions. Calls the adapter
9028
9029
  * makes to itself are not counted. */
9029
9030
  function memoryListingEntryCounter(store: import('../store/memory').MemoryBuildStore) {
@@ -9049,6 +9050,10 @@ function memoryListingEntryCounter(store: import('../store/memory').MemoryBuildS
9049
9050
  digests += (result as unknown[]).length
9050
9051
  })
9051
9052
  wrap('getRepoBuildDigests', (result) => (digests += (result as Map<string, unknown>).size))
9053
+ wrap(
9054
+ 'listMergedBuildsPage',
9055
+ (result) => (records += (result as { builds: unknown[] }).builds.length),
9056
+ )
9052
9057
  wrap('getReducerValue', (_result, args) => {
9053
9058
  if ((args[1] as { reducer: string }).reducer === 'buildDigest') digests++
9054
9059
  })
@@ -9380,9 +9385,154 @@ export async function openBuildListingReadBudget(opts: { commands?: boolean } =
9380
9385
  }
9381
9386
  // The counter bites: the explicit history listing grows with settled builds.
9382
9387
  expect(history.get(30)).toBeGreaterThan(history.get(1)!)
9388
+ await mergedBuildListingReadBudget()
9383
9389
  return baseline!
9384
9390
  }
9385
9391
 
9392
+ /** `builds.list` scope `merged` with `since`, `until` and `limit: 5`, cold
9393
+ * (nothing has read a reducer value) and again after post-merge writes, costs
9394
+ * the same store requests and entries at 10 and 1,000 merged builds and at 100
9395
+ * and 100,000 padding events: exactly one `listMergedBuildsPage` per page and
9396
+ * zero event rows. No warm-up: the first access is the measured one. */
9397
+ async function mergedBuildListingReadBudget() {
9398
+ const { MemoryBuildStore } = await import('../store/memory')
9399
+ const repo = '/merged-listing-budget'
9400
+ const t0 = Date.parse('2026-11-30T00:00:00.000Z')
9401
+ const at = (ms: number) => new Date(t0 + ms).toISOString()
9402
+ type Item = { slug: string; mergedAt: string; kind: string; pr?: unknown; target?: unknown }
9403
+ type Vector = { records: number; digests: number; calls: Record<string, number> }
9404
+ let baseline: Vector[] | undefined
9405
+ for (const count of [10, 1000])
9406
+ for (const padding of [100, 100_000]) {
9407
+ let now = at(0)
9408
+ const store = new MemoryBuildStore({ clock: () => new Date(now) })
9409
+ await store.ensureRepo(repo)
9410
+ await seedRepoFiller(store, repo, padding)
9411
+ const ticket = (id: string) => ({ source: 'file', id })
9412
+ const create = (slug: string, extra: Record<string, unknown> = {}) =>
9413
+ store.createBuild({
9414
+ slug,
9415
+ repo,
9416
+ ticket: ticket(slug),
9417
+ created: {
9418
+ actor: DISPATCHER,
9419
+ type: 'build.created',
9420
+ payload: { ticket: ticket(slug), repo, baseBranch: 'main', ...extra },
9421
+ },
9422
+ })
9423
+ const merge = (slug: string, ms: number) => {
9424
+ now = at(ms)
9425
+ return store.append(slug, {
9426
+ actor: DISPATCHER,
9427
+ type: 'build.completed',
9428
+ payload: { outcome: 'merged' },
9429
+ })
9430
+ }
9431
+ for (let i = 0; i < count; i++) {
9432
+ const slug = `merged-${String(i).padStart(4, '0')}`
9433
+ await create(slug)
9434
+ // The most recently merged leaf carries a long log.
9435
+ if (i === count - 1) await seedBuildFiller(store, slug, padding, INERT_BUILD_FILLER)
9436
+ await store.append(slug, {
9437
+ actor: KERNEL,
9438
+ type: 'finalize.completed',
9439
+ payload: { pr: { number: i + 1, url: `https://forge/${i + 1}`, headSha: 'head' } },
9440
+ })
9441
+ await merge(slug, (i + 1) * 1000)
9442
+ }
9443
+ await create('merged-node', { kind: 'node' })
9444
+ await merge('merged-node', (count + 1) * 1000)
9445
+ await create('merged-child', {
9446
+ target: { build: 'merged-node', ticket: ticket('merged-node') },
9447
+ })
9448
+ await merge('merged-child', (count + 2) * 1000)
9449
+ const window = { since: at((count - 4) * 1000), until: at((count + 3) * 1000) }
9450
+ const expected = [
9451
+ [
9452
+ 'merged-child',
9453
+ 'merged-node',
9454
+ ...[1, 2, 3].map((k) => `merged-${String(count - k).padStart(4, '0')}`),
9455
+ ],
9456
+ [4, 5].map((k) => `merged-${String(count - k).padStart(4, '0')}`),
9457
+ ]
9458
+
9459
+ const rows = memoryRepositoryReadCounter(store, repo)
9460
+ const entries = memoryListingEntryCounter(store)
9461
+ const calls = memoryStoreRequestCounter(store)
9462
+ const vectors: Vector[] = []
9463
+ const pages: Item[][] = []
9464
+ const walk = async () => {
9465
+ let cursor: string | undefined
9466
+ for (const slugs of expected) {
9467
+ // A fresh handle and registry: the stand-in for a fresh process.
9468
+ const fresh = new Proxy(store, {
9469
+ get(target, property) {
9470
+ const value = Reflect.get(target, property)
9471
+ return typeof value === 'function' ? value.bind(target) : value
9472
+ },
9473
+ })
9474
+ rows.reset()
9475
+ entries.reset()
9476
+ calls.reset()
9477
+ const page = (await buildRegistry({ store: fresh }).call('builds.list', {
9478
+ repo,
9479
+ scope: 'merged',
9480
+ limit: 5,
9481
+ ...window,
9482
+ ...(cursor === undefined ? {} : { cursor }),
9483
+ })) as { builds: Item[]; next: string | null }
9484
+ expect(page.builds.map((build) => build.slug)).toEqual(slugs)
9485
+ expect({ rows: rows.rows, buildRows: rows.buildRows }).toEqual({ rows: 0, buildRows: 0 })
9486
+ const vector = { ...entries.vector, calls: calls.vector() }
9487
+ expect(vector).toEqual({
9488
+ records: slugs.length,
9489
+ digests: 0,
9490
+ calls: { listMergedBuildsPage: 1 },
9491
+ })
9492
+ vectors.push(vector)
9493
+ pages.push(page.builds)
9494
+ cursor = page.next ?? undefined
9495
+ }
9496
+ expect(cursor).toBeUndefined()
9497
+ }
9498
+ try {
9499
+ await walk()
9500
+ // Post-merge writes move `updatedAt`, never the merge time.
9501
+ now = at((count + 10) * 1000)
9502
+ for (const slug of ['merged-child', 'merged-node']) {
9503
+ await store.append(slug, {
9504
+ actor: KERNEL,
9505
+ type: 'observation.recorded',
9506
+ payload: { id: `o-${slug}`, kind: 'followup', summary: 'after the merge' },
9507
+ })
9508
+ await store.append(slug, {
9509
+ actor: KERNEL,
9510
+ type: 'escalation.raised',
9511
+ payload: { id: `e-${slug}`, phase: 'implement', source: 'agent', question: 'q' },
9512
+ })
9513
+ }
9514
+ await walk()
9515
+ } finally {
9516
+ calls.restore()
9517
+ entries.restore()
9518
+ }
9519
+ const [cold, , warm] = pages
9520
+ expect(warm).toEqual(cold)
9521
+ expect(cold!.slice(0, 3)).toMatchObject([
9522
+ {
9523
+ slug: 'merged-child',
9524
+ mergedAt: at((count + 2) * 1000),
9525
+ kind: 'leaf',
9526
+ target: { build: 'merged-node', ticket: ticket('merged-node') },
9527
+ },
9528
+ { slug: 'merged-node', mergedAt: at((count + 1) * 1000), kind: 'node' },
9529
+ { kind: 'leaf', pr: { number: count, url: `https://forge/${count}` } },
9530
+ ])
9531
+ if (baseline) expect(vectors).toEqual(baseline)
9532
+ baseline = vectors
9533
+ }
9534
+ }
9535
+
9386
9536
  /** The repository-scoped MCP listing gate (`sandboxToolsListed`) over a
9387
9537
  * repository holding `revisions` deposited effective configs, the latest
9388
9538
  * enabling `[orchestrator]`. Proves the listing cost is one repository read
@@ -9549,12 +9699,17 @@ export async function buildFeedReadBudget(): Promise<{
9549
9699
  return { builds, repeated, paging }
9550
9700
  }
9551
9701
 
9702
+ const MERGED_LISTING_WALKS = new Set(['mergedAll', 'mergedSince', 'mergedWindow', 'mergedEmpty'])
9703
+
9552
9704
  /**
9553
9705
  * A filtered build page costs what its page costs: at most `limit + 1` listing
9554
9706
  * entries and no event row, the same at 100 and 100,000 builds, however many
9555
9707
  * builds match. Covers a rare filter matching only the oldest builds, a rare
9556
9708
  * activity window, a large active set, a rare kind inside it, an empty
9557
- * intersection and later pages. Returns each request's page costs by size.
9709
+ * intersection and later pages. The merged listing (`listMergedBuildsPage`)
9710
+ * is held to the same bound, unbounded, from a recent `since`, inside a
9711
+ * `since`/`until` window deep in history and over an empty window. Returns
9712
+ * each request's page costs by size.
9558
9713
  */
9559
9714
  export async function filteredBuildPageReadBudget(): Promise<
9560
9715
  Record<number, Record<string, BuildFeedReadCost[]>>
@@ -9566,6 +9721,7 @@ export async function filteredBuildPageReadBudget(): Promise<
9566
9721
  const slug = (i: number) => `lf-${String(i).padStart(6, '0')}`
9567
9722
  const t0 = '2026-11-24T00:00:00.000Z'
9568
9723
  const t1 = '2026-11-24T01:00:00.000Z'
9724
+ const t2 = '2026-11-24T02:00:00.000Z'
9569
9725
  const nodes = 30
9570
9726
  const range = (from: number, to: number) =>
9571
9727
  Array.from({ length: from - to + 1 }, (_, i) => slug(from - i))
@@ -9603,6 +9759,38 @@ export async function filteredBuildPageReadBudget(): Promise<
9603
9759
  return costs
9604
9760
  }
9605
9761
 
9762
+ /** The same walk over `listMergedBuildsPage`. */
9763
+ const walkMerged = async (
9764
+ store: Store,
9765
+ opts: import('../store/build-feed').MergedBuildPageOptions,
9766
+ expected: string[][],
9767
+ ) => {
9768
+ const costs: BuildFeedReadCost[] = []
9769
+ let cursor: string | undefined
9770
+ for (const [index, slugs] of expected.entries()) {
9771
+ const feedReads = Reflect.get(store, 'feedReads') as { examined: number }
9772
+ feedReads.examined = 0
9773
+ let page: import('../store/build-feed').MergedBuildPage | undefined
9774
+ const metrics = await measureStoreReads(store, async () => {
9775
+ page = await store.listMergedBuildsPage(repo, {
9776
+ ...opts,
9777
+ ...(cursor === undefined ? {} : { cursor }),
9778
+ })
9779
+ })
9780
+ expect(page!.builds.map((build) => build.record.slug)).toEqual(slugs)
9781
+ expect(page!.next === null).toBe(index === expected.length - 1)
9782
+ cursor = page!.next ?? undefined
9783
+ costs.push({
9784
+ calls: metrics.calls,
9785
+ rows: metrics.rows,
9786
+ repoRows: metrics.repoRows,
9787
+ bytes: metrics.bytes,
9788
+ examined: feedReads.examined,
9789
+ })
9790
+ }
9791
+ return costs
9792
+ }
9793
+
9606
9794
  const sizes = [100, 100_000] as const
9607
9795
  const costs: Record<number, Record<string, BuildFeedReadCost[]>> = {}
9608
9796
  for (const n of sizes) {
@@ -9658,18 +9846,48 @@ export async function filteredBuildPageReadBudget(): Promise<
9658
9846
  ]),
9659
9847
  recentLeaf: await walk(store, { activeSince: t1, kind: 'leaf' }, [[]]),
9660
9848
  }
9849
+ // The merged listing: thirty leaves merge a minute apart after the nodes,
9850
+ // so merge order differs from creation and update order.
9851
+ const mergedAt = (i: number) => new Date(Date.parse(t2) + i * 60_000).toISOString()
9852
+ for (let i = nodes; i < 2 * nodes; i++) {
9853
+ now = mergedAt(i)
9854
+ await store.append(slug(i), {
9855
+ actor: DISPATCHER,
9856
+ type: 'build.completed',
9857
+ payload: { outcome: 'merged' },
9858
+ })
9859
+ }
9860
+ Object.assign(costs[n]!, {
9861
+ mergedAll: await walkMerged(store, {}, [
9862
+ range(59, 35),
9863
+ [...range(34, 30), ...range(29, 10)],
9864
+ range(9, 0),
9865
+ ]),
9866
+ mergedSince: await walkMerged(store, { since: mergedAt(50) }, [range(59, 50)]),
9867
+ mergedWindow: await walkMerged(store, { since: t0, until: mergedAt(40) }, [
9868
+ [...range(39, 30), ...range(29, 15)],
9869
+ range(14, 0),
9870
+ ]),
9871
+ mergedEmpty: await walkMerged(store, { since: mergedAt(45), until: mergedAt(45) }, [[]]),
9872
+ })
9661
9873
  }
9662
9874
  for (const n of sizes)
9663
9875
  for (const [name, pages] of Object.entries(costs[n]!))
9664
9876
  for (const cost of pages) {
9665
9877
  // `snapshot` is the memory store copying each returned record.
9666
9878
  const { snapshot: copies = 0, ...reads } = cost.calls
9667
- expect(reads).toEqual({ listBuildsPage: 1 })
9879
+ expect(reads).toEqual(
9880
+ MERGED_LISTING_WALKS.has(name) ? { listMergedBuildsPage: 1 } : { listBuildsPage: 1 },
9881
+ )
9668
9882
  expect(copies).toBeLessThanOrEqual(25)
9669
9883
  expect(cost.rows).toBe(0)
9670
9884
  expect(cost.repoRows).toBe(0)
9671
9885
  expect(cost.examined).toBeLessThanOrEqual(
9672
- name === 'recent' ? 4 : name === 'mergedLeaf' || name === 'recentLeaf' ? 1 : 26,
9886
+ name === 'recent'
9887
+ ? 4
9888
+ : name === 'mergedLeaf' || name === 'recentLeaf' || name === 'mergedEmpty'
9889
+ ? 1
9890
+ : 26,
9673
9891
  )
9674
9892
  }
9675
9893
  const shape = (pages: BuildFeedReadCost[]) =>
@@ -511,6 +511,10 @@ The distinctions that change an administrator's answer:
511
511
  logical credentials, or records a reasoned `harvest.session.resume-fallback`
512
512
  and starts fresh. Orderly suspension spends no recovery attempt; real
513
513
  crashes retain recovery accounting.
514
+ A hosted harvest launch that is still preparing stops at its next boundary,
515
+ and teardown joins it before releasing the lease. A harvest that a
516
+ dispatcher launches never claims, renews or releases the repository lease
517
+ on its own behalf.
514
518
  Current, distinct previous, held and live-process runtimes survive pruning.
515
519
  Cached Bun entries disable auto-install and explicitly pin a neutral compiler
516
520
  config. Third-party files remain as installed. `--plain`/non-TTY run directly
@@ -927,7 +931,13 @@ build status and the dashboard, stop dependent work, and retry up to
927
931
  `[policy].maxSetupAttempts`; exhaustion raises a setup-targeted escalation
928
932
  without manufacturing a pipeline phase or verdict. An answer from your operator
929
933
  agent or you re-arms the budget, and only a later successful setup, recorded as
930
- a new `runner.attached`, clears the current error. Values are never evaluated as config — they are handed to a
934
+ a new `runner.attached`, clears the current error. Setup must not modify
935
+ tracked files: paths it newly changes outside `[[generated]]` raise a
936
+ `policy/dirty-worktree` escalation naming them before the next phase runs;
937
+ declared generated outputs are tolerated. The check is skipped when that phase
938
+ is a `reconcile`, whose resolver works on its own in-progress replay, and while
939
+ an answered dirty-worktree recovery is pending; restack and reconcile
940
+ preparation still classify tracked dirt before replaying. Values are never evaluated as config — they are handed to a
931
941
  shell as written.
932
942
 
933
943
  Fresh init config deliberately leaves this map empty. The setup agent follows
@@ -964,6 +974,9 @@ index, or leftover conflict markers fails the regeneration; nothing is committed
964
974
  ordinary reconcile with the failure reason in its context. A replay that also
965
975
  conflicts in undeclared files goes straight to reconcile, whose context lists
966
976
  the generated files and commands to run after the other files are resolved.
977
+ Uncommitted changes to declared files, such as outputs setup rewrote, are
978
+ restored to `HEAD` before any restack or reconcile replay; an undeclared
979
+ tracked change refuses preparation with `policy/dirty-worktree` naming it.
967
980
  Declarations come from the dispatcher's live configuration, like `[policy]`.
968
981
  See [Restacking](references/restacking.md) for the recorded facts.
969
982
 
@@ -1260,7 +1273,12 @@ releases it and provisions the next generation. Provisioning cut off by a
1260
1273
  recorded dispatcher teardown is the exception: the next invocation asks the
1261
1274
  provider to verify and finish the same generation (the Vercel provider resumes
1262
1275
  after its last completed stage, at the commit it cloned), and if it cannot,
1263
- the replacement consumes no infrastructure attempt. A preservation or release
1276
+ the replacement consumes no infrastructure attempt. Its `dispatch.failed`
1277
+ names the stage cut off and how long it ran (`provisioning abandoned at
1278
+ dispatcher teardown during <stage> after <N>s`). A Vercel `provisioning` step
1279
+ that exceeds its `timeoutSeconds` is instead an ordinary, charged
1280
+ infrastructure failure. Its message, like every failed sandbox provisioning
1281
+ command's, carries the stage, redacted argv and stderr/stdout tails. A preservation or release
1264
1282
  failure is recorded against its build, as an infrastructure failure or janitor
1265
1283
  attention, and never stops the dispatcher from advancing other builds. The
1266
1284
  recorded error and the infrastructure-limit escalation name the failed recovery
@@ -1291,7 +1309,10 @@ through the latest-only `dispatcher.pass-cursors` fact, so every build is
1291
1309
  visited within a bounded number of passes. Each pass logs `stages:` with time
1292
1310
  and items per stage; a pass the work deadline cuts short logs `tick: work
1293
1311
  deadline reached during <stage>` naming the part in flight, and `ab repository
1294
- status` shows the latest as `last pass stages:`.
1312
+ status` shows the latest as `last pass stages:`. A hosted store service's
1313
+ request logs attribute each store request to its caller and pass stage
1314
+ through the
1315
+ [`X-Autobuild-Caller` header](references/remote-store-protocol.md#1-transport-and-conventions).
1295
1316
  Fencing is revalidated after restart; a saved receipt alone never authorizes
1296
1317
  cleanup of a newer execution. Current recovery notes are linked by the session
1297
1318
  manifest's `workspaceRecovery` field. Recovery notes apply to the next session
@@ -1675,8 +1696,19 @@ while `round` remains occurrence scope. Answering a runner-failure cause re-arms
1675
1696
  only its matching phase and round. The phase-level `verify-failure-limit` cause
1676
1697
  explicitly re-arms all rounds for its verify target, while
1677
1698
  `reconcile-no-progress`, `publication-retry-limit`, `wait-unresolvable`,
1678
- `measurement-failed`, `target-rewritten` and the setup-only cause reset no
1679
- phase-runner failures.
1699
+ `measurement-failed`, `target-rewritten`, `dirty-worktree` and the setup-only
1700
+ cause reset no phase-runner failures.
1701
+
1702
+ `dirty-worktree` targets `implement`. Setup newly modifying tracked files
1703
+ outside `[[generated]]` (except before a `reconcile` session), or a restack or
1704
+ reconcile preparation finding them, raises it with the bounded paths. Guidance or a bare retry returns the build to
1705
+ `implement` with those paths as feedback. A frozen preparation without a publish
1706
+ intent is first superseded (`reconcile.superseded {cause: dirty-worktree}`) and
1707
+ the files stay in the worktree. One with an intent settles first, with the
1708
+ changes stored as artifact `dirty-worktree-<escalation>` for the agent to
1709
+ re-apply. A superseded replay whose target also changed a dirty file stores
1710
+ them the same way, because Git cannot carry them back to the build branch. Autobuild never commits or discards them itself, and the escalation
1711
+ never needs an abort.
1680
1712
  The closed cause map forces every future policy condition to choose one of these
1681
1713
  semantics instead of inheriting behavior from a missing `round`. Runner failures
1682
1714
  while checking progress or refreshing the base therefore remain counted after a
@@ -3201,7 +3233,8 @@ break.
3201
3233
  `ab answer` answers every escalation that is open when the command runs,
3202
3234
  regardless of `agent`, `stall`, or `policy` source. Its text is joined, trimmed,
3203
3235
  and delivered as authoritative guidance. With no text (or only whitespace), it
3204
- requests a bare retry and supplies no agent guidance. Verify has two explicit
3236
+ requests a bare retry and supplies no agent guidance, except for a ticket wait
3237
+ and a `dirty-worktree` escalation (below). Verify has two explicit
3205
3238
  answer routes: guidance answering an agent verifier's own `ab escalate` returns
3206
3239
  to that same `verify:<step>` on `verify.started.feedback` and materializes as
3207
3240
  `$AB_CONTEXT_DIR/guidance.json`; the cited start carries it durably across any pre-launch
@@ -3246,9 +3279,14 @@ A producer round has one immediate feedback kind: on a guidance round,
3246
3279
  `$AB_CONTEXT_DIR/guidance.json` takes precedence over findings or the legacy
3247
3280
  single-report feedback. A referenced `verifyStageFailure` receipt remains
3248
3281
  available alongside guidance, with every failed report and cancelled/not-run
3249
- member; it is not erased by feedback precedence. Except for a ticket wait, a
3282
+ member; it is not erased by feedback precedence. Except for a ticket wait and a
3283
+ `dirty-worktree` escalation, a
3250
3284
  bare retry writes no `$AB_CONTEXT_DIR/guidance.json` and displaces nothing: the resumed round still gets whatever
3251
- the loop was already routing, such as the last review round's findings.
3285
+ the loop was already routing, such as the last review round's findings. A bare
3286
+ retry of a `dirty-worktree` escalation routes the next `implement` round the
3287
+ dirty-file question, its paths, any set-aside artifact's recovery instructions
3288
+ and a one-line retry summary as `$AB_CONTEXT_DIR/guidance.json`, exactly as
3289
+ guidance would.
3252
3290
 
3253
3291
  `--dismiss` is per escalation. It answers only blockers that cite at least one
3254
3292
  real plan-review or code-review finding; blockers with no such citation remain
@@ -5,7 +5,9 @@ contract at
5
5
  `/operator/v1/repos/{repo}`. It is versioned with remote store protocol **7**.
6
6
  Every request must send `X-Autobuild-Version`,
7
7
  `X-Autobuild-Protocol-Version: 7`, and `Authorization: Bearer …`. Identity is
8
- checked before authentication or resource lookup.
8
+ checked before authentication or resource lookup. The optional, diagnostic
9
+ `X-Autobuild-Caller` header follows the remote store protocol's transport
10
+ conventions.
9
11
 
10
12
  Project credentials are opaque `abp_1_<id>_<secret>` bearer values bound to one
11
13
  registered normalized repository. The service stores only a SHA-256 digest of
@@ -85,6 +87,7 @@ raw session-event append. External operator harnesses own agent execution.
85
87
  | Method and path | Result |
86
88
  |---|---|
87
89
  | `GET …/builds?scope=active\|queued\|all` | Build summaries, newest update first. `queued` means active plus queued, matching `ab builds --queued`. Each nonterminal summary's `slot` is `{state: "held"}`, `{state: "requested", request, priority?: "urgent" \| "high" \| "low"}` or `{state: "none"}`; absent means unknown (an older server), never `none`. Its `statusWord` is `{word, tone, note?}`, the status word every surface shows; `status` stays the reducer's lifecycle status. |
90
+ | `GET …/builds?scope=merged&since=T&until=T&limit=N&cursor=C` | `{builds, next}`: merged builds, most recently merged first, each `{slug, mergedAt, kind, ticket?, pr?, target?}`. `mergedAt` is when the build merged, never a later cleanup write; `kind` is `leaf` or `node`; `pr` is `{number, url}`; `target` is `{build, ticket}` for a child of a node. `since` (inclusive) and `until` (exclusive) are ISO instants with a zone; `limit` is 1–100 (default 25); pass `next` back as `cursor` with the same window. One indexed page read, no event rows. These four parameters on another scope are a `400 validation`; a bad window, limit or cursor is `400 validation` with code `invalid-page`. |
88
91
  | `GET …/builds/{slug}` | `{detail, dashboardRow}`; `detail.slot` and `dashboardRow.slot` carry the build's slot state, shaped as in `GET …/builds`; `detail.runnerAttaches` records chronological attach boundaries and their runtime identity (version, commit, source kind/location), with null runtime for unrecorded historical attaches; `dashboardRow` remains a `CLEANING` row after `build.aborted` and becomes `null` only when the dashboard stops listing it: at `build.completed` when no escalation is open. A completed build with an open escalation keeps, or regains, a `BLOCKED` row (note `done`), including one raised during abort cleanup; abort itself closes the escalations open when it is accepted. The row becomes `null` once the escalation is acknowledged; neither step reopens its lifecycle state. |
89
92
  | `GET …/dashboard` | `{generatedAt, model, settingsHeader}`. `model` is the dashboard's rows, steps, elapsed timing inputs, harvest row, triage (when the dispatcher published one)/queue/capacity and settings projection. `model.capacity.slots` maps each build to its slot state, and each `model.builds[].slot` repeats it; absent means unknown. `model.configuration` is `"no-dispatcher-run"` when the repository records no dispatcher run, and absent otherwise. Optional `rollback` contains `correlation`, `lineage`, full `failed` and `restored` runtime identities and rollback event `ts` for the authoritative dispatcher lineage’s unresolved hold. Both dashboards name failed, restored and held runtime plus timestamp. Matching durable different-target hold clearance removes it; a fresh operator lineage hides it only after a committed operational tick or accepted takeover. Run-started and yielded ticks alone cannot replace authority; same-lineage generations retain the notice. Historical rollback records are not fallback notices. Optional `handoffs` lists all accepted unfinished handoffs with predecessor `run`, optional `successor`, `correlation`, full `from`/`to` runtimes, `mode` and optional `deadline`. Outstanding drain-mode builds carry `draining: true`, also on build-detail `dashboardRow`; matching settlement removes it. Accepted completion removes the handoff; neither takeover nor the clock does. Missing historical mode means cutover and missing deadline displays unknown. |
90
93
  | `GET …/status` | Repository intake, pause, and default-auto-merge projection, plus `ticketStarts` (`{pending, recent}`, each entry with its `priority`) when single-ticket start requests are pending or recently settled. `capacity.slots`, when the held configuration is readable, maps each nonterminal build to its slot state; `capacity.occupied` counts its `held` entries. Its `operator` is `{presence: "unavailable", reason}`: this route does not load presence registrations, so it is not evidence that no operator is present. |
@@ -194,7 +197,8 @@ both refusals record nothing.
194
197
 
195
198
  One generic route executes any entry of the agent tool registry (the same
196
199
  closed table `ab mcp` serves over stdio): the body is the tool's validated input — `repo`
197
- included and required to equal the URL's repository — and the response is the
200
+ included and required to equal the URL's repository; a `repository` key is
201
+ refused as `400 validation` with code `repo-argument` — and the response is the
198
202
  registry result verbatim. The verified operator token supplies the acting
199
203
  identity and, when minted with one, the `via` attribution marker; the body
200
204
  never does. Failures keep the shared `{kind,error,code?,progress?,state?}` shape
@@ -208,7 +212,10 @@ deployment can host operator sandboxes, and each call is gated per repository
208
212
  on the latest deposited effective config. A closed gate is a `409 refusal`
209
213
  with code `sandbox-orchestrator-disabled`, `sandbox-no-effective-config`,
210
214
  `sandbox-effective-config-invalid`, `sandbox-credentials-missing` or
211
- `sandbox-backend-unavailable`.
215
+ `sandbox-backend-unavailable`. Hosted `/mcp` tool calls reach this route
216
+ with the caller attribution `X-Autobuild-Caller: kind=operator;client=mcp`
217
+ (see the remote store protocol's transport conventions), so the service's
218
+ request logs can tell them apart.
212
219
 
213
220
  ### Per-repository MCP URLs
214
221
 
@@ -220,7 +227,8 @@ URL. Adding it to an agent harness connects that harness to one repository.
220
227
  | URL | `<resource>` | `<resource>/<host><path>`, e.g. `https://ops.example/mcp/github.com/acme/widgets` for `https://github.com/acme/widgets` |
221
228
  | Tool schemas | every tool requires `repo` | no `repo` field; the URL's repository is supplied |
222
229
  | `repositories.list` | offered | not offered |
223
- | A `repo` argument | names the repository | equal to the URL's repository is ignored; any other is a `validation` result |
230
+ | A `repo` argument | names the repository | refused, even the URL's own repository: a `validation` result with code `repo-argument` |
231
+ | A `repository` argument | refused: `validation`, code `repo-argument` (the argument is `repo`) | refused: `validation`, code `repo-argument` |
224
232
  | `sandbox.*` listed | when the deployment can host sandboxes | also needs the repository's latest deposited effective config to enable `[orchestrator]` (one latest-artifact read per listing) |
225
233
  | Instructions | describe the deployment, with each accessible repository's agent context | name only that repository, with its agent context |
226
234
  | Prompts | one per skill per accessible repository, `<label>.<skill>` | one per skill, named for the skill |
@@ -327,7 +335,9 @@ the browser user's human actor while no token or signing secret reaches client
327
335
  code. Responses are private/no-store; 401 requires reauthentication.
328
336
  Polling clients may use a two-second interval. The gateway provides no
329
337
  streaming transport; `ab watch` polls store event reads client-side. Delegated bearer tokens remain
330
- server-side.
338
+ server-side. Delegated requests carry `X-Autobuild-Caller:
339
+ kind=operator;client=web`, set by the gateway; a browser cannot choose its
340
+ own attribution.
331
341
 
332
342
  The API does not expose phase-session commands, runner startup, a push or
333
343
  long-poll streaming transport, or a generic event-append operation; event
@@ -50,6 +50,7 @@ Declare served model prefixes and a default. Optional tool-free `oneShot` sits b
50
50
  - Resume an intact branch non-destructively, never silently re-cut from a newer base. Rematerialize a lost copy. Make release idempotent.
51
51
  - Optional `provision.publication` supplies a durable confirmed SHA and known cache tips for authoritative readback and cache repair. Preserve unknown unpublished work.
52
52
  - Optional `provision.fresh: { owner }` marks a build's first provision. A pre-existing branch of that name is not the build's work: never return it as the base unless you hold your own creation receipt for `owner` (stable across that build's retries). Cut from `baseBranch` and keep the old tip recoverable. Providers that ignore it rely on claim-time deduplication.
53
+ - Optional `provision.signal` is the invocation's teardown token: abort in-flight provisioning promptly and record nothing; the dispatcher records the abandonment. Optional `provision.onProgress({ stage, step? })` reports each stage just before it runs, so a teardown can name it; it must never block or throw.
53
54
  - Optional `localBranchExists(repo, branch)` reports a local `refs/heads/<branch>` in the checkout you create branches in, and throws when the probe fails. Dispatch calls it only at claim time and skips such a slug. Omit it when your branches aren't local; `remoteBranchExists` covers those.
54
55
 
55
56
  ### `forge`