@defrex/autobuild 1.10.0 → 1.11.1

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 (255) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +745 -69
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +165 -29
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +64 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +111 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +179 -76
  41. package/packages/core/src/cli/dashboard/render.ts +159 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +40 -40
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +202 -38
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +105 -49
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +381 -30
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  95. package/packages/core/src/kernel/build-roster.ts +230 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  97. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  98. package/packages/core/src/kernel/engine.ts +43 -5
  99. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  100. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  101. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  102. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  103. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  104. package/packages/core/src/kernel/log-index.ts +19 -0
  105. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  106. package/packages/core/src/kernel/optimization.ts +183 -4
  107. package/packages/core/src/kernel/phase-failures.ts +121 -0
  108. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  109. package/packages/core/src/kernel/read-facts.ts +15 -13
  110. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  111. package/packages/core/src/kernel/reducer-revisions.ts +27 -0
  112. package/packages/core/src/kernel/reducer.ts +63 -4
  113. package/packages/core/src/kernel/rollup.ts +61 -0
  114. package/packages/core/src/kernel/setup-streak.ts +38 -0
  115. package/packages/core/src/kernel/step-durations.ts +257 -0
  116. package/packages/core/src/kernel/target-observation.ts +6 -1
  117. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  118. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  119. package/packages/core/src/kernel/verify-stages.ts +13 -3
  120. package/packages/core/src/ontology.ts +5 -0
  121. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  122. package/packages/core/src/operator/annotations.ts +75 -5
  123. package/packages/core/src/operator/attention.ts +470 -0
  124. package/packages/core/src/operator/canonical-skills.ts +35 -0
  125. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  126. package/packages/core/src/operator/context-prompts.ts +61 -0
  127. package/packages/core/src/operator/index.ts +49 -1
  128. package/packages/core/src/operator/landings.ts +28 -19
  129. package/packages/core/src/operator/optimization.ts +7 -0
  130. package/packages/core/src/operator/protocol.ts +3 -0
  131. package/packages/core/src/operator/query.ts +129 -74
  132. package/packages/core/src/operator/read-view.ts +5 -2
  133. package/packages/core/src/operator/registry.ts +406 -46
  134. package/packages/core/src/operator/requests.ts +20 -18
  135. package/packages/core/src/operator/sandbox-host.ts +107 -11
  136. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  137. package/packages/core/src/operator/sandbox.ts +778 -82
  138. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  139. package/packages/core/src/operator/ticket-assets.ts +167 -0
  140. package/packages/core/src/operator/tickets.ts +33 -2
  141. package/packages/core/src/plugin-sdk/index.ts +22 -0
  142. package/packages/core/src/plugins/manifest.ts +1 -1
  143. package/packages/core/src/ports/forge/fake.ts +92 -1
  144. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  145. package/packages/core/src/ports/forge/github.ts +82 -0
  146. package/packages/core/src/ports/forge/local-git.ts +61 -1
  147. package/packages/core/src/ports/forge-failure.ts +24 -0
  148. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  149. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  150. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  151. package/packages/core/src/ports/tickets/contract.ts +71 -0
  152. package/packages/core/src/ports/tickets/fake.ts +11 -0
  153. package/packages/core/src/ports/tickets/file.ts +18 -0
  154. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  155. package/packages/core/src/ports/tickets/github.ts +387 -30
  156. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  157. package/packages/core/src/ports/tickets/linear.ts +130 -0
  158. package/packages/core/src/ports/tickets/priority.ts +9 -0
  159. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  160. package/packages/core/src/ports/tickets/remote.ts +70 -6
  161. package/packages/core/src/ports/tickets/search.ts +139 -0
  162. package/packages/core/src/ports/types.ts +104 -2
  163. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  164. package/packages/core/src/ports/workspace/create.ts +15 -1
  165. package/packages/core/src/ports/workspace/fake.ts +340 -12
  166. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  167. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  168. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  169. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  170. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  171. package/packages/core/src/processes/agent-context.ts +469 -0
  172. package/packages/core/src/processes/build-runner.ts +387 -236
  173. package/packages/core/src/processes/dispatcher.ts +211 -55
  174. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  175. package/packages/core/src/processes/optimization-activity.ts +120 -0
  176. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  177. package/packages/core/src/processes/repo-view.ts +78 -2
  178. package/packages/core/src/processes/sandbox-state.ts +53 -6
  179. package/packages/core/src/processes/tick-publication.ts +2 -0
  180. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  181. package/packages/core/src/scenarios/harness.ts +0 -5
  182. package/packages/core/src/store/account-redaction.ts +1 -0
  183. package/packages/core/src/store/adapter.ts +52 -1
  184. package/packages/core/src/store/agent-context.ts +432 -0
  185. package/packages/core/src/store/build-feed.ts +291 -0
  186. package/packages/core/src/store/build-scope.ts +19 -1
  187. package/packages/core/src/store/contract.ts +911 -14
  188. package/packages/core/src/store/digest.ts +19 -6
  189. package/packages/core/src/store/histogram.ts +113 -0
  190. package/packages/core/src/store/local/schema.ts +62 -0
  191. package/packages/core/src/store/local/store.ts +628 -22
  192. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  193. package/packages/core/src/store/memory.ts +461 -69
  194. package/packages/core/src/store/open-builds.ts +19 -0
  195. package/packages/core/src/store/phase-session.ts +32 -4
  196. package/packages/core/src/store/reduced-reads.ts +14 -4
  197. package/packages/core/src/store/reducer-value-shapes.json +7027 -5751
  198. package/packages/core/src/store/reducer-values.ts +6 -1
  199. package/packages/core/src/store/remote/client.ts +208 -2
  200. package/packages/core/src/store/remote/compatibility.ts +1 -1
  201. package/packages/core/src/store/remote/index.ts +33 -0
  202. package/packages/core/src/store/remote/protocol.ts +69 -0
  203. package/packages/core/src/store/remote/released-clients.json +22 -0
  204. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  205. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  206. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  207. package/packages/core/src/store/retention.ts +23 -1
  208. package/packages/core/src/store/rollups.ts +337 -0
  209. package/packages/core/src/store/session-handle.ts +20 -2
  210. package/packages/core/src/store/snapshots.ts +10 -0
  211. package/packages/core/src/store/types.ts +108 -9
  212. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  213. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  214. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  215. package/packages/core/src/testing/index.ts +27 -0
  216. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  217. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  218. package/packages/core/src/web/analytics-source.ts +303 -0
  219. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  220. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  221. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  222. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  223. package/packages/core/src/web/assets/app.css +1 -0
  224. package/packages/core/src/web/assets/app.js +9 -0
  225. package/packages/core/src/web/assets/manifest.json +31 -0
  226. package/packages/core/src/web/assets/theme.js +1 -0
  227. package/packages/core/src/web/bounded.ts +31 -0
  228. package/packages/core/src/web/http.ts +315 -0
  229. package/packages/core/src/web/hub.ts +160 -0
  230. package/packages/core/src/web/options.ts +38 -0
  231. package/packages/core/src/web/overview-source.ts +322 -0
  232. package/packages/core/src/web/page.ts +56 -0
  233. package/packages/core/src/web/protocol.ts +151 -0
  234. package/packages/core/src/web/read-only.ts +23 -0
  235. package/packages/core/src/web/repository-source.ts +39 -0
  236. package/packages/core/src/web/server.ts +97 -0
  237. package/skills/code-review/SKILL.md +10 -2
  238. package/skills/guide/SKILL.md +376 -54
  239. package/skills/guide/references/accounts.md +2 -1
  240. package/skills/guide/references/integration-tree.md +2 -2
  241. package/skills/guide/references/operator-api.md +134 -6
  242. package/skills/guide/references/optimization-nodes.md +69 -11
  243. package/skills/guide/references/plugin-authoring.md +37 -1
  244. package/skills/guide/references/remote-store-protocol.md +94 -13
  245. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  246. package/skills/guide/references/restacking.md +20 -4
  247. package/skills/guide/references/setup.md +14 -2
  248. package/skills/guide/references/ticket-dependencies.md +10 -3
  249. package/skills/implement/SKILL.md +23 -4
  250. package/skills/operate/SKILL.md +134 -32
  251. package/skills/plan/SKILL.md +10 -4
  252. package/skills/plan-review/SKILL.md +9 -2
  253. package/skills/spec/SKILL.md +34 -8
  254. package/skills/tickets/SKILL.md +51 -5
  255. package/templates/hosted-service/package.json +2 -2
