@defrex/autobuild 1.1.0 → 1.3.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 (157) hide show
  1. package/README.md +5 -13
  2. package/SPEC.md +249 -15
  3. package/bin/ab-dispatch-generation.ts +11 -2
  4. package/docs/accounts.md +130 -0
  5. package/docs/agent-runtimes.md +4 -4
  6. package/docs/answering-blocked-builds.md +4 -1
  7. package/docs/architecture.md +224 -12
  8. package/docs/build-store.md +3 -41
  9. package/docs/builds.md +2 -0
  10. package/docs/cli.md +14 -0
  11. package/docs/configuration-overview.md +117 -0
  12. package/docs/configuration.md +266 -141
  13. package/docs/dispatcher-hosting.md +18 -33
  14. package/docs/intake.md +2 -0
  15. package/docs/integration-tree.md +16 -5
  16. package/docs/merge-policy.md +1 -3
  17. package/docs/operating.md +1 -2
  18. package/docs/operator-api.md +144 -53
  19. package/docs/operator-surfaces.md +32 -20
  20. package/docs/overview.md +1 -1
  21. package/docs/plugin-authoring.md +27 -1
  22. package/docs/remote-store-protocol.md +259 -91
  23. package/docs/remote-ticket-protocol.md +29 -49
  24. package/docs/restacking.md +45 -0
  25. package/docs/seams.md +8 -8
  26. package/docs/setup.md +34 -129
  27. package/docs/spec-standard.md +4 -2
  28. package/docs/ticket-dependencies.md +8 -0
  29. package/docs/ticket-sources.md +18 -0
  30. package/docs/troubleshooting.md +7 -11
  31. package/docs/upgrading.md +1 -1
  32. package/docs/workspaces.md +4 -4
  33. package/package.json +14 -5
  34. package/packages/core/src/accounts/chatgpt-oauth.ts +216 -0
  35. package/packages/core/src/accounts/chatgpt-state.ts +41 -0
  36. package/packages/core/src/accounts/local-credentials.ts +194 -0
  37. package/packages/core/src/accounts/local-inference.ts +106 -0
  38. package/packages/core/src/accounts/local-owner.ts +123 -0
  39. package/packages/core/src/accounts/sensitive.ts +2 -0
  40. package/packages/core/src/cli/accounts.ts +147 -0
  41. package/packages/core/src/cli/binary.ts +3 -1
  42. package/packages/core/src/cli/connect.ts +3 -3
  43. package/packages/core/src/cli/dispatch-frontend.ts +1 -0
  44. package/packages/core/src/cli/dispatch-handoff.ts +125 -44
  45. package/packages/core/src/cli/dispatch-launch-contract.ts +187 -0
  46. package/packages/core/src/cli/dispatch-launcher.ts +54 -21
  47. package/packages/core/src/cli/dispatch-preflight.ts +6 -1
  48. package/packages/core/src/cli/dispatch-repository-feed.ts +107 -26
  49. package/packages/core/src/cli/dispatch.ts +135 -27
  50. package/packages/core/src/cli/dispatcher-liveness.ts +6 -1
  51. package/packages/core/src/cli/forge-clear.ts +30 -0
  52. package/packages/core/src/cli/help.ts +17 -0
  53. package/packages/core/src/cli/init-readiness-remote.ts +22 -1
  54. package/packages/core/src/cli/init-readiness-shared.ts +5 -1
  55. package/packages/core/src/cli/init-validation.ts +160 -18
  56. package/packages/core/src/cli/main.ts +72 -0
  57. package/packages/core/src/cli/publication-settlement.ts +4 -1
  58. package/packages/core/src/cli/secrets.ts +173 -0
  59. package/packages/core/src/cli/store-opening.ts +11 -1
  60. package/packages/core/src/cli/upgrade-agent.ts +9 -1
  61. package/packages/core/src/cli/watch.ts +12 -14
  62. package/packages/core/src/config/accounts.ts +101 -0
  63. package/packages/core/src/config/live.ts +14 -1
  64. package/packages/core/src/config/roles.ts +54 -3
  65. package/packages/core/src/config/schema.ts +60 -0
  66. package/packages/core/src/events/catalog.ts +1 -0
  67. package/packages/core/src/events/compatibility.ts +2 -1
  68. package/packages/core/src/events/forge-degradation-policy.ts +11 -0
  69. package/packages/core/src/events/payloads.ts +13 -0
  70. package/packages/core/src/events/policy.ts +9 -0
  71. package/packages/core/src/events/repository.ts +75 -2
  72. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +278 -0
  73. package/packages/core/src/kernel/change-presence.ts +74 -8
  74. package/packages/core/src/kernel/engine.ts +8 -0
  75. package/packages/core/src/kernel/generators/node-restack-log.ts +14 -0
  76. package/packages/core/src/kernel/node-polling.ts +40 -7
  77. package/packages/core/src/kernel/node-restack-demand.ts +74 -0
  78. package/packages/core/src/kernel/node-restack-state.ts +5 -1
  79. package/packages/core/src/kernel/node-restack-transaction.ts +33 -1
  80. package/packages/core/src/kernel/read-facts.ts +6 -0
  81. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  82. package/packages/core/src/kernel/reducer.ts +4 -1
  83. package/packages/core/src/kernel/ticket-preparation.ts +66 -0
  84. package/packages/core/src/operator/annotations.ts +6 -0
  85. package/packages/core/src/operator/control.ts +20 -0
  86. package/packages/core/src/operator/index.ts +4 -0
  87. package/packages/core/src/operator/protocol.ts +6 -0
  88. package/packages/core/src/operator/registry.ts +42 -1
  89. package/packages/core/src/operator/tickets.ts +25 -4
  90. package/packages/core/src/plugins/manifest.ts +2 -1
  91. package/packages/core/src/ports/runner/account-env.ts +139 -0
  92. package/packages/core/src/ports/runner/chatgpt-provider.ts +85 -0
  93. package/packages/core/src/ports/runner/claude.ts +70 -42
  94. package/packages/core/src/ports/runner/codex.ts +63 -31
  95. package/packages/core/src/ports/runner/one-shot.ts +2 -0
  96. package/packages/core/src/ports/runner/provider-error.ts +5 -0
  97. package/packages/core/src/ports/runner/routing.ts +35 -4
  98. package/packages/core/src/ports/tickets/contract.ts +58 -0
  99. package/packages/core/src/ports/tickets/tree.ts +1 -1
  100. package/packages/core/src/ports/types.ts +28 -7
  101. package/packages/core/src/ports/workspace/account-policy.ts +72 -0
  102. package/packages/core/src/ports/workspace/build-execution.ts +6 -1
  103. package/packages/core/src/ports/workspace/builtin-capabilities.ts +1 -0
  104. package/packages/core/src/ports/workspace/create.ts +2 -0
  105. package/packages/core/src/ports/workspace/git-worktree.ts +6 -1
  106. package/packages/core/src/ports/workspace/provider-capabilities.ts +1 -0
  107. package/packages/core/src/ports/workspace/vercel-sandbox.ts +125 -35
  108. package/packages/core/src/processes/build-runner.ts +32 -1
  109. package/packages/core/src/processes/dispatcher.ts +493 -121
  110. package/packages/core/src/processes/execution-no-progress.ts +1 -0
  111. package/packages/core/src/processes/execution-settlement.ts +21 -3
  112. package/packages/core/src/processes/harvest-runner.ts +68 -8
  113. package/packages/core/src/processes/harvest.ts +11 -16
  114. package/packages/core/src/processes/repo-view.ts +3 -0
  115. package/packages/core/src/project-secrets.ts +105 -0
  116. package/packages/core/src/secret-name.ts +41 -0
  117. package/packages/core/src/store/account-redaction.ts +156 -0
  118. package/packages/core/src/store/artifact-meta.ts +7 -0
  119. package/packages/core/src/store/contract.ts +60 -1
  120. package/packages/core/src/store/memory.ts +4 -0
  121. package/packages/core/src/store/reducer-value-shapes.json +7389 -6647
  122. package/packages/core/src/store/reducer-value-validation.ts +106 -6
  123. package/packages/core/src/store/remote/client.ts +85 -50
  124. package/packages/core/src/store/remote/compatibility.ts +57 -0
  125. package/packages/core/src/store/remote/index.ts +6 -0
  126. package/packages/core/src/store/remote/protocol.ts +8 -1
  127. package/packages/core/src/store/remote/released-reducer-values/1.2.0.json +8129 -0
  128. package/packages/core/src/store/remote/version.ts +4 -0
  129. package/packages/core/src/store/repo-state-events.ts +4 -2
  130. package/packages/core/src/store/snapshots.ts +16 -3
  131. package/packages/core/src/store/types.ts +2 -0
  132. package/packages/core/src/testing/dispatch-read-budget.ts +266 -5
  133. package/packages/core/src/testing/index.ts +2 -1
  134. package/packages/core/src/testing/reduced-read-budget.ts +560 -5
  135. package/skills/guide/SKILL.md +164 -37
  136. package/skills/guide/references/accounts.md +130 -0
  137. package/skills/guide/references/integration-tree.md +16 -5
  138. package/skills/guide/references/merge-policy.md +1 -3
  139. package/skills/guide/references/operator-api.md +144 -53
  140. package/skills/guide/references/plugin-authoring.md +27 -1
  141. package/skills/guide/references/remote-store-protocol.md +259 -91
  142. package/skills/guide/references/remote-ticket-protocol.md +29 -49
  143. package/skills/guide/references/restacking.md +45 -0
  144. package/skills/guide/references/setup.md +34 -129
  145. package/skills/guide/references/spec-standard.md +4 -2
  146. package/skills/guide/references/ticket-dependencies.md +8 -0
  147. package/skills/harvest/SKILL.md +3 -1
  148. package/skills/harvest-review/SKILL.md +3 -1
  149. package/skills/operate/SKILL.md +26 -11
  150. package/skills/reconcile/SKILL.md +6 -0
  151. package/skills/spec/SKILL.md +1 -1
  152. package/skills/tickets/SKILL.md +10 -5
  153. package/templates/hosted-service/package.json +2 -2
  154. package/docs/hosted-dispatcher-cutover-validation.md +0 -178
  155. package/docs/hosted-dispatcher.md +0 -278
  156. package/docs/hosted-service.md +0 -304
  157. package/docs/mcp.md +0 -150
