@defrex/autobuild 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +140 -10
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +119 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/architecture.md +107 -8
  7. package/docs/build-store.md +3 -41
  8. package/docs/cli.md +14 -0
  9. package/docs/configuration-overview.md +111 -0
  10. package/docs/configuration.md +260 -141
  11. package/docs/dispatcher-hosting.md +18 -33
  12. package/docs/intake.md +2 -0
  13. package/docs/merge-policy.md +1 -3
  14. package/docs/operating.md +1 -2
  15. package/docs/operator-api.md +100 -47
  16. package/docs/operator-surfaces.md +3 -20
  17. package/docs/overview.md +1 -1
  18. package/docs/plugin-authoring.md +21 -0
  19. package/docs/remote-store-protocol.md +198 -89
  20. package/docs/remote-ticket-protocol.md +29 -49
  21. package/docs/seams.md +8 -8
  22. package/docs/setup.md +34 -129
  23. package/docs/ticket-sources.md +18 -0
  24. package/docs/troubleshooting.md +7 -11
  25. package/docs/upgrading.md +1 -1
  26. package/docs/workspaces.md +4 -4
  27. package/package.json +14 -5
  28. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  29. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  30. package/packages/core/src/accounts/local-credentials.ts +194 -0
  31. package/packages/core/src/accounts/local-inference.ts +106 -0
  32. package/packages/core/src/accounts/local-owner.ts +123 -0
  33. package/packages/core/src/accounts/sensitive.ts +2 -0
  34. package/packages/core/src/cli/accounts.ts +147 -0
  35. package/packages/core/src/cli/binary.ts +3 -1
  36. package/packages/core/src/cli/connect.ts +3 -3
  37. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  38. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  39. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  40. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  41. package/packages/core/src/cli/dispatch.ts +71 -2
  42. package/packages/core/src/cli/help.ts +16 -0
  43. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  44. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  45. package/packages/core/src/cli/init-validation.ts +160 -18
  46. package/packages/core/src/cli/main.ts +44 -0
  47. package/packages/core/src/cli/publication-settlement.ts +4 -1
  48. package/packages/core/src/cli/secrets.ts +173 -0
  49. package/packages/core/src/cli/store-opening.ts +11 -1
  50. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  51. package/packages/core/src/cli/watch.ts +3 -1
  52. package/packages/core/src/config/accounts.ts +101 -0
  53. package/packages/core/src/config/live.ts +14 -1
  54. package/packages/core/src/config/roles.ts +54 -3
  55. package/packages/core/src/config/schema.ts +60 -0
  56. package/packages/core/src/events/compatibility.ts +2 -1
  57. package/packages/core/src/events/payloads.ts +3 -0
  58. package/packages/core/src/events/repository.ts +2 -0
  59. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +3 -0
  60. package/packages/core/src/kernel/reducer.ts +4 -1
  61. package/packages/core/src/operator/index.ts +2 -0
  62. package/packages/core/src/operator/protocol.ts +6 -0
  63. package/packages/core/src/operator/registry.ts +22 -1
  64. package/packages/core/src/operator/tickets.ts +25 -4
  65. package/packages/core/src/plugins/manifest.ts +2 -1
  66. package/packages/core/src/ports/runner/account-env.ts +88 -0
  67. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  68. package/packages/core/src/ports/runner/claude.ts +26 -2
  69. package/packages/core/src/ports/runner/codex.ts +63 -31
  70. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  71. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  72. package/packages/core/src/ports/runner/routing.ts +35 -4
  73. package/packages/core/src/ports/tickets/contract.ts +58 -0
  74. package/packages/core/src/ports/tickets/tree.ts +1 -1
  75. package/packages/core/src/ports/types.ts +28 -7
  76. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  77. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  78. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  79. package/packages/core/src/ports/workspace/create.ts +2 -0
  80. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  81. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  82. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  83. package/packages/core/src/processes/build-runner.ts +32 -1
  84. package/packages/core/src/processes/dispatcher.ts +23 -0
  85. package/packages/core/src/processes/execution-settlement.ts +21 -3
  86. package/packages/core/src/processes/harvest-runner.ts +68 -8
  87. package/packages/core/src/project-secrets.ts +105 -0
  88. package/packages/core/src/secret-name.ts +41 -0
  89. package/packages/core/src/store/account-redaction.ts +156 -0
  90. package/packages/core/src/store/contract.ts +3 -1
  91. package/packages/core/src/store/reducer-value-shapes.json +2889 -2781
  92. package/packages/core/src/store/remote/client.ts +42 -47
  93. package/packages/core/src/store/remote/compatibility.ts +18 -0
  94. package/packages/core/src/testing/dispatch-read-budget.ts +122 -0
  95. package/packages/core/src/testing/index.ts +1 -0
  96. package/packages/core/src/testing/reduced-read-budget.ts +47 -0
  97. package/skills/guide/SKILL.md +120 -30
  98. package/skills/guide/references/accounts.md +119 -0
  99. package/skills/guide/references/merge-policy.md +1 -3
  100. package/skills/guide/references/operator-api.md +100 -47
  101. package/skills/guide/references/plugin-authoring.md +21 -0
  102. package/skills/guide/references/remote-store-protocol.md +198 -89
  103. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  104. package/skills/guide/references/setup.md +34 -129
  105. package/skills/harvest/SKILL.md +3 -1
  106. package/skills/harvest-review/SKILL.md +3 -1
  107. package/skills/operate/SKILL.md +5 -6
  108. package/skills/spec/SKILL.md +1 -1
  109. package/skills/tickets/SKILL.md +3 -2
  110. package/templates/hosted-service/package.json +2 -2
  111. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  112. package/docs/hosted-dispatcher.md +0 -278
  113. package/docs/hosted-service.md +0 -304
  114. package/docs/mcp.md +0 -150
