@defrex/autobuild 1.6.0 → 1.8.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 (165) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +423 -57
  3. package/docs/agent-runtimes.md +1 -1
  4. package/docs/answering-blocked-builds.md +44 -3
  5. package/docs/architecture.md +124 -29
  6. package/docs/cli.md +1 -0
  7. package/docs/configuration-overview.md +11 -1
  8. package/docs/configuration.md +334 -14
  9. package/docs/dispatcher.md +1 -1
  10. package/docs/forges.md +1 -0
  11. package/docs/integration-overview.md +2 -2
  12. package/docs/integration-tree.md +7 -4
  13. package/docs/merge-policy.md +78 -6
  14. package/docs/migration-1.0.md +4 -2
  15. package/docs/operating.md +3 -2
  16. package/docs/operator-api.md +45 -13
  17. package/docs/operator-surfaces.md +16 -3
  18. package/docs/plugin-authoring.md +45 -7
  19. package/docs/remote-store-protocol.md +28 -7
  20. package/docs/restacking.md +35 -11
  21. package/docs/ticket-dependencies.md +9 -4
  22. package/docs/ticket-sources.md +34 -6
  23. package/docs/tickets.md +7 -1
  24. package/docs/troubleshooting.md +1 -1
  25. package/docs/workspaces.md +1 -1
  26. package/package.json +3 -3
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary-direct.ts +1 -0
  29. package/packages/core/src/cli/build-control.ts +65 -7
  30. package/packages/core/src/cli/context.ts +55 -14
  31. package/packages/core/src/cli/dashboard/actions.ts +13 -4
  32. package/packages/core/src/cli/dashboard/landing-display.ts +32 -8
  33. package/packages/core/src/cli/dashboard/model.ts +61 -8
  34. package/packages/core/src/cli/dashboard/render.ts +28 -3
  35. package/packages/core/src/cli/dashboard/tree.ts +9 -1
  36. package/packages/core/src/cli/dispatch-frontend.ts +10 -14
  37. package/packages/core/src/cli/dispatch-preflight.ts +1 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +145 -109
  39. package/packages/core/src/cli/dispatch.ts +9 -3
  40. package/packages/core/src/cli/help.ts +80 -11
  41. package/packages/core/src/cli/init-validation.ts +14 -1
  42. package/packages/core/src/cli/landings.ts +1 -1
  43. package/packages/core/src/cli/main.ts +60 -9
  44. package/packages/core/src/cli/publication-settlement.ts +10 -0
  45. package/packages/core/src/cli/repository-status.ts +37 -2
  46. package/packages/core/src/cli/status.ts +186 -12
  47. package/packages/core/src/cli/terminals.ts +197 -4
  48. package/packages/core/src/cli/ticket.ts +22 -4
  49. package/packages/core/src/cli/wait.ts +1 -0
  50. package/packages/core/src/cli/watch.ts +73 -0
  51. package/packages/core/src/config/landing.ts +12 -0
  52. package/packages/core/src/config/live.ts +4 -0
  53. package/packages/core/src/config/path-selectors.ts +68 -0
  54. package/packages/core/src/config/profiles.ts +96 -0
  55. package/packages/core/src/config/ready-assignee.ts +43 -11
  56. package/packages/core/src/config/roles.ts +33 -10
  57. package/packages/core/src/config/schema.ts +205 -81
  58. package/packages/core/src/events/catalog.ts +17 -3
  59. package/packages/core/src/events/compatibility.ts +4 -1
  60. package/packages/core/src/events/forge-degradation-policy.ts +16 -2
  61. package/packages/core/src/events/head-paths-limits.ts +25 -0
  62. package/packages/core/src/events/payloads.ts +323 -20
  63. package/packages/core/src/events/policy.ts +22 -0
  64. package/packages/core/src/events/repository.ts +47 -1
  65. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +320 -130
  66. package/packages/core/src/kernel/build-creation.ts +29 -0
  67. package/packages/core/src/kernel/consent-revocation.ts +72 -0
  68. package/packages/core/src/kernel/dispatch-capacity.ts +19 -8
  69. package/packages/core/src/kernel/engine.ts +48 -8
  70. package/packages/core/src/kernel/forge-health.ts +47 -0
  71. package/packages/core/src/kernel/guarded-forge.ts +76 -18
  72. package/packages/core/src/kernel/head-paths-state.ts +63 -0
  73. package/packages/core/src/kernel/head-paths.ts +401 -0
  74. package/packages/core/src/kernel/landing-policy-identity.ts +20 -0
  75. package/packages/core/src/kernel/landing-policy.ts +55 -2
  76. package/packages/core/src/kernel/landing-readiness.ts +104 -9
  77. package/packages/core/src/kernel/landing-state.ts +44 -4
  78. package/packages/core/src/kernel/leaf-restack-state.ts +50 -2
  79. package/packages/core/src/kernel/log-index.ts +27 -1
  80. package/packages/core/src/kernel/node-parent.ts +2 -0
  81. package/packages/core/src/kernel/node-polling.ts +13 -3
  82. package/packages/core/src/kernel/node-restack-state.ts +8 -1
  83. package/packages/core/src/kernel/node-restack-transaction.ts +45 -0
  84. package/packages/core/src/kernel/read-deferrals.ts +3 -1
  85. package/packages/core/src/kernel/read-facts.ts +37 -2
  86. package/packages/core/src/kernel/reducer-registry.ts +22 -1
  87. package/packages/core/src/kernel/reducer.ts +332 -16
  88. package/packages/core/src/kernel/target-observation.ts +2 -5
  89. package/packages/core/src/kernel/terminal-guard.ts +52 -3
  90. package/packages/core/src/kernel/ticket-handbacks.ts +40 -0
  91. package/packages/core/src/kernel/ticket-preparation.ts +15 -1
  92. package/packages/core/src/kernel/ticket-wait.ts +345 -0
  93. package/packages/core/src/kernel/verify-applicability.ts +9 -19
  94. package/packages/core/src/ontology.ts +1 -0
  95. package/packages/core/src/operator/annotations.ts +6 -0
  96. package/packages/core/src/operator/index.ts +3 -0
  97. package/packages/core/src/operator/protocol.ts +25 -2
  98. package/packages/core/src/operator/query.ts +1 -1
  99. package/packages/core/src/operator/registry.ts +122 -10
  100. package/packages/core/src/operator/repository-events.ts +67 -0
  101. package/packages/core/src/operator/sandbox-host.ts +3 -0
  102. package/packages/core/src/operator/tickets.ts +15 -3
  103. package/packages/core/src/plugin-sdk/index.ts +4 -0
  104. package/packages/core/src/ports/forge/create.ts +6 -0
  105. package/packages/core/src/ports/forge/github-transport.ts +40 -3
  106. package/packages/core/src/ports/forge/github.ts +12 -1
  107. package/packages/core/src/ports/forge/workspace-ancestry.ts +60 -0
  108. package/packages/core/src/ports/forge-failure.ts +31 -2
  109. package/packages/core/src/ports/runner/routing.ts +66 -5
  110. package/packages/core/src/ports/tickets/assignees.ts +54 -0
  111. package/packages/core/src/ports/tickets/contract.ts +164 -4
  112. package/packages/core/src/ports/tickets/create.ts +17 -3
  113. package/packages/core/src/ports/tickets/fake.ts +5 -0
  114. package/packages/core/src/ports/tickets/github-fake.ts +18 -2
  115. package/packages/core/src/ports/tickets/github.ts +247 -29
  116. package/packages/core/src/ports/tickets/hosted-index.ts +1 -0
  117. package/packages/core/src/ports/tickets/operations.ts +6 -1
  118. package/packages/core/src/ports/tickets/tree.ts +12 -2
  119. package/packages/core/src/ports/tickets/update.ts +6 -2
  120. package/packages/core/src/ports/types.ts +36 -5
  121. package/packages/core/src/ports/workspace/vercel-sandbox.ts +9 -0
  122. package/packages/core/src/processes/build-child.ts +28 -7
  123. package/packages/core/src/processes/build-execution-state.ts +34 -2
  124. package/packages/core/src/processes/build-runner.ts +165 -19
  125. package/packages/core/src/processes/dispatcher.ts +837 -115
  126. package/packages/core/src/processes/execution-no-progress.ts +22 -2
  127. package/packages/core/src/processes/harvest-child.ts +4 -0
  128. package/packages/core/src/processes/harvest-runner.ts +5 -0
  129. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  130. package/packages/core/src/processes/publication-state.ts +6 -1
  131. package/packages/core/src/processes/repo-view.ts +2 -0
  132. package/packages/core/src/scenarios/harness.ts +15 -1
  133. package/packages/core/src/store/digest.ts +41 -2
  134. package/packages/core/src/store/reduced-reads.ts +4 -1
  135. package/packages/core/src/store/reducer-value-shapes.json +10310 -8441
  136. package/packages/core/src/store/remote/client.ts +49 -10
  137. package/packages/core/src/store/remote/index.ts +4 -0
  138. package/packages/core/src/store/remote/protocol.ts +18 -1
  139. package/packages/core/src/store/remote/released-clients.json +22 -0
  140. package/packages/core/src/store/remote/released-reducer-values/1.7.0.json +27366 -0
  141. package/packages/core/src/store/remote/released-reducer-values/1.8.0.json +29043 -0
  142. package/packages/core/src/store/remote/released-reducer-values/index.ts +4 -0
  143. package/packages/core/src/store/repo-state-events.ts +3 -0
  144. package/packages/core/src/store/types.ts +27 -0
  145. package/packages/core/src/testing/dispatch-read-budget.ts +84 -58
  146. package/packages/core/src/testing/index.ts +2 -0
  147. package/packages/core/src/testing/reduced-read-budget.ts +419 -9
  148. package/skills/code-review/SKILL.md +8 -0
  149. package/skills/finalize/SKILL.md +4 -0
  150. package/skills/guide/SKILL.md +241 -47
  151. package/skills/guide/references/integration-tree.md +7 -4
  152. package/skills/guide/references/merge-policy.md +78 -6
  153. package/skills/guide/references/migration-1.0.md +4 -2
  154. package/skills/guide/references/operator-api.md +45 -13
  155. package/skills/guide/references/plugin-authoring.md +45 -7
  156. package/skills/guide/references/remote-store-protocol.md +28 -7
  157. package/skills/guide/references/restacking.md +35 -11
  158. package/skills/guide/references/ticket-dependencies.md +9 -4
  159. package/skills/implement/SKILL.md +15 -1
  160. package/skills/operate/SKILL.md +133 -16
  161. package/skills/plan/SKILL.md +17 -2
  162. package/skills/plan-review/SKILL.md +8 -0
  163. package/skills/reconcile/SKILL.md +21 -5
  164. package/skills/tickets/SKILL.md +23 -6
  165. package/templates/hosted-service/package.json +2 -2
