@defrex/autobuild 1.10.0 → 1.11.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 (250) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +738 -68
  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 +155 -25
  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 +63 -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 +101 -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 +178 -76
  41. package/packages/core/src/cli/dashboard/render.ts +129 -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 +29 -38
  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 +200 -34
  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 +97 -43
  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 +316 -0
  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/79f0e0f4ccd43ba2.json +455 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  94. package/packages/core/src/kernel/build-roster.ts +230 -0
  95. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  96. package/packages/core/src/kernel/engine.ts +43 -5
  97. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  98. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  99. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  100. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  101. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  102. package/packages/core/src/kernel/log-index.ts +19 -0
  103. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  104. package/packages/core/src/kernel/optimization.ts +183 -4
  105. package/packages/core/src/kernel/phase-failures.ts +121 -0
  106. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  107. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  108. package/packages/core/src/kernel/reducer-revisions.ts +25 -0
  109. package/packages/core/src/kernel/reducer.ts +63 -4
  110. package/packages/core/src/kernel/rollup.ts +61 -0
  111. package/packages/core/src/kernel/setup-streak.ts +38 -0
  112. package/packages/core/src/kernel/step-durations.ts +257 -0
  113. package/packages/core/src/kernel/target-observation.ts +6 -1
  114. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  115. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  116. package/packages/core/src/kernel/verify-stages.ts +13 -3
  117. package/packages/core/src/ontology.ts +5 -0
  118. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  119. package/packages/core/src/operator/annotations.ts +75 -5
  120. package/packages/core/src/operator/attention.ts +470 -0
  121. package/packages/core/src/operator/canonical-skills.ts +35 -0
  122. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  123. package/packages/core/src/operator/context-prompts.ts +61 -0
  124. package/packages/core/src/operator/index.ts +49 -1
  125. package/packages/core/src/operator/landings.ts +28 -19
  126. package/packages/core/src/operator/optimization.ts +7 -0
  127. package/packages/core/src/operator/protocol.ts +3 -0
  128. package/packages/core/src/operator/query.ts +122 -72
  129. package/packages/core/src/operator/read-view.ts +5 -2
  130. package/packages/core/src/operator/registry.ts +406 -46
  131. package/packages/core/src/operator/requests.ts +20 -18
  132. package/packages/core/src/operator/sandbox-host.ts +107 -11
  133. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  134. package/packages/core/src/operator/sandbox.ts +778 -82
  135. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  136. package/packages/core/src/operator/ticket-assets.ts +167 -0
  137. package/packages/core/src/operator/tickets.ts +33 -2
  138. package/packages/core/src/plugin-sdk/index.ts +22 -0
  139. package/packages/core/src/plugins/manifest.ts +1 -1
  140. package/packages/core/src/ports/forge/fake.ts +92 -1
  141. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  142. package/packages/core/src/ports/forge/github.ts +82 -0
  143. package/packages/core/src/ports/forge/local-git.ts +61 -1
  144. package/packages/core/src/ports/forge-failure.ts +24 -0
  145. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  146. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  147. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  148. package/packages/core/src/ports/tickets/contract.ts +71 -0
  149. package/packages/core/src/ports/tickets/fake.ts +11 -0
  150. package/packages/core/src/ports/tickets/file.ts +18 -0
  151. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  152. package/packages/core/src/ports/tickets/github.ts +387 -30
  153. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  154. package/packages/core/src/ports/tickets/linear.ts +130 -0
  155. package/packages/core/src/ports/tickets/priority.ts +9 -0
  156. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  157. package/packages/core/src/ports/tickets/remote.ts +70 -6
  158. package/packages/core/src/ports/tickets/search.ts +139 -0
  159. package/packages/core/src/ports/types.ts +104 -2
  160. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  161. package/packages/core/src/ports/workspace/create.ts +15 -1
  162. package/packages/core/src/ports/workspace/fake.ts +340 -12
  163. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  164. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  165. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  166. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  167. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  168. package/packages/core/src/processes/agent-context.ts +469 -0
  169. package/packages/core/src/processes/build-runner.ts +387 -236
  170. package/packages/core/src/processes/dispatcher.ts +211 -55
  171. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  172. package/packages/core/src/processes/optimization-activity.ts +120 -0
  173. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  174. package/packages/core/src/processes/repo-view.ts +78 -2
  175. package/packages/core/src/processes/sandbox-state.ts +53 -6
  176. package/packages/core/src/processes/tick-publication.ts +2 -0
  177. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  178. package/packages/core/src/scenarios/harness.ts +0 -5
  179. package/packages/core/src/store/account-redaction.ts +1 -0
  180. package/packages/core/src/store/adapter.ts +52 -1
  181. package/packages/core/src/store/agent-context.ts +432 -0
  182. package/packages/core/src/store/build-feed.ts +291 -0
  183. package/packages/core/src/store/build-scope.ts +19 -1
  184. package/packages/core/src/store/contract.ts +911 -14
  185. package/packages/core/src/store/digest.ts +19 -6
  186. package/packages/core/src/store/histogram.ts +113 -0
  187. package/packages/core/src/store/local/schema.ts +62 -0
  188. package/packages/core/src/store/local/store.ts +628 -22
  189. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  190. package/packages/core/src/store/memory.ts +461 -69
  191. package/packages/core/src/store/open-builds.ts +19 -0
  192. package/packages/core/src/store/phase-session.ts +32 -4
  193. package/packages/core/src/store/reduced-reads.ts +14 -4
  194. package/packages/core/src/store/reducer-value-shapes.json +6987 -5749
  195. package/packages/core/src/store/reducer-values.ts +6 -1
  196. package/packages/core/src/store/remote/client.ts +208 -2
  197. package/packages/core/src/store/remote/compatibility.ts +1 -1
  198. package/packages/core/src/store/remote/index.ts +33 -0
  199. package/packages/core/src/store/remote/protocol.ts +69 -0
  200. package/packages/core/src/store/remote/released-clients.json +11 -0
  201. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  202. package/packages/core/src/store/remote/released-reducer-values/index.ts +18 -16
  203. package/packages/core/src/store/retention.ts +23 -1
  204. package/packages/core/src/store/rollups.ts +337 -0
  205. package/packages/core/src/store/session-handle.ts +20 -2
  206. package/packages/core/src/store/snapshots.ts +10 -0
  207. package/packages/core/src/store/types.ts +108 -9
  208. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  209. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  210. package/packages/core/src/testing/index.ts +27 -0
  211. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  212. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  213. package/packages/core/src/web/analytics-source.ts +303 -0
  214. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  215. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  216. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  217. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  218. package/packages/core/src/web/assets/app.css +1 -0
  219. package/packages/core/src/web/assets/app.js +9 -0
  220. package/packages/core/src/web/assets/manifest.json +31 -0
  221. package/packages/core/src/web/assets/theme.js +1 -0
  222. package/packages/core/src/web/bounded.ts +31 -0
  223. package/packages/core/src/web/http.ts +315 -0
  224. package/packages/core/src/web/hub.ts +160 -0
  225. package/packages/core/src/web/options.ts +38 -0
  226. package/packages/core/src/web/overview-source.ts +322 -0
  227. package/packages/core/src/web/page.ts +56 -0
  228. package/packages/core/src/web/protocol.ts +151 -0
  229. package/packages/core/src/web/read-only.ts +23 -0
  230. package/packages/core/src/web/repository-source.ts +35 -0
  231. package/packages/core/src/web/server.ts +97 -0
  232. package/skills/code-review/SKILL.md +10 -2
  233. package/skills/guide/SKILL.md +366 -52
  234. package/skills/guide/references/accounts.md +2 -1
  235. package/skills/guide/references/integration-tree.md +2 -2
  236. package/skills/guide/references/operator-api.md +134 -6
  237. package/skills/guide/references/optimization-nodes.md +69 -11
  238. package/skills/guide/references/plugin-authoring.md +37 -1
  239. package/skills/guide/references/remote-store-protocol.md +94 -13
  240. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  241. package/skills/guide/references/restacking.md +20 -4
  242. package/skills/guide/references/setup.md +14 -2
  243. package/skills/guide/references/ticket-dependencies.md +10 -3
  244. package/skills/implement/SKILL.md +23 -4
  245. package/skills/operate/SKILL.md +134 -32
  246. package/skills/plan/SKILL.md +10 -4
  247. package/skills/plan-review/SKILL.md +9 -2
  248. package/skills/spec/SKILL.md +34 -8
  249. package/skills/tickets/SKILL.md +51 -5
  250. package/templates/hosted-service/package.json +2 -2