@@ -9,15 +9,16 @@ import {
9
9
  type OperatorPresence,
10
10
  } from '../operator-presence'
11
11
  import {
12
+ ReducerValueIncompatibilityError,
12
13
  clientIdentityError,
13
14
  classifyClient,
14
15
  releaseVersion,
15
16
  supportedClientRangeSchema,
16
17
  } from './compatibility'
17
18
  import { stampCompatibility, buildEventPolicy, repositoryEventPolicy } from '../../events/policy'
18
- import { READ_CATALOG_IDENTITY, projectStoredEvents } from '../../events/compatibility'
19
+ import { READ_CATALOG_IDENTITY } from '../../events/compatibility'
19
20
  import { CATALOG_IDENTITY_HEADER } from './version'
20
- import { validateReducerValue } from '../reducer-value-validation'
21
+ import { diagnoseReducerValue } from '../reducer-value-validation'
21
22
  import { prepareEventWrite as validateEventWrite } from '../../events/catalog'
22
23
  import { prepareRepositoryEventWrite as validateRepositoryEventWrite } from '../../events/repository'
23
24
  import {
@@ -195,9 +196,6 @@ export interface RemoteBuildStoreOptions {
195
196
  export class RemoteBuildStore implements BuildStore {
196
197
  readonly catalogIdentity = READ_CATALOG_IDENTITY
197
198
  readonly networkReads = true
198
- // Reader-local accumulators for this client instance. Never publish these into the service's
199
- // cache: its catalog may interpret the same journal differently.
200
- private readonly replayStates = new Map<string, { cursor: number; acc: unknown }>()
201
199
  private readonly base: string
202
200
  private readonly token: string | undefined
203
201
  private readonly fetchFn: typeof fetch
@@ -365,10 +363,7 @@ export class RemoteBuildStore implements BuildStore {
365
363
  const response = await this.raw('GET', `${this.repoPath(repo)}/build-digests`)
366
364
  if (!response.ok) throw await this.toError(response)
367
365
  const digests = buildDigestListSchema.parse(await response.json())
368
- if (response.headers.get(CATALOG_IDENTITY_HEADER) === READ_CATALOG_IDENTITY)
369
- return new Map(digests.map((digest) => [digest.slug, digest]))
370
- const { readPersistedBuildDigests } = await import('../reduced-reads')
371
- return readPersistedBuildDigests(this, repo)
366
+ return new Map(digests.map((digest) => [digest.slug, digest]))
372
367
  }
373
368
 
374
369
  async append<T extends EventType>(slug: string, event: EventWrite<T>): Promise<EventEnvelope<T>> {
@@ -760,49 +755,49 @@ export class RemoteBuildStore implements BuildStore {
760
755
  }
761
756
 
762
757
  async getReducerValue(scope: SnapshotScope, request: ReducerValueRequest): Promise<ReducerValue> {
763
- const { reducer, entry, identity: replayIdentity } = resolveReducerValue(scope, request)
758
+ const { reducer } = resolveReducerValue(scope, request)
764
759
  const root = scope.kind === 'build' ? this.buildPath(scope.slug) : this.repoPath(scope.repo)
765
760
  const response = await this.raw('POST', `${root}/reducer-values`, request)
766
761
  if (!response.ok) throw await this.toError(response)
767
- const result = reducerValueSchema.parse(await response.json())
768
- const identity = response.headers.get(CATALOG_IDENTITY_HEADER)
769
- if (
770
- identity === READ_CATALOG_IDENTITY &&
771
- result.version === reducer.version &&
772
- validateReducerValue(request.reducer, result.value)
773
- )
774
- return {
775
- version: result.version,
776
- cursor: result.cursor,
777
- value: result.value as ReducerValue['value'],
778
- catalogIdentity: identity,
779
- }
780
- // Freeze at this response's cursor, including when concurrent reads finish
781
- // out of order. Clone before folding: reducers may mutate their accumulator.
782
- const cached = this.replayStates.get(replayIdentity)
783
- const reusable = cached !== undefined && cached.cursor <= result.cursor ? cached : undefined
784
- let cursor = reusable?.cursor ?? 0
785
- let acc = reusable === undefined ? reducer.initial() : structuredClone(reusable.acc)
786
- if (cursor < result.cursor) {
787
- const events =
788
- scope.kind === 'build'
789
- ? await this.getEvents(scope.slug, cursor)
790
- : await this.getRepoEvents(scope.repo, cursor)
791
- const bounded = events.filter((event) => event.seq <= result.cursor)
792
- for (const event of bounded) {
793
- if (event.seq !== cursor + 1) throw new Error('noncontiguous reducer log')
794
- cursor = event.seq
795
- }
796
- if (cursor !== result.cursor) throw new Error('incomplete reducer log')
797
- acc = reducer.advance(acc, entry.adapt(projectStoredEvents(bounded)))
762
+ let body: unknown
763
+ try {
764
+ body = await response.json()
765
+ } catch (error) {
766
+ if (!(error instanceof SyntaxError)) throw error
767
+ throw new ReducerValueIncompatibilityError(
768
+ request.reducer,
769
+ scope,
770
+ reducer.version,
771
+ undefined,
772
+ 'invalid reducer envelope: expected JSON',
773
+ )
774
+ }
775
+ const parsed = reducerValueSchema.safeParse(body)
776
+ const serverVersion =
777
+ body && typeof body === 'object' && 'version' in body && typeof body.version === 'number'
778
+ ? body.version
779
+ : undefined
780
+ const fail = (reason: string): never => {
781
+ throw new ReducerValueIncompatibilityError(
782
+ request.reducer,
783
+ scope,
784
+ reducer.version,
785
+ serverVersion,
786
+ reason,
787
+ )
798
788
  }
799
- const value = entry.value(reducer.finish(structuredClone(acc)))
800
- // Commit only successful folds, and never regress a concurrent accumulator.
801
- if ((this.replayStates.get(replayIdentity)?.cursor ?? -1) <= cursor) {
802
- this.replayStates.delete(replayIdentity)
803
- this.replayStates.set(replayIdentity, { cursor, acc })
789
+ if (!parsed.success) fail(`invalid reducer envelope: ${parsed.error.message}`)
790
+ const result = parsed.data!
791
+ if (result.version !== reducer.version) fail('reducer version mismatch')
792
+ const failure = diagnoseReducerValue(request.reducer, result.value)
793
+ if (failure) fail(`invalid finished value at ${failure.path}: expected ${failure.expected}`)
794
+ const identity = response.headers.get(CATALOG_IDENTITY_HEADER)
795
+ return {
796
+ version: result.version,
797
+ cursor: result.cursor,
798
+ value: result.value as ReducerValue['value'],
799
+ ...(identity === null ? {} : { catalogIdentity: identity }),
804
800
  }
805
- return { version: reducer.version, cursor, value, catalogIdentity: READ_CATALOG_IDENTITY }
806
801
  }
807
802
 
808
803
  private snapshotPath(scope: SnapshotScope, reducer: string): string {
@@ -80,6 +80,8 @@ export function compatibilityAdvice(
80
80
  export const RELEASE_LINE_PROTOCOLS: Readonly<Record<string, string>> = {
81
81
  // v1.0.x shipped protocol 4; protocol 5+ requires the next minor line.
82
82
  '1.0': '4',
83
+ // v1.1.x shipped protocol 6; retain it when this line becomes historical.
84
+ '1.1': '6',
83
85
  '0.9': '3',
84
86
  '0.10': '3',
85
87
  '0.11': '3',
@@ -108,3 +110,19 @@ export function clientIdentityError(
108
110
  if (!advice && expected !== undefined && protocol === expected) return undefined
109
111
  return `remote store version mismatch: client Autobuild ${client ?? '(missing)'} protocol ${protocol ?? '(missing)'}; server Autobuild ${serviceVersion} protocol ${serviceProtocol}; ${advice ?? `supported clients ${formatClientRange(range)}; unsupported protocol identity`}`
110
112
  }
113
+
114
+ /** A successful server answer cannot be represented by this client's reducer. */
115
+ export class ReducerValueIncompatibilityError extends Error {
116
+ override readonly name = 'ReducerValueIncompatibilityError'
117
+ constructor(
118
+ readonly reducer: string,
119
+ readonly scope: import('../snapshots').SnapshotScope,
120
+ readonly clientVersion: number,
121
+ readonly serverVersion: number | undefined,
122
+ readonly reason: string,
123
+ ) {
124
+ super(
125
+ `incompatible reducer ${reducer}: client version ${clientVersion}, server version ${serverVersion ?? '(unavailable)'}; ${reason}`,
126
+ )
127
+ }
128
+ }
@@ -229,3 +229,125 @@ export async function dispatchReadBudget(store: BuildStore, backing: BuildStore)
229
229
  expect(metrics.rows - before.rows).toBe(1)
230
230
  expect(metrics.state - before.state).toBe(0)
231
231
  }
232
+
233
+ /** Script a minute at both launcher cadences using the real runtime reader and
234
+ * launcher cache. Each helper gets a fresh facade; private reads use that same
235
+ * instrumented receiver rather than escaping into an uncounted reducer. */
236
+ export async function upgradeReadBudget(store: BuildStore): Promise<void> {
237
+ const { readUpgradeProjection } = await import('../cli/dispatch-handoff')
238
+ const { conditionalUpgradeClient } = await import('../cli/dispatch-launch-contract')
239
+ for (const length of [100, 10_000]) {
240
+ const repo = `/upgrade-budget-${length}`
241
+ await store.ensureRepo(repo)
242
+ for (let i = 0; i < length; i++)
243
+ await store.appendRepo(repo, {
244
+ actor: humanActor('budget'),
245
+ type: 'dispatcher.intake-set',
246
+ payload: { enabled: false },
247
+ })
248
+ const metrics = { position: 0, metadata: 0, reducer: 0, events: 0, rows: 0 }
249
+ const launch = {
250
+ version: 1 as const,
251
+ runtimeRoot: '/runtime',
252
+ checkout: repo,
253
+ journal: { repo, storeRef: '/memory' },
254
+ run: 'budget',
255
+ lineage: 'budget',
256
+ }
257
+ const client = conditionalUpgradeClient()
258
+ const check = () =>
259
+ client(repo, (condition) =>
260
+ readUpgradeProjection(
261
+ launch,
262
+ ['dispatch'],
263
+ {},
264
+ {
265
+ condition,
266
+ openStore: () =>
267
+ new Proxy(store, {
268
+ get(target, key, receiver) {
269
+ if (key === 'close') return async () => {}
270
+ // Memory reducer storage reads bypass public getRepoEvents. Count
271
+ // the actual sliced rows at that private boundary as well.
272
+ if (key === 'repoState')
273
+ return (...args: unknown[]) => {
274
+ const state = Reflect.get(target, key).apply(receiver, args)
275
+ return new Proxy(state, {
276
+ get(state, field) {
277
+ const value = Reflect.get(state, field)
278
+ if (field !== 'events') return value
279
+ return new Proxy(value, {
280
+ get(events, method) {
281
+ if (method === 'slice')
282
+ return (since: number, through: number) => {
283
+ const rows = events.slice(since, through)
284
+ metrics.events++
285
+ metrics.rows += rows.length
286
+ return rows
287
+ }
288
+ return Reflect.get(events, method)
289
+ },
290
+ })
291
+ },
292
+ })
293
+ }
294
+ const value = Reflect.get(target, key, receiver)
295
+ if (typeof value !== 'function') return value
296
+ if (typeof key !== 'string' || !key.startsWith('get')) return value.bind(receiver)
297
+ return async (...args: unknown[]) => {
298
+ // The queried run has not started. No candidate means no
299
+ // historical per-run reconstruction, even at bootstrap.
300
+ if (key === 'getReducerValue')
301
+ expect((args[1] as { reducer: string }).reducer).not.toBe(
302
+ 'dispatcherRunFacts',
303
+ )
304
+ if (key === 'getRepoChangePosition') metrics.position++
305
+ else if (key === 'getReducerValue' || key === 'getReducerSnapshot')
306
+ metrics.reducer++
307
+ else if (key === 'getRepoEvents' || key === 'getRepoStateEvents')
308
+ metrics.events++
309
+ else if (typeof key === 'string' && key.startsWith('get')) metrics.metadata++
310
+ const result = await value.apply(receiver, args)
311
+ if (
312
+ (key === 'getRepoEvents' || key === 'getRepoStateEvents') &&
313
+ Array.isArray(result)
314
+ )
315
+ metrics.rows += result.length
316
+ return result
317
+ }
318
+ },
319
+ }),
320
+ },
321
+ ),
322
+ )
323
+ // Bootstrap is explicitly measured separately from the idle bound.
324
+ await check()
325
+ expect(metrics.position).toBe(1)
326
+ expect(metrics.metadata).toBeGreaterThan(0)
327
+ expect(metrics.reducer).toBeGreaterThan(0)
328
+ expect(metrics.rows).toBeGreaterThanOrEqual(length)
329
+ for (const interval of [1_000, 250]) {
330
+ for (const key of Object.keys(metrics) as (keyof typeof metrics)[]) metrics[key] = 0
331
+ let now = 0
332
+ while (now < 60_000) {
333
+ await check()
334
+ now += interval
335
+ }
336
+ expect(metrics).toEqual({
337
+ position: 60_000 / interval,
338
+ metadata: 0,
339
+ reducer: 0,
340
+ events: 0,
341
+ rows: 0,
342
+ })
343
+ }
344
+ await store.appendRepo(repo, {
345
+ actor: humanActor('budget'),
346
+ type: 'dispatcher.intake-set',
347
+ payload: { enabled: true },
348
+ })
349
+ metrics.reducer = 0
350
+ await check()
351
+ expect(metrics.reducer).toBeGreaterThan(0)
352
+ }
353
+ }
@@ -68,6 +68,7 @@ export { ProjectCredentials } from '../cli/project-credentials'
68
68
  export { dispatchReadBudget } from './dispatch-read-budget'
69
69
 
70
70
  export {
71
+ catalogSkewReadBudget,
71
72
  reducedReadBudget,
72
73
  countHistoricalRows,
73
74
  type ReducedReadCosts,
@@ -180,6 +180,17 @@ export async function reducedReadBudget(opts: {
180
180
  return typeof value === 'function' ? value.bind(target) : value
181
181
  },
182
182
  })
183
+ // Explicit operation multiplication on fresh handles at both history sizes.
184
+ // Unchanged reduced reads never acquire historical event rows.
185
+ for (const operations of [1, 8]) {
186
+ reset()
187
+ for (let n = 0; n < operations; n++) {
188
+ await readBuildFacts(cold, slug)
189
+ await readRepositoryFacts(cold, repo)
190
+ }
191
+ expect(costs.events).toBe(0)
192
+ expect(costs.metadata).toBeLessThan(operations * 20)
193
+ }
183
194
  await coldDispatchOnceBudget(store, cold, length, costs)
184
195
  reset()
185
196
  const view = new RepoViewStore(cold, { repo })
@@ -503,3 +514,39 @@ export function countHistoricalRows(costs: ReducedReadCosts, rows: unknown): num
503
514
  return repo === costs.history!.repo && seq <= costs.history!.through
504
515
  }).length
505
516
  }
517
+
518
+ /** Fresh remote processes must never turn catalog skew into history reads.
519
+ * Callers instrument backing storage (including private checkpoint reads). */
520
+ export async function catalogSkewReadBudget(opts: {
521
+ backing: BuildStore
522
+ fresh: () => BuildStore
523
+ repo: string
524
+ slug: string
525
+ reset: () => void
526
+ eventRows: () => number
527
+ }) {
528
+ const reads = [
529
+ [{ kind: 'repo', repo: opts.repo }, { reducer: 'dispatchUpgrade' }],
530
+ [{ kind: 'build', slug: opts.slug }, { reducer: 'buildReadFacts' }],
531
+ [
532
+ { kind: 'build', slug: opts.slug },
533
+ { reducer: 'phaseFailures', args: { phase: 'plan', round: 1 } },
534
+ ],
535
+ ] as const
536
+ const expected = []
537
+ for (const [scope, request] of reads)
538
+ expected.push(await opts.backing.getReducerValue(scope, request))
539
+ const batch = await opts.backing.getRepoBuildDigests(opts.repo)
540
+ opts.reset()
541
+ for (let i = 0; i < 3; i++) {
542
+ const client = opts.fresh()
543
+ for (const [index, [scope, request]] of reads.entries()) {
544
+ const { catalogIdentity: _, ...answer } = await client.getReducerValue(scope, request)
545
+ const { catalogIdentity: __, ...canonical } = expected[index]!
546
+ expect(answer).toEqual(canonical)
547
+ }
548
+ expect(await client.getRepoBuildDigests(opts.repo)).toEqual(batch)
549
+ await client.close()
550
+ }
551
+ expect(opts.eventRows()).toBe(0)
552
+ }