@defrex/autobuild 1.15.0 → 1.17.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 (80) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +110 -10
  3. package/docs/answering-blocked-builds.md +34 -1
  4. package/docs/architecture.md +41 -7
  5. package/docs/configuration.md +41 -7
  6. package/docs/dispatcher-hosting.md +3 -0
  7. package/docs/operator-api.md +15 -5
  8. package/docs/plugin-authoring.md +1 -0
  9. package/docs/remote-store-protocol.md +13 -3
  10. package/docs/remote-ticket-protocol.md +3 -1
  11. package/docs/restacking.md +41 -1
  12. package/docs/setup.md +15 -6
  13. package/docs/troubleshooting.md +51 -3
  14. package/docs/workspaces.md +4 -1
  15. package/package.json +3 -3
  16. package/packages/core/src/cli/accounts.ts +3 -0
  17. package/packages/core/src/cli/binary-direct.ts +14 -1
  18. package/packages/core/src/cli/binary.ts +10 -7
  19. package/packages/core/src/cli/dispatch.ts +610 -356
  20. package/packages/core/src/cli/secrets.ts +2 -0
  21. package/packages/core/src/config/schema.ts +15 -2
  22. package/packages/core/src/events/payloads.ts +8 -5
  23. package/packages/core/src/events/repository.ts +12 -6
  24. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/e28c68e63cbd265f.json +108 -0
  25. package/packages/core/src/kernel/engine.ts +118 -0
  26. package/packages/core/src/kernel/reconcile-restack.ts +72 -9
  27. package/packages/core/src/kernel/reducer-revisions.ts +1 -0
  28. package/packages/core/src/kernel/tracked-dirt.ts +173 -0
  29. package/packages/core/src/ontology.ts +1 -0
  30. package/packages/core/src/operator/index.ts +10 -0
  31. package/packages/core/src/operator/merged-builds.ts +51 -0
  32. package/packages/core/src/operator/registry.ts +190 -101
  33. package/packages/core/src/operator/repo-argument.ts +43 -0
  34. package/packages/core/src/ports/tickets/grants.ts +2 -0
  35. package/packages/core/src/ports/tickets/remote.ts +2 -0
  36. package/packages/core/src/ports/types.ts +25 -4
  37. package/packages/core/src/ports/workspace/vercel-command-diagnostics.ts +144 -0
  38. package/packages/core/src/ports/workspace/vercel-sandbox.ts +811 -169
  39. package/packages/core/src/processes/build-child.ts +15 -1
  40. package/packages/core/src/processes/build-runner.ts +349 -20
  41. package/packages/core/src/processes/dispatcher.ts +509 -104
  42. package/packages/core/src/processes/harvest-child.ts +21 -1
  43. package/packages/core/src/processes/harvest-runner.ts +82 -35
  44. package/packages/core/src/processes/invocation-budget.ts +6 -0
  45. package/packages/core/src/processes/launch-cut.ts +37 -0
  46. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  47. package/packages/core/src/processes/provisioning-progress.ts +23 -0
  48. package/packages/core/src/processes/repo-view.ts +25 -4
  49. package/packages/core/src/processes/workspace-preparation.ts +1 -0
  50. package/packages/core/src/store/adapter.ts +34 -5
  51. package/packages/core/src/store/build-feed.ts +148 -22
  52. package/packages/core/src/store/build-scope.ts +12 -3
  53. package/packages/core/src/store/caller-attribution.ts +170 -0
  54. package/packages/core/src/store/contract.ts +1038 -165
  55. package/packages/core/src/store/local/schema.ts +12 -1
  56. package/packages/core/src/store/local/store.ts +260 -25
  57. package/packages/core/src/store/memory.ts +156 -9
  58. package/packages/core/src/store/phase-session.ts +23 -3
  59. package/packages/core/src/store/reducer-value-shapes.json +5351 -5338
  60. package/packages/core/src/store/remote/client.ts +90 -11
  61. package/packages/core/src/store/remote/credentials.ts +2 -0
  62. package/packages/core/src/store/remote/index.ts +31 -5
  63. package/packages/core/src/store/remote/protocol.ts +45 -8
  64. package/packages/core/src/store/remote/released-clients.json +22 -0
  65. package/packages/core/src/store/remote/released-reducer-values/1.16.0.json +36358 -0
  66. package/packages/core/src/store/remote/released-reducer-values/1.17.0.json +36367 -0
  67. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  68. package/packages/core/src/store/remote/released-value-policy.ts +7 -0
  69. package/packages/core/src/store/session-handle.ts +12 -3
  70. package/packages/core/src/store/types.ts +48 -3
  71. package/packages/core/src/testing/reduced-read-budget.ts +310 -12
  72. package/skills/guide/SKILL.md +58 -9
  73. package/skills/guide/references/operator-api.md +15 -5
  74. package/skills/guide/references/plugin-authoring.md +1 -0
  75. package/skills/guide/references/remote-store-protocol.md +13 -3
  76. package/skills/guide/references/remote-ticket-protocol.md +3 -1
  77. package/skills/guide/references/restacking.md +41 -1
  78. package/skills/guide/references/setup.md +15 -6
  79. package/skills/operate/SKILL.md +31 -7
  80. package/templates/hosted-service/package.json +2 -2
