@defrex/autobuild 1.0.1 → 1.1.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 (186) hide show
  1. package/README.md +6 -6
  2. package/SPEC.md +360 -229
  3. package/docs/answering-blocked-builds.md +2 -2
  4. package/docs/architecture.md +155 -45
  5. package/docs/assets/headline-wide.png +0 -0
  6. package/docs/builds.md +4 -4
  7. package/docs/cli.md +4 -4
  8. package/docs/configuration-overview.md +4 -4
  9. package/docs/configuration.md +245 -210
  10. package/docs/dispatcher-hosting.md +2 -2
  11. package/docs/dispatcher.md +1 -1
  12. package/docs/forges.md +5 -5
  13. package/docs/getting-started.md +2 -2
  14. package/docs/glossary.md +6 -6
  15. package/docs/hosted-dispatcher.md +6 -3
  16. package/docs/hosted-service.md +16 -5
  17. package/docs/integration-overview.md +15 -15
  18. package/docs/integration-tree.md +45 -38
  19. package/docs/integration.md +6 -6
  20. package/docs/mcp.md +16 -15
  21. package/docs/{landing-policy.md → merge-policy.md} +42 -24
  22. package/docs/migration-1.0.md +17 -13
  23. package/docs/operating.md +41 -18
  24. package/docs/operator-api.md +91 -15
  25. package/docs/operator-surfaces.md +8 -4
  26. package/docs/overview.md +3 -3
  27. package/docs/remote-store-protocol.md +76 -11
  28. package/docs/remote-ticket-protocol.md +1 -1
  29. package/docs/restacking.md +54 -15
  30. package/docs/setup.md +41 -6
  31. package/docs/skills.md +1 -1
  32. package/docs/spec-standard.md +6 -6
  33. package/docs/ticket-dependencies.md +7 -7
  34. package/docs/tickets.md +8 -2
  35. package/docs/troubleshooting.md +2 -2
  36. package/docs/upgrading.md +8 -3
  37. package/docs/verification.md +60 -14
  38. package/package.json +7 -5
  39. package/packages/core/src/cli/binary-direct.ts +13 -1
  40. package/packages/core/src/cli/binary-lifecycle.ts +65 -2
  41. package/packages/core/src/cli/build-control.ts +83 -28
  42. package/packages/core/src/cli/context.ts +81 -38
  43. package/packages/core/src/cli/dashboard/facts.ts +2 -1
  44. package/packages/core/src/cli/dashboard/integration-detail.ts +8 -8
  45. package/packages/core/src/cli/dashboard/integration-row.ts +40 -13
  46. package/packages/core/src/cli/dashboard/landing-display.ts +25 -0
  47. package/packages/core/src/cli/dashboard/model.ts +56 -33
  48. package/packages/core/src/cli/dashboard/poll.ts +9 -3
  49. package/packages/core/src/cli/dashboard/render.ts +59 -37
  50. package/packages/core/src/cli/dashboard/target-distance.ts +14 -0
  51. package/packages/core/src/cli/dashboard/tree.ts +3 -2
  52. package/packages/core/src/cli/dispatch-args.ts +1 -1
  53. package/packages/core/src/cli/dispatch-frontend.ts +6 -3
  54. package/packages/core/src/cli/dispatch.ts +35 -9
  55. package/packages/core/src/cli/env.ts +4 -0
  56. package/packages/core/src/cli/help.ts +30 -23
  57. package/packages/core/src/cli/main.ts +24 -8
  58. package/packages/core/src/cli/node-verification-provenance.ts +1 -97
  59. package/packages/core/src/cli/publication-settlement.ts +43 -20
  60. package/packages/core/src/cli/repository-status.ts +20 -9
  61. package/packages/core/src/cli/status.ts +42 -5
  62. package/packages/core/src/cli/store-opening.ts +6 -1
  63. package/packages/core/src/cli/terminal.ts +22 -1
  64. package/packages/core/src/cli/terminals.ts +14 -10
  65. package/packages/core/src/cli/upgrade-landing.ts +70 -30
  66. package/packages/core/src/cli/upgrade.ts +3 -1
  67. package/packages/core/src/cli/wait.ts +15 -7
  68. package/packages/core/src/cli/watch-lifetime.ts +111 -0
  69. package/packages/core/src/cli/watch.ts +634 -511
  70. package/packages/core/src/config/effective-artifact.fixture.ts +27 -0
  71. package/packages/core/src/config/effective-artifact.ts +13 -0
  72. package/packages/core/src/config/landing.ts +1 -1
  73. package/packages/core/src/config/load.ts +21 -1
  74. package/packages/core/src/config/pipeline-source.ts +28 -0
  75. package/packages/core/src/config/reference-metadata.ts +2 -0
  76. package/packages/core/src/config/reference.ts +22 -7
  77. package/packages/core/src/config/schema.ts +86 -162
  78. package/packages/core/src/context-directory.ts +26 -0
  79. package/packages/core/src/distribution-packaging.ts +26 -5
  80. package/packages/core/src/events/catalog.ts +10 -2
  81. package/packages/core/src/events/globs.ts +1 -1
  82. package/packages/core/src/events/payloads.ts +70 -1
  83. package/packages/core/src/events/policy.ts +7 -0
  84. package/packages/core/src/events/repository.ts +2 -4
  85. package/packages/core/src/events/sessions.ts +6 -6
  86. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +571 -0
  87. package/packages/core/src/kernel/auto-merge.ts +2 -2
  88. package/packages/core/src/kernel/engine.ts +255 -26
  89. package/packages/core/src/kernel/generators/leaf-restack-log.ts +10 -0
  90. package/packages/core/src/kernel/integration-landing.ts +3 -3
  91. package/packages/core/src/kernel/integration-state.ts +27 -4
  92. package/packages/core/src/kernel/leaf-restack-state.ts +28 -3
  93. package/packages/core/src/kernel/log-index.ts +13 -1
  94. package/packages/core/src/kernel/node-landing.ts +8 -8
  95. package/packages/core/src/kernel/node-parent.ts +2 -2
  96. package/packages/core/src/kernel/node-restack-transaction.ts +1 -1
  97. package/packages/core/src/kernel/node-verification-context.ts +216 -0
  98. package/packages/core/src/kernel/phases.ts +1 -1
  99. package/packages/core/src/kernel/plan-verify-selection.ts +16 -0
  100. package/packages/core/src/kernel/publication-retry.ts +168 -0
  101. package/packages/core/src/kernel/reconcile-restack.ts +29 -1
  102. package/packages/core/src/kernel/reducer.ts +82 -5
  103. package/packages/core/src/kernel/target-distance.ts +45 -0
  104. package/packages/core/src/kernel/terminal-guard.ts +10 -1
  105. package/packages/core/src/kernel/verify-stage-state.ts +123 -0
  106. package/packages/core/src/kernel/verify-stages.ts +39 -0
  107. package/packages/core/src/ontology.ts +1 -0
  108. package/packages/core/src/operator/annotations.ts +6 -0
  109. package/packages/core/src/operator/control.ts +1 -1
  110. package/packages/core/src/operator/index.ts +1 -7
  111. package/packages/core/src/operator/landings.ts +5 -1
  112. package/packages/core/src/operator/presentation.ts +6 -1
  113. package/packages/core/src/operator/query.ts +14 -18
  114. package/packages/core/src/operator/registry.ts +17 -6
  115. package/packages/core/src/operator/sandbox-host.ts +64 -40
  116. package/packages/core/src/operator/sandbox.ts +3 -0
  117. package/packages/core/src/operator/ticket-source-backend.ts +3 -12
  118. package/packages/core/src/ports/forge/contract.ts +2 -2
  119. package/packages/core/src/ports/forge/git-rewrite.ts +25 -2
  120. package/packages/core/src/ports/forge/github-readiness.ts +2 -2
  121. package/packages/core/src/ports/forge/github.ts +26 -7
  122. package/packages/core/src/ports/forge/local-git.ts +4 -4
  123. package/packages/core/src/ports/forge/readiness.ts +1 -1
  124. package/packages/core/src/ports/forge-failure.ts +24 -0
  125. package/packages/core/src/ports/workspace/build-execution.ts +3 -1
  126. package/packages/core/src/ports/workspace/phase-scratch.ts +4 -3
  127. package/packages/core/src/ports/workspace/vercel-sandbox.ts +59 -39
  128. package/packages/core/src/processes/build-child.ts +6 -8
  129. package/packages/core/src/processes/build-execution-state.ts +8 -5
  130. package/packages/core/src/processes/build-runner.ts +522 -98
  131. package/packages/core/src/processes/dispatcher.ts +186 -101
  132. package/packages/core/src/processes/execution-no-progress.ts +8 -1
  133. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  134. package/packages/core/src/processes/publication-loss.ts +8 -2
  135. package/packages/core/src/processes/publication-state.ts +42 -4
  136. package/packages/core/src/processes/repo-view.ts +14 -0
  137. package/packages/core/src/processes/verify-cycle-config.ts +96 -0
  138. package/packages/core/src/{integration → scenarios}/harness.ts +330 -317
  139. package/packages/core/src/store/adapter.ts +1 -0
  140. package/packages/core/src/store/build-scope.ts +9 -0
  141. package/packages/core/src/store/contract.ts +113 -1
  142. package/packages/core/src/store/local/schema.ts +13 -0
  143. package/packages/core/src/store/local/store.ts +42 -0
  144. package/packages/core/src/store/memory.ts +47 -0
  145. package/packages/core/src/store/operator-presence.ts +21 -0
  146. package/packages/core/src/store/phase-session.ts +10 -0
  147. package/packages/core/src/store/reducer-value-shapes.json +5081 -4160
  148. package/packages/core/src/store/remote/client.ts +47 -1
  149. package/packages/core/src/store/remote/compatibility.ts +2 -0
  150. package/packages/core/src/store/remote/protocol.ts +4 -0
  151. package/packages/core/src/store/remote/version.ts +3 -1
  152. package/packages/core/src/store/retention.ts +2 -3
  153. package/packages/core/src/store/session-handle.ts +9 -0
  154. package/packages/core/src/store/streams/session-writer.ts +1 -1
  155. package/packages/core/src/store/types.ts +12 -2
  156. package/packages/core/src/testing/index.ts +11 -1
  157. package/packages/core/src/testing/temp-directories.ts +58 -0
  158. package/skills/code-review/SKILL.md +23 -9
  159. package/skills/finalize/SKILL.md +15 -7
  160. package/skills/guide/SKILL.md +253 -118
  161. package/skills/guide/references/integration-tree.md +45 -38
  162. package/skills/guide/references/{landing-policy.md → merge-policy.md} +42 -24
  163. package/skills/guide/references/migration-1.0.md +17 -13
  164. package/skills/guide/references/operator-api.md +91 -15
  165. package/skills/guide/references/remote-store-protocol.md +76 -11
  166. package/skills/guide/references/remote-ticket-protocol.md +1 -1
  167. package/skills/guide/references/restacking.md +54 -15
  168. package/skills/guide/references/setup.md +41 -6
  169. package/skills/guide/references/spec-standard.md +6 -6
  170. package/skills/guide/references/ticket-dependencies.md +7 -7
  171. package/skills/implement/SKILL.md +43 -17
  172. package/skills/operate/SKILL.md +117 -116
  173. package/skills/plan/SKILL.md +39 -13
  174. package/skills/plan-review/SKILL.md +15 -10
  175. package/skills/reconcile/SKILL.md +22 -3
  176. package/skills/spec/SKILL.md +19 -19
  177. package/skills/tickets/SKILL.md +9 -7
  178. package/templates/autobuild.toml +1 -1
  179. package/templates/hosted-service/package.json +2 -2
  180. package/packages/core/src/orchestrator/approvals.ts +0 -115
  181. package/packages/core/src/orchestrator/conversation.ts +0 -167
  182. package/packages/core/src/orchestrator/model.ts +0 -86
  183. package/packages/core/src/orchestrator/prompt.ts +0 -63
  184. package/packages/core/src/orchestrator/tools.ts +0 -117
  185. package/packages/core/src/orchestrator/turn-runner.ts +0 -457
  186. package/packages/core/src/processes/orchestrator-tick.ts +0 -360