@@ -0,0 +1,101 @@
1
+ import { z } from 'zod'
2
+ import { documentSchema, documentFields } from './reference-metadata'
3
+
4
+ const accountCredentialEnvSchema = z
5
+ .string()
6
+ .regex(/^[A-Za-z_][A-Za-z0-9_]*$/)
7
+ .refine(
8
+ (name) => !name.startsWith('AB_'),
9
+ 'Autobuild control variables cannot hold account credentials',
10
+ )
11
+ export const accountSchema = z.discriminatedUnion('kind', [
12
+ z.strictObject({
13
+ kind: z.literal('chatgpt-subscription'),
14
+ credentialEnv: accountCredentialEnvSchema,
15
+ }),
16
+ z.strictObject({
17
+ kind: z.literal('claude-subscription'),
18
+ credentialEnv: accountCredentialEnvSchema,
19
+ }),
20
+ z.strictObject({
21
+ kind: z.literal('kimi-code'),
22
+ credentialEnv: accountCredentialEnvSchema,
23
+ region: z.enum(['overseas', 'china']).default('overseas'),
24
+ }),
25
+ ])
26
+
27
+ documentSchema(accountSchema, { description: 'Named nonsecret billing account descriptor.' })
28
+ documentSchema(accountCredentialEnvSchema, {
29
+ constraints: 'Portable environment variable identifier; AB_ control variables are reserved.',
30
+ })
31
+ for (const branch of accountSchema.options)
32
+ documentFields(branch, {
33
+ kind: 'Claude subscription, Kimi Code membership, or ChatGPT subscription (Codex only).',
34
+ credentialEnv:
35
+ 'Host credential variable name; ChatGPT names a host-resolved access-token slot, never a credential value.',
36
+ ...(branch.shape.kind.value === 'kimi-code'
37
+ ? {
38
+ region:
39
+ 'Membership region: overseas (default) or china. Selects the base URL and exact egress host together.',
40
+ }
41
+ : {}),
42
+ })
43
+
44
+ /** Nonsecret billing descriptors. Credential values are resolved only at execution boundaries. */
45
+ export type Account =
46
+ | { kind: 'claude-subscription'; credentialEnv: string }
47
+ | { kind: 'chatgpt-subscription'; credentialEnv: string }
48
+ | { kind: 'kimi-code'; credentialEnv: string; region: 'overseas' | 'china' }
49
+ export type Accounts = Readonly<Record<string, Account>>
50
+ export const selectedAccountSchema = z.strictObject({
51
+ name: z.string().min(1),
52
+ descriptor: accountSchema,
53
+ })
54
+ export type SelectedAccount = z.infer<typeof selectedAccountSchema>
55
+
56
+ export function kimiEndpoint(region: 'overseas' | 'china'): { baseUrl: string; host: string } {
57
+ return region === 'china'
58
+ ? { baseUrl: 'https://api.kimi.com/coding/', host: 'api.kimi.com' }
59
+ : { baseUrl: 'https://api.kimi.ai/coding/', host: 'api.kimi.ai' }
60
+ }
61
+
62
+ export function selectAccount(
63
+ accounts: Accounts,
64
+ runtime: string | undefined,
65
+ name: string | undefined,
66
+ label: string,
67
+ ): SelectedAccount | undefined {
68
+ if (name === undefined && runtime === 'claude') {
69
+ const defaults = Object.entries(accounts).filter(
70
+ ([, account]) => account.kind === 'claude-subscription',
71
+ )
72
+ if (defaults.length > 1)
73
+ throw new Error(`${label}: ambiguous Claude subscription account; select account explicitly`)
74
+ name = defaults[0]?.[0]
75
+ }
76
+ if (name === undefined) return undefined
77
+ if (!Object.hasOwn(accounts, name))
78
+ throw new Error(`${label}: unknown account ${JSON.stringify(name)}`)
79
+ const requiredRuntime = accounts[name]!.kind === 'chatgpt-subscription' ? 'codex' : 'claude'
80
+ if (runtime !== requiredRuntime)
81
+ throw new Error(
82
+ `${label}: account ${JSON.stringify(name)} requires runtime "${requiredRuntime}"`,
83
+ )
84
+ return { name, descriptor: accounts[name]! }
85
+ }
86
+
87
+ export function accountRemedy(account: SelectedAccount): string {
88
+ return (
89
+ `account ${JSON.stringify(account.name)} (${account.descriptor.credentialEnv}): ` +
90
+ (account.descriptor.kind === 'chatgpt-subscription'
91
+ ? `sign in again with ab accounts login ${JSON.stringify(account.name)} (--local for the local dispatcher or --project for the connected project)`
92
+ : account.descriptor.kind === 'claude-subscription'
93
+ ? 'renew with claude setup-token and set the dispatcher credential variable'
94
+ : 'replace the Kimi Code membership key in the dispatcher credential variable')
95
+ )
96
+ }
97
+
98
+ /** Encodes arbitrary names injectively; never a credential. */
99
+ export function accountPlaceholder(name: string): string {
100
+ return `autobuild-account-${Buffer.from(name).toString('hex')}`
101
+ }
@@ -29,6 +29,7 @@ export const CONFIG_RELOAD_CLASSIFICATION = {
29
29
  verify: 'hot',
30
30
  finalize: 'hot',
31
31
  roles: 'hot',
32
+ accounts: 'hot',
32
33
  policy: 'hot',
33
34
  orchestrator: 'restart',
34
35
  tickets: {
@@ -184,7 +185,12 @@ export class LiveConfig {
184
185
  this.acceptedContent = startupContent
185
186
  this.snapshot = {
186
187
  config: startup,
187
- resolver: createRuntimeResolver(runtimes, startup.roles, startup.policy.sessionBudgetSeconds),
188
+ resolver: createRuntimeResolver(
189
+ runtimes,
190
+ startup.roles,
191
+ startup.policy.sessionBudgetSeconds,
192
+ startup.accounts,
193
+ ),
188
194
  revision: 0,
189
195
  }
190
196
  }
@@ -244,10 +250,17 @@ export class LiveConfig {
244
250
  const config = composeReloadedConfig(this.startup, candidate)
245
251
  let resolver: RuntimeResolver
246
252
  try {
253
+ for (const [name, account] of Object.entries(this.snapshot.config.accounts)) {
254
+ if (account.kind === 'chatgpt-subscription' && !same(account, config.accounts[name]))
255
+ throw new Error(
256
+ `ChatGPT account ${JSON.stringify(name)} cannot change while dispatch is active; stop dispatch before replacing its descriptor`,
257
+ )
258
+ }
247
259
  resolver = createRuntimeResolver(
248
260
  this.runtimes,
249
261
  config.roles,
250
262
  config.policy.sessionBudgetSeconds,
263
+ config.accounts,
251
264
  )
252
265
  } catch (error) {
253
266
  const message = error instanceof Error ? error.message : String(error)
@@ -1,3 +1,4 @@
1
+ import { selectAccount, type SelectedAccount } from './accounts'
1
2
  /**
2
3
  * Role-key consumability diagnostics (SPEC §9).
3
4
  *
@@ -79,6 +80,9 @@ export interface RoleKeyDiagnostics {
79
80
  type StepTable = { kind: 'check' } | { kind: 'agent'; skill: string }
80
81
 
81
82
  export interface RuntimeReferenceGroup {
83
+ /** Account-free routes, retained separately when accounts are declared. */
84
+ legacyAuthentication?: { models: string[]; usesRuntimeDefaultModel: boolean }
85
+ accountTargets?: Array<{ account: SelectedAccount; model?: string; references: string[] }>
82
86
  runtime: string
83
87
  /** Human-readable routes selecting this runtime, including alternates. */
84
88
  references: string[]
@@ -95,7 +99,7 @@ export interface RuntimeReferenceGroup {
95
99
  * bootstrap share one source of truth.
96
100
  */
97
101
  export function effectiveRuntimeReferences(
98
- config: Pick<Config, 'roles' | 'verify' | 'finalize'>,
102
+ config: Pick<Config, 'roles' | 'verify' | 'finalize'> & Partial<Pick<Config, 'accounts'>>,
99
103
  ): RuntimeReferenceGroup[] {
100
104
  const defaultSpec = config.roles.default ?? {}
101
105
  const routes: Array<{ role: string; aliases?: string[]; label: string }> = [
@@ -112,6 +116,14 @@ export function effectiveRuntimeReferences(
112
116
  })),
113
117
  ]
114
118
 
119
+ const legacyAuthentication = new Map<
120
+ string,
121
+ { models: Set<string>; usesRuntimeDefaultModel: boolean }
122
+ >()
123
+ const accountTargets = new Map<
124
+ string,
125
+ Array<{ account: SelectedAccount; model?: string; references: string[] }>
126
+ >()
115
127
  const grouped = new Map<
116
128
  string,
117
129
  { references: Set<string>; models: Set<string>; usesRuntimeDefaultModel: boolean }
@@ -123,8 +135,28 @@ export function effectiveRuntimeReferences(
123
135
  }
124
136
  return defaultSpec
125
137
  }
126
- const add = (runtime: string | undefined, model: string | undefined, reference: string) => {
138
+ const add = (
139
+ runtime: string | undefined,
140
+ model: string | undefined,
141
+ reference: string,
142
+ accountName?: string,
143
+ ) => {
144
+ const account = selectAccount(config.accounts ?? {}, runtime, accountName, reference)
145
+ if (account && runtime) {
146
+ const targets = accountTargets.get(runtime) ?? []
147
+ targets.push({ account, ...(model === undefined ? {} : { model }), references: [reference] })
148
+ accountTargets.set(runtime, targets)
149
+ }
127
150
  if (runtime === undefined || runtime.trim() === '') return
151
+ if (!account) {
152
+ const legacy = legacyAuthentication.get(runtime) ?? {
153
+ models: new Set<string>(),
154
+ usesRuntimeDefaultModel: false,
155
+ }
156
+ if (model === undefined) legacy.usesRuntimeDefaultModel = true
157
+ else legacy.models.add(model)
158
+ legacyAuthentication.set(runtime, legacy)
159
+ }
128
160
  const group = grouped.get(runtime) ?? {
129
161
  references: new Set(),
130
162
  models: new Set(),
@@ -140,21 +172,40 @@ export function effectiveRuntimeReferences(
140
172
  const spec = declaredSpec(route.role, route.aliases)
141
173
  const runtime = spec.runtime ?? defaultSpec.runtime
142
174
  const model = spec.model ?? defaultSpec.model
143
- add(runtime, model, `${route.label} primary`)
175
+ add(runtime, model, `${route.label} primary`, spec.account ?? defaultSpec.account)
144
176
  const alternates = spec.alternates ?? defaultSpec.alternates ?? []
145
177
  alternates.forEach((alternate, index) => {
146
178
  add(
147
179
  alternate.runtime ?? runtime,
148
180
  alternate.model ?? model,
149
181
  `${route.label} alternate[${index}]`,
182
+ alternate.account ?? spec.account ?? defaultSpec.account,
150
183
  )
151
184
  })
152
185
  }
153
186
 
187
+ // Unused accounts still require their actual runtime for readiness.
188
+ for (const [name, descriptor] of Object.entries(config.accounts ?? {}))
189
+ add(
190
+ descriptor.kind === 'chatgpt-subscription' ? 'codex' : 'claude',
191
+ descriptor.kind === 'kimi-code' ? 'kimi-for-coding' : undefined,
192
+ `account ${displayName(name)} readiness`,
193
+ name,
194
+ )
195
+
154
196
  return [...grouped.entries()]
155
197
  .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
156
198
  .map(([runtime, group]) => ({
157
199
  runtime,
200
+ ...(Object.keys(config.accounts ?? {}).length && legacyAuthentication.has(runtime)
201
+ ? {
202
+ legacyAuthentication: {
203
+ models: [...legacyAuthentication.get(runtime)!.models].sort(),
204
+ usesRuntimeDefaultModel: legacyAuthentication.get(runtime)!.usesRuntimeDefaultModel,
205
+ },
206
+ }
207
+ : {}),
208
+ ...(accountTargets.has(runtime) ? { accountTargets: accountTargets.get(runtime)! } : {}),
158
209
  references: [...group.references].sort(),
159
210
  models: [...group.models].sort(),
160
211
  usesRuntimeDefaultModel: group.usesRuntimeDefaultModel,
@@ -1,3 +1,4 @@
1
+ import { accountSchema, selectAccount } from './accounts'
1
2
  import { isSafeStepName } from '../context-directory'
2
3
  /**
3
4
  * autobuild.toml schema (SPEC §16.1, D9): the one declarative per-repo config
@@ -645,6 +646,7 @@ export const finalizeSectionSchema = stepSection(
645
646
  const roleArgsSchema = z.array(z.string().min(1))
646
647
 
647
648
  const runtimeAxesSchema = z.strictObject({
649
+ account: z.string().min(1).regex(/\S/).optional(),
648
650
  runtime: z.string().min(1).optional(),
649
651
  model: z.string().min(1).optional(),
650
652
  args: roleArgsSchema.optional(),
@@ -653,6 +655,8 @@ const runtimeAxesSchema = z.strictObject({
653
655
  })
654
656
 
655
657
  documentFields(runtimeAxesSchema, {
658
+ account:
659
+ 'Named billing account; inherits independently. Claude selects the sole subscription account when omitted.',
656
660
  runtime: 'Select an agent adapter.',
657
661
  model: 'Select the exact model. Codex uses unqualified `gpt-*`; Pi ids are provider-qualified.',
658
662
  args: 'Ordered extra CLI argv tokens applied to every phase and tool-free one-shot invocation. A supplied list replaces, rather than unions with, the inherited list.',
@@ -679,6 +683,8 @@ export const roleSchema = runtimeAxesSchema.extend({
679
683
  })
680
684
 
681
685
  documentFields(roleSchema, {
686
+ account:
687
+ 'Named billing account; inherits independently. Claude selects the sole subscription account when omitted.',
682
688
  runtime: 'Select an agent adapter.',
683
689
  model: 'Select the exact model. Codex uses unqualified `gpt-*`; Pi ids are provider-qualified.',
684
690
  args: 'Ordered extra CLI argv tokens applied to every phase and tool-free one-shot invocation. A supplied list replaces, rather than unions with, the inherited list.',
@@ -1069,6 +1075,7 @@ export const configRootSchema = z.strictObject({
1069
1075
  // disappear ahead of both eager resolution and the unconsumed-key warning;
1070
1076
  // the registry-aware eager resolver requires default.runtime and can
1071
1077
  // therefore include the complete materialized runtime list in its diagnostic.
1078
+ accounts: openMap('[accounts]', accountSchema).default({}),
1072
1079
  roles: openMap('[roles]', roleSchema),
1073
1080
  policy: policySchema.prefault({}),
1074
1081
  orchestrator: orchestratorSchema.prefault({}),
@@ -1103,6 +1110,8 @@ documentFields(configRootSchema, {
1103
1110
  'Ordered verification steps and applicability rules. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1104
1111
  finalize:
1105
1112
  'Ordered post-PR steps. Failures are recorded without blocking the PR. Step names use ASCII letters, digits, ., _ and -; exactly . and .. are forbidden.',
1113
+ accounts:
1114
+ 'Named Claude subscription, Kimi Code, or ChatGPT subscription billing accounts. Descriptors contain credential variable names only.',
1106
1115
  roles: 'Named agent roles. The reserved default role provides inherited runtime axes.',
1107
1116
  policy: 'Lifecycle budgets, retries, convergence and harvest limits.',
1108
1117
  orchestrator:
@@ -1149,6 +1158,57 @@ const normalizedConfigSchema = configRootSchema.transform((input, ctx) => {
1149
1158
  })
1150
1159
 
1151
1160
  export const configSchema = normalizedConfigSchema.superRefine((config, ctx) => {
1161
+ for (const [name, account] of Object.entries(config.accounts)) {
1162
+ if (account.kind !== 'chatgpt-subscription') continue
1163
+ if (
1164
+ Object.entries(config.accounts).some(
1165
+ ([other, a]) => other !== name && a.credentialEnv === account.credentialEnv,
1166
+ )
1167
+ )
1168
+ ctx.addIssue({
1169
+ code: 'custom',
1170
+ path: ['accounts', name],
1171
+ message: 'ChatGPT accounts require distinct credentialEnv slots',
1172
+ })
1173
+ }
1174
+
1175
+ const accountVariables = new Set(
1176
+ Object.values(config.accounts).map((account) => account.credentialEnv),
1177
+ )
1178
+ for (const name of config.orchestrator.sandbox.environmentVariables)
1179
+ if (accountVariables.has(name))
1180
+ ctx.addIssue({
1181
+ code: 'custom',
1182
+ path: ['orchestrator', 'sandbox', 'environmentVariables'],
1183
+ message: `Account credential variable ${JSON.stringify(name)} cannot enter an operator sandbox`,
1184
+ })
1185
+ const defaults = config.roles.default ?? {}
1186
+ for (const [role, spec] of Object.entries(config.roles)) {
1187
+ const primary = {
1188
+ runtime: spec.runtime ?? defaults.runtime,
1189
+ account: spec.account ?? defaults.account,
1190
+ }
1191
+ const targets = [
1192
+ primary,
1193
+ ...(spec.alternates ?? defaults.alternates ?? []).map((alt) => ({
1194
+ runtime: alt.runtime ?? primary.runtime,
1195
+ account: alt.account ?? primary.account,
1196
+ })),
1197
+ ]
1198
+ targets.forEach((target, index) => {
1199
+ try {
1200
+ selectAccount(
1201
+ config.accounts,
1202
+ target.runtime,
1203
+ target.account,
1204
+ `role ${JSON.stringify(role)}${index ? ` alternate[${index - 1}]` : ''}`,
1205
+ )
1206
+ } catch (error) {
1207
+ ctx.addIssue({ code: 'custom', path: ['roles', role], message: (error as Error).message })
1208
+ }
1209
+ })
1210
+ }
1211
+
1152
1212
  for (const kind of ['verify', 'finalize'] as const) {
1153
1213
  const section = config[kind]
1154
1214
  if (!section) continue
@@ -72,6 +72,7 @@ export const allowedActorKinds: Record<EventType, readonly ActorKind[]> = {
72
72
  'integration.audited': ['kernel', 'dispatcher'],
73
73
  'node.restack-requested': ['dispatcher', 'human'],
74
74
  'node.restack-satisfied': ['kernel', 'dispatcher'],
75
+ 'node.restack-availability-observed': ['kernel', 'dispatcher'],
75
76
  'node.parent-distance': ['kernel', 'dispatcher'],
76
77
  'node.parent-requested': ['dispatcher', 'human'],
77
78
  'node.parent-accepted': ['dispatcher', 'human'],
@@ -23,7 +23,8 @@ export interface StoredEvent {
23
23
  }
24
24
 
25
25
  /** Change this revision whenever projection semantics change without new types. */
26
- export const READ_DECODER_REVISION = 2
26
+ // Revision 3 retains optional billing-account descriptors in session/attempt projections.
27
+ export const READ_DECODER_REVISION = 3
27
28
  export function catalogIdentity(
28
29
  build: Record<string, string> = buildEventPolicy,
29
30
  repository: Record<string, string> = repositoryEventPolicy,
@@ -0,0 +1,11 @@
1
+ import { forgeHealthEventPayloadSchemas } from './repository'
2
+
3
+ /** Hosted admission horizon; never applied to historical event decoding. */
4
+ export const MAX_FORGE_DEGRADATION_MS = 24 * 60 * 60 * 1000
5
+
6
+ export function validateForgeDegradation(payload: unknown, now: Date): void {
7
+ const parsed = forgeHealthEventPayloadSchemas['dispatcher.forge-degraded'].parse(payload)
8
+ const deadline = Date.parse(parsed.resetAt)
9
+ if (!Number.isFinite(deadline) || deadline > now.getTime() + MAX_FORGE_DEGRADATION_MS)
10
+ throw new Error('forge resetAt must be a finite ISO deadline within 24 hours of server time')
11
+ }
@@ -1,3 +1,4 @@
1
+ import { selectedAccountSchema } from '../config/accounts'
1
2
  import { runtimeIdentitySchema } from './runtime'
2
3
  import { viaSchema } from './envelope'
3
4
  import { nativeSessionHandleSchema } from './native-session'
@@ -141,6 +142,7 @@ export const agentFailureCauseSchema = z.enum([
141
142
 
142
143
  /** One configured execution target that failed within a single phase attempt. */
143
144
  export const providerAttemptSchema = z.strictObject({
145
+ account: selectedAccountSchema.optional(),
144
146
  index: z.number().int().nonnegative(),
145
147
  session: z.string().min(1),
146
148
  runner: z.string().min(1),
@@ -345,6 +347,16 @@ export const eventPayloadSchemas = {
345
347
  parent: z.string().min(1),
346
348
  outcome: z.enum(['covered', 'destination-changed']),
347
349
  }),
350
+ 'node.restack-availability-observed': z.strictObject({
351
+ version: z.literal(1),
352
+ fingerprint: z.string().min(1),
353
+ branch: z.string().min(1),
354
+ parentBranch: z.string().min(1),
355
+ head: z.string().min(1),
356
+ parent: z.string().min(1),
357
+ base: z.string().min(1),
358
+ available: z.array(z.string()),
359
+ }),
348
360
  'node.parent-distance': z.strictObject({
349
361
  base: z.string().min(1),
350
362
  parent: z.string().min(1),
@@ -846,6 +858,7 @@ export const eventPayloadSchemas = {
846
858
  model: z.string().optional(),
847
859
  /** Optional only so historical events replay without migration. */
848
860
  args: z.array(z.string()).optional(),
861
+ account: selectedAccountSchema.optional(),
849
862
  phase: phaseSchema,
850
863
  round: round.optional(),
851
864
  /** Stream id this session's live view writes to (SPEC §9, session
@@ -40,6 +40,7 @@ export const buildEventPolicy = {
40
40
  'node.restack-requested': 'decisive',
41
41
  'node.restack-satisfied': 'decisive',
42
42
  'node.poll-checked': 'advisory',
43
+ 'node.restack-availability-observed': 'advisory',
43
44
  'node.parent-distance': 'advisory',
44
45
  'node.parent-requested': 'decisive',
45
46
  'node.parent-accepted': 'decisive',
@@ -153,6 +154,14 @@ export const buildEventPolicy = {
153
154
  'phase.deferral-escalated': 'decisive',
154
155
  } satisfies Record<EventType, FactClassification>
155
156
  export const repositoryEventPolicy = {
157
+ 'ticket-preparation.intended': 'decisive',
158
+ 'ticket-preparation.claimed': 'decisive',
159
+ 'ticket-preparation.creation-selected': 'decisive',
160
+ 'ticket-preparation.failed': 'decisive',
161
+ 'ticket-preparation.recovery-failed': 'decisive',
162
+ 'ticket-preparation.handback-selected': 'decisive',
163
+ 'ticket-preparation.resolved': 'decisive',
164
+
156
165
  'tickets.migration-recorded': 'decisive',
157
166
  'change-presence.observed': 'decisive',
158
167
  'harvest.pause-requested': 'decisive',
@@ -1,3 +1,4 @@
1
+ import { selectedAccountSchema } from '../config/accounts'
1
2
  import { nativeSessionHandleSchema } from './native-session'
2
3
  import { runtimeIdentitySchema } from './runtime'
3
4
  import { stampCompatibility, type CompatibilityMetadata, repositoryEventPolicy } from './policy'
@@ -278,6 +279,7 @@ export const harvestEventPayloadSchemas = {
278
279
  model: z.string().optional(),
279
280
  /** Optional only so historical repository journals replay without migration. */
280
281
  args: z.array(z.string()).optional(),
282
+ account: selectedAccountSchema.optional(),
281
283
  step: z.enum(['synthesize', 'review']),
282
284
  round,
283
285
  /** Stream id this session's live view writes to (SPEC §9, session
@@ -677,9 +679,26 @@ export const ticketSourceHealthEventPayloadSchemas = {
677
679
  }),
678
680
  } as const
679
681
 
682
+ const presenceWitnessSchema = z.strictObject({
683
+ version: z.literal(1),
684
+ commits: z
685
+ .array(z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/))
686
+ .refine(
687
+ (ids) => ids.every((id, index) => index === 0 || ids[index - 1]! < id),
688
+ 'commits must be sorted and unique',
689
+ ),
690
+ identities: z
691
+ .array(z.templateLiteral(['build:', z.string().regex(/^[a-z0-9][a-z0-9-]*$/)]))
692
+ .refine(
693
+ (ids) => ids.every((id, index) => index === 0 || ids[index - 1]! < id),
694
+ 'identities must be sorted and unique',
695
+ ),
696
+ })
697
+
680
698
  /** Head-bound admission evidence. Historical observations remain append-only. */
681
699
  export const changePresenceEventPayloadSchemas = {
682
700
  'change-presence.observed': z.strictObject({
701
+ witness: presenceWitnessSchema.optional(),
683
702
  branch: z.string().min(1),
684
703
  destination: z.string().min(1),
685
704
  head: z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/),
@@ -702,7 +721,10 @@ export const forgeHealthEventPayloadSchemas = {
702
721
  resetAt: z.iso.datetime(),
703
722
  firstFailureAt: z.iso.datetime(),
704
723
  }),
705
- 'dispatcher.forge-recovered': z.strictObject({ forge: z.string().min(1) }),
724
+ 'dispatcher.forge-recovered': z.strictObject({
725
+ forge: z.string().min(1),
726
+ reason: z.string().trim().min(1).optional(),
727
+ }),
706
728
  } as const
707
729
 
708
730
  export const ticketMigrationEventPayloadSchemas = {
@@ -724,7 +746,50 @@ export const ticketMigrationEventPayloadSchemas = {
724
746
  }),
725
747
  } as const
726
748
 
749
+ /** Durable claim-to-build preparation boundaries, independent of build streams. */
750
+ const preparationIdentity = {
751
+ attempt: z.string().min(1),
752
+ ticket: ticketRefSchema,
753
+ }
754
+ export const ticketPreparationEventPayloadSchemas = {
755
+ 'ticket-preparation.intended': z.strictObject({
756
+ ...preparationIdentity,
757
+ readyState: z.string().min(1),
758
+ claimedState: z.string().min(1),
759
+ }),
760
+ 'ticket-preparation.claimed': z.strictObject(preparationIdentity),
761
+ 'ticket-preparation.creation-selected': z.strictObject({
762
+ ...preparationIdentity,
763
+ slug: z.string().min(1),
764
+ }),
765
+ 'ticket-preparation.failed': z.strictObject({
766
+ ...preparationIdentity,
767
+ stage: z.string().min(1),
768
+ claimed: z.boolean(),
769
+ handback: z.string().min(1),
770
+ error: z.string().min(1).max(4000),
771
+ }),
772
+ 'ticket-preparation.recovery-failed': z.strictObject({
773
+ ...preparationIdentity,
774
+ claimed: z.boolean().optional(),
775
+ preparationError: z.string().min(1).max(4000).optional(),
776
+ handback: z.string().min(1).optional(),
777
+ error: z.string().min(1).max(4000),
778
+ retryAt: z.string().datetime(),
779
+ }),
780
+ 'ticket-preparation.handback-selected': z.strictObject({
781
+ ...preparationIdentity,
782
+ state: z.string().min(1),
783
+ }),
784
+ 'ticket-preparation.resolved': z.strictObject({
785
+ ...preparationIdentity,
786
+ outcome: z.enum(['lost-claim', 'handed-back', 'bounced', 'owned', 'abandoned']),
787
+ reason: z.string().min(1).max(4000).optional(),
788
+ }),
789
+ }
790
+
727
791
  export const repositoryEventPayloadSchemas = {
792
+ ...ticketPreparationEventPayloadSchemas,
728
793
  ...ticketMigrationEventPayloadSchemas,
729
794
  ...forgeHealthEventPayloadSchemas,
730
795
  ...changePresenceEventPayloadSchemas,
@@ -792,6 +857,14 @@ export type HarvestEventWrite<T extends HarvestEventType = HarvestEventType> =
792
857
  export const HARVEST_EVENT_TYPES = Object.keys(harvestEventPayloadSchemas) as HarvestEventType[]
793
858
 
794
859
  const allowedActorKinds: Record<RepositoryEventType, readonly ActorKind[]> = {
860
+ 'ticket-preparation.intended': ['dispatcher'],
861
+ 'ticket-preparation.claimed': ['dispatcher'],
862
+ 'ticket-preparation.creation-selected': ['dispatcher'],
863
+ 'ticket-preparation.failed': ['dispatcher'],
864
+ 'ticket-preparation.recovery-failed': ['dispatcher'],
865
+ 'ticket-preparation.handback-selected': ['dispatcher'],
866
+ 'ticket-preparation.resolved': ['dispatcher'],
867
+
795
868
  'tickets.migration-recorded': ['human'],
796
869
  'change-presence.observed': ['dispatcher', 'kernel'],
797
870
  'harvest.pause-requested': ['human'],
@@ -859,7 +932,7 @@ const allowedActorKinds: Record<RepositoryEventType, readonly ActorKind[]> = {
859
932
  'dispatcher.ticket-scan-completed': ['dispatcher'],
860
933
  'dispatcher.ticket-source-dependency-limited': ['dispatcher'],
861
934
  'dispatcher.forge-degraded': ['dispatcher', 'kernel'],
862
- 'dispatcher.forge-recovered': ['dispatcher', 'kernel'],
935
+ 'dispatcher.forge-recovered': ['dispatcher', 'kernel', 'human'],
863
936
  'dispatcher.ticket-source-degraded': ['dispatcher'],
864
937
  'dispatcher.ticket-source-recovered': ['dispatcher'],
865
938
  'dispatcher.tick-failed': ['dispatcher'],