@@ -11,6 +11,8 @@
11
11
  * Browser-safe: no `Buffer` and no Bun APIs, because the operator web app
12
12
  * bundles the store contract and the remote protocol.
13
13
  */
14
+ import { z } from 'zod'
15
+ import { ticketRefSchema, type TicketRef } from '../ontology'
14
16
  import type { BuildRecord } from './types'
15
17
 
16
18
  /** One build whose latest change position is after the requested position. */
@@ -72,11 +74,12 @@ export interface BuildPageOptions extends BuildPageFilters {
72
74
  limit?: number
73
75
  }
74
76
 
75
- /** The order a page walks: by creation, or by update under `activeSince`. */
76
- export type BuildPageOrder = 'created' | 'updated'
77
+ /** The order a page walks: by creation, or by update under `activeSince`;
78
+ * `merged` is the merged listing's merge-time order. */
79
+ export type BuildPageOrder = 'created' | 'updated' | 'merged'
77
80
 
78
- /** The cursor's decoded sort key: the adapter's exact creation or update key
79
- * and slug, and which of the two orders it continues. */
81
+ /** The cursor's decoded sort key: the adapter's exact creation, update or
82
+ * merge key and slug, and which order it continues. */
80
83
  export interface BuildPageCursor {
81
84
  order: BuildPageOrder
82
85
  at: string
@@ -95,11 +98,19 @@ export class BuildFeedValidationError extends Error {
95
98
  * the paged listing. The client never falls back to listing builds or reading
96
99
  * events to answer instead. */
97
100
  export class BuildFeedUnsupportedError extends Error {
98
- constructor(readonly capability: 'changedBuilds' | 'buildPage' | 'buildPageFilters') {
101
+ constructor(
102
+ readonly capability: 'changedBuilds' | 'buildPage' | 'buildPageFilters' | 'mergedBuildPage',
103
+ ) {
99
104
  super(
100
105
  capability === 'buildPageFilters'
101
106
  ? 'the remote store does not filter the paged build listing'
102
- : `the remote store does not serve ${capability === 'changedBuilds' ? 'the changed-builds feed' : 'the paged build listing'}`,
107
+ : `the remote store does not serve ${
108
+ capability === 'changedBuilds'
109
+ ? 'the changed-builds feed'
110
+ : capability === 'mergedBuildPage'
111
+ ? 'the merged build listing'
112
+ : 'the paged build listing'
113
+ }`,
103
114
  )
104
115
  this.name = 'BuildFeedUnsupportedError'
105
116
  }
@@ -157,8 +168,13 @@ export function parseBuildPageLimitParam(value: string | null): number {
157
168
  }
158
169
 
159
170
  /** Cursor format versions: v1 continues creation order (its bytes predate
160
- * filters and stay unchanged); v2 continues update order. */
161
- const CURSOR_VERSIONS: Record<BuildPageOrder, number> = { created: 1, updated: 2 }
171
+ * filters and stay unchanged); v2 continues update order; v3 continues the
172
+ * merged listing's merge-time order. */
173
+ const CURSOR_VERSIONS: Record<BuildPageOrder, number> = {
174
+ created: 1,
175
+ updated: 2,
176
+ merged: 3,
177
+ }
162
178
  const MAX_CURSOR_LENGTH = 2048
163
179
 
164
180
  function toBase64Url(text: string): string {
@@ -177,7 +193,11 @@ function fromBase64Url(value: string): string {
177
193
  /** Encode an adapter's sort key as an opaque cursor. */
178
194
  export function encodeBuildPageCursor(cursor: BuildPageCursor): string {
179
195
  return toBase64Url(
180
- JSON.stringify({ v: CURSOR_VERSIONS[cursor.order], at: cursor.at, slug: cursor.slug }),
196
+ JSON.stringify({
197
+ v: CURSOR_VERSIONS[cursor.order],
198
+ at: cursor.at,
199
+ slug: cursor.slug,
200
+ }),
181
201
  )
182
202
  }
183
203
 
@@ -205,14 +225,15 @@ export function decodeBuildPageCursor(cursor: unknown): BuildPageCursor {
205
225
  )
206
226
  throw invalid()
207
227
  const { v, at, slug } = parsed as Record<string, unknown>
208
- const order = v === 1 ? 'created' : v === 2 ? 'updated' : undefined
228
+ const order = v === 1 ? 'created' : v === 2 ? 'updated' : v === 3 ? 'merged' : undefined
209
229
  if (order === undefined || typeof at !== 'string' || typeof slug !== 'string' || at === '')
210
230
  throw invalid()
211
231
  return { order, at, slug }
212
232
  }
213
233
 
214
- /** The order a request with these filters walks. */
215
- export function buildPageOrder(filters: BuildPageFilters): BuildPageOrder {
234
+ /** The order a request with these filters walks; never `merged`, so a
235
+ * merged-listing cursor is refused by `listBuildsPage`. */
236
+ export function buildPageOrder(filters: BuildPageFilters): 'created' | 'updated' {
216
237
  return filters.activeSince === undefined ? 'created' : 'updated'
217
238
  }
218
239
 
@@ -230,6 +251,18 @@ export function requireBuildPageCursorOrder(
230
251
  const ACTIVE_SINCE_PATTERN =
231
252
  /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?(Z|[+-]\d{2}:\d{2})$/
232
253
 
254
+ /** Parse an ISO instant with a zone into its `toISOString()` form; anything
255
+ * else rejects naming `field`. */
256
+ function resolveInstant(field: string, value: unknown): string {
257
+ const time =
258
+ typeof value === 'string' && ACTIVE_SINCE_PATTERN.test(value) ? Date.parse(value) : NaN
259
+ if (!Number.isFinite(time))
260
+ throw new BuildFeedValidationError(
261
+ `${field} must be an ISO instant with a zone, got ${JSON.stringify(value)}`,
262
+ )
263
+ return new Date(time).toISOString()
264
+ }
265
+
233
266
  /**
234
267
  * Validate and normalize a request's filters. `activeSince` becomes its
235
268
  * `toISOString()` form, which is how every adapter writes `updatedAt`. Only
@@ -251,16 +284,8 @@ export function resolveBuildPageFilters(opts: BuildPageFilters = {}): BuildPageF
251
284
  )
252
285
  filters.outcome = opts.outcome
253
286
  }
254
- if (opts.activeSince !== undefined) {
255
- const value: unknown = opts.activeSince
256
- const time =
257
- typeof value === 'string' && ACTIVE_SINCE_PATTERN.test(value) ? Date.parse(value) : NaN
258
- if (!Number.isFinite(time))
259
- throw new BuildFeedValidationError(
260
- `build page activeSince must be an ISO instant with a zone, got ${JSON.stringify(value)}`,
261
- )
262
- filters.activeSince = new Date(time).toISOString()
263
- }
287
+ if (opts.activeSince !== undefined)
288
+ filters.activeSince = resolveInstant('build page activeSince', opts.activeSince)
264
289
  return filters
265
290
  }
266
291
 
@@ -289,3 +314,104 @@ export function sameBuildPageFilters(
289
314
  ): boolean {
290
315
  return FILTER_PARAMS.every((name) => a?.[name] === b?.[name])
291
316
  }
317
+
318
+ // ── The merged build listing ────────────────────────────────────────────────
319
+
320
+ /** The merged listing's merge-time window. */
321
+ export interface MergedBuildWindow {
322
+ /** An ISO instant with a zone; builds merged at or after it (inclusive). */
323
+ since?: string
324
+ /** An ISO instant with a zone; builds merged before it (exclusive). */
325
+ until?: string
326
+ }
327
+
328
+ export interface MergedBuildPageOptions extends MergedBuildWindow {
329
+ /** A `next` value from an earlier merged page of the same adapter,
330
+ * requested with the same window. */
331
+ cursor?: string
332
+ /** Page size, 1 to `BUILD_PAGE_MAX_LIMIT`; default `BUILD_PAGE_DEFAULT_LIMIT`. */
333
+ limit?: number
334
+ }
335
+
336
+ /** A merged build's node target, as its `build.created` or latest
337
+ * `node.parent-accepted` recorded it. */
338
+ export interface MergedBuildTarget {
339
+ build: string
340
+ ticket: TicketRef
341
+ }
342
+
343
+ /** One merged build and its listing facts. */
344
+ export interface MergedBuild {
345
+ record: BuildRecord
346
+ /** The latest `build.completed` (outcome merged) envelope `ts`, ISO. */
347
+ mergedAt: string
348
+ kind: BuildPageKind
349
+ /** From the latest `pr.opened` or `finalize.completed`; absent without one. */
350
+ pr?: { number: number; url: string }
351
+ /** From `build.created`, or a node's latest `node.parent-accepted`. */
352
+ target?: MergedBuildTarget
353
+ }
354
+
355
+ /** One page of a repository's merged builds, most recently merged first. */
356
+ export interface MergedBuildPage {
357
+ builds: MergedBuild[]
358
+ /** Opaque cursor for the next page; null on the last page. */
359
+ next: string | null
360
+ }
361
+
362
+ /** Validate and normalize a merged window: each bound becomes its
363
+ * `toISOString()` form, and `since` after `until` rejects. Only present
364
+ * bounds are returned. */
365
+ export function resolveMergedBuildWindow(opts: MergedBuildWindow = {}): MergedBuildWindow {
366
+ const window: MergedBuildWindow = {}
367
+ if (opts.since !== undefined) window.since = resolveInstant('merged builds since', opts.since)
368
+ if (opts.until !== undefined) window.until = resolveInstant('merged builds until', opts.until)
369
+ if (window.since !== undefined && window.until !== undefined && window.since > window.until)
370
+ throw new BuildFeedValidationError(
371
+ `merged builds since (${window.since}) is after until (${window.until})`,
372
+ )
373
+ return window
374
+ }
375
+
376
+ /** Parse `since` and `until` query parameters; an absent parameter is no
377
+ * bound, and an empty or invalid value rejects. */
378
+ export function parseMergedBuildWindowParams(params: URLSearchParams): MergedBuildWindow {
379
+ const raw: Record<string, string> = {}
380
+ for (const name of ['since', 'until'] as const) {
381
+ const value = params.get(name)
382
+ if (value !== null) raw[name] = value
383
+ }
384
+ return resolveMergedBuildWindow(raw)
385
+ }
386
+
387
+ /** Decode a merged-listing cursor; a malformed cursor or a cursor of another
388
+ * order rejects. */
389
+ export function requireMergedCursor(cursor: unknown): BuildPageCursor {
390
+ const decoded = decodeBuildPageCursor(cursor)
391
+ if (decoded.order !== 'merged')
392
+ throw new BuildFeedValidationError('build page cursor belongs to a different ordering')
393
+ return decoded
394
+ }
395
+
396
+ const listingTargetSchema = z.strictObject({
397
+ build: z.string().min(1),
398
+ ticket: ticketRefSchema,
399
+ })
400
+
401
+ /** Parse a stored target listing fact (JSON text or an already-parsed value);
402
+ * null or undefined is no target, and a malformed value throws. */
403
+ export function parseListingTarget(raw: unknown): MergedBuildTarget | undefined {
404
+ if (raw === null || raw === undefined) return undefined
405
+ let value: unknown = raw
406
+ if (typeof raw === 'string') {
407
+ try {
408
+ value = JSON.parse(raw)
409
+ } catch {
410
+ throw new Error(`malformed build listing target ${JSON.stringify(raw)}`)
411
+ }
412
+ }
413
+ const parsed = listingTargetSchema.safeParse(value)
414
+ if (!parsed.success) throw new Error(`malformed build listing target ${JSON.stringify(raw)}`)
415
+ const { build, ticket } = parsed.data
416
+ return { build, ticket }
417
+ }
@@ -29,7 +29,7 @@ import type {
29
29
  SubscribeOptions,
30
30
  Unsubscribe,
31
31
  } from './types'
32
- import type { BuildPage, ChangedBuilds } from './types'
32
+ import type { BuildPage, ChangedBuilds, MergedBuildPage } from './types'
33
33
  import type {
34
34
  TicketAsset,
35
35
  TicketAssetInput,
@@ -130,6 +130,9 @@ export function createBuildScopedStore(store: BuildStore, scope: string): BuildS
130
130
  listBuildsPage(repo: string): Promise<BuildPage> {
131
131
  return Promise.reject(new BuildScopeError(scope, 'listBuildsPage', repo))
132
132
  },
133
+ listMergedBuildsPage(repo: string): Promise<MergedBuildPage> {
134
+ return Promise.reject(new BuildScopeError(scope, 'listMergedBuildsPage', repo))
135
+ },
133
136
  listBuilds(): Promise<BuildRecord[]> {
134
137
  return Promise.reject(new BuildScopeError(scope, 'listBuilds'))
135
138
  },
@@ -262,7 +265,10 @@ export function createBuildScopedStore(store: BuildStore, scope: string): BuildS
262
265
  repo: string,
263
266
  _artifacts: ArtifactInput[],
264
267
  _makeEvent: (deposited: RepositoryArtifactMeta[]) => RepositoryEventWrite<T>,
265
- ): Promise<{ event: RepositoryEventEnvelope<T>; artifacts: RepositoryArtifactMeta[] }> {
268
+ ): Promise<{
269
+ event: RepositoryEventEnvelope<T>
270
+ artifacts: RepositoryArtifactMeta[]
271
+ }> {
266
272
  return Promise.reject(new BuildScopeError(scope, 'appendRepoWithArtifacts', repo))
267
273
  },
268
274
  getRepoEvents(repo: string, _sinceSeq?: number): Promise<RepositoryEvent[]> {
@@ -412,7 +418,10 @@ export function createBuildScopedStore(store: BuildStore, scope: string): BuildS
412
418
  id: string,
413
419
  _artifacts: ArtifactInput[],
414
420
  _makeEvent: (deposited: SessionArtifactMeta[]) => SessionEventWrite<T>,
415
- ): Promise<{ event: SessionEventEnvelope<T>; artifacts: SessionArtifactMeta[] }> {
421
+ ): Promise<{
422
+ event: SessionEventEnvelope<T>
423
+ artifacts: SessionArtifactMeta[]
424
+ }> {
416
425
  return Promise.reject(new BuildScopeError(scope, 'appendSessionWithArtifacts', id))
417
426
  },
418
427
  putSessionArtifact(id: string, _artifact: ArtifactInput): Promise<SessionArtifactMeta> {
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Caller attribution for hosted store requests.
3
+ *
4
+ * Every hosted store and ticket client sends one optional, bounded
5
+ * `x-autobuild-caller` header naming who made the request: a dispatcher
6
+ * (invocation, run, pass stage), a runner (build or harvest), or an operator
7
+ * client (CLI, MCP, web). The value comes from an ambient scope that process
8
+ * entries establish, so clients need no caller parameter threaded through
9
+ * every store opener.
10
+ *
11
+ * The header is diagnostic only. The server parses it as untrusted input,
12
+ * never uses it for authorization or routing, and treats a missing header as
13
+ * an unattributed request from an older client.
14
+ *
15
+ * This module deliberately imports nothing but `node:async_hooks`, so local
16
+ * import graphs that never reach a hosted store gain nothing from it.
17
+ */
18
+ import { AsyncLocalStorage } from 'node:async_hooks'
19
+
20
+ export const STORE_CALLER_HEADER = 'x-autobuild-caller'
21
+ export const STORE_CALLER_VALUE_MAX = 96
22
+ export const STORE_CALLER_HEADER_MAX = 512
23
+ const STORE_CALLER_PARSE_MAX = 1024
24
+
25
+ export type StoreCaller =
26
+ | { kind: 'dispatcher'; invocation?: string; run?: string; stage?: string }
27
+ | {
28
+ kind: 'runner'
29
+ runner: 'build' | 'harvest'
30
+ build?: string
31
+ harvest?: string
32
+ execution?: string
33
+ session?: string
34
+ phase?: string
35
+ command?: string
36
+ }
37
+ | { kind: 'operator'; client: 'cli' | 'mcp' | 'web'; command?: string }
38
+
39
+ /** Allowlisted keys, in wire order. */
40
+ const KEYS = [
41
+ 'kind',
42
+ 'client',
43
+ 'runner',
44
+ 'invocation',
45
+ 'run',
46
+ 'stage',
47
+ 'build',
48
+ 'harvest',
49
+ 'execution',
50
+ 'session',
51
+ 'phase',
52
+ 'command',
53
+ ] as const
54
+ const ALLOWED: ReadonlySet<string> = new Set(KEYS)
55
+
56
+ /** Restricts a value to a log-safe charset and bounds its length. The
57
+ * charset excludes whitespace, quotes, `;` and `=`, so a sanitized value can
58
+ * never break the header format or a JSON log line. */
59
+ export function sanitizeCallerValue(value: string): string {
60
+ return value.replace(/[^A-Za-z0-9._:@+/-]/g, '_').slice(0, STORE_CALLER_VALUE_MAX)
61
+ }
62
+
63
+ export function encodeStoreCaller(caller: StoreCaller): string {
64
+ const fields = caller as Record<string, unknown>
65
+ let out = ''
66
+ for (const key of KEYS) {
67
+ const raw = fields[key]
68
+ if (typeof raw !== 'string' || raw === '') continue
69
+ const pair = `${key}=${sanitizeCallerValue(raw)}`
70
+ const next = out === '' ? pair : `${out};${pair}`
71
+ if (next.length > STORE_CALLER_HEADER_MAX) break
72
+ out = next
73
+ }
74
+ return out
75
+ }
76
+
77
+ /** Server-side parse of an untrusted header value. Returns only allowlisted
78
+ * keys with sanitized values, or `null` when nothing usable survives. */
79
+ export function parseStoreCaller(raw: string | null | undefined): Record<string, string> | null {
80
+ if (raw == null) return null
81
+ const parsed: Record<string, string> = {}
82
+ let any = false
83
+ for (const part of raw.slice(0, STORE_CALLER_PARSE_MAX).split(';')) {
84
+ const eq = part.indexOf('=')
85
+ if (eq < 0) continue
86
+ const key = part.slice(0, eq).trim()
87
+ if (!ALLOWED.has(key) || Object.hasOwn(parsed, key)) continue
88
+ const value = sanitizeCallerValue(part.slice(eq + 1).trim())
89
+ if (value === '') continue
90
+ parsed[key] = value
91
+ any = true
92
+ }
93
+ return any ? parsed : null
94
+ }
95
+
96
+ const scope = new AsyncLocalStorage<StoreCaller>()
97
+
98
+ export const currentStoreCaller = (): StoreCaller | undefined => scope.getStore()
99
+
100
+ export function withStoreCaller<T>(caller: StoreCaller, work: () => T): T {
101
+ return scope.run(caller, work)
102
+ }
103
+
104
+ /** Names the dispatcher pass stage for requests made inside `work`. Outside a
105
+ * dispatcher scope this is a plain call. */
106
+ export function withCallerStage<T>(stage: string, work: () => T): T {
107
+ const current = scope.getStore()
108
+ if (current?.kind !== 'dispatcher') return work()
109
+ return scope.run({ ...current, stage }, work)
110
+ }
111
+
112
+ /** Enters a dispatcher run: keeps the hosted invocation id when there is one
113
+ * and clears any setup stage. */
114
+ export function withDispatcherRun<T>(run: string, work: () => T): T {
115
+ const current = scope.getStore()
116
+ const invocation = current?.kind === 'dispatcher' ? current.invocation : undefined
117
+ return scope.run({ kind: 'dispatcher', ...(invocation ? { invocation } : {}), run }, work)
118
+ }
119
+
120
+ /** The header to send: the explicit caller when given, else the ambient one,
121
+ * else nothing. */
122
+ export function storeCallerHeaders(explicit?: StoreCaller): Record<string, string> {
123
+ const caller = explicit ?? scope.getStore()
124
+ if (!caller) return {}
125
+ const value = encodeStoreCaller(caller)
126
+ return value === '' ? {} : { [STORE_CALLER_HEADER]: value }
127
+ }
128
+
129
+ const nonblank = (value: string | undefined): string | undefined =>
130
+ value != null && value.trim() !== '' ? value : undefined
131
+
132
+ /** Who a CLI invocation is, from its command and session environment. Only
133
+ * the command name is used, never its arguments. */
134
+ export function cliStoreCaller(
135
+ argv: readonly string[],
136
+ env: Readonly<Record<string, string | undefined>>,
137
+ ): StoreCaller {
138
+ const command = argv[0]
139
+ if (command === 'dispatch') {
140
+ return argv.includes('--viewer')
141
+ ? { kind: 'operator', client: 'cli', command: 'dispatch-viewer' }
142
+ : { kind: 'dispatcher' }
143
+ }
144
+ const session = nonblank(env.AB_SESSION)
145
+ const phase = nonblank(env.AB_PHASE)
146
+ const build = nonblank(env.AB_BUILD)
147
+ if (build) {
148
+ return {
149
+ kind: 'runner',
150
+ runner: 'build',
151
+ build,
152
+ ...(session ? { session } : {}),
153
+ ...(phase ? { phase } : {}),
154
+ ...(command ? { command } : {}),
155
+ }
156
+ }
157
+ const harvest = nonblank(env.AB_HARVEST)
158
+ if (harvest) {
159
+ return {
160
+ kind: 'runner',
161
+ runner: 'harvest',
162
+ harvest,
163
+ ...(session ? { session } : {}),
164
+ ...(phase ? { phase } : {}),
165
+ ...(command ? { command } : {}),
166
+ }
167
+ }
168
+ if (command === 'mcp') return { kind: 'operator', client: 'mcp', command: 'mcp' }
169
+ return { kind: 'operator', client: 'cli', ...(command ? { command } : {}) }
170
+ }