@@ -17,15 +17,15 @@ session.
17
17
  ## Node tickets and targets
18
18
 
19
19
  Write a node ticket as a **charter**: the integration goal, checkable completion
20
- conditions for the whole, and its destination and landing expectations under the
20
+ conditions for the whole, and its destination and merge expectations under the
21
21
  repository's effective policy. Put evolving feature specifics in child tickets.
22
22
  The charter still follows all four parts of the spec standard: what and why,
23
23
  verifiable acceptance criteria, out of scope, and evidence.
24
24
 
25
25
  For example: “Integrate a coherent account-management flow so users can manage
26
26
  their account in one place. Done means the child-delivered account settings and
27
- account closure flows work together and pass integration verification. Land the
28
- complete flow into its parent under the configured landing policy.” Record the
27
+ account closure flows work together and pass integration verification. Merge the
28
+ complete flow into its parent under the configured merge policy.” Record the
29
29
  scope exclusions and supporting evidence alongside these criteria; describe each
30
30
  flow's detailed requirements in its child spec.
31
31
 
@@ -56,8 +56,8 @@ the split is warranted under the standard's
56
56
  guidance, then explicitly choose root or a node before filing,
57
57
  including when fleshing out an existing ticket splits it into several tickets.
58
58
  Consult the shared destination criteria and read
