@defrex/autobuild 1.6.0 → 1.7.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 (97) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +107 -10
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/architecture.md +62 -22
  5. package/docs/configuration-overview.md +10 -0
  6. package/docs/configuration.md +285 -5
  7. package/docs/forges.md +1 -0
  8. package/docs/operator-api.md +19 -8
  9. package/docs/operator-surfaces.md +6 -3
  10. package/docs/plugin-authoring.md +44 -6
  11. package/docs/remote-store-protocol.md +19 -6
  12. package/docs/restacking.md +12 -7
  13. package/docs/ticket-sources.md +34 -6
  14. package/docs/tickets.md +6 -0
  15. package/docs/workspaces.md +1 -1
  16. package/package.json +3 -3
  17. package/packages/core/src/cli/attention.ts +1 -0
  18. package/packages/core/src/cli/binary-direct.ts +1 -0
  19. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  20. package/packages/core/src/cli/dispatch-preflight.ts +1 -0
  21. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  22. package/packages/core/src/cli/dispatch.ts +9 -3
  23. package/packages/core/src/cli/help.ts +11 -4
  24. package/packages/core/src/cli/init-validation.ts +14 -1
  25. package/packages/core/src/cli/repository-status.ts +37 -2
  26. package/packages/core/src/cli/status.ts +8 -0
  27. package/packages/core/src/cli/ticket.ts +22 -4
  28. package/packages/core/src/cli/watch.ts +2 -0
  29. package/packages/core/src/config/live.ts +4 -0
  30. package/packages/core/src/config/profiles.ts +96 -0
  31. package/packages/core/src/config/ready-assignee.ts +43 -11
  32. package/packages/core/src/config/roles.ts +33 -10
  33. package/packages/core/src/config/schema.ts +166 -24
  34. package/packages/core/src/events/compatibility.ts +3 -1
  35. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  36. package/packages/core/src/events/payloads.ts +8 -0
  37. package/packages/core/src/events/policy.ts +1 -0
  38. package/packages/core/src/events/repository.ts +17 -0
  39. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +73 -124
  40. package/packages/core/src/kernel/build-creation.ts +29 -0
  41. package/packages/core/src/kernel/forge-health.ts +47 -0
  42. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  43. package/packages/core/src/kernel/node-parent.ts +2 -0
  44. package/packages/core/src/kernel/read-facts.ts +9 -1
  45. package/packages/core/src/kernel/reducer.ts +18 -1
  46. package/packages/core/src/kernel/ticket-preparation.ts +4 -1
  47. package/packages/core/src/operator/protocol.ts +10 -0
  48. package/packages/core/src/operator/query.ts +1 -1
  49. package/packages/core/src/operator/registry.ts +25 -5
  50. package/packages/core/src/operator/sandbox-host.ts +3 -0
  51. package/packages/core/src/operator/tickets.ts +15 -3
  52. package/packages/core/src/plugin-sdk/index.ts +4 -0
  53. package/packages/core/src/ports/forge/create.ts +6 -0
  54. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  55. package/packages/core/src/ports/forge/github.ts +12 -1
  56. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  57. package/packages/core/src/ports/forge-failure.ts +31 -2
  58. package/packages/core/src/ports/runner/routing.ts +66 -5
  59. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  60. package/packages/core/src/ports/tickets/contract.ts +164 -4
  61. package/packages/core/src/ports/tickets/create.ts +17 -3
  62. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  63. package/packages/core/src/ports/tickets/github.ts +247 -29
  64. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  65. package/packages/core/src/ports/tickets/operations.ts +6 -1
  66. package/packages/core/src/ports/tickets/tree.ts +12 -2
  67. package/packages/core/src/ports/tickets/update.ts +6 -2
  68. package/packages/core/src/ports/types.ts +33 -3
  69. package/packages/core/src/ports/workspace/vercel-sandbox.ts +9 -0
  70. package/packages/core/src/processes/build-child.ts +28 -7
  71. package/packages/core/src/processes/build-execution-state.ts +4 -1
  72. package/packages/core/src/processes/build-runner.ts +15 -1
  73. package/packages/core/src/processes/dispatcher.ts +98 -18
  74. package/packages/core/src/processes/harvest-child.ts +4 -0
  75. package/packages/core/src/processes/harvest-runner.ts +5 -0
  76. package/packages/core/src/processes/repo-view.ts +2 -0
  77. package/packages/core/src/scenarios/harness.ts +15 -1
  78. package/packages/core/src/store/reducer-value-shapes.json +3119 -2926
  79. package/packages/core/src/store/remote/client.ts +21 -8
  80. package/packages/core/src/store/remote/index.ts +4 -0
  81. package/packages/core/src/store/remote/protocol.ts +7 -0
  82. package/packages/core/src/store/remote/released-clients.json +11 -0
  83. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  84. package/packages/core/src/store/remote/released-reducer-values/index.ts +2 -0
  85. package/packages/core/src/store/repo-state-events.ts +1 -0
  86. package/packages/core/src/store/types.ts +11 -0
  87. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  88. package/packages/core/src/testing/index.ts +2 -0
  89. package/packages/core/src/testing/reduced-read-budget.ts +72 -9
  90. package/skills/guide/SKILL.md +116 -21
  91. package/skills/guide/references/operator-api.md +19 -8
  92. package/skills/guide/references/plugin-authoring.md +44 -6
  93. package/skills/guide/references/remote-store-protocol.md +19 -6
  94. package/skills/guide/references/restacking.md +12 -7
  95. package/skills/operate/SKILL.md +29 -3
  96. package/skills/tickets/SKILL.md +18 -2
  97. package/templates/hosted-service/package.json +2 -2