@@ -1,4 +1,6 @@
1
1
  import { readBuildPage } from '../store/event-reads'
2
+ import { abortDestinationSchema } from '../events/payloads'
3
+ import { readRepositoryAttentionPage } from './repository-events'
2
4
  import { requestNodeRestack } from './restack'
3
5
  import { listOperatorLandings } from './landings'
4
6
  import { getOperatorTicketTree } from './tickets'
@@ -6,6 +8,7 @@ import { openOperatorTickets, operatorControlTickets } from './tickets'
6
8
  import { TicketRevisionConflict, TicketRevisionUnsupported } from '../ports/tickets/revision'
7
9
  import { TicketIssueLinksUnsupported } from '../ports/tickets/issue-links'
8
10
  import { TicketPriorityUnsupported } from '../ports/tickets/priority'
11
+ import { TicketAssigneesUnsupported } from '../ports/tickets/assignees'
9
12
  /**
10
13
  * The agent tool registry — one typed table that is the single source of
11
14
  * truth for the agent-facing operator surface (AUT-338).
@@ -32,7 +35,12 @@ import { TicketPriorityUnsupported } from '../ports/tickets/priority'
32
35
  * every mutator, and — for constrained bindings — repository targeting.
33
36
  */
34
37
  import { z } from 'zod'