@@ -118,6 +118,7 @@ export const policyEscalationCauseSchema = z.enum([
118
118
  'non-retryable-phase-failure',
119
119
  'wait-unresolvable',
120
120
  'measurement-failed',
121
+ 'target-rewritten',
121
122
  ])
122
123
  export type PolicyEscalationCause = z.infer<typeof policyEscalationCauseSchema>
123
124
 
@@ -142,6 +143,10 @@ export const escalationResolutionSchema = z.enum([
142
143
  'abort',
143
144
  /** Bare re-attempt with no phase guidance: human UI, or policy-only startup. */
144
145
  'retry',
146
+ /** Accept a rewritten target for a leaf's `policy/target-rewritten`
147
+ * escalation: waive the rejected base and restack the build's own commits
148
+ * onto the current target. Re-arms no budget and is never guidance. */
149
+ 'accept-target',
145
150
  ])
146
151
  export type EscalationResolution = z.infer<typeof escalationResolutionSchema>
147
152
 
@@ -0,0 +1,631 @@
1
+ /**
2
+ * Serving a repository's agent context to connected agents (#1225).
3
+ *
4
+ * The dispatcher captures the base branch's skills and agent instructions
5
+ * into one record (`store/agent-context.ts`). This module turns that record,
6
+ * or the canonical skills bundled with the serving Autobuild when a
7
+ * repository has none, into what an MCP client needs for progressive
8
+ * disclosure:
9
+ *
10
+ * - the index (`context.list`): skills with descriptions and files, agent
11
+ * instructions with scopes, and which to load before operating or ticket
12
+ * work;
13
+ * - one file (`context.read`), found by path or by a relative link from
14
+ * another file, with a generated preamble that maps the `ab` commands the
15
+ * text mentions onto the operator tools (`operator/cli-equivalents.ts`) and
16
+ * frames agent instructions as the repository's own file;
17
+ * - the server-instruction section and the MCP prompt identities.
18
+ *
19
+ * It is pure: no store, no filesystem. Every binding (hosted `/mcp`, the
20
+ * per-repository endpoint, `ab mcp`) renders through it, so wording and
21
+ * prompt names cannot drift between them.
22
+ */
23
+ import { createHash } from 'node:crypto'
24
+ import type { DistSkill } from '../cli/init'
25
+ import { normalizeRepoPath } from '../processes/agent-context-assemble'
26
+ import { contentBytes, type AgentContextRecord } from '../store/agent-context'
27
+ import { cliMentions, renderCliMapping } from './cli-equivalents'
28
+
29
+ /** The canonical skills bundled with the serving Autobuild, in install form. */
30
+ export interface CanonicalSkillBundle {
31
+ version: string
32
+ skills: readonly Pick<DistSkill, 'installName' | 'files'>[]
33
+ }
34
+
35
+ export type ContextSource = 'captured' | 'canonical'
36
+ export type ContextFileKind = 'skill' | 'skill-file' | 'instructions' | 'import'
37
+
38
+ interface ContextFile {
39
+ path: string
40
+ aliases: string[]
41
+ kind: ContextFileKind
42
+ skill?: string
43
+ scope?: string
44
+ importedBy?: string[]
45
+ text?: string
46
+ base64?: string
47
+ }
48
+
49
+ /** A uniform view over a captured record or the canonical bundle. */
50
+ export interface ContextView {
51
+ source: ContextSource
52
+ commit: string | null
53
+ baseBranch?: string
54
+ version?: string
55
+ files: ContextFile[]
56
+ skills: { name: string; paths: string[]; entry: string; files: string[] }[]
57
+ instructions: { path: string; aliases: string[]; scope: string; imports: string[] }[]
58
+ imports: { path: string; importedBy: string[] }[]
59
+ links: { path: string; target: string }[]
60
+ omitted: { path: string; reason: string }[]
61
+ }
62
+
63
+ export interface ContextIndex {
64
+ repo: string
65
+ source: ContextSource
66
+ commit: string | null
67
+ baseBranch?: string
68
+ version?: string
69
+ notice?: string
70
+ skills: {
71
+ name: string
72
+ description: string | null
73
+ paths: string[]
74
+ entry: string
75
+ files: string[]
76
+ }[]
77
+ instructions: { path: string; aliases: string[]; scope: string; imports: string[] }[]
78
+ imports: { path: string; importedBy: string[] }[]
79
+ load: { beforeOperating: string[]; beforeTicketWork: string[] }
80
+ }
81
+
82
+ export type ContextReadResult = {
83
+ path: string
84
+ kind: ContextFileKind
85
+ skill?: string
86
+ scope?: string
87
+ source: ContextSource
88
+ commit: string | null
89
+ links: { href: string; path: string }[]
90
+ } & ({ text: string } | { contentBase64: string })
91
+
92
+ export type ContextReadOutcome =
93
+ | ({ kind: 'found' } & { result: ContextReadResult })
94
+ | { kind: 'not-found'; message: string }
95
+
96
+ const SKILL_FILE = 'SKILL.md'
97
+ const OPERATE_SKILL = 'ab-operate'
98
+ const TICKET_SKILLS = ['ab-spec', 'ab-tickets'] as const
99
+
100
+ const utf8 = new TextDecoder('utf-8')
101
+
102
+ function compare(a: string, b: string): number {
103
+ return a < b ? -1 : a > b ? 1 : 0
104
+ }
105
+
106
+ function body(entry: { text?: string; base64?: string; oid: string; bytes: number }): {
107
+ text?: string
108
+ base64?: string
109
+ } {
110
+ if (entry.text !== undefined) return { text: entry.text }
111
+ return { base64: Buffer.from(contentBytes(entry)).toString('base64') }
112
+ }
113
+
114
+ /** Build the view: the record when one is captured, else the bundle. */
115
+ export function contextSource(
116
+ record: AgentContextRecord | null,
117
+ bundle: CanonicalSkillBundle | null,
118
+ ): ContextView {
119
+ if (record !== null) {
120
+ const files: ContextFile[] = []
121
+ const skills: ContextView['skills'] = []
122
+ for (const skill of record.skills) {
123
+ const [primary, ...others] = skill.paths
124
+ const paths: string[] = []
125
+ for (const file of skill.files) {
126
+ const path = `${primary}/${file.path}`
127
+ paths.push(path)
128
+ files.push({
129
+ path,
130
+ aliases: others.map((other) => `${other}/${file.path}`),
131
+ kind: file.path === SKILL_FILE ? 'skill' : 'skill-file',
132
+ skill: skill.name,
133
+ ...body(file),
134
+ })
135
+ }
136
+ skills.push({
137
+ name: skill.name,
138
+ paths: skill.paths,
139
+ entry: `${primary}/${SKILL_FILE}`,
140
+ files: paths,
141
+ })
142
+ }
143
+ const instructions = record.instructions.map((entry) => {
144
+ const [path, ...aliases] = entry.paths as [string, ...string[]]
145
+ files.push({ path, aliases, kind: 'instructions', scope: entry.directory, ...body(entry) })
146
+ return { path, aliases, scope: entry.directory, imports: entry.imports }
147
+ })
148
+ // Repository root first, then by path.
149
+ instructions.sort(
150
+ (a, b) => Number(a.scope !== '') - Number(b.scope !== '') || compare(a.path, b.path),
151
+ )
152
+ const imports = record.imports.map((entry) => {
153
+ files.push({
154
+ path: entry.path,
155
+ aliases: [],
156
+ kind: 'import',
157
+ importedBy: entry.importedBy,
158
+ ...body(entry),
159
+ })
160
+ return { path: entry.path, importedBy: entry.importedBy }
161
+ })
162
+ return {
163
+ source: 'captured',
164
+ commit: record.commit,
165
+ baseBranch: record.baseBranch,
166
+ files,
167
+ skills,
168
+ instructions,
169
+ imports,
170
+ links: record.links,
171
+ omitted: record.omitted,
172
+ }
173
+ }
174
+ if (bundle === null) throw new Error('no captured record and no canonical skill bundle')
175
+ const files: ContextFile[] = []
176
+ const skills: ContextView['skills'] = []
177
+ for (const skill of bundle.skills) {
178
+ const root = `.agents/skills/${skill.installName}`
179
+ const paths: string[] = []
180
+ for (const file of skill.files) {
181
+ const path = `${root}/${file.path}`
182
+ paths.push(path)
183
+ files.push({
184
+ path,
185
+ aliases: [`.claude/skills/${skill.installName}/${file.path}`],
186
+ kind: file.path === SKILL_FILE ? 'skill' : 'skill-file',
187
+ skill: skill.installName,
188
+ text: file.content,
189
+ })
190
+ }
191
+ skills.push({
192
+ name: skill.installName,
193
+ paths: [root, `.claude/skills/${skill.installName}`],
194
+ entry: `${root}/${SKILL_FILE}`,
195
+ files: paths,
196
+ })
197
+ }
198
+ return {
199
+ source: 'canonical',
200
+ commit: null,
201
+ version: bundle.version,
202
+ files,
203
+ skills,
204
+ instructions: [],
205
+ imports: [],
206
+ links: [],
207
+ omitted: [],
208
+ }
209
+ }
210
+
211
+ // ── Frontmatter ─────────────────────────────────────────────────────────────
212
+
213
+ function unquote(value: string): string {
214
+ const trimmed = value.trim()
215
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
216
+ try {
217
+ return JSON.parse(trimmed) as string
218
+ } catch {
219
+ return trimmed.slice(1, -1)
220
+ }
221
+ }
222
+ if (trimmed.length >= 2 && trimmed.startsWith("'") && trimmed.endsWith("'"))
223
+ return trimmed.slice(1, -1).replaceAll("''", "'")
224
+ return trimmed
225
+ }
226
+
227
+ /** `description` from a SKILL.md YAML frontmatter: a single-line plain or
228
+ * quoted value, or a folded (`>`) or literal (`|`) block scalar. Null when
229
+ * the frontmatter is absent or the field cannot be read. */
230
+ export function skillDescription(text: string): string | null {
231
+ const lines = text.replace(/^�/, '').split(/\r?\n/)
232
+ if (lines[0]?.trim() !== '---') return null
233
+ const close = lines.findIndex((line, index) => index > 0 && line.trim() === '---')
234
+ if (close < 0) return null
235
+ const front = lines.slice(1, close)
236
+ const at = front.findIndex((line) => /^description\s*:/.test(line))
237
+ if (at < 0) return null
238
+ const value = front[at]!.replace(/^description\s*:/, '').trim()
239
+ const block = /^([>|])[+-]?\d*$/.exec(value)
240
+ if (block === null) {
241
+ if (value === '') return null
242
+ return unquote(value) || null
243
+ }
244
+ const continued: string[] = []
245
+ for (const line of front.slice(at + 1)) {
246
+ if (line.trim() !== '' && !/^\s/.test(line)) break
247
+ continued.push(line.trim())
248
+ }
249
+ while (continued.at(-1) === '') continued.pop()
250
+ if (continued.length === 0) return null
251
+ if (block[1] === '|') return continued.join('\n')
252
+ return continued
253
+ .join('\n')
254
+ .split(/\n{2,}/)
255
+ .map((paragraph) => paragraph.split('\n').join(' '))
256
+ .join('\n')
257
+ }
258
+
259
+ // ── Index ───────────────────────────────────────────────────────────────────
260
+
261
+ function canonicalNotice(repo: string, version: string | undefined): string {
262
+ return `${repo} has no captured agent context: serving the canonical skills bundled with Autobuild ${version ?? 'unknown'}; agent instructions are absent.`
263
+ }
264
+
265
+ function fileByPath(view: ContextView, path: string): ContextFile | undefined {
266
+ return view.files.find((file) => file.path === path || file.aliases.includes(path))
267
+ }
268
+
269
+ export function contextIndex(view: ContextView, repo: string): ContextIndex {
270
+ const skills = view.skills.map((skill) => {
271
+ const entry = fileByPath(view, skill.entry)
272
+ return {
273
+ name: skill.name,
274
+ description: entry?.text !== undefined ? skillDescription(entry.text) : null,
275
+ paths: skill.paths,
276
+ entry: skill.entry,
277
+ files: skill.files,
278
+ }
279
+ })
280
+ const entryOf = (name: string) => skills.find((skill) => skill.name === name)?.entry
281
+ const operate = entryOf(OPERATE_SKILL)
282
+ return {
283
+ repo,
284
+ source: view.source,
285
+ commit: view.commit,
286
+ ...(view.baseBranch !== undefined ? { baseBranch: view.baseBranch } : {}),
287
+ ...(view.version !== undefined ? { version: view.version } : {}),
288
+ ...(view.source === 'canonical' ? { notice: canonicalNotice(repo, view.version) } : {}),
289
+ skills,
290
+ instructions: view.instructions,
291
+ imports: view.imports,
292
+ load: {
293
+ beforeOperating: operate !== undefined ? [operate] : [],
294
+ beforeTicketWork: [
295
+ ...TICKET_SKILLS.map(entryOf).filter((entry): entry is string => entry !== undefined),
296
+ ...view.instructions.map((entry) => entry.path),
297
+ ],
298
+ },
299
+ }
300
+ }
301
+
302
+ // ── Reads ───────────────────────────────────────────────────────────────────
303
+
304
+ function stripTarget(path: string): string {
305
+ return path.replace(/[#?].*$/, '')
306
+ }
307
+
308
+ function dirnameOf(path: string): string {
309
+ const slash = path.lastIndexOf('/')
310
+ return slash < 0 ? '' : path.slice(0, slash)
311
+ }
312
+
313
+ /** Normalize `path` (relative to `from`'s directory when given) to a
314
+ * repository path; null when it climbs above the root. */
315
+ function normalizePath(path: string, from?: string): string | null {
316
+ const target = stripTarget(path)
317
+ if (from !== undefined && !target.startsWith('/'))
318
+ return normalizeRepoPath(dirnameOf(stripTarget(from).replace(/^\/+/, '')), target)
319
+ return normalizeRepoPath('', target.replace(/^\/+/, ''))
320
+ }
321
+
322
+ /** Find a file by path, following captured directory links (bounded). */
323
+ function findFile(view: ContextView, path: string): ContextFile | undefined {
324
+ let current = path
325
+ for (let depth = 0; depth < 8; depth++) {
326
+ const file = fileByPath(view, current)
327
+ if (file !== undefined) return file
328
+ const link = view.links.find(
329
+ (entry) => current === entry.path || current.startsWith(`${entry.path}/`),
330
+ )
331
+ if (link === undefined) return undefined
332
+ const target = normalizeRepoPath(dirnameOf(link.path), link.target)
333
+ if (target === null) return undefined
334
+ current = `${target}${current.slice(link.path.length)}`
335
+ }
336
+ return undefined
337
+ }
338
+
339
+ const MARKDOWN_LINK = /\[[^\]]*\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g
340
+
341
+ /** Resolve `path` relative to `from`: against the requested spelling of
342
+ * `from` first, then against the primary path of the file it names (an
343
+ * alias directory need not hold every sibling skill). */
344
+ function findRelative(
345
+ view: ContextView,
346
+ path: string,
347
+ from: string | undefined,
348
+ ): { requested: string | null; file: ContextFile | undefined } {
349
+ const requested = normalizePath(path, from)
350
+ let file = requested === null || requested === '' ? undefined : findFile(view, requested)
351
+ if (file === undefined && from !== undefined) {
352
+ const base = normalizePath(from)
353
+ const origin = base === null ? undefined : findFile(view, base)
354
+ if (origin !== undefined && origin.path !== base) {
355
+ const viaPrimary = normalizePath(path, origin.path)
356
+ if (viaPrimary !== null && viaPrimary !== '') file = findFile(view, viaPrimary)
357
+ }
358
+ }
359
+ return { requested, file }
360
+ }
361
+
362
+ /** Every relative markdown link in `text` that resolves to a file in the
363
+ * view, relative to the requested path. */
364
+ function resolvedLinks(view: ContextView, text: string, requested: string) {
365
+ const links: { href: string; path: string }[] = []
366
+ const seen = new Set<string>()
367
+ for (const match of text.matchAll(MARKDOWN_LINK)) {
368
+ const href = match[1]!
369
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('#') || seen.has(href)) continue
370
+ seen.add(href)
371
+ const { file } = findRelative(view, href, requested)
372
+ if (file !== undefined) links.push({ href, path: file.path })
373
+ }
374
+ return links
375
+ }
376
+
377
+ const PREAMBLE_HEAD = '[Autobuild context preamble — generated by the server; not part of the file]'
378
+
379
+ function short(commit: string): string {
380
+ return commit.slice(0, 12)
381
+ }
382
+
383
+ function sourceLine(view: ContextView): string {
384
+ return view.source === 'captured'
385
+ ? `captured from the repository at commit ${short(view.commit ?? '')}${view.baseBranch !== undefined ? ` (${view.baseBranch})` : ''}`
386
+ : `the canonical skill bundled with Autobuild ${view.version ?? 'unknown'}, served because this repository has no captured agent context`
387
+ }
388
+
389
+ function mappingLines(text: string): string[] {
390
+ const commands = cliMentions(text)
391
+ if (commands.length === 0) return []
392
+ return [
393
+ 'The `ab` commands this file mentions, and what to use instead:',
394
+ ...renderCliMapping(commands),
395
+ ]
396
+ }
397
+
398
+ function skillPreamble(view: ContextView, file: ContextFile, text: string): string {
399
+ const instructions = view.instructions.map((entry) => `\`${entry.path}\``)
400
+ const mapping = mappingLines(text)
401
+ return [
402
+ PREAMBLE_HEAD,
403
+ `Skill \`${file.skill}\` (\`${file.path}\`): ${sourceLine(view)}.`,
404
+ 'You are connected over MCP. You have no shell and no `ab` CLI: act through the operator tools.',
405
+ ...mapping,
406
+ ...(mapping.some((line) => line.includes('inside the sandbox'))
407
+ ? [
408
+ 'A command marked for the sandbox runs there: `sandbox.open`, poll `sandbox.status` until ready, then `sandbox.exec`.',
409
+ ]
410
+ : []),
411
+ view.source === 'captured'
412
+ ? `Where this repository's agent instructions conflict with this skill, the instructions win for this repository: ${instructions.length > 0 ? instructions.join(', ') : 'none captured'}.`
413
+ : "Where this repository's agent instructions conflict with this skill, the instructions win for this repository: none captured.",
414
+ ].join('\n')
415
+ }
416
+
417
+ function instructionsPreamble(view: ContextView, file: ContextFile, text: string): string {
418
+ const own =
419
+ file.kind === 'import'
420
+ ? `\`${file.path}\` is this repository's own file, imported by ${(file.importedBy ?? []).map((path) => `\`${path}\``).join(', ')}`
421
+ : `\`${file.path}\` is this repository's own agent instructions file (scope: ${file.scope === '' || file.scope === undefined ? 'the repository root' : `\`${file.scope}\``})`
422
+ return [
423
+ PREAMBLE_HEAD,
424
+ `${own}, captured at commit ${short(view.commit ?? '')}.`,
425
+ '- It was written for agents working in a checkout of the repository.',
426
+ '- Its conventions and constraints apply to the tickets, specs and answers you write for this repository.',
427
+ '- Its commands and its rules about local processes apply only inside the sandbox (`sandbox.open`, then `sandbox.exec`); you have no shell of your own.',
428
+ '- It takes precedence over Autobuild skills for this repository.',
429
+ ...mappingLines(text),
430
+ ].join('\n')
431
+ }
432
+
433
+ /** Resolve and return one file with its preamble. */
434
+ export function readContextFile(
435
+ view: ContextView,
436
+ input: { path: string; from?: string },
437
+ ): ContextReadOutcome {
438
+ const { requested, file } = findRelative(view, input.path, input.from)
439
+ if (file === undefined || requested === null) {
440
+ const shown = requested ?? input.path
441
+ const omission = view.omitted.find((entry) => entry.path === shown)
442
+ return {
443
+ kind: 'not-found',
444
+ message:
445
+ `no file "${shown}" in the ${view.source} agent context` +
446
+ (omission !== undefined
447
+ ? `: the capture omitted it (${omission.reason})`
448
+ : '; call context.list'),
449
+ }
450
+ }
451
+ const meta = {
452
+ path: file.path,
453
+ kind: file.kind,
454
+ ...(file.skill !== undefined ? { skill: file.skill } : {}),
455
+ ...(file.scope !== undefined ? { scope: file.scope } : {}),
456
+ source: view.source,
457
+ commit: view.commit,
458
+ }
459
+ if (file.text === undefined)
460
+ return { kind: 'found', result: { ...meta, contentBase64: file.base64 ?? '', links: [] } }
461
+ const raw = file.text
462
+ const links = resolvedLinks(view, raw, requested)
463
+ let preamble: string | undefined
464
+ if (file.kind === 'skill') preamble = skillPreamble(view, file, raw)
465
+ else if (file.kind === 'skill-file') {
466
+ if (cliMentions(raw).length > 0) preamble = skillPreamble(view, file, raw)
467
+ } else preamble = instructionsPreamble(view, file, raw)
468
+ const text = preamble === undefined ? raw : `${preamble}\n---\n${raw}`
469
+ return { kind: 'found', result: { ...meta, text, links } }
470
+ }
471
+
472
+ // ── Server instructions ─────────────────────────────────────────────────────
473
+
474
+ export type ContextEntry = { repo: string; index: ContextIndex } | { repo: string; error: string }
475
+
476
+ function code(value: string): string {
477
+ return `\`${value}\``
478
+ }
479
+
480
+ function repositorySection(index: ContextIndex, scoped: boolean): string[] {
481
+ const lines: string[] = []
482
+ lines.push(
483
+ index.source === 'captured'
484
+ ? `Captured from the base branch${index.baseBranch !== undefined ? ` ${code(index.baseBranch)}` : ''} at commit ${short(index.commit ?? '')}.`
485
+ : (index.notice ?? canonicalNotice(index.repo, index.version)),
486
+ )
487
+ lines.push('Skills:')
488
+ for (const skill of index.skills)
489
+ lines.push(`- ${skill.name}${skill.description !== null ? ` — ${skill.description}` : ''}`)
490
+ if (index.skills.length === 0) lines.push('- none')
491
+ lines.push(
492
+ `Agent instructions: ${
493
+ index.source === 'canonical'
494
+ ? 'absent (no captured record).'
495
+ : index.instructions.length === 0
496
+ ? 'none.'
497
+ : `${index.instructions
498
+ .map(
499
+ (entry) =>
500
+ `${code(entry.path)} (${entry.scope === '' ? 'repository root' : code(entry.scope)})`,
501
+ )
502
+ .join(', ')}.`
503
+ }`,
504
+ )
505
+ const named = (path: string) => index.skills.find((skill) => skill.entry === path)?.name ?? path
506
+ const operate = index.load.beforeOperating
507
+ const ticketSkills = index.load.beforeTicketWork.filter((path) =>
508
+ index.skills.some((skill) => skill.entry === path),
509
+ )
510
+ if (operate.length > 0)
511
+ lines.push(
512
+ `Before operating, load ${operate.map((path) => `${code(named(path))} (${code(path)})`).join(', ')}.`,
513
+ )
514
+ if (ticketSkills.length > 0 || index.instructions.length > 0)
515
+ lines.push(
516
+ `Before filing or revising tickets, load ${[
517
+ ...ticketSkills.map((path) => `${code(named(path))} (${code(path)})`),
518
+ ...(index.instructions.length > 0 ? ['the agent instructions above'] : []),
519
+ ].join(', ')}.`,
520
+ )
521
+ lines.push(
522
+ scoped
523
+ ? 'Load any skill or instructions file with `context.read` and its path, or invoke the MCP prompt named for the skill.'
524
+ : `Load any skill or instructions file with \`context.read\` (repo ${code(index.repo)}) and its path, or invoke the MCP prompt named for the skill.`,
525
+ )
526
+ return lines
527
+ }
528
+
529
+ /** The server-instruction section for one or more repositories. */
530
+ export function contextInstructions(
531
+ entries: readonly ContextEntry[],
532
+ options: { scoped: boolean },
533
+ ): string {
534
+ const lines = [
535
+ '',
536
+ '## Agent context',
537
+ 'Call `context.list` first: it indexes the skills and agent instructions to load. Every `context.read` result starts with a generated preamble that maps the `ab` commands the file mentions onto these tools. Agent instructions are the repository’s own files and win over Autobuild skills for that repository.',
538
+ ]
539
+ for (const entry of entries) {
540
+ if (!options.scoped) lines.push('', `### ${entry.repo}`)
541
+ else lines.push('')
542
+ if ('error' in entry)
543
+ lines.push(
544
+ `Agent context is unavailable right now; call \`context.list\`${options.scoped ? '' : ` with repo ${code(entry.repo)}`} to retry.`,
545
+ )
546
+ else lines.push(...repositorySection(entry.index, options.scoped))
547
+ }
548
+ return lines.join('\n')
549
+ }
550
+
551
+ // ── Prompts ─────────────────────────────────────────────────────────────────
552
+
553
+ export interface ContextPrompt {
554
+ name: string
555
+ repo: string
556
+ skill: string
557
+ entry: string
558
+ description: string
559
+ }
560
+
561
+ /** The readable label a deployment-wide prompt name starts with: the
562
+ * identity without its scheme, every character outside [A-Za-z0-9_-] as `_`.
563
+ * A label never contains `.`, so the first `.` of a name ends it. */
564
+ export function promptLabel(repo: string): string {
565
+ return repo.replace(/^https?:\/\//, '').replace(/[^A-Za-z0-9_-]/g, '_')
566
+ }
567
+
568
+ function digest(repo: string, entry: string): string {
569
+ return createHash('sha256').update(`${repo}\0${entry}`).digest('hex')
570
+ }
571
+
572
+ /** One prompt per skill across `entries`, with names unique in the listing:
573
+ * the readable name (the skill on a scoped binding, `<label>.<skill>` on a
574
+ * deployment binding), suffixed `~<hash>` only for colliding names. The
575
+ * names depend only on the colliding group, so recomputing from the subset
576
+ * of repositories that share a label yields the same names. */
577
+ export function contextPrompts(
578
+ entries: readonly { repo: string; index: ContextIndex }[],
579
+ options: { scoped: boolean },
580
+ ): ContextPrompt[] {
581
+ const candidates = entries.flatMap(({ repo, index }) =>
582
+ index.skills.map((skill) => ({
583
+ base: options.scoped ? skill.name : `${promptLabel(repo)}.${skill.name}`,
584
+ repo,
585
+ skill: skill.name,
586
+ entry: skill.entry,
587
+ description: options.scoped
588
+ ? (skill.description ?? `The ${skill.name} skill.`)
589
+ : `${repo} · ${skill.entry}${skill.description !== null ? ` — ${skill.description}` : ''}`,
590
+ })),
591
+ )
592
+ const groups = new Map<string, typeof candidates>()
593
+ for (const candidate of candidates) {
594
+ const group = groups.get(candidate.base) ?? []
595
+ group.push(candidate)
596
+ groups.set(candidate.base, group)
597
+ }
598
+ const prompts: ContextPrompt[] = []
599
+ for (const [base, group] of groups) {
600
+ if (group.length === 1) {
601
+ const { base: _base, ...rest } = group[0]!
602
+ prompts.push({ name: base, ...rest })
603
+ continue
604
+ }
605
+ const named = (length: number) =>
606
+ group.map(({ base: _base, ...rest }) => ({
607
+ name: `${base}~${digest(rest.repo, rest.entry).slice(0, length)}`,
608
+ ...rest,
609
+ }))
610
+ let suffixed = named(12)
611
+ if (new Set(suffixed.map((prompt) => prompt.name)).size !== suffixed.length)
612
+ suffixed = named(64)
613
+ prompts.push(...suffixed)
614
+ }
615
+ return prompts.sort((a, b) => compare(a.name, b.name))
616
+ }
617
+
618
+ /** The label a deployment-wide prompt name was built from. */
619
+ export function promptNameLabel(name: string): string {
620
+ const dot = name.indexOf('.')
621
+ return dot < 0 ? name : name.slice(0, dot)
622
+ }
623
+
624
+ /** A prompt's messages: one user message whose text is the read's text. */
625
+ export function contextPromptMessages(
626
+ result: ContextReadResult,
627
+ ): { role: 'user'; content: { type: 'text'; text: string } }[] {
628
+ const text =
629
+ 'text' in result ? result.text : utf8.decode(Buffer.from(result.contentBase64, 'base64'))
630
+ return [{ role: 'user', content: { type: 'text', text } }]
631
+ }