@@ -65,6 +65,12 @@ export interface NodeIssueLinksState {
65
65
  published?: { pr: number; issueLinks: IssueLink[]; seq: number }
66
66
  }
67
67
 
68
+ /** A build's frozen role profile (SPEC §9). */
69
+ export interface BuildProfile {
70
+ name: string
71
+ configured: boolean
72
+ }
73
+
68
74
  export interface OpenEscalation {
69
75
  id: string
70
76
  phase: EscalationTarget
@@ -331,6 +337,11 @@ export interface BuildState {
331
337
  /** seq of the fact that closed the downgrade window: `issue-links.sealed`,
332
338
  * `publication.requested {operation: 'finalize'}` or `finalize.completed`. */
333
339
  issueLinksSealedSeq?: number
340
+ /** The role profile `build.created` froze at claim. `configured` is the
341
+ * latest `session.started` observation of whether the session's config
342
+ * still defined it; true until a session says otherwise. Absent for builds
343
+ * without a profile and historical logs. */
344
+ profile?: BuildProfile
334
345
  /** Latest spec artifact rev — `spec.imported`/`spec.authored` set it,
335
346
  * `spec.revised` bumps it (§6.3: rev N+1 restarts leaves from plan and nodes from collection). */
336
347
  specRev?: number
@@ -496,6 +507,7 @@ export interface BuildAcc {
496
507
  pinnedAssets: PinnedAsset[]
497
508
  issueLinks: BuildIssueLink[]
498
509
  issueLinksSealedSeq?: number
510
+ profile?: BuildProfile
499
511
  finalizeCompletedSeq: number
500
512
  pipelineSettled?: number
501
513
  finalizeSteps: BuildState['finalizeSteps']
@@ -527,7 +539,7 @@ export interface BuildAcc {
527
539
  }
528
540
 
529
541
  /** Bump when `BuildAcc`'s shape or the fold's semantics change. */
530
- export const BUILD_REDUCER_VERSION = 32
542
+ export const BUILD_REDUCER_VERSION = 33
531
543
 
532
544
  function initialBuildAcc(): BuildAcc {
533
545
  return {
@@ -802,6 +814,8 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
802
814
  acc.baseBranch = event.payload.baseBranch
803
815
  pinnedAssets = event.payload.assets ?? []
804
816
  acc.issueLinks = (event.payload.issueLinks ?? []).map((link) => ({ ...link }))
817
+ if (event.payload.profile !== undefined)
818
+ acc.profile = { name: event.payload.profile, configured: true }
805
819
  break
806
820
  case 'issue-link.downgraded': {
807
821
  // One-way and only before the seal: a later, a repeated or an
@@ -980,6 +994,8 @@ function foldBuild(acc: BuildAcc, events: readonly AbEvent[]): void {
980
994
  break
981
995
 
982
996
  case 'session.started': {
997
+ if (event.payload.profile !== undefined && event.payload.profile.name === acc.profile?.name)
998
+ acc.profile = { ...acc.profile, configured: event.payload.profile.configured }
983
999
  const root = event.payload.continuation?.root ?? event.payload.session
984
1000
  acc.sessionTotals[root] ??= { activeMs: 0, transcripts: [] }
985
1001
  const totals = acc.sessionTotals[root]
@@ -1491,6 +1507,7 @@ function finishBuild(acc: BuildAcc): BuildState {
1491
1507
  ...(acc.issueLinksSealedSeq !== undefined
1492
1508
  ? { issueLinksSealedSeq: acc.issueLinksSealedSeq }
1493
1509
  : {}),
1510
+ ...(acc.profile !== undefined ? { profile: { ...acc.profile } } : {}),
1494
1511
  specRev: acc.specRev,
1495
1512
  restartSince: acc.restartSince,
1496
1513
  plan: acc.plan,
@@ -9,6 +9,8 @@ export interface TicketPreparation {
9
9
  claimedState: string
10
10
  claimed: boolean
11
11
  slug?: string
12
+ /** Present when the store attested keyed creation for this attempt. */
13
+ creationKey?: string
12
14
  handback?: string
13
15
  stage?: string
14
16
  error?: string
@@ -21,7 +23,7 @@ export const ticketPreparationReducer = defineReducer<
21
23
  RepositoryEvent,
22
24
  Record<string, TicketPreparation>
23
25
  >({
24
- version: 1,
26
+ version: 2,
25
27
  initial: () => ({}),
26
28
  fold(acc, events) {
27
29
  for (const event of events) {
@@ -39,6 +41,7 @@ export const ticketPreparationReducer = defineReducer<
39
41
  break
40
42
  case 'ticket-preparation.creation-selected':
41
43
  held.slug = event.payload.slug
44
+ if (event.payload.creationKey) held.creationKey = event.payload.creationKey
42
45
  break
43
46
  case 'ticket-preparation.handback-selected':
44
47
  held.handback = event.payload.state
@@ -2,6 +2,7 @@ import { z } from 'zod'
2
2
  import { issueLinksInputSchema } from '../ports/tickets/issue-links'
3
3
  import { TICKET_MOVE_ROLES } from '../ports/tickets/lifecycle'
4
4
  import { ticketPrioritySchema } from '../ports/tickets/priority'
5
+ import { ticketAssigneesSchema } from '../ports/tickets/assignees'
5
6
 
6
7
  const issueLinksField = issueLinksInputSchema
7
8
  .optional()
@@ -15,6 +16,12 @@ const priorityField = ticketPrioritySchema
15
16
  'Dispatch class: "urgent" is claimed before normal ready work (never preempting a running build); "normal" (the default) removes urgency. Sources that cannot store priority refuse urgent.',
16
17
  )
17
18
 
19
+ const assigneesField = ticketAssigneesSchema
20
+ .optional()
21
+ .describe(
22
+ 'Usernames to assign, or "me" for the owner of the ticket-source credential. On create, replaces the [tickets].createAssignee default ([] creates an unassigned ticket); on update, a complete replacement ([] clears). Sources that cannot store assignees refuse it.',
23
+ )
24
+
18
25
  export const buildListScopeSchema = z.enum(['active', 'queued', 'all'])
19
26
 
20
27
  export const buildControlRequestSchema = z.discriminatedUnion('action', [
@@ -73,6 +80,7 @@ export const ticketCreateRequestSchema = z.strictObject({
73
80
  blockedBy: z.array(z.string().min(1)).optional(),
74
81
  issueLinks: issueLinksField,
75
82
  priority: priorityField,
83
+ assignees: assigneesField,
76
84
  })
77
85
  const expectedRevisionSchema = z
78
86
  .string()
@@ -88,6 +96,7 @@ export const ticketUpdateRequestSchema = z
88
96
  labels: z.array(z.string()).optional(),
89
97
  issueLinks: issueLinksField,
90
98
  priority: priorityField,
99
+ assignees: assigneesField,
91
100
  })
92
101
  .refine(
93
102
  (value) =>
@@ -96,6 +105,7 @@ export const ticketUpdateRequestSchema = z
96
105
  value.labels !== undefined ||
97
106
  value.issueLinks !== undefined ||
98
107
  value.priority !== undefined ||
108
+ value.assignees !== undefined ||
99
109
  value.kind !== undefined ||
100
110
  value.target !== undefined,
101
111
  'update must name at least one field',
@@ -358,7 +358,7 @@ export async function getRepositoryStatus(
358
358
  return withOperatorView(store, repo, 'journal', async (view) => {
359
359
  const { dispatcher } = await readDispatcherLiveness(store, repo, now)
360
360
  const facts = (await readRepositoryFacts(view, repo)).value
361
- const status = repositoryStatusFromFacts(repo, facts, dispatcher)
361
+ const status = repositoryStatusFromFacts(repo, facts, dispatcher, now)
362
362
  const capacity = await readRepositoryCapacity(store, repo, facts, dispatcher, now)
363
363
  return { ...status, ...(capacity ? { capacity } : {}) }
364
364
  })
@@ -6,6 +6,7 @@ import { openOperatorTickets, operatorControlTickets } from './tickets'
6
6
  import { TicketRevisionConflict, TicketRevisionUnsupported } from '../ports/tickets/revision'
7
7
  import { TicketIssueLinksUnsupported } from '../ports/tickets/issue-links'
8
8
  import { TicketPriorityUnsupported } from '../ports/tickets/priority'
9
+ import { TicketAssigneesUnsupported } from '../ports/tickets/assignees'
9
10
  /**
10
11
  * The agent tool registry — one typed table that is the single source of
11
12
  * truth for the agent-facing operator surface (AUT-338).
@@ -330,7 +331,7 @@ const ticketsListInput = z.strictObject({
330
331
  .enum(['oldest', 'newest'])
331
332
  .optional()
332
333
  .describe(
333
- 'Dispatch order, urgent tickets first and then the source order (the default), or newest filed first.',
334
+ 'Dispatch order, urgent tickets first and then the source order (the default), or newest filed first regardless of urgency.',
334
335
  ),
335
336
  })
336
337
 
@@ -345,6 +346,7 @@ const ticketsUpdateInput = ticketUpdateRequestSchema
345
346
  value.labels !== undefined ||
346
347
  value.issueLinks !== undefined ||
347
348
  value.priority !== undefined ||
349
+ value.assignees !== undefined ||
348
350
  value.kind !== undefined ||
349
351
  value.target !== undefined,
350
352
  'update must name at least one field',
@@ -851,13 +853,24 @@ export const TOOLS: readonly ToolEntry[] = [
851
853
  ),
852
854
  defineTool(
853
855
  'tickets.create',
854
- 'Create a ticket in the configured source, optionally labelled, pre-blocked, linked to the forge issues it addresses, urgent so it dispatches before normal ready work, or filed in a nondefault state.',
856
+ 'Create a ticket in the configured source, optionally labelled, pre-blocked, linked to the forge issues it addresses, urgent so it dispatches before normal ready work, assigned (explicit assignees replace the [tickets].createAssignee default), or filed in a nondefault state.',
855
857
  ticketsCreateInput,
856
858
  '{ticket, blockers, build}: the created ticket and its (usually empty) dependency states.',
857
859
  async (raw, ctx) => {
858
860
  const input = raw as z.infer<typeof ticketsCreateInput>
859
- const { repo, title, body, labels, state, blockedBy, issueLinks, priority, kind, target } =
860
- input
861
+ const {
862
+ repo,
863
+ title,
864
+ body,
865
+ labels,
866
+ state,
867
+ blockedBy,
868
+ issueLinks,
869
+ priority,
870
+ assignees,
871
+ kind,
872
+ target,
873
+ } = input
861
874
  return mutateOperatorTicket({
862
875
  store: ctx.store,
863
876
  repo,
@@ -873,13 +886,14 @@ export const TOOLS: readonly ToolEntry[] = [
873
886
  ...(blockedBy !== undefined ? { blockedBy } : {}),
874
887
  ...(issueLinks !== undefined ? { issueLinks } : {}),
875
888
  ...(priority !== undefined ? { priority } : {}),
889
+ ...(assignees !== undefined ? { assignees } : {}),
876
890
  },
877
891
  })
878
892
  },
879
893
  ),
880
894
  defineTool(
881
895
  'tickets.update',
882
- 'Partially replace a ticket’s editable fields (title, body, labels, issue links, priority, kind, target); urgent priority dispatches before normal ready work. State is never changed here.',
896
+ 'Partially replace a ticket’s editable fields (title, body, labels, issue links, priority, assignees, kind, target); urgent priority dispatches before normal ready work, and assignees replace the whole set ([] clears). State is never changed here.',
883
897
  ticketsUpdateInput,
884
898
  '{ticket, blockers, build}: the updated ticket.',
885
899
  async (raw, ctx) => {
@@ -1127,6 +1141,12 @@ function mapDomainError(error: unknown): RegistryError {
1127
1141
  error: error.message,
1128
1142
  code: 'priority-unsupported',
1129
1143
  })
1144
+ if (error instanceof TicketAssigneesUnsupported)
1145
+ return new RegistryError('domain', error.message, {
1146
+ kind: 'refusal',
1147
+ error: error.message,
1148
+ code: 'assignees-unsupported',
1149
+ })
1130
1150
  if (error instanceof TicketOperationError) {
1131
1151
  return new RegistryError('domain', error.message, {
1132
1152
  kind: error.code === 'not-found' ? 'not-found' : 'refusal',
@@ -117,6 +117,9 @@ export async function createHostedOperatorSandboxService(
117
117
  env: options.env,
118
118
  repoRoot: scratch,
119
119
  repository: options.repo,
120
+ // A deployment without a token must fail typed, never spend the
121
+ // hosting platform's shared anonymous GitHub quota.
122
+ requireCredential: 'hosted operator sandbox backend',
120
123
  }))
121
124
  if (forge.remoteBranchSha === undefined) {
122
125
  throw new Error(
@@ -6,6 +6,7 @@ import {
6
6
  import { updateTicketTarget } from '../kernel/node-parent'
7
7
  import { normalizeIssueLinks, type IssueLinkInput } from '../ports/tickets/issue-links'
8
8
  import { urgentFirst } from '../ports/tickets/priority'
9
+ import { creationAssignees } from '../ports/tickets/assignees'
9
10
  import type { IssueLink } from '../ports/types'
10
11
  import { projectTicketTree, compatibleTicketSource } from '../ports/tickets/tree'
11
12
  import { readBuildFacts } from '../store/reduced-reads'
@@ -64,7 +65,7 @@ export interface OperatorTicketQueue {
64
65
  }
65
66
 
66
67
  /** A window over a listing. `oldest` (default) is dispatch order: urgent first,
67
- * then the source's order; `newest` reverses the source's filing order. */
68
+ * then the source's order; `newest` is newest filed first, regardless of urgency. */
68
69
  export type OperatorTicketPage = TicketPage
69
70
 
70
71
  export interface OperatorTicketBuild {
@@ -150,7 +151,10 @@ export async function listOperatorTickets(opts: {
150
151
  nativePage ? source.listPage!(criteria, opts.page!) : source.listReady(criteria),
151
152
  opts.backend.statesFor(context, source),
152
153
  ])
153
- // Native pages arrive ordered; the fallback mirrors the dispatcher's claim order.
154
+ // Native pages arrive ordered; the fallback mirrors the dispatcher's claim
155
+ // order. listReady is in the source's filing order, so reversing it is newest
156
+ // filed first. The remote hosted client is the exception: its listing arrives
157
+ // urgent-first with no filing time, so there newest is reversed dispatch order.
154
158
  const ordered = nativePage
155
159
  ? listing.tickets
156
160
  : opts.page?.order === 'newest'
@@ -280,6 +284,7 @@ export async function mutateOperatorTicket(opts: {
280
284
  blockedBy?: string[]
281
285
  issueLinks?: IssueLinkInput[]
282
286
  priority?: import('../ports/types').TicketPriority
287
+ assignees?: string[]
283
288
  }
284
289
  | {
285
290
  kind: 'update'
@@ -298,7 +303,14 @@ export async function mutateOperatorTicket(opts: {
298
303
  if (operation.kind === 'update') await requireTicket(source, operation.id)
299
304
  const ticket =
300
305
  operation.kind === 'create'
301
- ? await createTicket(source, issueLinkDefaults({ ...operation, kind: operation.ticketKind }))
306
+ ? await createTicket(
307
+ source,
308
+ issueLinkDefaults({
309
+ ...operation,
310
+ kind: operation.ticketKind,
311
+ assignees: creationAssignees(context.tickets, operation.assignees),
312
+ }),
313
+ )
302
314
  : operation.kind === 'update'
303
315
  ? (await (operation.patch.target === undefined
304
316
  ? updateTicket(
@@ -168,6 +168,10 @@ export {
168
168
  withoutUnsupportedPriority,
169
169
  urgentFirst,
170
170
  } from '../ports/tickets/priority'
171
+ export {
172
+ TicketAssigneesUnsupported,
173
+ refuseUnsupportedAssignees,
174
+ } from '../ports/tickets/assignees'
171
175
  export {
172
176
  issueKeywordLines,
173
177
  landingMessage,
@@ -41,6 +41,9 @@ export async function createForge(opts: {
41
41
  /** Subprocess seam for the builtin GitHub forge's Git commands, including
42
42
  * `kernelExec`. Absent, the adapter spawns from the host `PATH`. */
43
43
  exec?: Exec
44
+ /** Process label for the builtin GitHub forge: refuse requests that would
45
+ * go out without a credential. Plugins and `local-git` ignore it. */
46
+ requireCredential?: string
44
47
  }): Promise<Forge> {
45
48
  const registration = resolveForgeRegistration(opts.name, opts.registry)
46
49
  if (registration.owner.kind === 'builtin') {
@@ -50,6 +53,9 @@ export async function createForge(opts: {
50
53
  repoRoot: opts.repoRoot,
51
54
  ...(opts.repository !== undefined ? { repository: opts.repository } : {}),
52
55
  ...(opts.exec !== undefined ? { exec: opts.exec } : {}),
56
+ ...(opts.requireCredential !== undefined
57
+ ? { requireCredential: opts.requireCredential }
58
+ : {}),
53
59
  })
54
60
  }
55
61
  if (opts.name === 'local-git') return new LocalGitForge({ repoRoot: opts.repoRoot })
@@ -7,7 +7,7 @@
7
7
  * shelling `gh`.
8
8
  */
9
9
  import { z } from 'zod'
10
- import { ForgeFailure, isForgeFailure } from '../forge-failure'
10
+ import { ForgeCredentialMissing, ForgeFailure, isForgeFailure } from '../forge-failure'
11
11
  import { spawnExec } from '../workspace/git-worktree'
12
12
 
13
13
  export interface GitHubRequestOpts {
@@ -58,6 +58,8 @@ export class GitHubApiError extends Error {
58
58
  message: string,
59
59
  body?: unknown,
60
60
  readonly headers: Record<string, string> = {},
61
+ /** Why the request went out without a credential, when it did. */
62
+ readonly unauthenticated?: string,
61
63
  ) {
62
64
  super(message)
63
65
  this.name = 'GitHubApiError'
@@ -106,14 +108,32 @@ export type GitHubTokenSource =
106
108
  /** Minimum interval between two invocations of a token resolver. */
107
109
  export const CREDENTIAL_MISS_TTL_MS = 60_000
108
110
 
111
+ /** Marks a process environment whose GitHub API requests must carry a
112
+ * credential. Remote workspace providers set it for every guest process. */
113
+ export const GITHUB_REQUIRE_CREDENTIAL_ENV = 'AB_GITHUB_REQUIRE_CREDENTIAL'
114
+
115
+ /** The process label a transport names when it refuses an anonymous request:
116
+ * an explicit label, else a generic one when the environment carries
117
+ * {@link GITHUB_REQUIRE_CREDENTIAL_ENV}, else none (anonymous allowed). */
118
+ export function githubCredentialRequirement(
119
+ env: Readonly<Record<string, string | undefined>>,
120
+ label?: string,
121
+ ): string | undefined {
122
+ if (label !== undefined) return label
123
+ return env[GITHUB_REQUIRE_CREDENTIAL_ENV] === '1' ? 'remote guest process' : undefined
124
+ }
125
+
109
126
  /** Production transport: token-authenticated fetch against api.github.com.
110
127
  * Callers pass a literal token or a resolver such as
111
128
  * {@link githubTokenSource}; no `Authorization` header is sent when neither
112
- * yields one. */
129
+ * yields one — unless `requireCredential` names the process, in which case a
130
+ * request that would go out anonymously throws {@link ForgeCredentialMissing}
131
+ * before anything is sent. */
113
132
  export function createGitHubFetchTransport(opts: {
114
133
  token?: GitHubTokenSource
115
134
  apiBase?: string
116
135
  now?: () => number
136
+ requireCredential?: string
117
137
  }): GitHubRequest {
118
138
  const source = opts.token
119
139
  const now = opts.now ?? Date.now
@@ -162,6 +182,15 @@ export function createGitHubFetchTransport(opts: {
162
182
  return async (method, path, request = {}) => {
163
183
  const credential = await resolveToken()
164
184
  const token = credential.token
185
+ // `in` for the same strictNullChecks reason as the anonymous error below.
186
+ const missReason =
187
+ token === undefined || token === ''
188
+ ? 'reason' in credential
189
+ ? credential.reason
190
+ : 'no GitHub credential was available'
191
+ : undefined
192
+ if (missReason !== undefined && opts.requireCredential !== undefined)
193
+ throw new ForgeCredentialMissing(opts.requireCredential, missReason)
165
194
  let url = /^https:\/\//i.test(path) ? path : `${base}/${path.replace(/^\/+/, '')}`
166
195
  if (request.query !== undefined) {
167
196
  const params = new URLSearchParams(request.query)
@@ -232,6 +261,7 @@ export function createGitHubFetchTransport(opts: {
232
261
  `${githubErrorMessage(response.status, json, text)}${anonymous}`,
233
262
  json,
234
263
  headerMap,
264
+ missReason,
235
265
  )
236
266
  }
237
267
  return {
@@ -422,7 +452,14 @@ export function classifyGitHubFailure(error: unknown, now = Date.now()): unknown
422
452
  if (isForgeFailure(error)) return error
423
453
  const resetAt = githubRateLimitUntil(error, now)
424
454
  const message = error instanceof Error ? error.message : String(error)
425
- if (resetAt) return new ForgeFailure(message, { kind: 'rate-limited', resetAt })
455
+ if (resetAt) {
456
+ const unauthenticated = error instanceof GitHubApiError ? error.unauthenticated : undefined
457
+ return new ForgeFailure(message, {
458
+ kind: 'rate-limited',
459
+ resetAt,
460
+ ...(unauthenticated ? { unauthenticated } : {}),
461
+ })
462
+ }
426
463
  const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined
427
464
  if (
428
465
  (error instanceof GitHubApiError && error.status >= 500) ||
@@ -55,6 +55,7 @@ import {
55
55
  GitHubApiError,
56
56
  classifyGitHubFailure,
57
57
  createGitHubFetchTransport,
58
+ githubCredentialRequirement,
58
59
  githubTokenSource,
59
60
  restPlanLimitation,
60
61
  type GitHubRequest,
@@ -765,6 +766,10 @@ export class GitHubForge implements Forge {
765
766
  * Defaults to `MERGEABILITY_RETRY_DELAYS_MS` (7 re-queries, ~30 s);
766
767
  * tests inject `[0, 0]` or all-zero schedules so no test sleeps. */
767
768
  mergeabilityRetryDelaysMs?: number[]
769
+ /** Process label: the default transport refuses to send a request
770
+ * without a credential. Absent, the environment's
771
+ * `AB_GITHUB_REQUIRE_CREDENTIAL` marker decides. */
772
+ requireCredential?: string
768
773
  } = {},
769
774
  ) {
770
775
  this.now = opts.now ?? Date.now
@@ -775,7 +780,13 @@ export class GitHubForge implements Forge {
775
780
  // stored login, probed lazily through this adapter's exec seam on the
776
781
  // first request. A request that still goes out anonymously carries the
777
782
  // miss reason in its error, so nothing is probed at construction time.
778
- const transport = opts.transport ?? createGitHubFetchTransport({ token: this.token })
783
+ const requireCredential = githubCredentialRequirement(this.env, opts.requireCredential)
784
+ const transport =
785
+ opts.transport ??
786
+ createGitHubFetchTransport({
787
+ token: this.token,
788
+ ...(requireCredential !== undefined ? { requireCredential } : {}),
789
+ })
779
790
  this.transport = async (...args) =>
780
791
  guardedForgeRequest(async () => {
781
792
  const context = forgeRequestContext()
@@ -0,0 +1,60 @@
1
+ import { gitOid } from '../../events/payloads'
2
+ import type { Forge } from '../types'
3
+ import type { Exec } from '../workspace/git-worktree'
4
+
5
+ /**
6
+ * A remote guest has no forge credential, so the GitHub `compare` request
7
+ * behind `isCommitAncestor` would go out anonymously and spend the shared
8
+ * sandbox address's unauthenticated quota. The guest's workspace is a full
9
+ * clone with an already-authorized Git read channel, so ancestry is proven
10
+ * there instead: `merge-base --is-ancestor`, fetching both commits by SHA once
11
+ * when either object is missing. Every other member passes through unchanged.
12
+ * It makes no forge API request and no Store read.
13
+ */
14
+ export function withWorkspaceAncestry(
15
+ forge: Forge,
16
+ deps: { exec: Exec; workspacePath: string },
17
+ ): Forge {
18
+ const isAncestor = (ancestor: string, descendant: string) =>
19
+ deps.exec(['git', 'merge-base', '--is-ancestor', ancestor, descendant], {
20
+ cwd: deps.workspacePath,
21
+ })
22
+ const isCommitAncestor = async (ancestor: string, descendant: string): Promise<boolean> => {
23
+ if (!gitOid.safeParse(ancestor).success || !gitOid.safeParse(descendant).success)
24
+ throw new Error('invalid ancestry OID')
25
+ let result = await isAncestor(ancestor, descendant)
26
+ if (result.exitCode === 0) return true
27
+ if (result.exitCode === 1) return false
28
+ const fetched = await deps.exec(
29
+ [
30
+ 'git',
31
+ 'fetch',
32
+ '--no-tags',
33
+ '--no-write-fetch-head',
34
+ '--refmap=',
35
+ 'origin',
36
+ ancestor,
37
+ descendant,
38
+ ],
39
+ { cwd: deps.workspacePath },
40
+ )
41
+ if (fetched.exitCode !== 0)
42
+ throw new Error(
43
+ `workspace ancestry fetch failed (exit ${fetched.exitCode}): ${fetched.stderr.trim()}`,
44
+ )
45
+ result = await isAncestor(ancestor, descendant)
46
+ if (result.exitCode === 0) return true
47
+ if (result.exitCode === 1) return false
48
+ throw new Error(
49
+ `workspace ancestry check failed (exit ${result.exitCode}): ${result.stderr.trim()}`,
50
+ )
51
+ }
52
+ return new Proxy(forge, {
53
+ get(target, key) {
54
+ // Capability-preserving: a forge without ancestry proof keeps none.
55
+ if (key === 'isCommitAncestor' && target.isCommitAncestor) return isCommitAncestor
56
+ const value = Reflect.get(target, key, target)
57
+ return typeof value === 'function' ? value.bind(target) : value
58
+ },
59
+ })
60
+ }
@@ -1,7 +1,14 @@
1
1
  import { z } from 'zod'
2
2
  /** Additive plugin API: recognizable across separately loaded SDK copies. */
3
3
  export type ForgeFailureDetails =
4
- | { kind: 'rate-limited'; resetAt: string }
4
+ | {
5
+ kind: 'rate-limited'
6
+ resetAt: string
7
+ /** Set when the limited request carried no credential: why it went out
8
+ * anonymously. Such a limit belongs to the caller's network address, not
9
+ * to the dispatcher's credential, so it never pauses the repository. */
10
+ unauthenticated?: string
11
+ }
5
12
  | { kind: 'transient'; retry: 'retryable' }
6
13
 
7
14
  export class ForgeFailure extends Error {
@@ -28,11 +35,33 @@ export function isForgeFailure(error: unknown): error is ForgeFailure {
28
35
  const details = value.details
29
36
  return (
30
37
  !!details &&
31
- ((details.kind === 'rate-limited' && z.iso.datetime().safeParse(details.resetAt).success) ||
38
+ ((details.kind === 'rate-limited' &&
39
+ z.iso.datetime().safeParse(details.resetAt).success &&
40
+ (details.unauthenticated === undefined ||
41
+ (typeof details.unauthenticated === 'string' && details.unauthenticated.length > 0))) ||
32
42
  (details.kind === 'transient' && details.retry === 'retryable'))
33
43
  )
34
44
  }
35
45
 
46
+ /** A GitHub API request refused before sending because the process has no
47
+ * credential where one is required (a remote guest, or a hosted backend). It
48
+ * is deliberately not a `ForgeFailure`: it is neither a rate limit nor
49
+ * transient, and retrying cannot succeed without a credential. */
50
+ export class ForgeCredentialMissing extends Error {
51
+ readonly credential = 'GITHUB_TOKEN or GH_TOKEN' as const
52
+ constructor(
53
+ readonly process: string,
54
+ readonly reason: string,
55
+ ) {
56
+ super(
57
+ `${process}: GitHub API request refused — no GitHub credential (${reason}). ` +
58
+ 'Provide GITHUB_TOKEN or GH_TOKEN to this process; remote guests receive no forge ' +
59
+ 'credential, so their GitHub API work must run kernel-side.',
60
+ )
61
+ this.name = 'ForgeCredentialMissing'
62
+ }
63
+ }
64
+
36
65
  export interface ForgeRejectionDetails {
37
66
  /** Human-readable forge name, e.g. `GitHub`. */
38
67
  forge: string