35
- import { controlBuild, BuildControlError, type BuildControlAction } from '../cli/build-control'
38
+ import {
39
+ controlBuild,
40
+ BuildControlError,
41
+ parseConsentHead,
42
+ type BuildControlAction,
43
+ } from '../cli/build-control'
36
44
  import type { Via } from '../events/envelope'
37
45
  import { bulkControlRepository, BulkWalkError } from '../cli/bulk-control'
38
46
  import { systemClock, type BuildStore, type Clock } from '../store/types'
@@ -270,12 +278,57 @@ const buildArtifactInput = z.strictObject({
270
278
  })
271
279
 
272
280
  const buildControlInput = z.strictObject({
281
+ head: z
282
+ .string()
283
+ .min(1)
284
+ .optional()
285
+ .describe(
286
+ 'Only with "merge"/"land": the candidate head (full SHA or ≥7-character prefix) the operator reviewed. Consent is refused, with nothing recorded, unless it is the current candidate head.',
287
+ ),
288
+
273
289
  repo: repoField,
274
290
  slug: slugField,
275
291
  action: z
276
292
  .enum(['pause', 'cancel-pause', 'resume', 'merge', 'land', 'hold', 'abort', 'discard'])
277
293
  .describe(
278
- 'Control to request: "pause" (or "cancel-pause" to revoke a pending pause), "resume" a paused build, "merge" (deprecated alias "land") for merge consent or "hold" to withdraw consent — or the destructive "abort" (cancels the build, cleans up its PR and workspace, returns the ticket to triage) and "discard" (dequeue a queued build).',
294
+ 'Control to request: "pause" (or "cancel-pause" to revoke a pending pause), "resume" a paused build, "merge" (deprecated alias "land") for merge consent or "hold" to withdraw consent — or the destructive "abort" (cancels the build, cleans up its PR and workspace, hands the ticket back to triage, or to ready with `to`) and "discard" (dequeue a queued build).',
295
+ ),
296
+ to: abortDestinationSchema
297
+ .optional()
298
+ .describe(
299
+ 'Abort only: where cleanup hands the ticket back — "triage" (the default) or "ready" (blockers kept, redispatched once they merge; falls back to triage when the ticket no longer conforms to the spec standard).',
300
+ ),
301
+ reason: z
302
+ .string()
303
+ .optional()
304
+ .describe('Abort only: why, 1–2000 characters; quoted in the hand-back ticket comment.'),
305
+ })
306
+
307
+ const repositoryEventsInput = z.strictObject({
308
+ repo: repoField,
309
+ cursor: z
310
+ .number()
311
+ .int()
312
+ .min(0)
313
+ .safe()
314
+ .optional()
315
+ .describe(
316
+ 'Repository journal cursor: return events with seq strictly greater than this. Omit to receive no events and a baseline cursor for the current head.',
317
+ ),
318
+ waitSeconds: z
319
+ .number()
320
+ .int()
321
+ .min(0)
322
+ .max(30)
323
+ .default(0)
324
+ .describe(
325
+ 'Bounded wait: hold the call for at most this many seconds waiting for a new event before returning an empty page (0–30; 0 returns immediately).',
326
+ ),
327
+ filter: z
328
+ .enum(['attention', 'all'])
329
+ .default('attention')
330
+ .describe(
331
+ '"attention" (the default) returns only the repository events `ab watch --operator` reports by default, such as ticket.handed-back; "all" returns every scanned event.',
279
332
  ),
280
333
  })