@@ -1,6 +1,7 @@
1
1
  import { readBuildPage } from '../store/event-reads'
2
2
  import { abortDestinationSchema, unmeasuredSettlementPolicySchema } from '../events/payloads'
3
3
  import { readRepositoryAttentionPage } from './repository-events'
4
+ import { getOperatorAttention } from './attention'
4
5
  import { requestNodeRestack } from './restack'
5
6
  import { reviseObjective, settleUnmeasuredAttempt, stopObjective } from './optimization'
6
7
  import { objectiveEpsilonSchema } from '../objective'
@@ -47,7 +48,14 @@ import type { Via } from '../events/envelope'
47
48
  import { bulkControlRepository, BulkWalkError } from '../cli/bulk-control'
48
49
  import { systemClock, type BuildStore, type Clock } from '../store/types'
49
50
  import { TicketOperationError } from '../ports/tickets/operations'
51
+ import { TicketSearchCursorInvalid, TicketSearchUnsupported } from '../ports/tickets/search'
50
52
  import { controlTicketStart } from './ticket-start'
53
+ import {
54
+ attachOperatorTicketAsset,
55
+ getOperatorTicketAsset,
56
+ removeOperatorTicketAsset,
57
+ } from './ticket-assets'
58
+ import { TICKET_ASSET_MAX_BYTES, TicketAssetValidationError } from '../store/ticket-assets'
51
59
  import { OPERATOR_NOTES_REPO_KIND } from '../store/retention'
52
60
  import {
53
61
  clearForgeDegradation,
@@ -86,13 +94,23 @@ import {
86
94
  RouteRefusalError,
87
95
  } from './requests'
88
96
  import { SandboxOperationError } from '../ports/workspace/operator-sandbox'
97
+ import { readAgentContext } from '../store/agent-context'
98
+ import {
99
+ contextIndex,
100
+ contextSource,
101
+ readContextFile,
102
+ type CanonicalSkillBundle,
103
+ } from './agent-context-serve'
104
+ import { defaultCanonicalSkills } from './canonical-skills'
89
105
  import type { OperatorSandboxService } from './sandbox'
106
+ import { SandboxUnavailableError } from './sandbox-resolver'
90
107
  import {
91
108
  prepareOperatorTicketAssets,
92
109
  listOperatorTicketStates,
93
110
  createOperatorTicketState,
94
111
  getOperatorTicket,
95
112
  listOperatorTickets,
113
+ searchOperatorTickets,
96
114
  mutateOperatorTicket,
97
115
  type OperatorTicketBackend,
98
116
  } from './tickets'
@@ -115,6 +133,15 @@ export interface ToolContext {
115
133
  via?: Via
116
134
  /** The operator-sandbox backend; required only by the sandbox tools. */
117
135
  sandbox?: OperatorSandboxService
136
+ /** Lazy per-call backend resolution (the hosted mode): invoked only by a
137
+ * sandbox handler, and only when `sandbox` is absent. It may throw
138
+ * `SandboxUnavailableError`, which maps to a typed `sandbox-<reason>`
139
+ * refusal. */
140
+ sandboxFor?: () => Promise<OperatorSandboxService>
141
+ /** The canonical skill bundle the context tools serve when a repository
142
+ * has no captured agent context. Default: the serving distribution's
143
+ * `skills/` tree, read once per process. */
144
+ canonicalSkills?: () => Promise<CanonicalSkillBundle>
118
145
  }
119
146
 
120
147
  /** The failure body shape the operator API emits, mapped one-to-one so a tool
@@ -125,6 +152,8 @@ export interface ToolFailureBody {
125
152
  error: string
126
153
  code?: string
127
154
  progress?: unknown
155
+ /** The operator sandbox's lifecycle state, on `sandbox-not-ready`. */
156
+ state?: string
128
157
  }
129
158
 
130
159
  export type RegistryErrorReason =
@@ -204,15 +233,15 @@ function ticketsOf(ctx: ToolContext): OperatorTicketBackend {
204
233
  return ctx.tickets
205
234
  }
206
235
 