59
- the repository's effective landing policy in `autobuild.toml`; explain the actual
60
- landing and consent flow to the human in plain terms. Ask the human when the
59
+ the repository's effective merge policy in `autobuild.toml`; explain the actual
60
+ merge and consent flow to the human in plain terms. Ask the human when the
61
61
  choice is unclear from grooming. Root is valid when each ticket can ship alone.
62
62
  Choosing root or a node never changes the requested workflow state or silently
63
63
  promotes tickets; the placement instructions below still apply.
@@ -111,8 +111,10 @@ setting is absent.
111
111
  When the explicitly named destination equals `[tickets].readyState`, tell the
112
112
  human in the completion response that the ticket may be claimed by the next
113
113
  dispatch once the repository's label, dependency, intake, capacity, and other
114
- readiness gates are satisfied, and that you will operate it from there (see
115
- [After filing: operate what you queued](#after-filing-operate-what-you-queued)).
114
+ readiness gates are satisfied. Before ready filing, follow
115
+ [After filing: check operator presence](#after-filing-check-operator-presence):
116
+ with a live operator, say the existing operator will pick it up; without one,
117
+ say you will operate it. The human's explicit instructions override either default.
116
118
 
117
119
  If grooming established prerequisites, follow the complete
118
120
  [safe blocker-filing workflow](../ab-guide/references/ticket-dependencies.md).
@@ -226,20 +228,18 @@ files over the store's size limit), keep the external link in Evidence and say
226
228
  plainly, in the spec and to the human, that builds cannot read it, so the
227
229
  planner does not treat it as a contract.
228
230
 
229
- ## After filing: operate what you queued
231
+ ## After filing: check operator presence
230
232
 
231
- Once work you specified sits in the ready state, its builds start without
232
- anyone watching them. By default, the agent that wrote the spec becomes their
233
- operator agent. You hold the context an escalation asks about — the intent, the
234
- alternatives the human rejected, what was ruled out of scope — and a build
235
- blocked on a question you could answer should not wait for a human.
233
+ Before leaving work in the ready state, run `ab repository status --json` and
234
+ inspect `operator.registrations`. If a live operator is present, record the
235
+ operating context in the ticket body: intent, rejected alternatives, and why
236
+ things were ruled out of scope. File the work, tell the human the existing
237
+ operator will pick it up, and stop without arming a watch.
236
238
 
237
- So when this conversation leaves work in the ready state, say in the
238
- completion response that you will shepherd it, then load the `ab-operate`
239
- skill and follow it: arm the standing watch, reconcile status, resolve
240
- attention, and report each outcome until every build you queued has merged or
241
- otherwise ended. Shepherd what this conversation queued unless the human
242
- widens the scope.
239
+ If no operator is present, say you will operate, load `ab-operate`, and follow
240
+ its startup check and standing watch. The role covers the builds the repository's dispatcher dispatches,
241
+ including newly dispatched builds, rather than only this conversation's tickets.
242
+ The human's explicit instructions override either default.
243
243
 
244
244
  This is the default, not a requirement:
245
245
 
@@ -12,7 +12,7 @@ content and blocker relationships. The default file source needs no secret.
12
12
  ## Node tickets and targets
13
13
 
14
14
  Use a spec-standard charter for the node's integration goal, whole-level
15
- completion and policy-controlled landing; put feature specifics in children.
15
+ completion and policy-controlled merge; put feature specifics in children.
16
16
  While the node is open, iterate by adding spec-standard children targeting its
17
17
  ticket id, pushing small maintainer-authorized tweaks to its recorded branch
18
18
  with meaningful intent in commit messages, or explicitly revising its charter.
@@ -169,12 +169,14 @@ bounces.
169
169
  **Don't hand-move anything out of `doing/`** — a build owns it. If you need to
170
170
  stop a build, that's `ab` (or a human), not `mv`.
171
171
 
172
- When a conversation queues work by moving it into `ready/` (or the configured
173
- ready state of any source), the agent that queued it becomes its operator agent by
174
- default, as the `ab-spec` skill describes under "After filing": load the
175
- `ab-operate` skill and shepherd those builds to completion unless the human
176
- says they will operate them, hands them to another agent, or the session
177
- cannot keep a long-running watch.
172
+ Before moving work into `ready/` (or any source's configured ready state),
173
+ check `ab repository status --json` for live `operator.registrations`. If an
174
+ operator is present, preserve intent, rejected alternatives and out-of-scope
175
+ reasons in the ticket body, file, tell the human the existing operator will
176
+ pick it up, and stop without a watch. Otherwise load `ab-operate` and take the
177
+ role for the builds the repository's dispatcher dispatches. Explicit human
178
+ instructions override these defaults; non-ready filing needs no watch. See
179
+ [After filing](../ab-spec/SKILL.md#after-filing-check-operator-presence).
178
180
 
179
181
  ## Icebox
180
182
 
@@ -6,7 +6,7 @@ baseBranch = "main"
6
6
  capacity = 4
7
7
 
8
8
  # First matching rule wins. Empty rules: leaves auto, nodes consent.
9
- landing = []
9
+ merge = []
10
10
 
11
11
  # Commands are derived by the setup agent from this repository's actual toolchain.
12
12
  [commands]
@@ -4,8 +4,8 @@
4
4
  "build": "ab-hosted-service-build"
5
5
  },
6
6
  "dependencies": {
7
- "@defrex/autobuild-hosted-store-service": "1.0.1",
8
- "@defrex/autobuild": "1.0.1",
7
+ "@defrex/autobuild-hosted-store-service": "1.1.0",
8
+ "@defrex/autobuild": "1.1.0",
9
9
  "next": "16.1.6",
10
10
  "react": "19.2.4",
11
11
  "react-dom": "19.2.4"
@@ -1,115 +0,0 @@
1
- /**
2
- * The turn approval list (AUT-342): which registry tool calls suspend a turn
3
- * until the operator answers. Configured as `[orchestrator].approvals` — a
4
- * list of registry tool names, optionally qualified by the accepted value of
5
- * the tool's discriminator field (`tool:qualifier`).
6
- *
7
- * Semantics:
8
- * - A bare entry (`builds.control`) suspends every call to that tool.
9
- * - A qualified entry (`tickets.move:ready`) suspends only calls whose
10
- * discriminator equals the qualifier; other values of the same tool run
11
- * without pause.
12
- * - An entry naming an absent or unknown tool is inert by design, never an
13
- * error — the default list is stable while the registry grows.
14
- * - A qualified entry for a tool without a declared discriminator never
15
- * matches (there is nothing to compare).
16
- *
17
- * Nothing here encodes this repository's specifics.
18
- */
19
- import type { ToolApprovalStatus } from 'ai'
20
-
21
- /** A per-tool approval configuration value: a static status or a function
22
- * deciding from the call's input. (The SDK's per-tool map accepts both.) */
23
- export type ApprovalDecision = ToolApprovalStatus | ((input: unknown) => ToolApprovalStatus)
24
-
25
- /** The registry tools' discriminator fields, for qualified entries. A tool
26
- * absent from this map has no discriminator; only bare entries match it. */
27
- const DISCRIMINATOR_FIELDS: Record<string, string> = {
28
- 'builds.control': 'action',
29
- 'builds.answer': 'resolution',
30
- 'tickets.move': 'state',
31
- }
32
-
33
- export interface ParsedApprovalEntry {
34
- tool: string
35
- qualifier?: string
36
- }
37
-
38
- /** Parse one configured entry into its tool and optional qualifier. The
39
- * config schema already enforces the entry shape syntactically. */
40
- export function parseApprovalEntry(entry: string): ParsedApprovalEntry {
41
- const separator = entry.indexOf(':')
42
- if (separator === -1) return { tool: entry }
43
- return { tool: entry.slice(0, separator), qualifier: entry.slice(separator + 1) }
44
- }
45
-
46
- /** Parse the whole configured list. Duplicate entries collapse harmlessly:
47
- * the resulting matcher is a predicate, not a table. */
48
- export function parseApprovalEntries(entries: readonly string[]): ParsedApprovalEntry[] {
49
- return entries.map(parseApprovalEntry)
50
- }
51
-
52
- /**
53
- * The AI SDK `toolApproval` per-tool configuration for the parsed list: a
54
- * bare entry maps the whole tool to `user-approval`; a qualified entry maps
55
- * to a function that returns `user-approval` when the discriminator equals
56
- * one of the tool's configured qualifiers, else `not-applicable`. Tools with
57
- * no matching entry get no key at all — the SDK treats an absent key as
58
- * not-applicable.
59
- */
60
- export function approvalConfiguration(
61
- entries: readonly ParsedApprovalEntry[],
62
- ): Record<string, ApprovalDecision> {
63
- const bare = new Set<string>()
64
- const qualified = new Map<string, Set<string>>()
65
- for (const entry of entries) {
66
- if (entry.qualifier === undefined) {
67
- bare.add(entry.tool)
68
- continue
69
- }
70
- if (bare.has(entry.tool)) continue
71
- const set = qualified.get(entry.tool) ?? new Set<string>()
72
- set.add(entry.qualifier)
73
- qualified.set(entry.tool, set)
74
- }
75
- const configuration: Record<string, ApprovalDecision> = {}
76
- for (const tool of bare) configuration[tool] = 'user-approval'
77
- for (const [tool, qualifiers] of qualified) {
78
- if (bare.has(tool)) continue
79
- const field = DISCRIMINATOR_FIELDS[tool]
80
- configuration[tool] = (input: unknown) => {
81
- // A qualified entry for a tool without a declared discriminator never
82
- // matches — there is nothing to compare.
83
- if (field === undefined) return 'not-applicable'
84
- const discriminator =
85
- typeof input === 'object' && input !== null
86
- ? (input as Record<string, unknown>)[field]
87
- : undefined
88
- return typeof discriminator === 'string' && qualifiers.has(discriminator)
89
- ? 'user-approval'
90
- : 'not-applicable'
91
- }
92
- }
93
- return configuration
94
- }
95
-
96
- /** Whether a specific call would be suspended — the mirror of
97
- * `approvalConfiguration` for tests and for the runner's own diagnostics. */
98
- export function callNeedsApproval(
99
- entries: readonly ParsedApprovalEntry[],
100
- tool: string,
101
- input: unknown,
102
- ): boolean {
103
- for (const entry of entries) {
104
- if (entry.tool !== tool) continue
105
- if (entry.qualifier === undefined) return true
106
- const field = DISCRIMINATOR_FIELDS[tool]
107
- if (field === undefined) continue
108
- const discriminator =
109
- typeof input === 'object' && input !== null
110
- ? (input as Record<string, unknown>)[field]
111
- : undefined
112
- if (discriminator === entry.qualifier) return true
113
- }
114
- return false
115
- }
@@ -1,167 +0,0 @@
1
- /**
2
- * Durable conversation reconstruction (AUT-342): a turn runner holds no
3
- * process memory. On every invocation the whole conversation is rebuilt from
4
- * the session's durable state alone — the finalized artifacts of earlier
5
- * turns, the live stream of the open turn, and the session events.
6
- *
7
- * Ordering rule: a turn's assembled messages attach AT ITS `turn.started`
8
- * event, not at its terminal fact. Attaching at the terminal fact would
9
- * place a message posted while the turn was suspended BEFORE that turn's
10
- * already-generated output, interleaving the new message into the middle of
11
- * the checkpoint the original invocation produced — breaking the identical-
12
- * input guarantee for a resumed turn in exactly the reachable case (a
13
- * message landing during a suspension). Attached at `turn.started`, every
14
- * step the original invocation completed appears verbatim and in the
15
- * position the model generated it from, and a mid-suspension message reads
16
- * as a plain next user message.
17
- *
18
- * Message-triggered turns contribute no input message of their own (the
19
- * `message.posted` fact is the input); wake-triggered turns carry their
20
- * input — the event record and the build's reduced state, frozen at wake
21
- * time — in the `turn.started` payload, so reconstruction is byte-identical
22
- * across invocations even though live build state keeps moving.
23
- */
24
- import { assembleUIMessageDocument } from '../store/streams/assemble'
25
- import type { StreamPart, StreamRead } from '../store/streams/types'
26
- import type { UIMessage } from 'ai'
27
- import type { BuildStore } from '../store/types'
28
- import type { SessionEvent } from '../events/sessions'
29
- import type { StreamRecord } from '../store/streams/types'
30
-
31
- const STREAM_ARTIFACT_PREFIX = 'stream:'
32
-
33
- interface TurnStreamSource {
34
- /** The turn's stream id, from its `turn.started` fact. */
35
- stream: string
36
- /** Durable status of the stream at read time. */
37
- status: 'open' | 'closed'
38
- }
39
-
40
- async function readTurnDocument(
41
- store: BuildStore,
42
- sessionId: string,
43
- source: TurnStreamSource,
44
- ): Promise<UIMessage[]> {
45
- if (source.status === 'open') {
46
- const read: StreamRead = await store.readStream(source.stream)
47
- const parts: StreamPart[] = read.chunks.flatMap((chunk) => chunk.parts)
48
- const { document } = await assembleUIMessageDocument(parts)
49
- return document
50
- }
51
- // Closed streams finalize into the `stream:<id>` session artifact; the
52
- // chunks themselves are retention-pruned, so the artifact is the durable
53
- // form a later invocation must read.
54
- const artifact = await store.getSessionArtifact(
55
- sessionId,
56
- `${STREAM_ARTIFACT_PREFIX}${source.stream}`,
57
- )
58
- if (artifact === null) return []
59
- let parsed: unknown
60
- try {
61
- parsed = JSON.parse(new TextDecoder().decode(artifact.content))
62
- } catch {
63
- return []
64
- }
65
- return Array.isArray(parsed) ? (parsed as UIMessage[]) : []
66
- }
67
-
68
- export interface ReconstructedConversation {
69
- messages: UIMessage[]
70
- /** Per turn, in start order: the turn id and how many messages its
71
- * document contributed. Diagnostics, not contract. */
72
- turns: { turn: string; messages: number }[]
73
- }
74
-
75
- /**
76
- * Reconstruct the conversation for a session from durable state alone.
77
- * `events` must be the complete session event log (seq 1 upward).
78
- */
79
- export async function reconstructConversation(
80
- store: BuildStore,
81
- sessionId: string,
82
- events: SessionEvent[],
83
- ): Promise<ReconstructedConversation> {
84
- const messages: UIMessage[] = []
85
- const turns: ReconstructedConversation['turns'] = []
86
-
87
- // Resolve each turn's stream status up front so the walk stays ordered:
88
- // the open turn reads its live stream, closed turns read their artifacts.
89
- const sources = new Map<string, TurnStreamSource>()
90
- for (const event of events) {
91
- if (event.type !== 'turn.started') continue
92
- const record: StreamRecord | null = await store.getStream(event.payload.stream)
93
- sources.set(event.payload.turn, {
94
- stream: event.payload.stream,
95
- status: record?.status === 'open' ? 'open' : 'closed',
96
- })
97
- }
98
-
99
- for (const event of events) {
100
- if (event.type === 'message.posted') {
101
- messages.push({
102
- id: `msg_${event.seq}`,
103
- role: 'user',
104
- parts: [{ type: 'text', text: event.payload.text }],
105
- })
106
- } else if (event.type === 'turn.started') {
107
- const source = sources.get(event.payload.turn)
108
- if (source === undefined) continue
109
- // A wake turn's input is the frozen snapshot carried by its own
110
- // `turn.started` fact — recorded before the fact, so every invocation
111
- // reconstructs the identical user message.
112
- if (event.payload.trigger.kind === 'wake' && event.payload.wake !== undefined) {
113
- messages.push(
114
- wakeTriggerInputMessage({
115
- build: event.payload.trigger.build,
116
- journal: event.payload.trigger.journal === true,
117
- type: event.payload.trigger.type,
118
- event: event.payload.wake.event,
119
- buildState: event.payload.wake.buildState,
120
- }),
121
- )
122
- }
123
- const document = await readTurnDocument(store, sessionId, source)
124
- turns.push({ turn: event.payload.turn, messages: document.length })
125
- messages.push(...document)
126
- }
127
- }
128
-
129
- return { messages, turns }
130
- }
131
-
132
- /**
133
- * The user input message a wake trigger delivers to its turn: the attention
134
- * event record and — for a build wake — the build's reduced state, as JSON.
135
- * A journal wake names the repository journal instead of a build and carries
136
- * no build-state section (there is no build; the turn's operator registry
137
- * exposes bounded repository reads). The runner embeds the same object in
138
- * the `turn.started` payload, so this function and the reconstruction agree
139
- * by construction.
140
- */
141
- export function wakeTriggerInputMessage(input: {
142
- build?: string
143
- journal?: boolean
144
- type: string
145
- event: { seq: number; ts: string; type: string; payload: unknown }
146
- buildState?: unknown
147
- }): UIMessage {
148
- const journal = input.journal === true || input.build === undefined
149
- return {
150
- id: journal ? `wake_journal_${input.event.seq}` : `wake_${input.build}_${input.event.seq}`,
151
- role: 'user',
152
- parts: [
153
- {
154
- type: 'text',
155
- text: journal
156
- ? `Repository-journal attention event: ${input.type} (seq ${input.event.seq}).\n` +
157
- 'Event record:\n' +
158
- JSON.stringify(input.event, null, 2)
159
- : `Attention event on build ${input.build}: ${input.type} (seq ${input.event.seq}).\n` +
160
- 'Event record:\n' +
161
- JSON.stringify(input.event, null, 2) +
162
- '\nBuild state:\n' +
163
- JSON.stringify(input.buildState, null, 2),
164
- },
165
- ],
166
- }
167
- }
@@ -1,86 +0,0 @@
1
- /**
2
- * Model resolution and typed failure classification (AUT-342): the
3
- * orchestrator's model comes from `[orchestrator].model`, a provider-
4
- * qualified string in the same vocabulary as `[roles]`, resolved through the
5
- * deployment's gateway credential. Model failures are typed on
6
- * `turn.failed` — provider availability, exhaustion, credentials, and
7
- * configuration are distinguished so nothing is ever retried unboundedly and
8
- * the class is visible in the session's reduced state.
9
- */
10
- import { LoadAPIKeyError, createGateway } from 'ai'
11
- import {
12
- GatewayAuthenticationError,
13
- GatewayInternalServerError,
14
- GatewayModelNotFoundError,
15
- GatewayRateLimitError,
16
- } from '@ai-sdk/gateway'
17
-
18
- /** Strip the optional `vercel-ai-gateway/` prefix so the value is written
19
- * exactly as `[roles]` spells it while the gateway provider receives the
20
- * bare model id. */
21
- export function resolveGatewayModelId(model: string): string {
22
- const prefix = 'vercel-ai-gateway/'
23
- return model.startsWith(prefix) ? model.slice(prefix.length) : model
24
- }
25
-
26
- /** Resolve the configured model string through the deployment's gateway
27
- * credential (`AI_GATEWAY_API_KEY`, read by `createGateway`). Missing or
28
- * rejected credentials surface at call time and classify as `credentials`. */
29
- export function resolveGatewayModel(model: string): ReturnType<ReturnType<typeof createGateway>> {
30
- return createGateway()(resolveGatewayModelId(model))
31
- }
32
-
33
- /** The typed model-failure vocabulary, mirroring `turn.failed`'s `kind`. */
34
- export type TurnFailureKind =
35
- | 'provider-unavailable'
36
- | 'exhausted'
37
- | 'credentials'
38
- | 'configuration'
39
- | 'internal'
40
-
41
- /**
42
- * Classify one model error. The gateway's own error classes are the primary
43
- * vocabulary: `GatewayModelNotFoundError` (`type: 'model_not_found'`, thrown
44
- * at call time — the gateway constructs a model for any id, so unknown-model
45
- * is never `NoSuchModelError`) is `configuration`;
46
- * `GatewayAuthenticationError` or `LoadAPIKeyError` (which the gateway does
47
- * not export; `ai` re-exports it from `@ai-sdk/provider`) is `credentials`;
48
- * `GatewayRateLimitError` or any 429 is `exhausted`;
49
- * `GatewayInternalServerError` and other 5xx/network/timeout errors are
50
- * `provider-unavailable`. Remaining errors classify by their `statusCode`
51
- * when present, else `internal`.
52
- */
53
- export function classifyModelError(error: unknown): TurnFailureKind {
54
- // `ai` rewrites gateway authentication errors flowing through a stream
55
- // into a plain Error (or AISDKError in production) that keeps only the
56
- // class NAME — classify those by name before the instanceof checks.
57
- const name =
58
- typeof (error as { name?: unknown })?.name === 'string'
59
- ? ((error as { name?: string }).name ?? '')
60
- : ''
61
- if (name === 'GatewayAuthenticationError' || name === 'GatewayError') return 'credentials'
62
- if (error instanceof GatewayModelNotFoundError) return 'configuration'
63
- if (error instanceof GatewayAuthenticationError || error instanceof LoadAPIKeyError) {
64
- return 'credentials'
65
- }
66
- if (error instanceof GatewayRateLimitError) return 'exhausted'
67
- if (error instanceof GatewayInternalServerError) return 'provider-unavailable'
68
-
69
- // Non-gateway shapes: classify by what they carry.
70
- const candidate = error as { statusCode?: unknown; name?: unknown; message?: unknown }
71
- if (typeof candidate?.statusCode === 'number') {
72
- if (candidate.statusCode === 401 || candidate.statusCode === 403) return 'credentials'
73
- if (candidate.statusCode === 404) return 'configuration'
74
- if (candidate.statusCode === 429) return 'exhausted'
75
- if (candidate.statusCode >= 500) return 'provider-unavailable'
76
- }
77
- const text = `${candidate?.name ?? ''} ${candidate?.message ?? ''}`.toLowerCase()
78
- if (text.includes('api key') || text.includes('apikey') || text.includes('unauthorized')) {
79
- return 'credentials'
80
- }
81
- if (text.includes('rate limit') || text.includes('too many requests')) return 'exhausted'
82
- if (text.includes('timeout') || text.includes('econnrefused') || text.includes('enotfound')) {
83
- return 'provider-unavailable'
84
- }
85
- return 'internal'
86
- }
@@ -1,63 +0,0 @@
1
- /**
2
- * The turn's system prompt (AUT-342): the canonical `ab-operate` skill body,
3
- * plus the current `operator-notes` artifact, plus the session's wake
4
- * settings, plus the session's repository identity.
5
- *
6
- * The skill is read from the distribution's `skills/operate/SKILL.md` — the
7
- * same tree `ab init` vendors from — through `distributionPath`, and is
8
- * shipped into every hosted function that executes a turn (see
9
- * packages/hosted-dispatcher/src/ship-packed-distribution.ts). It is
10
- * self-contained per the vendored-skill rule and teaches the tool surface,
11
- * the attention set, and when to escalate rather than act; nothing
12
- * repository-specific may be inlined here. The same skill is the manual for
13
- * the orchestrator role in a local coding-agent session (the `ab` CLI), so
14
- * hosted-only material stays under its own heading.
15
- */
16
- import { readFile } from 'node:fs/promises'
17
- import { distributionPath } from '../distribution'
18
- import { OPERATOR_NOTES_REPO_KIND } from '../store/retention'
19
- import type { BuildStore } from '../store/types'
20
- import type { OrchestratorConfig } from '../config/schema'
21
-
22
- /** Where the canonical skill lives in the distribution tree. */
23
- export const OPERATE_SKILL_PATH = 'skills/operate/SKILL.md'
24
-
25
- /** Read the canonical skill body from the distribution tree. Throws when
26
- * the file is missing — a deployment that cannot load the canonical skill
27
- * must not run turns with a silently empty system prompt. */
28
- export async function readOperateSkill(): Promise<string> {
29
- return readFile(distributionPath(...OPERATE_SKILL_PATH.split('/')), 'utf8')
30
- }
31
-
32
- export interface TurnPromptInput {
33
- store: BuildStore
34
- repo: string
35
- /** The session's wake globs (already resolved — empty means message-only). */
36
- wakeGlobs: readonly string[]
37
- config: OrchestratorConfig
38
- }
39
-
40
- /** Assemble the system prompt. The operator-notes artifact is empty when
41
- * absent; the skill body is always present (missing file throws). */
42
- export async function buildTurnSystemPrompt(input: TurnPromptInput): Promise<string> {
43
- const skill = await readOperateSkill()
44
- const notes = await input.store.getRepoArtifact(input.repo, OPERATOR_NOTES_REPO_KIND)
45
- const notesText = notes === null ? '' : new TextDecoder().decode(notes.content).trim()
46
- return [
47
- skill,
48
- '',
49
- '## Repository',
50
- '',
51
- `You operate the repository ${JSON.stringify(input.repo)}. Every tool call is bound to this repository; you never supply a repo argument yourself.`,
52
- '',
53
- '## Operator notes',
54
- '',
55
- notesText === '' ? '(none recorded)' : notesText,
56
- '',
57
- '## Wake settings',
58
- '',
59
- input.wakeGlobs.length === 0
60
- ? 'This session wakes only on operator messages (no attention-event wake sources).'
61
- : `This session wakes on these attention-event globs: ${input.wakeGlobs.map((glob) => JSON.stringify(glob)).join(', ')}.`,
62
- ].join('\n')
63
- }