281
334
 
@@ -330,7 +383,7 @@ const ticketsListInput = z.strictObject({
330
383
  .enum(['oldest', 'newest'])
331
384
  .optional()
332
385
  .describe(
333
- 'Dispatch order, urgent tickets first and then the source order (the default), or newest filed first.',
386
+ 'Dispatch order, urgent tickets first and then the source order (the default), or newest filed first regardless of urgency.',
334
387
  ),
335
388
  })
336
389
 
@@ -345,6 +398,7 @@ const ticketsUpdateInput = ticketUpdateRequestSchema
345
398
  value.labels !== undefined ||
346
399
  value.issueLinks !== undefined ||
347
400
  value.priority !== undefined ||
401
+ value.assignees !== undefined ||
348
402
  value.kind !== undefined ||
349
403
  value.target !== undefined,
350
404
  'update must name at least one field',
@@ -534,7 +588,7 @@ export const TOOLS: readonly ToolEntry[] = [
534
588
  'builds.list',
535
589
  'List one repository’s builds, newest first, with effective status derived from the build log.',
536
590
  buildListInput,
537
- 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, and durable-event progress.',
591
+ 'JSON array of build summaries: slug, ticket ref, effective status, phase/round/attempt, PR number/url/state, updatedAt, lease health, durable-event progress, and any ticket wait (`wait` with its state and tickets; `waitOnly` when the wait is the only open escalation).',
538
592
  async (raw, ctx) => {
539
593
  const input = raw as z.infer<typeof buildListInput>
540
594
  return listOperatorBuilds({
@@ -614,7 +668,7 @@ export const TOOLS: readonly ToolEntry[] = [
614
668
  ),
615
669
  defineTool(
616
670
  'builds.control',
617
- 'Pause immediately suspends a live agent session. Resume continues where stopped when supported; remote and unsupported sessions rerun fresh. Request a durable control for one active build: pause/cancel-pause, resume, hold or merge — or the destructive abort and discard. Merge requires a ready candidate; hold withdraws merge consent.',
671
+ 'Pause immediately suspends a live agent session. Resume continues where stopped when supported; remote and unsupported sessions rerun fresh. Request a durable control for one active build: pause/cancel-pause, resume, hold or merge — or the destructive abort and discard. Merge requires a ready candidate, and an optional head binds consent to the reviewed head; hold withdraws merge consent.',
618
672
  buildControlInput,
619
673
  'Either {kind: "command", slug, command, event} for an accepted control, or {kind: "answer-required", slug, escalationIds} when a resume needs its open escalations answered first.',
620
674
  async (raw, ctx) => {
@@ -623,6 +677,24 @@ export const TOOLS: readonly ToolEntry[] = [
623
677
  ...received,
624
678
  action: received.action === 'merge' ? ('land' as const) : received.action,
625
679
  }
680
+ let head: string | undefined
681
+ if (input.head !== undefined) {
682
+ if (input.action !== 'land')
683
+ throw new RouteRefusalError({
684
+ kind: 'validation',
685
+ error: 'head applies only to the merge action',
686
+ })
687
+ head = parseConsentHead(input.head)
688
+ if (head === undefined)
689
+ throw new RouteRefusalError({
690
+ kind: 'validation',
691
+ error: 'head must be a nonblank commit SHA without whitespace',
692
+ })
693
+ }
694
+ if (input.action !== 'abort' && (input.to !== undefined || input.reason !== undefined)) {
695
+ const error = `"to" and "reason" apply only to the abort action, not "${received.action}"`
696
+ throw new RegistryError('validation', error, { kind: 'validation', error })
697
+ }
626
698
  await controlPrechecks(ctx.store, input.repo, input.slug, input.action)
627
699
  // The route maps BOTH pause and cancel-pause to `dashboard-pause`:
628
700
  // on a running build it requests a pause, and on a build with a pending
@@ -633,7 +705,15 @@ export const TOOLS: readonly ToolEntry[] = [
633
705
  ? { kind: 'dashboard-pause' }
634
706
  : input.action === 'resume'
635
707
  ? { kind: 'dashboard-resume' }
636
- : { kind: input.action }
708
+ : input.action === 'land' && head !== undefined
709
+ ? { kind: 'land', head }
710
+ : input.action === 'abort'
711
+ ? {
712
+ kind: 'abort',
713
+ ...(input.to !== undefined ? { to: input.to } : {}),
714
+ ...(input.reason !== undefined ? { reason: input.reason } : {}),
715
+ }
716
+ : { kind: input.action }
637
717
  return controlBuild({
638
718
  store: ctx.store,
639
719
  ...operatorControlTickets({ store: ctx.store, repo: input.repo, backend: ctx.tickets }),
@@ -706,6 +786,20 @@ export const TOOLS: readonly ToolEntry[] = [
706
786
  return getRepositoryStatus(ctx.store, input.repo)
707
787
  },
708
788
  ),
789
+ defineTool(
790
+ 'repository.events',
791
+ 'Read one repository’s journal after a cursor, optionally waiting (bounded, ≤30s) for a new event — the connected agent’s repository attention watch, matching `ab watch --operator`’s default repository filter (for example ticket.handed-back after a ticket hand-back). Build attention comes from builds.events.',
792
+ repositoryEventsInput,
793
+ '{events, cursor, hasMore}: the matching events among at most 256 scanned journal rows in sequence order, and the cursor to pass next time — the last scanned seq, which advances past filtered events. hasMore means more rows are already waiting. An expired cursor fails with code "cursor-too-old": re-baseline by omitting the cursor and reconcile with repository.status.',
794
+ async (raw, ctx) => {
795
+ const input = raw as z.infer<typeof repositoryEventsInput>
796
+ return readRepositoryAttentionPage(ctx.store, input.repo, {
797
+ ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),
798
+ waitSeconds: input.waitSeconds,
799
+ filter: input.filter,
800
+ })
801
+ },
802
+ ),
709
803
  defineTool(
710
804
  'repository.settings',
711
805
  'Set or toggle a durable repository setting: ticket intake or the claim-time auto-merge default.',
@@ -851,13 +945,24 @@ export const TOOLS: readonly ToolEntry[] = [
851
945
  ),
852
946
  defineTool(
853
947
  '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.',
948
+ '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
949
  ticketsCreateInput,
856
950
  '{ticket, blockers, build}: the created ticket and its (usually empty) dependency states.',
857
951
  async (raw, ctx) => {
858
952
  const input = raw as z.infer<typeof ticketsCreateInput>
859
- const { repo, title, body, labels, state, blockedBy, issueLinks, priority, kind, target } =
860
- input
953
+ const {
954
+ repo,
955
+ title,
956
+ body,
957
+ labels,
958
+ state,
959
+ blockedBy,
960
+ issueLinks,
961
+ priority,
962
+ assignees,
963
+ kind,
964
+ target,
965
+ } = input
861
966
  return mutateOperatorTicket({
862
967
  store: ctx.store,
863
968
  repo,
@@ -873,13 +978,14 @@ export const TOOLS: readonly ToolEntry[] = [
873
978
  ...(blockedBy !== undefined ? { blockedBy } : {}),
874
979
  ...(issueLinks !== undefined ? { issueLinks } : {}),
875
980
  ...(priority !== undefined ? { priority } : {}),
981
+ ...(assignees !== undefined ? { assignees } : {}),
876
982
  },
877
983
  })
878
984
  },
879
985
  ),
880
986
  defineTool(
881
987
  '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.',
988
+ '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
989
  ticketsUpdateInput,
884
990
  '{ticket, blockers, build}: the updated ticket.',
885
991
  async (raw, ctx) => {
@@ -1127,6 +1233,12 @@ function mapDomainError(error: unknown): RegistryError {
1127
1233
  error: error.message,
1128
1234
  code: 'priority-unsupported',
1129
1235
  })
1236
+ if (error instanceof TicketAssigneesUnsupported)
1237
+ return new RegistryError('domain', error.message, {
1238
+ kind: 'refusal',
1239
+ error: error.message,
1240
+ code: 'assignees-unsupported',
1241
+ })
1130
1242
  if (error instanceof TicketOperationError) {
1131
1243
  return new RegistryError('domain', error.message, {
1132
1244
  kind: error.code === 'not-found' ? 'not-found' : 'refusal',
@@ -0,0 +1,67 @@
1
+ import { repositoryNeedsAttention } from '../cli/attention'
2
+ import type { RepositoryEvent } from '../events/repository'
3
+ import { BUILD_EVENT_PAGE_SIZE, CursorTooOldError } from '../store/event-reads'
4
+ import type { BuildStore } from '../store/types'
5
+ import { RegistryError } from './registry'
6
+
7
+ /** One `repository.events` call scans at most this many journal rows. */
8
+ export const REPOSITORY_EVENTS_PAGE = BUILD_EVENT_PAGE_SIZE
9
+
10
+ export interface RepositoryEventsPage {
11
+ events: RepositoryEvent[]
12
+ cursor: number
13
+ hasMore: boolean
14
+ }
15
+
16
+ /** The connected agent's repository attention watch: one bounded page of the
17
+ * repository journal after `cursor`, filtered by the same predicate as
18
+ * `ab watch --operator`. The read itself is bounded to `(cursor, cursor+256]`
19
+ * and the cursor advances past filtered events, so successive pages scan
20
+ * disjoint ranges. An omitted cursor reads only the repository record and
21
+ * its high-water mark. */
22
+ export async function readRepositoryAttentionPage(
23
+ store: BuildStore,
24
+ repo: string,
25
+ opts: { cursor?: number; waitSeconds?: number; filter?: 'attention' | 'all' } = {},
26
+ ): Promise<RepositoryEventsPage> {
27
+ // A repository no dispatcher has recorded yet has an empty journal, as
28
+ // `ab watch` treats it; one record read, no event rows.
29
+ if ((await store.getRepo(repo)) === null)
30
+ return { events: [], cursor: opts.cursor ?? 0, hasMore: false }
31
+ if (opts.cursor === undefined)
32
+ return { events: [], cursor: await store.getRepoHighWater(repo), hasMore: false }
33
+ const cursor = opts.cursor
34
+ if (store.getRepositoryTail === undefined) {
35
+ const error = 'this store cannot serve bounded repository event reads'
36
+ throw new RegistryError('domain', error, {
37
+ kind: 'refusal',
38
+ error,
39
+ code: 'unsupported-operation',
40
+ })
41
+ }
42
+ const through = cursor + REPOSITORY_EVENTS_PAGE
43
+ let scanned: RepositoryEvent[]
44
+ try {
45
+ scanned = await store.getRepositoryTail(repo, cursor, {
46
+ through,
47
+ ...(opts.waitSeconds ? { waitSeconds: opts.waitSeconds } : {}),
48
+ })
49
+ } catch (error) {
50
+ if (error instanceof CursorTooOldError)
51
+ throw new RegistryError('domain', error.message, {
52
+ kind: 'conflict',
53
+ error: error.message,
54
+ code: 'cursor-too-old',
55
+ })
56
+ throw error
57
+ }
58
+ // An older server that ignores `through` can never widen the page.
59
+ scanned = scanned.filter((event) => event.seq > cursor && event.seq <= through)
60
+ const next = scanned.at(-1)?.seq ?? cursor
61
+ const hasMore = next < (await store.getRepoHighWater(repo))
62
+ return {
63
+ events: opts.filter === 'all' ? scanned : scanned.filter(repositoryNeedsAttention),
64
+ cursor: next,
65
+ hasMore,
66
+ }
67
+ }
@@ -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