207
- /** The sandbox tools need the backend; same refusal shape as `ticketsOf`. */
208
- function sandboxOf(ctx: ToolContext): OperatorSandboxService {
209
- if (ctx.sandbox === undefined) {
210
- throw new RouteRefusalError({
211
- kind: 'conflict',
212
- error: 'operator sandbox backend is not configured',
213
- })
214
- }
215
- return ctx.sandbox
236
+ /** The sandbox tools need the backend: the static one, else the call's lazy
237
+ * resolution; otherwise the same refusal shape as `ticketsOf`. */
238
+ async function sandboxOf(ctx: ToolContext): Promise<OperatorSandboxService> {
239
+ if (ctx.sandbox !== undefined) return ctx.sandbox
240
+ if (ctx.sandboxFor !== undefined) return ctx.sandboxFor()
241
+ throw new RouteRefusalError({
242
+ kind: 'conflict',
243
+ error: 'operator sandbox backend is not configured',
244
+ })
216
245
  }
217
246
 
218
247
  /** Extend every member of a request-union schema with shared routing fields
@@ -254,6 +283,118 @@ const buildDetailInput = z.strictObject({ repo: repoField, slug: slugField })
254
283
 
255
284
  const ticketDetailInput = z.strictObject({ repo: repoField, id: ticketIdField })
256
285
 
286
+ const contextListInput = z.strictObject({ repo: repoField })
287
+ const contextReadInput = z.strictObject({
288
+ repo: repoField,
289
+ path: z
290
+ .string()
291
+ .min(1)
292
+ .describe(
293
+ 'A path from context.list (e.g. ".agents/skills/ab-operate/SKILL.md" or "AGENTS.md"), or a relative link from a file you read, with `from`.',
294
+ ),
295
+ from: z
296
+ .string()
297
+ .min(1)
298
+ .optional()
299
+ .describe(
300
+ 'The path of the file whose relative link `path` is (e.g. ".agents/skills/ab-spec/SKILL.md" with path "../ab-guide/references/spec-standard.md").',
301
+ ),
302
+ })
303
+
304
+ /** The context view for one repository: its captured record (one
305
+ * latest-revision artifact read), else the canonical bundle. A record that
306
+ * fails to decode propagates; it never falls back. */
307
+ async function contextViewFor(ctx: ToolContext, repo: string) {
308
+ const captured = await readAgentContext(ctx.store, repo)
309
+ if (captured !== null) return contextSource(captured.record, null)
310
+ return contextSource(null, await (ctx.canonicalSkills ?? defaultCanonicalSkills)())
311
+ }
312
+
313
+ /** Strict, padded standard base64: whole 4-character groups of the standard
314
+ * alphabet, `=` only as one or two trailing pad characters. Buffer.from would
315
+ * silently drop anything else. A linear scan, not a regex: a repeated-group
316
+ * pattern exhausts the regex engine on multi-megabyte payloads. */
317
+ function isPaddedBase64(value: string): boolean {
318
+ if (value.length % 4 !== 0) return false
319
+ const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0
320
+ for (let i = 0; i < value.length - padding; i++) {
321
+ const c = value.charCodeAt(i)
322
+ const ok =
323
+ (c >= 65 && c <= 90) || // A-Z
324
+ (c >= 97 && c <= 122) || // a-z
325
+ (c >= 48 && c <= 57) || // 0-9
326
+ c === 43 || // +
327
+ c === 47 // /
328
+ if (!ok) return false
329
+ }
330
+ return true
331
+ }
332
+
333
+ const contentBase64Field = z
334
+ .string()
335
+ .max(Math.ceil(TICKET_ASSET_MAX_BYTES / 3) * 4)
336
+ .refine(isPaddedBase64, { message: 'contentBase64 must be padded standard base64' })
337
+ .describe('The file’s exact bytes, standard padded base64 ("" for an empty file).')
338
+ const assetKindField = z
339
+ .string()
340
+ .min(1)
341
+ .describe('Asset kind, a label such as "design" or "reference".')
342
+ const assetNameField = z
343
+ .string()
344
+ .min(1)
345
+ .describe('Asset name, unique per kind on the ticket (e.g. "checkout-canvas").')
346
+ const ticketAssetAttachInput = z.strictObject({
347
+ repo: repoField,
348
+ id: ticketIdField,
349
+ kind: assetKindField,
350
+ name: assetNameField,
351
+ layout: z
352
+ .enum(['file', 'tree'])
353
+ .describe(
354
+ '"file": exactly one file entry, a single-file asset. "tree": any number of entries, a folder (an empty tree is allowed).',
355
+ ),
356
+ entries: z
357
+ .array(
358
+ z.discriminatedUnion('type', [
359
+ z.strictObject({
360
+ type: z.literal('file'),
361
+ path: z
362
+ .string()
363
+ .describe('Relative "/"-separated path inside the asset (e.g. "img/a.png").'),
364
+ contentBase64: contentBase64Field,
365
+ }),
366
+ z.strictObject({
367
+ type: z.literal('dir'),
368
+ path: z
369
+ .string()
370
+ .describe('Relative "/"-separated path of an explicit, possibly empty, directory.'),
371
+ }),
372
+ ]),
373
+ )
374
+ .describe('The asset’s files and explicit directories.'),
375
+ })
376
+ const ticketAssetGetInput = z.strictObject({
377
+ repo: repoField,
378
+ id: ticketIdField,
379
+ kind: assetKindField,
380
+ name: assetNameField,
381
+ rev: z
382
+ .number()
383
+ .int()
384
+ .min(0)
385
+ .safe()
386
+ .optional()
387
+ .describe(
388
+ 'Exact revision to read. Omit for the latest; a removed asset is readable only by revision.',
389
+ ),
390
+ })
391
+ const ticketAssetRemoveInput = z.strictObject({
392
+ repo: repoField,
393
+ id: ticketIdField,
394
+ kind: assetKindField,
395
+ name: assetNameField,
396
+ })
397
+
257
398
  const objectiveReviseInput = z
258
399
  .strictObject({
259
400
  repo: repoField,
@@ -409,6 +550,19 @@ const repositoryEventsInput = z.strictObject({
409
550
  ),
410
551
  })
411
552
 
553
+ const repositoryAttentionInput = z.strictObject({
554
+ repo: repoField,
555
+ cursor: z
556
+ .number()
557
+ .int()
558
+ .min(0)
559
+ .safe()
560
+ .optional()
561
+ .describe(
562
+ 'Repository journal cursor from the previous attention call: report attention events with seq strictly greater than this. Omit on the first call to receive no events and a baseline cursor for the current head.',
563
+ ),
564
+ })
565
+
412
566
  const buildsAnswerInput = extendUnion(answerRequestSchema, { repo: repoField, slug: slugField })
413
567
 
414
568
  const buildsReopenInput = reopenRequestSchema.extend({ repo: repoField, slug: slugField })
@@ -466,6 +620,33 @@ const ticketsListInput = z.strictObject({
466
620
  ),
467
621
  })
468
622
 
623
+ const ticketsSearchInput = z.strictObject({
624
+ repo: repoField,
625
+ query: z
626
+ .string()
627
+ .regex(/\S/, 'query must contain a nonblank word')
628
+ .describe(
629
+ 'Words to find in ticket titles and bodies; every word must appear, case-insensitively.',
630
+ ),
631
+ state: z
632
+ .string()
633
+ .min(1)
634
+ .optional()
635
+ .describe(
636
+ 'Only tickets in this provider state; omitted searches every state, including completed and rejected tickets.',
637
+ ),
638
+ labels: z
639
+ .array(z.string().min(1))
640
+ .optional()
641
+ .describe('Only tickets carrying every named label.'),
642
+ limit: z.number().int().min(1).max(100).optional().describe('Page size; default 20.'),
643
+ cursor: z
644
+ .string()
645
+ .min(1)
646
+ .optional()
647
+ .describe('The `cursor` from the previous page of the same search.'),
648
+ })
649
+
469
650
  const ticketsCreateInput = ticketCreateRequestSchema.extend({ repo: repoField })
470
651
 
471
652
  const ticketsUpdateInput = ticketUpdateRequestSchema
@@ -603,6 +784,10 @@ const sandboxWriteFileInput = z.strictObject({
603
784
  })
604
785
 
605
786
  const sandboxResetInput = z.strictObject({ repo: repoField })
787
+ const sandboxOpenInput = z.strictObject({ repo: repoField })
788
+ const sandboxStatusInput = z.strictObject({ repo: repoField })
789
+ const sandboxCloseInput = z.strictObject({ repo: repoField })
790
+ const sandboxRefreshInput = z.strictObject({ repo: repoField })
606
791
 
607
792
  const sandboxPublishInput = z.strictObject({
608
793
  repo: repoField,
@@ -619,7 +804,7 @@ const sandboxPublishInput = z.strictObject({
619
804
  .min(1)
620
805
  .optional()
621
806
  .describe(
622
- 'Optional commit-ish to publish instead of the checkout HEAD; must resolve to a commit that is a descendant of the base head recorded at provision or reset time.',
807
+ 'Optional commit-ish to publish instead of the checkout HEAD; must resolve to a commit that is a descendant of the base head recorded at provision, refresh, or reset time.',
623
808
  ),
624
809
  })
625
810
 
@@ -888,7 +1073,7 @@ export const TOOLS: readonly ToolEntry[] = [
888
1073
  ),
889
1074
  defineTool(
890
1075
  'builds.answer',
891
- 'Answer a blocked build’s open escalations: guidance text, a bare retry, a dismissal of the cited findings, a review-round ceiling, or a spec revision (destructive — replaces the spec). Leaves require an escalation and restart from plan; idle collecting or verification-failed nodes may revise without an escalation and recollect for verification.',
1076
+ 'Answer a blocked build’s open escalations: guidance text, a bare retry, a dismissal of the cited findings, a review-round ceiling, accept-target (answers only a leaf’s target-rewritten escalation: restack its own commits onto the rewritten target), or a spec revision (destructive — replaces the spec). Leaves require an escalation and restart from plan; idle collecting or verification-failed nodes may revise without an escalation and recollect for verification.',
892
1077
  buildsAnswerInput,
893
1078
  'The controlBuild answer result: {kind: "answered", slug, count, resolution, resumed, …} describing how many escalations were answered and with what.',
894
1079
  async (raw, ctx) => {
@@ -967,7 +1152,7 @@ export const TOOLS: readonly ToolEntry[] = [
967
1152
  'repository.status',
968
1153
  'Report one repository’s durable dispatcher settings and journal state.',
969
1154
  repositoryStatusInput,
970
- 'The repository status projection: ticket intake, repository-wide pause, claim-time auto-merge default, and the harvest/dispatch journal state the sessionless CLI and dashboard read. operator.presence is "unavailable" here because this tool does not load presence registrations; that is not evidence that no operator is present.',
1155
+ 'The repository status projection: dispatcherRunning is true for a holder, expired holder or unfinished draining handoff; ticket intake, repository-wide pause, claim-time auto-merge default, and the harvest/dispatch journal state the sessionless CLI and dashboard read. operator.presence is "unavailable" here because this tool does not load presence registrations; that is not evidence that no operator is present.',
971
1156
  async (raw, ctx) => {
972
1157
  const input = raw as z.infer<typeof repositoryStatusInput>
973
1158
  return getRepositoryStatus(ctx.store, input.repo)
@@ -987,6 +1172,21 @@ export const TOOLS: readonly ToolEntry[] = [
987
1172
  })
988
1173
  },
989
1174
  ),
1175
+ defineTool(
1176
+ 'repository.attention',
1177
+ 'One read of everything waiting on the operator for a repository — blocked builds with their open escalation questions, merges awaiting consent or held, repository attention events after the cursor, builds paused/stalled/failing verification, and dispatcher attention — each item naming the tool call that resolves it. The first call of each operator round.',
1178
+ repositoryAttentionInput,
1179
+ '{repo, generatedAt, escalations, merges, events: {items, cursor, hasMore}, waiting, dispatcher}. escalations: open builds with open escalations (as builds.get reports them), wait-only builds excluded. merges: the merges.list entries with each build’s PR. events: the repository.events attention page after the cursor; pass events.cursor back next call. waiting: builds paused, stalled (live lease, no durable event for an hour), failing node verification or failing forge CI, each with a reason and detail. dispatcher: no holder, a current upgrade failure, a rollback hold or a forge cooldown from repository.status. Every item carries resolve: [{tool, input, by, note?}], primary first; input is partial, and by "human" means no agent call fixes it — the tool reads the evidence to report. An omitted cursor returns no events and a baseline cursor beside every current-state section; an expired cursor fails with code "cursor-too-old": call again without one.',
1180
+ async (raw, ctx) => {
1181
+ const input = raw as z.infer<typeof repositoryAttentionInput>
1182
+ return getOperatorAttention({
1183
+ store: ctx.store,
1184
+ repo: input.repo,
1185
+ ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),
1186
+ now: ctx.clock(),
1187
+ })
1188
+ },
1189
+ ),
990
1190
  defineTool(
991
1191
  'repository.settings',
992
1192
  'Set or toggle a durable repository setting: ticket intake or the claim-time auto-merge default.',
@@ -1115,11 +1315,30 @@ export const TOOLS: readonly ToolEntry[] = [
1115
1315
  })
1116
1316
  },
1117
1317
  ),
1318
+ defineTool(
1319
+ 'tickets.search',
1320
+ 'Search the repository’s tickets by title and body text across every state, to find duplicates before filing. Sources without search refuse; nothing falls back to listing.',
1321
+ ticketsSearchInput,
1322
+ '{tickets, cursor?, diagnostics}: matches as {id, title, state, labels, kind, target?} in source order; cursor continues the search and is absent on the last page.',
1323
+ async (raw, ctx) => {
1324
+ const input = raw as z.infer<typeof ticketsSearchInput>
1325
+ return searchOperatorTickets({
1326
+ store: ctx.store,
1327
+ repo: input.repo,
1328
+ backend: ticketsOf(ctx),
1329
+ query: input.query,
1330
+ ...(input.state !== undefined ? { state: input.state } : {}),
1331
+ ...(input.labels !== undefined ? { labels: input.labels } : {}),
1332
+ ...(input.limit !== undefined ? { limit: input.limit } : {}),
1333
+ ...(input.cursor !== undefined ? { cursor: input.cursor } : {}),
1334
+ })
1335
+ },
1336
+ ),
1118
1337
  defineTool(
1119
1338
  'tickets.get',
1120
- 'Show one ticket with its hosted comments, blockers and any related build.',
1339
+ 'Show one ticket with its hosted comments, blockers, any related build and its current assets.',
1121
1340
  ticketDetailInput,
1122
- '{ticket, blockers, build}: the ticket (including hosted ticket.comments when available), its dependency states, and the most relevant build for it (null when none).',
1341
+ '{ticket, blockers, build, assets}: the ticket (including hosted ticket.comments when available), its dependency states, the most relevant build for it (null when none), and its current assets as `ab ticket show --json` lists them, each {kind, name, revision, size, layout, fileCount}.',
1123
1342
  async (raw, ctx) => {
1124
1343
  const input = raw as z.infer<typeof ticketDetailInput>
1125
1344
  return getOperatorTicket({
@@ -1265,6 +1484,46 @@ export const TOOLS: readonly ToolEntry[] = [
1265
1484
  })
1266
1485
  },
1267
1486
  ),
1487
+ defineTool(
1488
+ 'tickets.asset.attach',
1489
+ 'Attach one asset to a ticket by kind and name, like `ab ticket attach`: a single file (layout "file") or a folder (layout "tree"), with every file’s bytes as base64. Each attach stores a new revision; earlier revisions stay retrievable with tickets.asset.get rev. The CLI’s naming, path and layout rules apply, and so does the store’s size limit (25 MiB of file bytes by default, lower on stores with a request ceiling; a remote MCP transport may bound requests lower still). Leaves a note on the ticket. A build freezes its assets at the claim, so a running build keeps the ones it has.',
1490
+ ticketAssetAttachInput,
1491
+ '{asset, replaced, activeBuilds, noteError?}: the stored revision’s metadata (as `ab ticket attach --json` prints it), whether it replaced a current asset of that kind and name, the active builds for the ticket that keep their frozen assets, and noteError when the asset was stored but the note failed (do not retry: that stores another revision).',
1492
+ async (raw, ctx) => {
1493
+ const input = raw as z.infer<typeof ticketAssetAttachInput>
1494
+ attributed(ctx)
1495
+ return attachOperatorTicketAsset({ store: ctx.store, backend: ticketsOf(ctx), ...input })
1496
+ },
1497
+ ),
1498
+ defineTool(
1499
+ 'tickets.asset.get',
1500
+ 'Read one ticket asset, like `ab ticket asset get`: the latest revision, or an exact one by rev. Each file entry carries its exact bytes as base64.',
1501
+ ticketAssetGetInput,
1502
+ '{asset, entries}: the revision’s metadata and its entries in manifest order, each {type: "file", path, size, contentBase64} or {type: "dir", path}. Decode contentBase64 to recover the exact bytes.',
1503
+ async (raw, ctx) => {
1504
+ const input = raw as z.infer<typeof ticketAssetGetInput>
1505
+ return getOperatorTicketAsset({
1506
+ store: ctx.store,
1507
+ backend: ticketsOf(ctx),
1508
+ repo: input.repo,
1509
+ id: input.id,
1510
+ kind: input.kind,
1511
+ name: input.name,
1512
+ ...(input.rev !== undefined ? { rev: input.rev } : {}),
1513
+ })
1514
+ },
1515
+ ),
1516
+ defineTool(
1517
+ 'tickets.asset.remove',
1518
+ 'Destructive: remove one asset from the ticket’s current assets, like `ab ticket asset rm`. Its revisions stay retrievable with tickets.asset.get rev. Leaves a note on the ticket; running builds keep the assets they froze at the claim.',
1519
+ ticketAssetRemoveInput,
1520
+ '{removed, activeBuilds, noteError?}: the metadata of the revision that was current, the active builds for the ticket, and noteError when the asset was removed but the note failed.',
1521
+ async (raw, ctx) => {
1522
+ const input = raw as z.infer<typeof ticketAssetRemoveInput>
1523
+ attributed(ctx)
1524
+ return removeOperatorTicketAsset({ store: ctx.store, backend: ticketsOf(ctx), ...input })
1525
+ },
1526
+ ),
1268
1527
  defineTool(
1269
1528
  'notes.read',
1270
1529
  'Read the repository’s operator-notes artifact — the shared notes an operator agent leaves for the next round.',
@@ -1305,24 +1564,64 @@ export const TOOLS: readonly ToolEntry[] = [
1305
1564
  return { revision: meta.revision, blobRef: meta.blobRef, createdAt: meta.createdAt }
1306
1565
  },
1307
1566
  ),
1567
+ defineTool(
1568
+ 'sandbox.open',
1569
+ 'Open your operator sandbox, a persistent, credential-free environment provisioned from the repository, and return at once. Provisioning or resuming continues in the background; poll sandbox.status until it reports ready. Other sandbox tools refuse with code "sandbox-not-ready" until then. Idempotent: opening a ready or in-flight environment changes nothing.',
1570
+ sandboxOpenInput,
1571
+ '{state, environmentId, provider, baseSha?, failure?}: state is provisioning, resuming, ready, or failed; baseSha is the recorded base head once ready; failure ({stage, message}) explains a failed attempt.',
1572
+ async (raw, ctx) => {
1573
+ const input = raw as z.infer<typeof sandboxOpenInput>
1574
+ return (await sandboxOf(ctx)).open(attributed(ctx), input)
1575
+ },
1576
+ ),
1577
+ defineTool(
1578
+ 'sandbox.status',
1579
+ "Report your operator sandbox's lifecycle state: absent, provisioning, resuming, ready, stopped, or failed, plus the checkout head and the base head recorded at provisioning (or the last refresh or reset). Its only write records a finished background attempt's outcome, exactly once. Safe to poll; it never resumes a stopped environment or keeps an idle one alive.",
1580
+ sandboxStatusInput,
1581
+ "{state, environmentId, provider, headSha?, baseSha?, failure?, lastEvidenceAt?}: the lifecycle state, the checkout head when ready, the recorded base head, a failed attempt's {stage, message}, and the latest journaled evidence time.",
1582
+ async (raw, ctx) => {
1583
+ const input = raw as z.infer<typeof sandboxStatusInput>
1584
+ return (await sandboxOf(ctx)).status(attributed(ctx), input)
1585
+ },
1586
+ ),
1587
+ defineTool(
1588
+ 'sandbox.close',
1589
+ 'Close your operator sandbox: stop the environment and its detached commands and release provider capacity, keeping the checkout and any uncommitted work. A later sandbox.open resumes it. Cancels an in-flight provision. Closing an environment that does not exist succeeds and does nothing.',
1590
+ sandboxCloseInput,
1591
+ '{outcome, environmentId}: outcome is "closed", or "noop" when there was nothing to close.',
1592
+ async (raw, ctx) => {
1593
+ const input = raw as z.infer<typeof sandboxCloseInput>
1594
+ return (await sandboxOf(ctx)).close(attributed(ctx), input)
1595
+ },
1596
+ ),
1597
+ defineTool(
1598
+ 'sandbox.refresh',
1599
+ 'Fast-forward your operator sandbox\'s clean checkout to the current base-branch head and record that head as the publication base. Not destructive: a checkout with uncommitted changes refuses with code "sandbox-refresh-dirty", and one whose commits diverge from the base refuses with code "sandbox-refresh-diverged"; a refusal changes nothing. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code "sandbox-not-ready" naming the state.',
1600
+ sandboxRefreshInput,
1601
+ '{outcome, headSha, baseSha, previousHeadSha}: outcome is "refreshed" (fast-forwarded) or "current" (the checkout already contains the base head).',
1602
+ async (raw, ctx) => {
1603
+ const input = raw as z.infer<typeof sandboxRefreshInput>
1604
+ return (await sandboxOf(ctx)).refresh(attributed(ctx), input)
1605
+ },
1606
+ ),
1308
1607
  defineTool(
1309
1608
  'sandbox.exec',
1310
- 'Run one shell command inside your operator sandbox: a persistent, credential-free environment provisioned from the repository (first call provisions; later calls reuse it). The command waits at most 300 seconds; on expiry it is killed and the tool fails with code "sandbox-exec-timeout". Stdout and stderr are each truncated at 65,536 bytes with a "[truncated by autobuild: output exceeded 65536 bytes]" marker. The environment holds no store, forge, or model credentials — the typed tools remain the only route to build state.',
1609
+ 'Run one shell command inside your operator sandbox, a persistent, credential-free environment provisioned from the repository. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code "sandbox-not-ready" naming the state. The command waits at most 300 seconds; on expiry it is killed and the tool fails with code "sandbox-exec-timeout". Stdout and stderr are each truncated at 65,536 bytes with a "[truncated by autobuild: output exceeded 65536 bytes]" marker. The environment holds no store, forge, or model credentials — the typed tools remain the only route to build state.',
1311
1610
  sandboxExecInput,
1312
1611
  '{exitCode, stdout, stderr}: the command’s exit status and truncated output streams.',
1313
1612
  async (raw, ctx) => {
1314
1613
  const input = raw as z.infer<typeof sandboxExecInput>
1315
- return sandboxOf(ctx).exec(attributed(ctx), input)
1614
+ return (await sandboxOf(ctx)).exec(attributed(ctx), input)
1316
1615
  },
1317
1616
  ),
1318
1617
  defineTool(
1319
1618
  'sandbox.start',
1320
- 'Launch one shell command detached inside your operator sandbox and return immediately. Pair with sandbox.wait to observe it. Calls against one environment are serialized; a detached command is tracked only by the serving process.',
1619
+ 'Launch one shell command detached inside your operator sandbox and return immediately. Pair with sandbox.wait to observe it. Calls against one environment are serialized; a detached command is tracked only by the serving process. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code "sandbox-not-ready" naming the state.',
1321
1620
  sandboxStartInput,
1322
1621
  '{commandId}: the id to pass to sandbox.wait.',
1323
1622
  async (raw, ctx) => {
1324
1623
  const input = raw as z.infer<typeof sandboxStartInput>
1325
- return sandboxOf(ctx).start(attributed(ctx), input)
1624
+ return (await sandboxOf(ctx)).start(attributed(ctx), input)
1326
1625
  },
1327
1626
  ),
1328
1627
  defineTool(
@@ -1332,17 +1631,17 @@ export const TOOLS: readonly ToolEntry[] = [
1332
1631
  '{state, exitCode?, stdout?, stderr?}: the command state; once exited, its exit code and truncated output streams; while running, the streamed output so far when the provider reports it (Vercel reports output only after exit).',
1333
1632
  async (raw, ctx) => {
1334
1633
  const input = raw as z.infer<typeof sandboxWaitInput>
1335
- return sandboxOf(ctx).wait(attributed(ctx), input)
1634
+ return (await sandboxOf(ctx)).wait(attributed(ctx), input)
1336
1635
  },
1337
1636
  ),
1338
1637
  defineTool(
1339
1638
  'sandbox.read_file',
1340
- 'Read one file from your operator sandbox, rooted at the checkout. Absolute paths and ".." escapes are refused.',
1639
+ 'Read one file from your operator sandbox, rooted at the checkout. Absolute paths and ".." escapes are refused. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code "sandbox-not-ready" naming the state.',
1341
1640
  sandboxReadFileInput,
1342
1641
  '{encoding, content}: the file bytes — "utf8" when they decode as UTF-8, else "base64".',
1343
1642
  async (raw, ctx) => {
1344
1643
  const input = raw as z.infer<typeof sandboxReadFileInput>
1345
- const bytes = await sandboxOf(ctx).readFile(attributed(ctx), input)
1644
+ const bytes = await (await sandboxOf(ctx)).readFile(attributed(ctx), input)
1346
1645
  const decoded = new TextDecoder('utf-8').decode(bytes)
1347
1646
  if (!decoded.includes('\uFFFD')) {
1348
1647
  return { encoding: 'utf8', content: decoded }
@@ -1352,34 +1651,33 @@ export const TOOLS: readonly ToolEntry[] = [
1352
1651
  ),
1353
1652
  defineTool(
1354
1653
  'sandbox.write_file',
1355
- 'Write one file inside your operator sandbox, rooted at the checkout (parent directories are created). Absolute paths and ".." escapes are refused; content is bounded at 1 MiB after decoding.',
1654
+ 'Write one file inside your operator sandbox, rooted at the checkout (parent directories are created). Absolute paths and ".." escapes are refused; content is bounded at 1 MiB after decoding. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code "sandbox-not-ready" naming the state.',
1356
1655
  sandboxWriteFileInput,
1357
1656
  '{path}: the written path, confirming the durable write.',
1358
1657
  async (raw, ctx) => {
1359
1658
  const input = raw as z.infer<typeof sandboxWriteFileInput>
1360
- await sandboxOf(ctx).writeFile(attributed(ctx), input)
1659
+ await (await sandboxOf(ctx)).writeFile(attributed(ctx), input)
1361
1660
  return { path: input.path }
1362
1661
  },
1363
1662
  ),
1364
1663
  defineTool(
1365
1664
  'sandbox.reset',
1366
- 'Destructively reset your operator sandbox: discard every change, purge the environment and its snapshots, and re-provision fresh from the current base branch head. Use when the environment is wedged or its checkout is dirty beyond repair.',
1665
+ 'Destructively reset your operator sandbox: discard every change, purge the environment and its snapshots, and re-provision fresh from the current base branch head. Returns at once while the fresh provision continues in the background; poll sandbox.status until it reports ready. Use when the environment is wedged or its checkout is dirty beyond repair; sandbox.refresh updates a clean checkout without discarding anything.',
1367
1666
  sandboxResetInput,
1368
- '{ok: true}: the environment was released and re-provisioned from the current base head.',
1667
+ '{state, environmentId, provider, baseSha?, failure?}: the sandbox.open result for the fresh provision, normally state "provisioning".',
1369
1668
  async (raw, ctx) => {
1370
1669
  const input = raw as z.infer<typeof sandboxResetInput>
1371
- await sandboxOf(ctx).reset(attributed(ctx), input)
1372
- return { ok: true as const }
1670
+ return (await sandboxOf(ctx)).reset(attributed(ctx), input)
1373
1671
  },
1374
1672
  ),
1375
1673
  defineTool(
1376
1674
  'sandbox.publish',
1377
- "Publish your operator sandbox's work as a pull request: push the checkout's current head commit (or an explicit commit) to your operator's dedicated branch and open or update a PR against the base branch. Refuses when the checkout has uncommitted changes (tracked or untracked; the sandbox's own provisioning marker is excluded), when the commit is not a descendant of the base head recorded at provision or reset time, or when the base branch head itself would be published. The sandbox itself never pushes and holds no credential — the push and PR creation are kernel plumbing; a publication is a durable repository-journal fact. PR only: the base branch is never pushed to.",
1675
+ "Publish your operator sandbox's work as a pull request: push the checkout's current head commit (or an explicit commit) to your operator's dedicated branch and open or update a PR against the base branch. Refuses when the checkout has uncommitted changes (tracked or untracked; the sandbox's own provisioning marker is excluded), when the commit is not a descendant of the base head recorded at provision, refresh, or reset time, or when the base branch head itself would be published. The sandbox itself never pushes and holds no credential — the push and PR creation are kernel plumbing; a publication is a durable repository-journal fact. PR only: the base branch is never pushed to. The environment must be open and ready first (sandbox.open, then sandbox.status); otherwise the call refuses with code \"sandbox-not-ready\" naming the state.",
1378
1676
  sandboxPublishInput,
1379
1677
  '{branch, sha, pr: {number, url, headSha}}: the publication branch, the published commit, and the opened or updated pull request.',
1380
1678
  async (raw, ctx) => {
1381
1679
  const input = raw as z.infer<typeof sandboxPublishInput>
1382
- return sandboxOf(ctx).publish(attributed(ctx), {
1680
+ return (await sandboxOf(ctx)).publish(attributed(ctx), {
1383
1681
  repo: input.repo,
1384
1682
  title: input.title,
1385
1683
  ...(input.body !== undefined ? { body: input.body } : {}),
@@ -1388,6 +1686,29 @@ export const TOOLS: readonly ToolEntry[] = [
1388
1686
  })
1389
1687
  },
1390
1688
  ),
1689
+ defineTool(
1690
+ 'context.list',
1691
+ 'Call first: the repository’s agent context — its skills (name, description, files) and its agent instructions files (AGENTS.md / CLAUDE.md, with scopes and imports), captured from the base branch, and which to load before operating and before ticket work. A repository with no captured context lists the canonical skills bundled with this Autobuild and reports agent instructions absent.',
1692
+ contextListInput,
1693
+ '{repo, source: "captured"|"canonical", commit, baseBranch?, version?, notice?, skills: [{name, description, paths, entry, files}], instructions: [{path, aliases, scope, imports}], imports: [{path, importedBy}], load: {beforeOperating, beforeTicketWork}}: load entries are paths for context.read.',
1694
+ async (raw, ctx) => {
1695
+ const input = raw as z.infer<typeof contextListInput>
1696
+ return contextIndex(await contextViewFor(ctx, input.repo), input.repo)
1697
+ },
1698
+ ),
1699
+ defineTool(
1700
+ 'context.read',
1701
+ 'Read one skill file or agent instructions file from the repository’s agent context, by a path from context.list or a relative link with `from`. A SKILL.md (and any skill file that mentions `ab` commands) returns with a generated preamble that maps each `ab` command it mentions to the tool that performs it, or says it has no tool; an agent instructions file returns with a preamble framing it as the repository’s own file, which takes precedence over Autobuild skills.',
1702
+ contextReadInput,
1703
+ '{path, kind: "skill"|"skill-file"|"instructions"|"import", skill?, scope?, source, commit, text | contentBase64, links: [{href, path}]}: text is the preamble, a "---" line, then the exact file; links are the relative links in the file that resolve to other context files.',
1704
+ async (raw, ctx) => {
1705
+ const input = raw as z.infer<typeof contextReadInput>
1706
+ const outcome = readContextFile(await contextViewFor(ctx, input.repo), input)
1707
+ if (outcome.kind === 'not-found')
1708
+ throw new RouteRefusalError({ kind: 'not-found', error: outcome.message })
1709
+ return outcome.result
1710
+ },
1711
+ ),
1391
1712
  ]
1392
1713
 
1393
1714
  // ── The registry constructor ─────────────────────────────────────────────────
@@ -1395,13 +1716,21 @@ export const TOOLS: readonly ToolEntry[] = [
1395
1716
  export interface RegistryOptions {
1396
1717
  store: BuildStore
1397
1718
  tickets?: OperatorTicketBackend
1398
- /** The operator-sandbox backend; when absent the sandbox tools are
1399
- * neither advertised nor callable (the compatibility case). When present
1400
- * but `canPublish` is false, only `sandbox.publish` is filtered. */
1719
+ /** The operator-sandbox backend; when absent (and `sandboxResolution` is
1720
+ * absent) the sandbox tools are neither advertised nor callable (the
1721
+ * compatibility case). When present but `canPublish` is false, only
1722
+ * `sandbox.publish` is filtered. */
1401
1723
  sandbox?: OperatorSandboxService
1724
+ /** The hosted mode: a declared sandbox capability with no backend yet. The
1725
+ * sandbox tools are served per `operatorToolTable(sandboxResolution)`, and
1726
+ * each call's backend arrives through `ToolContext.sandboxFor`. When both
1727
+ * this and `sandbox` are given, `sandbox` wins. */
1728
+ sandboxResolution?: { canPublish: boolean }
1402
1729
  clock?: Clock
1403
1730
  /** Constrain every call to this repository identity (the `ab mcp --repo` flag). */
1404
1731
  allowedRepo?: string
1732
+ /** The canonical skill loader for the context tools; tests inject one. */
1733
+ canonicalSkills?: () => Promise<CanonicalSkillBundle>
1405
1734
  }
1406
1735
 
1407
1736
  export interface OperatorToolRegistry {
@@ -1445,6 +1774,24 @@ function mapDomainError(error: unknown): RegistryError {
1445
1774
  error: error.message,
1446
1775
  code: 'assignees-unsupported',
1447
1776
  })
1777
+ if (error instanceof TicketAssetValidationError)
1778
+ return new RegistryError('domain', error.message, {
1779
+ kind: 'validation',
1780
+ error: error.message,
1781
+ code: 'ticket-asset-invalid',
1782
+ })
1783
+ if (error instanceof TicketSearchUnsupported)
1784
+ return new RegistryError('domain', error.message, {
1785
+ kind: 'refusal',
1786
+ error: error.message,
1787
+ code: 'search-unsupported',
1788
+ })
1789
+ if (error instanceof TicketSearchCursorInvalid)
1790
+ return new RegistryError('domain', error.message, {
1791
+ kind: 'refusal',
1792
+ error: error.message,
1793
+ code: 'search-cursor-invalid',
1794
+ })
1448
1795
  if (error instanceof TicketOperationError) {
1449
1796
  return new RegistryError('domain', error.message, {
1450
1797
  kind: error.code === 'not-found' ? 'not-found' : 'refusal',
@@ -1467,11 +1814,19 @@ function mapDomainError(error: unknown): RegistryError {
1467
1814
  progress: error.progress,
1468
1815
  })
1469
1816
  }
1817
+ if (error instanceof SandboxUnavailableError) {
1818
+ return new RegistryError('domain', error.message, {
1819
+ kind: 'refusal',
1820
+ error: error.message,
1821
+ code: `sandbox-${error.reason}`,
1822
+ })
1823
+ }
1470
1824
  if (error instanceof SandboxOperationError) {
1471
1825
  return new RegistryError('domain', error.message, {
1472
1826
  kind: 'refusal',
1473
1827
  error: error.message,
1474
1828
  code: `sandbox-${error.stage}`,
1829
+ ...(error.state !== undefined ? { state: error.state } : {}),
1475
1830
  })
1476
1831
  }
1477
1832
  if (error instanceof OperatorQueryError) {
@@ -1492,25 +1847,27 @@ function mapDomainError(error: unknown): RegistryError {
1492
1847
  )
1493
1848
  }
1494
1849
 
1850
+ const sandboxToolNames: ReadonlySet<string> = new Set(
1851
+ Object.keys(OPERATOR_TOOL_ANNOTATIONS).filter((name) => name.startsWith('sandbox.')),
1852
+ )
1853
+
1854
+ /** The served table for a sandbox capability — the one filter rule both
1855
+ * advertisement and dispatch use. Without a capability every sandbox tool is
1856
+ * filtered; with one that cannot publish (no forge or no provider publication
1857
+ * capability), only `sandbox.publish` is filtered. */
1858
+ export function operatorToolTable(sandbox?: { canPublish: boolean }): readonly ToolEntry[] {
1859
+ if (sandbox === undefined) return TOOLS.filter((tool) => !sandboxToolNames.has(tool.name))
1860
+ if (sandbox.canPublish === false) return TOOLS.filter((tool) => tool.name !== 'sandbox.publish')
1861
+ return TOOLS
1862
+ }
1863
+
1495
1864
  /** Bind the closed table to an opened store (and optional ticket and sandbox
1496
1865
  * backends). The returned registry is the in-process binding; every other
1497
1866
  * binding is generated from `entries`. Advertisement and dispatch share ONE
1498
1867
  * table: a filtered tool is neither advertised nor served. */
1499
1868
  export function buildRegistry(options: RegistryOptions): OperatorToolRegistry {
1500
- const sandboxToolNames = new Set(
1501
- Object.keys(OPERATOR_TOOL_ANNOTATIONS).filter((name) => name.startsWith('sandbox.')),
1502
- )
1503
- // Without a sandbox backend every sandbox tool is filtered; with a backend
1504
- // that cannot publish (no forge or no provider publication capability),
1505
- // only `sandbox.publish` is filtered. Filtered tools are absent from
1506
- // `entries` AND from `call()` dispatch.
1507
- const filtered = new Set<string>()
1508
- if (options.sandbox === undefined) {
1509
- for (const name of sandboxToolNames) filtered.add(name)
1510
- } else if (options.sandbox.canPublish === false) {
1511
- filtered.add('sandbox.publish')
1512
- }
1513
- const table = filtered.size === 0 ? TOOLS : TOOLS.filter((tool) => !filtered.has(tool.name))
1869
+ // Filtered tools are absent from `entries` AND from `call()` dispatch.
1870
+ const table = operatorToolTable(options.sandbox ?? options.sandboxResolution)
1514
1871
  return {
1515
1872
  entries: table,
1516
1873
  async call(name, input, partial = {}) {
@@ -1551,10 +1908,13 @@ export function buildRegistry(options: RegistryOptions): OperatorToolRegistry {
1551
1908
  }
1552
1909
  const tickets = partial.tickets ?? options.tickets
1553
1910
  const sandbox = partial.sandbox ?? options.sandbox
1911
+ const canonicalSkills = partial.canonicalSkills ?? options.canonicalSkills
1554
1912
  const ctx: ToolContext = {
1555
1913
  store: partial.store ?? options.store,
1556
1914
  ...(tickets !== undefined ? { tickets } : {}),
1557
1915
  ...(sandbox !== undefined ? { sandbox } : {}),
1916
+ ...(partial.sandboxFor !== undefined ? { sandboxFor: partial.sandboxFor } : {}),
1917
+ ...(canonicalSkills !== undefined ? { canonicalSkills } : {}),
1558
1918
  clock: partial.clock ?? options.clock ?? systemClock,
1559
1919
  ...(identity !== undefined ? { identity } : {}),
1560
1920
  ...(partial.via !== undefined ? { via: partial.via } : {}),