@cat-factory/contracts 0.152.0 → 0.152.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1290 @@
1
+ import * as v from 'valibot';
2
+ import { testConcernSchema, testReportSchema, testerInfraSetupSchema } from './testing.js';
3
+ import { consensusStepConfigSchema, stepGatingSchema } from './consensus.js';
4
+ import { followUpsStepStateSchema } from './followUp.js';
5
+ import { forkDecisionStepStateSchema } from './forkDecision.js';
6
+ import { ralphStepStateSchema } from './ralph.js';
7
+ import { prReviewStepStateSchema } from './prReview.js';
8
+ import { releaseSignalSchema } from './release.js';
9
+ import { environmentStatusSchema, infraEngineSchema, provisionTypeSchema, serviceProvisioningSchema, } from './environments.js';
10
+ import { resolvedFrontendBindingSchema } from './frontend.js';
11
+ import { agentKindSchema, agentStateSchema } from './primitives.js';
12
+ import { stepOptionsSchema } from './entities.js';
13
+ // ---------------------------------------------------------------------------
14
+ // Run / execution runtime state: the shapes that describe an in-flight run and
15
+ // its steps' live state — human decisions, subtasks, review comments, companion
16
+ // verdicts, approvals, agent-run failures, the gate / tester / human-test /
17
+ // visual-confirm step-state machines, per-step metrics, the pipeline STEP (the
18
+ // runtime instance of a pipeline's step), and the execution instance itself.
19
+ // Split out of entities.ts (which keeps the board / pipeline-definition / model
20
+ // / workspace shapes); re-exported from the package barrel, so consumers are
21
+ // unaffected. Depends on entities.ts (for stepOptionsSchema); entities.ts does
22
+ // NOT depend back on this file.
23
+ // ---------------------------------------------------------------------------
24
+ export const decisionSchema = v.object({
25
+ id: v.string(),
26
+ question: v.string(),
27
+ options: v.array(v.string()),
28
+ chosen: v.nullable(v.string()),
29
+ });
30
+ /** One entry of a running step's todo list — its label and current status. */
31
+ export const stepSubtaskItemSchema = v.object({
32
+ /** The task's human-readable subject, as the agent wrote it. */
33
+ label: v.string(),
34
+ status: v.picklist(['pending', 'in_progress', 'completed']),
35
+ });
36
+ /**
37
+ * Live subtask counts for a running step, reported by the container agent from
38
+ * the coding tool's own todo list (e.g. "3/8 done, 1 in progress"). Present only
39
+ * while an async job is in flight and the agent maintains a todo list; the board
40
+ * renders it as a finer-grained progress indicator than `progress` alone.
41
+ *
42
+ * `items` carries the individual todo entries (label + status) so a zoomed-in
43
+ * card can render the actual task list, not just the count. It is optional — an
44
+ * older agent/poll that only reported counts, or the simpler `todos[].done`
45
+ * fallback shape, still validates without it.
46
+ */
47
+ export const stepSubtasksSchema = v.object({
48
+ completed: v.number(),
49
+ inProgress: v.number(),
50
+ total: v.number(),
51
+ items: v.optional(v.array(stepSubtaskItemSchema)),
52
+ });
53
+ /**
54
+ * One GitHub-review-style comment left on a specific block or item of an agent's
55
+ * proposal — either by a human reviewing an approval gate, or by a quality
56
+ * companion (e.g. the Spec Reviewer) grading a structured output. `quotedSource`
57
+ * is the verbatim raw markdown of the block the comment targets (sliced from the
58
+ * proposal by its source line range), so a "request changes" re-run can quote the
59
+ * agent's own text back to it rather than a re-rendered approximation. It is
60
+ * OPTIONAL because a comment may instead anchor to a structured item via
61
+ * {@link anchorId} (e.g. a spec requirement / acceptance-criterion id), where the
62
+ * reviewed output is rendered as discrete items rather than free prose and there is
63
+ * no quoted source range — the shape a companion returns.
64
+ */
65
+ export const stepReviewCommentSchema = v.object({
66
+ /**
67
+ * Verbatim raw-markdown source of the commented prose block. Optional: a comment
68
+ * may instead anchor to a structured item via {@link anchorId}, where there is no
69
+ * prose source to quote.
70
+ */
71
+ quotedSource: v.optional(v.string()),
72
+ /**
73
+ * 0-based source line range [start, end) of the commented prose block, for
74
+ * best-effort re-anchoring. Optional: a comment may instead anchor to a structured
75
+ * item via {@link anchorId} (e.g. a spec requirement/acceptance-criterion id), where
76
+ * there is no prose line range.
77
+ */
78
+ srcStart: v.optional(v.number()),
79
+ srcEnd: v.optional(v.number()),
80
+ /**
81
+ * Stable id of the structured item the comment targets (e.g. a spec
82
+ * requirement/criterion id), when the reviewed output is rendered as structured
83
+ * items rather than free prose. Absent for prose-range comments.
84
+ */
85
+ anchorId: v.optional(v.string()),
86
+ /** The reviewer's note on this block / item. */
87
+ body: v.string(),
88
+ });
89
+ /**
90
+ * The standardized, stored verdict a quality companion produced for an output it
91
+ * graded — shared by every companion site (the pipeline companion step and the
92
+ * requirements-rework gate). The raw model response is {@link companionAssessmentSchema}
93
+ * (rating + summary + comments); this is the persisted, self-describing record of how
94
+ * that assessment was applied: the `rating`, the `threshold` it was judged against,
95
+ * whether it `passed`, and the `feedback` surfaced to the human / fed into a rework.
96
+ */
97
+ export const companionVerdictSchema = v.object({
98
+ /** Overall quality of the graded output (0..1, higher = better). */
99
+ rating: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
100
+ /** The quality bar the rating had to reach to pass. */
101
+ threshold: v.pipe(v.number(), v.minValue(0), v.maxValue(1)),
102
+ /** Whether the rating met the threshold. */
103
+ passed: v.boolean(),
104
+ /** The companion's challenge / justification (its assessment summary). */
105
+ feedback: v.string(),
106
+ });
107
+ /**
108
+ * A human approval gate raised after a step whose pipeline marked it
109
+ * `requiresApproval`. Unlike a {@link Decision} (which an agent raises and which
110
+ * re-runs the same step on resolution), an approval gate fires once the step has
111
+ * already produced its `proposal`; approving advances the run (carrying the —
112
+ * possibly edited — proposal forward as context), requesting changes re-runs the
113
+ * same step with the human's `feedback` (+ per-block `comments`), and rejecting
114
+ * stops the run entirely (a terminal `rejected` failure the board can retry).
115
+ */
116
+ export const stepApprovalSchema = v.object({
117
+ /** Unique id of this gate; the durable run parks on it like a decision. */
118
+ id: v.string(),
119
+ /** `pending` while awaiting the human; terminal `approved`/`rejected`; `changes_requested` re-runs the step. */
120
+ status: v.picklist(['pending', 'approved', 'changes_requested', 'rejected']),
121
+ /** The agent's output the human is reviewing (editable before approval). */
122
+ proposal: v.string(),
123
+ /** When changes were requested, the human's freeform guidance fed into the re-run. */
124
+ feedback: v.optional(v.string()),
125
+ /** When changes were requested, per-block review comments fed into the re-run. */
126
+ comments: v.optional(v.array(stepReviewCommentSchema)),
127
+ });
128
+ /**
129
+ * The agent flows that produce an "agent run" (a container-backed job whose
130
+ * lifecycle, progress and failure the board surfaces uniformly):
131
+ * - `bootstrap` — a "bootstrap repo" run that scaffolds/adapts a new repo.
132
+ * - `execution` — a task pipeline run that implements a board task.
133
+ * - `env-config-repair` — a coding agent that repairs an environment-provider
134
+ * config file in an existing repo (no board block; surfaced on the infra window).
135
+ */
136
+ export const agentRunKindSchema = v.picklist(['bootstrap', 'execution', 'env-config-repair']);
137
+ /**
138
+ * How an agent run faulted, so the board can classify the failure (and hint
139
+ * whether a retry is likely to help). The union spans both flows; a given flow
140
+ * only ever produces a subset:
141
+ * - `preflight` — rejected before dispatch (repo missing/not empty, not connected). [bootstrap]
142
+ * - `dispatch` — the container accept-request itself failed (HTTP / network). [bootstrap]
143
+ * - `evicted` — the container vanished mid-run (eviction/crash). Retrying spins a fresh one.
144
+ * - `timeout` — a container watchdog fired (inactivity or max-duration).
145
+ * - `agent` — the agent / git push reported a failure.
146
+ * - `job_failed` — an async container job came back failed. [execution]
147
+ * - `rejected` — a human rejected a gated proposal, stopping the run. [execution]
148
+ * - `cancelled` — the user (or an orphan sweep) explicitly stopped the run.
149
+ * - `unknown` — anything not otherwise classified.
150
+ */
151
+ export const agentFailureKindSchema = v.picklist([
152
+ 'preflight',
153
+ 'dispatch',
154
+ // A `deployer` step's ephemeral-environment provisioning failed (the EnvironmentProvider
155
+ // threw or returned `status:'failed'`) — distinct from `dispatch` (a container/runner
156
+ // never accepting the job). The provider's verbatim error rides the failure `detail`.
157
+ 'environment',
158
+ 'evicted',
159
+ 'timeout',
160
+ 'agent',
161
+ 'job_failed',
162
+ 'rejected',
163
+ // A companion agent could not return a parseable quality assessment (truncated /
164
+ // malformed) even after a repair retry, so the run was failed for human attention.
165
+ // (Exhausting the automatic rework budget no longer fails the run — it parks on the
166
+ // companion iteration-cap gate for a human; see `companion.exceeded`.)
167
+ 'companion_rejected',
168
+ // The run was still `running` in storage but its durable driver was gone (a crashed /
169
+ // restarted orchestrator left the advance job orphaned), and the stale-run sweeper could
170
+ // not recover it within the hard-stall deadline — so it is failed for human attention
171
+ // instead of spinning `running` forever with no progress. Retry spins a fresh run.
172
+ 'stalled',
173
+ 'cancelled',
174
+ 'unknown',
175
+ ]);
176
+ /**
177
+ * Structured diagnostics captured when an agent run fails, stored on the run and
178
+ * surfaced on the board so a crash isn't just a one-line message. The container's
179
+ * stdout/stderr can't always be pulled into this record (an evicted container is
180
+ * gone), so for `evicted`/`timeout` failures the `hint` points at where to look.
181
+ */
182
+ export const agentFailureSchema = v.object({
183
+ kind: agentFailureKindSchema,
184
+ /** Human-readable summary (mirrors the run's `error` for back-compat). */
185
+ message: v.string(),
186
+ /** Extended detail when available (the harness's reason, an HTTP body, …). */
187
+ detail: v.nullable(v.string()),
188
+ /** Where to look next (e.g. "check the container logs for this job id"). */
189
+ hint: v.nullable(v.string()),
190
+ /**
191
+ * Optional machine-readable cause code so the SPA can render precise, actionable guidance
192
+ * without string-matching the prose `message`/`detail` (the failure analogue of a
193
+ * {@link ConflictReason}). Kind-scoped: an `environment` failure carries an
194
+ * {@link EnvironmentFailureReason} (e.g. `deploy_runner_unwired`). Absent when the cause has
195
+ * no client-specific handling.
196
+ */
197
+ reason: v.optional(v.nullable(v.string())),
198
+ /** Epoch ms the failure was recorded. */
199
+ occurredAt: v.number(),
200
+ /** Last subtask counts seen before the failure, for context (null if none). */
201
+ lastSubtasks: v.nullable(stepSubtasksSchema),
202
+ /**
203
+ * Index of the pipeline step that was in flight when the run failed (the run's
204
+ * `currentStep` at fail time), so the per-attempt failure trail can be attributed to a
205
+ * specific step — the step-detail overlay filters its "execution history" to the failures
206
+ * recorded for that step. Absent on a bootstrap failure (no steps) and on legacy records.
207
+ */
208
+ stepIndex: v.optional(v.number()),
209
+ });
210
+ /**
211
+ * A SUCCESSFUL step attempt whose output a restart later superseded — the positive
212
+ * complement of {@link agentFailureSchema}. When a run is restarted from a step, that
213
+ * step and every later one are reset and their `output` dropped; the ones that had
214
+ * already succeeded are recorded here so the step-detail overlay's "execution history"
215
+ * surfaces what a superseded attempt PRODUCED, not only the errors. Attributed to a
216
+ * `stepIndex` exactly like a failure, and rides in the run's `detail` JSON (no column).
217
+ */
218
+ export const priorStepOutputSchema = v.object({
219
+ /** Index of the pipeline step that produced this output (see {@link agentFailureSchema} `stepIndex`). */
220
+ stepIndex: v.number(),
221
+ /** Epoch ms the superseded attempt finished (its `finishedAt`, else when it was recorded). */
222
+ occurredAt: v.number(),
223
+ /** The attempt's prose/JSON output, clipped to a stored-size bound when {@link truncated}. */
224
+ output: v.string(),
225
+ /** Whether {@link output} was clipped because the original exceeded the per-entry size bound. */
226
+ truncated: v.optional(v.boolean()),
227
+ });
228
+ /**
229
+ * State a polling **gate** step carries (today `ci` and `conflicts`). A gate is
230
+ * special (like a `deployer` step): it is NOT itself an LLM/container agent. It
231
+ * runs a programmatic precheck against a provider (CI check runs / PR mergeability)
232
+ * for the PR head commit and only escalates to a helper container agent (`ci-fixer`
233
+ * / `conflict-resolver`) on a negative verdict, looping until the precheck passes or
234
+ * the attempt budget is spent. Which gate a step is comes from its `agentKind`, so it
235
+ * is not duplicated here. See the engine's `GateDefinition` registry.
236
+ * - `phase: 'checking'` — running the precheck / waiting for the provider.
237
+ * - `phase: 'working'` — a helper agent is in flight (tracked via the step's
238
+ * `jobId`); on completion the gate returns to `checking`.
239
+ */
240
+ /** One failing check the CI gate's precheck saw, flattened for display. */
241
+ export const gateFailingCheckSchema = v.object({
242
+ name: v.string(),
243
+ /** GitHub conclusion (e.g. `failure`, `timed_out`), or null when not reported. */
244
+ conclusion: v.nullable(v.string()),
245
+ /**
246
+ * The check run's GitHub web URL (`html_url`), so the UI can link straight to the
247
+ * failed run's logs. Null when GitHub didn't report one.
248
+ */
249
+ url: v.optional(v.nullable(v.string())),
250
+ /**
251
+ * The repo (owner/name) this check belongs to, on a MULTI-REPO block — so the UI can group
252
+ * failing checks by service. Absent on a single-repo block (there is only the own repo).
253
+ */
254
+ repo: v.optional(v.string()),
255
+ });
256
+ /**
257
+ * One helper-agent attempt the gate dispatched (a ci-fixer / conflict-resolver run),
258
+ * recorded when the job finishes so the UI can show what each attempt tried and how it
259
+ * ended — detail that used to be discarded the moment the gate re-probed.
260
+ */
261
+ export const gateAttemptSchema = v.object({
262
+ /** 1-based attempt number (matches `attempts` at the time the helper was dispatched). */
263
+ attempt: v.number(),
264
+ /** Epoch ms when the helper job finished. */
265
+ at: v.number(),
266
+ /**
267
+ * How the helper job ended:
268
+ * - `completed` — the container finished (it may or may not have fully fixed the
269
+ * issue; the gate's next precheck is the source of truth, and `summary` carries
270
+ * the agent's own account, e.g. which files it left conflicting).
271
+ * - `failed` — the job errored / was evicted without finishing.
272
+ */
273
+ outcome: v.picklist(['completed', 'failed']),
274
+ /** The PR head commit the helper worked against, when known. */
275
+ headSha: v.optional(v.nullable(v.string())),
276
+ /**
277
+ * The fixing instructions handed to the helper for this round — the failing-check
278
+ * summary the CI gate fed the `ci-fixer`, the conflict reason / human-review comments
279
+ * the other gates fed their fixer. Stashed at dispatch and recorded with the attempt so
280
+ * the run-detail UI can show WHAT each round was asked to fix (not only that a round
281
+ * happened) — the gate analogue of the Tester attempt's `concerns`. Null when the gate
282
+ * hands its fixer no textual instructions (the conflicts gate: GitHub reports mergeability
283
+ * as a single bit and the harness leaves the conflict markers for the resolver).
284
+ */
285
+ instructions: v.optional(v.nullable(v.string())),
286
+ /**
287
+ * Structured failing checks handed to this attempt's helper (the CI gate's red check runs
288
+ * behind {@link instructions}), snapshotted at dispatch so each attempt shows the checks it
289
+ * set out to fix. Absent for the conflicts gate (no file-level detail) and when the round
290
+ * carried no structured checks.
291
+ */
292
+ failingChecks: v.optional(v.nullable(v.array(gateFailingCheckSchema))),
293
+ /** The helper's own summary (or the failure reason), naming what it did / what remains. */
294
+ summary: v.optional(v.nullable(v.string())),
295
+ });
296
+ export const gateStepStateSchema = v.object({
297
+ phase: v.picklist(['checking', 'working']),
298
+ /** How many helper-agent attempts have been dispatched so far. */
299
+ attempts: v.number(),
300
+ /** Ceiling on attempts, resolved from the task's merge preset at step start. */
301
+ maxAttempts: v.number(),
302
+ /** The PR head commit being gated, once resolved (the own-service PR on a multi-repo block). */
303
+ headSha: v.optional(v.nullable(v.string())),
304
+ /**
305
+ * Per-PR head commits for a MULTI-REPO block (service-connections phase 4), keyed by repo
306
+ * full name (owner/name) — own-service PR plus each peer-service PR. Set by the CI /
307
+ * conflicts gates whose precheck aggregates across every PR the task opened. Absent for a
308
+ * single-repo block (the scalar {@link headSha} is the only head).
309
+ */
310
+ headShas: v.optional(v.nullable(v.record(v.string(), v.string()))),
311
+ /**
312
+ * The repo the conflicts gate's most recent `fail` verdict found conflicted, so the
313
+ * single-repo conflict-resolver is dispatched at THAT repo (own-service or a peer) rather
314
+ * than always the own-service one. Absent ⇒ the own-service repo. Only the conflicts gate
315
+ * sets it (the CI-fixer runs across all repos, so the CI gate leaves it undefined).
316
+ */
317
+ conflictTarget: v.optional(v.nullable(v.object({
318
+ repo: v.string(),
319
+ frameId: v.optional(v.string()),
320
+ branch: v.optional(v.string()),
321
+ }))),
322
+ /**
323
+ * The most recent precheck verdict, so the UI can show why the gate is looping
324
+ * (failing → a helper is fixing) vs idle-passing. Set on every probe.
325
+ */
326
+ lastVerdict: v.optional(v.nullable(v.picklist(['pass', 'pending', 'fail']))),
327
+ /**
328
+ * Human-readable summary of the latest failing precheck (the failing CI checks /
329
+ * the conflict reason) — the conclusion detail that used to be fed only to the
330
+ * helper agent and then discarded. Carried across the helper dispatch so the
331
+ * window keeps showing what is being fixed. Null when the last probe passed.
332
+ */
333
+ lastFailureSummary: v.optional(v.nullable(v.string())),
334
+ /**
335
+ * Structured failing checks behind {@link lastFailureSummary} for the CI gate, so
336
+ * the UI can list each red check by name + conclusion. Absent for the conflicts
337
+ * gate (GitHub reports no file-level detail) and when the last probe passed.
338
+ */
339
+ failingChecks: v.optional(v.nullable(v.array(gateFailingCheckSchema))),
340
+ /**
341
+ * The fixing instructions handed to the most-recently dispatched helper (the failing-check
342
+ * summary / conflict reason / human fix prompt), stashed at dispatch so the attempt recorded
343
+ * when that helper's job settles can carry WHAT the round was asked to fix onto its
344
+ * {@link gateAttemptSchema} entry. Transient bookkeeping — the durable per-round history lives
345
+ * on {@link attemptLog}. Null when the gate hands its fixer no textual instructions.
346
+ */
347
+ lastDispatchedInstructions: v.optional(v.nullable(v.string())),
348
+ /**
349
+ * Epoch ms of the release marker for a time-windowed gate (post-release-health) — the
350
+ * moment it began watching the deployed release. The gate keeps polling `pending`
351
+ * until this + the preset's watch window has elapsed (then a clean run passes) or a
352
+ * monitor/SLO regresses (then it escalates to the on-call agent). Absent for the
353
+ * CI/conflicts gates.
354
+ */
355
+ watchSince: v.optional(v.nullable(v.number())),
356
+ /**
357
+ * The watch-window length (minutes) for a time-windowed gate (post-release-health),
358
+ * resolved from the task's merge preset ONCE on first entry (alongside `maxAttempts`)
359
+ * so the probe doesn't re-load the block + re-resolve the preset on every poll. Absent
360
+ * for the CI/conflicts gates.
361
+ */
362
+ watchWindowMinutes: v.optional(v.nullable(v.number())),
363
+ /**
364
+ * The regressed signals captured when the post-release-health gate escalated to the
365
+ * on-call agent, so the agent's completion handler can build the `release_regression`
366
+ * notification + incident enrichment from the SAME evidence the agent investigated
367
+ * — rather than re-reading Datadog (a third round-trip that could also disagree with
368
+ * what the agent saw if the window moved). Absent for the CI/conflicts gates.
369
+ */
370
+ regressedSignals: v.optional(v.nullable(v.array(releaseSignalSchema))),
371
+ /**
372
+ * Append-only history of the helper-agent attempts this gate dispatched (ci-fixer /
373
+ * conflict-resolver runs), each recorded when its job finished. Lets the UI show what
374
+ * every attempt tried and how it ended, instead of only a bare `attempts` count.
375
+ * Absent for the post-release-health gate (its on-call helper is resolved specially).
376
+ */
377
+ attemptLog: v.optional(v.nullable(v.array(gateAttemptSchema))),
378
+ // ---- human-review gate only (absent for the CI/conflicts/post-release-health gates) ----
379
+ /**
380
+ * The number of approving reviews the PR had at the last probe, so the UI can show
381
+ * "1 / N approvals". The "required" side is derived from {@link requiredApprovingReviewCount}
382
+ * via the same `max(1, …)` floor the gate applies (see review.logic.ts) rather than persisted
383
+ * a second time. Absent for the other gates.
384
+ */
385
+ lastApprovals: v.optional(v.nullable(v.number())),
386
+ /**
387
+ * The raw branch-protection required-approving-review count, cached after the FIRST probe
388
+ * resolves it so subsequent polls skip the static protection read (branch protection is repo
389
+ * config, not PR activity — re-reading it every poll over a multi-day review only burns GitHub
390
+ * rate budget). The UI's displayed "required" count is `max(1, this)` (the gate's effective
391
+ * floor). Absent for the other gates.
392
+ */
393
+ requiredApprovingReviewCount: v.optional(v.nullable(v.number())),
394
+ /**
395
+ * The GraphQL ids of the review threads the gate just handed the `fixer`, stashed at
396
+ * dispatch so the helper-completion hook can post a reply + RESOLVE exactly those threads
397
+ * on GitHub before the next probe reads them. Absent for the other gates.
398
+ */
399
+ pendingThreadIds: v.optional(v.nullable(v.array(v.string()))),
400
+ /**
401
+ * Epoch ms of the newest plain PR comment the gate has already handed the `fixer`. Plain
402
+ * conversation comments (unlike review threads) can't be "resolved" on GitHub, so they are
403
+ * tracked by timestamp: a comment newer than this is outstanding; the dispatch advances it to
404
+ * the batch max. A reviewer's later comment (newer timestamp) re-opens the work. Absent for
405
+ * the other gates.
406
+ */
407
+ lastAddressedCommentAt: v.optional(v.nullable(v.number())),
408
+ /**
409
+ * The grace window (minutes) the human-review gate waits after the latest review comment
410
+ * before dispatching the fixer, resolved from the task's merge preset ONCE on first entry
411
+ * (alongside `maxAttempts`) so the probe doesn't re-resolve the preset every poll. Absent
412
+ * for the other gates.
413
+ */
414
+ humanReviewGraceMinutes: v.optional(v.nullable(v.number())),
415
+ /**
416
+ * A human-initiated freeform fix request parked on the gate (an in-app prompt). Consumed at
417
+ * the top of the next `evaluateGate` pass, which dispatches the fixer with these instructions
418
+ * folded in — bypassing the grace window. Absent for the other gates.
419
+ */
420
+ pendingFix: v.optional(v.nullable(v.object({
421
+ instructions: v.string(),
422
+ at: v.number(),
423
+ }))),
424
+ });
425
+ /**
426
+ * State a `tester` step carries while it runs the Tester → Fixer loop. Unlike `ci`,
427
+ * the gate's own work IS a container job (the Tester); on a withheld greenlight the
428
+ * engine loops a `fixer` container agent and re-tests.
429
+ * - `phase: 'testing'` — a Tester job is in flight (tracked via the step's `jobId`).
430
+ * - `phase: 'fixing'` — a Fixer job is in flight; on completion the step returns to
431
+ * `testing` and a fresh Tester job is dispatched.
432
+ */
433
+ /**
434
+ * One round of the Tester→Fixer loop, recorded when a `fixer` job finishes so the test
435
+ * window can show what each fixer attempt set out to fix and how it ended — the analogue of
436
+ * a polling gate's {@link gateAttemptSchema}, since a fixer run is otherwise an opaque
437
+ * sub-job with no surface of its own (only a bare `attempts` count).
438
+ */
439
+ export const testerAttemptSchema = v.object({
440
+ /** 1-based fixer round (matches `attempts` after the fixer for this round was dispatched). */
441
+ attempt: v.number(),
442
+ /** Epoch ms when the fixer job finished. */
443
+ at: v.number(),
444
+ /** Whether the fixer container finished (`completed`) or errored/was evicted (`failed`). */
445
+ outcome: v.picklist(['completed', 'failed']),
446
+ /** The fixer's own summary (or the failure reason), naming what it changed / what failed. */
447
+ summary: v.optional(v.nullable(v.string())),
448
+ /**
449
+ * The concerns the fixer was handed for this round (from the Tester report that withheld
450
+ * its greenlight), so the window can show WHAT each round tried to address — not only that
451
+ * a round happened.
452
+ */
453
+ concerns: v.optional(v.nullable(v.array(testConcernSchema))),
454
+ });
455
+ export const testerStepStateSchema = v.object({
456
+ phase: v.picklist(['testing', 'fixing']),
457
+ /** How many `fixer` attempts have been dispatched so far. */
458
+ attempts: v.number(),
459
+ /** Ceiling on fixer attempts, resolved from the task's merge preset at step start. */
460
+ maxAttempts: v.number(),
461
+ /** The most recent Tester report (what was tested, outcomes, concerns, greenlight). */
462
+ lastReport: v.optional(v.nullable(testReportSchema)),
463
+ /**
464
+ * Append-only history of the `fixer` rounds this Tester step looped through, each recorded
465
+ * when its job finished. Lets the test window surface an inspectable timeline of the fixer
466
+ * attempts (what each addressed, how it ended) instead of only a bare `attempts` count.
467
+ */
468
+ attemptLog: v.optional(v.nullable(v.array(testerAttemptSchema))),
469
+ /**
470
+ * The most recent in-container docker-compose dependency stand-up record (local-infra
471
+ * tester): whether the dependencies came up and the captured (redacted, bounded)
472
+ * `docker compose up` logs. Refreshed on each Tester round (it stands the infra up anew),
473
+ * so the test window can surface WHY local infra failed to come up — the failure-class
474
+ * artifact the orchestrator-side provisioning logs can't see. Absent for ephemeral /
475
+ * no-infra runs. See {@link testerInfraSetupSchema}.
476
+ */
477
+ infraSetup: v.optional(v.nullable(testerInfraSetupSchema)),
478
+ });
479
+ /**
480
+ * One test quality-control companion verdict, recorded per QC evaluation of a Tester
481
+ * report (in order; newest last). `adequate` is the QC's judgement that the report is
482
+ * complete enough to conclude testing / go to the fixer; when false, `gaps` lists the
483
+ * concrete things the Tester still needs to exercise and `feedback` is the prose the
484
+ * Tester is handed on its re-run.
485
+ */
486
+ export const testerQualityVerdictSchema = v.object({
487
+ /** Whether the report is complete/coherent enough to proceed (no QC re-run needed). */
488
+ adequate: v.boolean(),
489
+ /** The QC's prose challenge / justification, folded into the Tester's re-run context. */
490
+ feedback: v.string(),
491
+ /** Concrete coverage gaps the Tester must still address (empty when adequate). */
492
+ gaps: v.array(v.string()),
493
+ /** Epoch ms the verdict was produced. */
494
+ at: v.number(),
495
+ /** The model that produced the verdict, for transparency. */
496
+ model: v.optional(v.nullable(v.string())),
497
+ });
498
+ /**
499
+ * Live test quality-control loop state carried on a run's Tester step, copied from the
500
+ * pipeline's per-step `testerQualityConfigSchema` (see entities.ts) at run start. The QC companion reads
501
+ * each Tester report BEFORE the greenlight/fixer decision; when the report is inadequate and
502
+ * `attempts < maxAttempts` it loops the Tester (folding the prior report + `feedback` in),
503
+ * bounded independently of the fixer budget. `verdicts` records each evaluation for the UI.
504
+ */
505
+ export const testerQualityStepStateSchema = v.object({
506
+ /** Whether the QC companion is active on this Tester step (the builder toggle). */
507
+ enabled: v.boolean(),
508
+ /** How many QC-driven Tester re-runs have been dispatched so far. */
509
+ attempts: v.optional(v.number(), 0),
510
+ /** Ceiling on QC-driven re-runs, from the task's merge preset (`maxTesterQualityIterations`). */
511
+ maxAttempts: v.number(),
512
+ /** Optional estimate gating copied from the pipeline; evaluated against the block estimate. */
513
+ gating: v.optional(v.nullable(stepGatingSchema)),
514
+ /** One verdict per QC evaluation, in order (newest last). Empty before the first grade. */
515
+ verdicts: v.array(testerQualityVerdictSchema),
516
+ /** Set true once the QC budget was spent with the report still judged inadequate. */
517
+ exceeded: v.optional(v.boolean()),
518
+ });
519
+ /**
520
+ * The compact ephemeral-environment view a `human-test` gate carries on its step, so the
521
+ * dedicated window can surface the live URL/status without a second fetch. The full record
522
+ * (with encrypted access creds) lives in the `environments` table; this is the non-secret
523
+ * projection. Null in degraded manual mode (no env provider wired) or after the human
524
+ * destroys the env from the gate.
525
+ */
526
+ /**
527
+ * The compact, non-secret projection of the ephemeral environment a run's step is
528
+ * associated with — its lifecycle state, public URL, TTL, and (when failed) the
529
+ * exact provider error. Surfaced in a run's details (esp. the Tester step) so the
530
+ * env's spinning-up / running / shut-down / errored state is visible without a
531
+ * second fetch. The full record (with encrypted creds) lives in the `environments`
532
+ * table. {@link humanTestEnvironmentSchema} is the human-test gate's subset of this.
533
+ */
534
+ export const runEnvironmentSchema = v.object({
535
+ /** The `environments` row id (lets a window fetch access creds / re-poll status). */
536
+ id: v.string(),
537
+ /** The provisioned public URL (null while still provisioning). */
538
+ url: v.nullable(v.string()),
539
+ /** The environment lifecycle status; see {@link environmentStatusSchema}. */
540
+ status: environmentStatusSchema,
541
+ /** Epoch ms the environment expires (TTL), when known. */
542
+ expiresAt: v.optional(v.nullable(v.number())),
543
+ /** The verbatim provider error when the environment failed/expired, else null. */
544
+ lastError: v.optional(v.nullable(v.string())),
545
+ /**
546
+ * The service's declared provision type this environment was stood up for
547
+ * (`kubernetes` | `docker-compose` | `custom` | `infraless`), recorded at provision
548
+ * time so a run's details show exactly what was provisioned. Null for legacy rows /
549
+ * pre-resolution.
550
+ */
551
+ provisionType: v.optional(v.nullable(provisionTypeSchema)),
552
+ /**
553
+ * The resolved engine that handled the provisioning (`local-docker` | `local-k3s` |
554
+ * `remote-kubernetes` | `remote-custom` | `none`), surfaced in run details alongside the
555
+ * environment state. Null for legacy rows / pre-resolution.
556
+ */
557
+ engine: v.optional(v.nullable(infraEngineSchema)),
558
+ });
559
+ /**
560
+ * The lifecycle status of the per-run container backing a container agent step:
561
+ * `starting` (dispatching / cold-booting), `up` (running the agent's job),
562
+ * `errored` (the container failed to start, was evicted, or its job faulted), and
563
+ * `destroyed` (the run's container has been reclaimed). The SPA additionally derives
564
+ * `destroyed` for a finished run's container steps (the container is reclaimed as a
565
+ * unit when the run terminates), so the backend only ever persists the first three.
566
+ */
567
+ export const runContainerStatusSchema = v.picklist(['starting', 'up', 'errored', 'destroyed']);
568
+ /**
569
+ * The compact, non-secret projection of the per-run container a container agent step
570
+ * runs in, so a run's details can show WHAT the container is doing and WHERE it lives
571
+ * instead of a step's "spinning up container…" badge vanishing into a blank "working"
572
+ * state once the container is up. Populated by the engine across the dispatch + poll
573
+ * lifecycle of an async (container) step; only ever set on container-backed steps.
574
+ */
575
+ export const runContainerSchema = v.object({
576
+ /** The container lifecycle status; see {@link runContainerStatusSchema}. */
577
+ status: runContainerStatusSchema,
578
+ /**
579
+ * The coarse phase the agent's job is in while the container is `up` (`clone` →
580
+ * `agent` → `push`, seeded `starting`), forwarded from the harness. Lets the details
581
+ * distinguish "still preparing the checkout" from "the agent is making calls". Absent
582
+ * until the first poll, or when the runner doesn't report a phase.
583
+ */
584
+ phase: v.optional(v.nullable(v.string())),
585
+ /** Provider container/runner id (Cloudflare DO id, docker container id), when known. */
586
+ id: v.optional(v.nullable(v.string())),
587
+ /** A reachable address for the running container (the local docker host URL), when one exists. */
588
+ url: v.optional(v.nullable(v.string())),
589
+ });
590
+ /** The web-search backend a run's container searches through, when search is available. */
591
+ export const webSearchProviderSchema = v.picklist(['brave', 'searxng']);
592
+ /**
593
+ * Narrow a free-text stored value (a telemetry `provider` column, which is plain TEXT) back
594
+ * to the {@link WebSearchProvider} union, or null when it isn't one. The single source of
595
+ * truth both telemetry stores use to map their rows, so the union is defined once.
596
+ */
597
+ export function isWebSearchProvider(value) {
598
+ return value === 'brave' || value === 'searxng';
599
+ }
600
+ /**
601
+ * Whether a container agent had web search available for its run, and — when it did —
602
+ * which upstream backend served it (resolved backend-side at dispatch from the run's
603
+ * account keys, else the deployment default). Surfaced on a container step so the run
604
+ * details can say "Web search: SearXNG" vs "Web search: unavailable"; it is a static
605
+ * dispatch-time fact, NOT gated by prompt-recording telemetry (the performed queries
606
+ * are — see the agent-search-query observability sink). `provider` is null when search
607
+ * was unavailable.
608
+ */
609
+ export const webSearchAvailabilitySchema = v.object({
610
+ available: v.boolean(),
611
+ provider: v.nullable(webSearchProviderSchema),
612
+ });
613
+ /**
614
+ * The TERMINAL per-frame outcome of one environment a `deployer` step provisioned during a
615
+ * multi-env fan-out (the task's own service frame + every involved-service frame): `ready`
616
+ * (a live env, `url` set), `failed` (the provision broke, `error` carries the cause), or
617
+ * `skipped` (the frame is `infraless`, nothing stood up). The IN-FLIGHT frame is not recorded
618
+ * here — it lives on `step.jobId`/`step.deployFrameId` until it settles. See
619
+ * {@link pipelineStepSchema.entries.deployEnvs}.
620
+ */
621
+ export const deployEnvStateSchema = v.object({
622
+ status: v.picklist(['ready', 'failed', 'skipped']),
623
+ /** The provisioned URL for a `ready` env (absent for `failed`/`skipped`). */
624
+ url: v.optional(v.nullable(v.string())),
625
+ /** The verbatim provider error for a `failed` env. */
626
+ error: v.optional(v.nullable(v.string())),
627
+ });
628
+ /** Per-frame deploy outcomes keyed by service-frame block id; see {@link deployEnvStateSchema}. */
629
+ export const deployEnvsSchema = v.record(v.string(), deployEnvStateSchema);
630
+ export const humanTestEnvironmentSchema = v.object({
631
+ /** The `environments` row id, so the window can fetch access creds / re-poll status. */
632
+ id: v.string(),
633
+ /** The provisioned public URL the human tests against (null while still provisioning). */
634
+ url: v.nullable(v.string()),
635
+ /** The environment lifecycle status; see {@link environmentStatusSchema}. */
636
+ status: environmentStatusSchema,
637
+ /** Epoch ms the environment expires (TTL), when known. */
638
+ expiresAt: v.optional(v.nullable(v.number())),
639
+ });
640
+ /**
641
+ * One round of human-driven remediation on a `human-test` gate: the human wrote findings and
642
+ * asked for a fix (helper `fixer`), or pulled main and hit a conflict (helper
643
+ * `conflict-resolver`). Appended when the round opens and stamped with its outcome once the
644
+ * helper job settles, so the window can show the full history of what was asked and how it ended.
645
+ */
646
+ export const humanTestRoundSchema = v.object({
647
+ /** The kind of round — a findings-driven fix or a pull-main-with-conflicts resolve. */
648
+ kind: v.picklist(['fix', 'pull-main']),
649
+ /** The human's findings prompt (fix), or a one-line note for the pull-main round. */
650
+ findings: v.string(),
651
+ /** The helper container kind this round dispatched (`fixer` / `conflict-resolver`). */
652
+ helperKind: v.string(),
653
+ /** The helper job's id while it ran, for cross-referencing the run timeline. */
654
+ jobId: v.optional(v.nullable(v.string())),
655
+ /** How the helper ended once its job settled. Absent while still in flight. */
656
+ outcome: v.optional(v.nullable(v.picklist(['completed', 'failed']))),
657
+ /** Epoch ms the round opened (the human clicked Request fix / Pull main). */
658
+ at: v.number(),
659
+ });
660
+ /**
661
+ * State a `human-test` gate carries while it runs. Unlike a polling gate (`ci`/`conflicts`)
662
+ * there is no programmatic verdict — the HUMAN is the verdict — so the step spins up an
663
+ * ephemeral environment, parks for a person to validate it, and on demand dispatches the same
664
+ * helpers the other gates use (the Tester's `fixer` for findings; the `conflict-resolver` for a
665
+ * conflicting pull-main). Phases:
666
+ * - `provisioning` — an environment is being stood up (the driver polls until ready).
667
+ * - `awaiting_human` — parked: the human tests the env and confirms / requests a fix / etc.
668
+ * - `fixing` — a `fixer` job (from the human's findings) is in flight.
669
+ * - `resolving_conflicts` — a `conflict-resolver` job (from a conflicting pull-main) is in flight.
670
+ * - `passed` — the human confirmed; the env is torn down and the run advances.
671
+ */
672
+ export const humanTestStepStateSchema = v.object({
673
+ phase: v.picklist(['provisioning', 'awaiting_human', 'fixing', 'resolving_conflicts', 'passed']),
674
+ /** The live ephemeral environment (null in degraded manual mode / after destroy). */
675
+ environment: v.optional(v.nullable(humanTestEnvironmentSchema)),
676
+ /**
677
+ * Why no environment was auto-provisioned — set in degraded manual mode (no env provider
678
+ * wired, or provisioning errored) so the window can explain it and let the human test
679
+ * against the PR branch manually. Absent when an env was provisioned.
680
+ */
681
+ degradedReason: v.optional(v.nullable(v.string())),
682
+ /** How many helper (fixer / conflict-resolver) attempts have been dispatched so far. */
683
+ attempts: v.number(),
684
+ /** Ceiling on helper attempts, resolved from the task's merge preset (`ciMaxAttempts`). */
685
+ maxAttempts: v.number(),
686
+ /** The PR head commit being tested, when known. */
687
+ headSha: v.optional(v.nullable(v.string())),
688
+ /** Append-only history of fix / pull-main rounds; see {@link humanTestRoundSchema}. */
689
+ rounds: v.optional(v.array(humanTestRoundSchema)),
690
+ /**
691
+ * Transient action the human requested while the gate is parked — recorded on the parked
692
+ * step and consumed by the durable driver when it re-enters the gate (the analogue of
693
+ * `pendingIncorporation` on a requirements gate). Cleared once the driver acts on it.
694
+ */
695
+ pendingAction: v.optional(v.nullable(v.object({
696
+ type: v.picklist(['confirm', 'request-fix', 'pull-main', 'recreate']),
697
+ /** The findings prompt for a `request-fix` action. */
698
+ findings: v.optional(v.string()),
699
+ }))),
700
+ });
701
+ /**
702
+ * One actual-vs-reference pairing the visual-confirmation gate shows the human: a logical
703
+ * view, the screenshot the UI tester captured of it (`actualArtifactId`), and the reference
704
+ * design image for the same view when one was uploaded (`referenceArtifactId`). Either side
705
+ * may be absent (a captured view with no reference, or a reference whose view wasn't captured).
706
+ */
707
+ export const visualConfirmPairSchema = v.object({
708
+ view: v.string(),
709
+ actualArtifactId: v.optional(v.nullable(v.string())),
710
+ referenceArtifactId: v.optional(v.nullable(v.string())),
711
+ });
712
+ /** One human-requested fix round on a visual-confirmation gate (dispatches the `fixer`). */
713
+ export const visualConfirmRoundSchema = v.object({
714
+ findings: v.string(),
715
+ helperKind: v.string(),
716
+ jobId: v.optional(v.nullable(v.string())),
717
+ outcome: v.optional(v.nullable(v.picklist(['completed', 'failed']))),
718
+ at: v.number(),
719
+ });
720
+ /**
721
+ * State a `visual-confirmation` gate carries while it runs. Like `human-test` there is no
722
+ * programmatic verdict — a HUMAN reviews the UI tester's screenshots against the uploaded
723
+ * reference designs and approves, or requests a fix (which dispatches the `fixer` and then
724
+ * re-captures via the UI tester). Phases:
725
+ * - `awaiting_human`— parked: the human reviews actual-vs-reference and approves / requests a fix.
726
+ * - `fixing` — a `fixer` job (from the human's findings) is in flight.
727
+ * - `approved` — the human approved; the run advances.
728
+ *
729
+ * (A dedicated `capturing` phase for an auto re-run of the UI tester after a fix is deferred
730
+ * until that loop is wired — see the visual-confirmation handover doc — so it is intentionally
731
+ * absent from the picklist rather than carried as dead state.)
732
+ */
733
+ export const visualConfirmStepStateSchema = v.object({
734
+ phase: v.picklist(['awaiting_human', 'fixing', 'approved']),
735
+ /** The actual-vs-reference pairs the human reviews, refreshed on each (re)capture. */
736
+ pairs: v.optional(v.array(visualConfirmPairSchema)),
737
+ /** Set when no screenshots could be gathered (no UI tester ran / no storage) — manual mode. */
738
+ degradedReason: v.optional(v.nullable(v.string())),
739
+ /** How many fixer attempts have been dispatched so far. */
740
+ attempts: v.number(),
741
+ /** Ceiling on fixer attempts, resolved from the task's merge preset (`ciMaxAttempts`). */
742
+ maxAttempts: v.number(),
743
+ /** Append-only history of fix rounds; see {@link visualConfirmRoundSchema}. */
744
+ rounds: v.optional(v.array(visualConfirmRoundSchema)),
745
+ /**
746
+ * Transient action the human requested while parked — consumed by the durable driver
747
+ * when it re-enters the gate. Cleared once acted on.
748
+ */
749
+ pendingAction: v.optional(v.nullable(v.object({
750
+ type: v.picklist(['approve', 'request-fix', 'recapture']),
751
+ /** The findings prompt for a `request-fix` action. */
752
+ findings: v.optional(v.string()),
753
+ }))),
754
+ });
755
+ /**
756
+ * Per-step LLM observability rollup: a compact aggregate over every model call the
757
+ * step's container made, recorded by the LLM proxy and summed by the engine for the
758
+ * board. It surfaces, at a glance, token usage, how close the step ran to its
759
+ * output-token limit (truncation), the latency split between transport/proxy
760
+ * overhead and actual model execution, and any errors/warnings. The full per-call
761
+ * detail (prompts + responses) is fetched on demand for the drill-down panel.
762
+ * Absent when the observability sink is not wired.
763
+ */
764
+ export const stepMetricsSchema = v.object({
765
+ /** Number of model calls recorded for this step. */
766
+ calls: v.number(),
767
+ /** Sum of prompt (input) tokens across the step's calls. */
768
+ promptTokens: v.number(),
769
+ /**
770
+ * Sum of prompt tokens served from the provider's prefix cache. A subset of
771
+ * promptTokens on OpenAI/DeepSeek, but on Anthropic cache reads are reported
772
+ * separately from input tokens, so this can exceed promptTokens. 0 on a cache-less
773
+ * flavour (Workers AI); the metrics bar shows the cached split when present. Absent ⇒
774
+ * unknown (older snapshot).
775
+ */
776
+ cachedPromptTokens: v.optional(v.number()),
777
+ /** Sum of completion (output) tokens across the step's calls. */
778
+ completionTokens: v.number(),
779
+ /** Largest single completion the model produced (closest approach to the limit). */
780
+ peakCompletionTokens: v.number(),
781
+ /** The output ceiling in effect (max requested `max_tokens`), or null when unknown. */
782
+ maxOutputTokens: v.nullable(v.number()),
783
+ /** Calls cut short by the output limit (`finish_reason === 'length'`). */
784
+ truncatedCalls: v.number(),
785
+ /** Sum of model execution time (ms) — the "actual prompt/tool execution" slice. */
786
+ upstreamMs: v.number(),
787
+ /** Sum of transport/proxy overhead (ms) — the interim-layer cost. */
788
+ overheadMs: v.number(),
789
+ /** Calls that failed (non-2xx / refused / in-process error). */
790
+ errors: v.number(),
791
+ /** Successful calls that warned (truncated or content-filtered). */
792
+ warnings: v.number(),
793
+ });
794
+ export const pipelineStepSchema = v.object({
795
+ /**
796
+ * Id of the execution run (the {@link executionInstanceSchema} `id`) this step
797
+ * belongs to — surfaced on every step so a lone step in a log line or a detail view
798
+ * can name its run, for easier debugging. A projection that always equals the parent
799
+ * instance's `id`: stamped from the enclosing instance when the run is read or
800
+ * emitted, not persisted independently. Absent only on steps not yet round-tripped.
801
+ */
802
+ runId: v.optional(v.string()),
803
+ agentKind: agentKindSchema,
804
+ state: agentStateSchema,
805
+ progress: v.number(),
806
+ /** LLM observability rollup for this step; see {@link stepMetricsSchema}. */
807
+ metrics: v.optional(v.nullable(stepMetricsSchema)),
808
+ /**
809
+ * Live gate state while a polling gate step (`ci` / `conflicts`) runs its
810
+ * precheck-or-escalate loop; see {@link gateStepStateSchema}. The gate kind is
811
+ * `agentKind`.
812
+ */
813
+ gate: v.optional(v.nullable(gateStepStateSchema)),
814
+ /** Live Tester→Fixer loop state while a `tester` step runs/fixes; see {@link testerStepStateSchema}. */
815
+ test: v.optional(v.nullable(testerStepStateSchema)),
816
+ /**
817
+ * Live test quality-control companion state on a `tester-api`/`tester-ui` step, copied
818
+ * from the pipeline's per-step `testerQuality` config at run start. Drives the QC loop that
819
+ * gates each Tester report for completeness before the greenlight/fixer decision. Absent
820
+ * for non-Tester steps / when the companion is disabled. See {@link testerQualityStepStateSchema}.
821
+ */
822
+ testerQuality: v.optional(v.nullable(testerQualityStepStateSchema)),
823
+ /**
824
+ * Live state of a `human-test` gate (ephemeral env + human validation loop); see
825
+ * {@link humanTestStepStateSchema}. Absent for every other step kind.
826
+ */
827
+ humanTest: v.optional(v.nullable(humanTestStepStateSchema)),
828
+ /**
829
+ * Live state of a `visual-confirmation` gate (screenshot review + fix loop); see
830
+ * {@link visualConfirmStepStateSchema}. Absent for every other step kind.
831
+ */
832
+ visualConfirm: v.optional(v.nullable(visualConfirmStepStateSchema)),
833
+ /**
834
+ * The ephemeral environment this step runs against (when the block has one), so a
835
+ * run's details can show its spinning-up / running / shut-down / errored state +
836
+ * the exact error. Populated by the engine for container/deployer steps from the
837
+ * block's live environment; see {@link runEnvironmentSchema}. The `human-test` gate
838
+ * keeps its own richer `humanTest.environment` and is not double-populated here.
839
+ */
840
+ environment: v.optional(v.nullable(runEnvironmentSchema)),
841
+ /** Live subtask counts while an async (container) step runs; see {@link stepSubtasksSchema}. */
842
+ subtasks: v.optional(stepSubtasksSchema),
843
+ /**
844
+ * The per-run container this async (container) step runs in — its lifecycle status
845
+ * (starting / up / errored), the agent's current phase (clone / agent / push), and
846
+ * the container's id + reachable URL once up. Lets a run's details surface what the
847
+ * container is doing and where it lives, so the board shows an explicit "Spinning up
848
+ * container…" → live-phase progression instead of a blank "working" state. Set the
849
+ * moment the job is dispatched (the dispatch blocks until the container accepts the
850
+ * job) and refined on each poll. Only ever set on async (container) steps; absent on
851
+ * non-container steps and steps not yet dispatched. See {@link runContainerSchema}.
852
+ */
853
+ container: v.optional(v.nullable(runContainerSchema)),
854
+ /**
855
+ * Whether web search was available to this container step, and which upstream backend
856
+ * served it. Set at dispatch (a static per-run fact resolved from the account's
857
+ * web-search keys, else the deployment default). Only ever set on async (container)
858
+ * steps; absent on non-container steps and steps not yet dispatched. Distinct from the
859
+ * telemetry-gated per-query log — this is always surfaced. See {@link webSearchAvailabilitySchema}.
860
+ */
861
+ search: v.optional(v.nullable(webSearchAvailabilitySchema)),
862
+ decision: v.nullable(decisionSchema),
863
+ /**
864
+ * Whether a human approval gate fires after this step completes. Copied from
865
+ * the pipeline's `gates` at run start; absent means no gate.
866
+ */
867
+ requiresApproval: v.optional(v.boolean()),
868
+ /**
869
+ * The live approval gate for this step (see {@link stepApprovalSchema}). Set
870
+ * once the step's proposal is ready and `requiresApproval` is true; null/absent
871
+ * otherwise.
872
+ */
873
+ approval: v.optional(v.nullable(stepApprovalSchema)),
874
+ /**
875
+ * Live state of a companion step that reviews a preceding producer step. Set when
876
+ * this step's `agentKind` is a companion kind. `threshold` is the quality bar the
877
+ * companion's latest rating (the last `verdicts` entry) must reach; `attempts`
878
+ * counts only the AUTOMATIC reworks performed, and once it reaches `maxAttempts` the
879
+ * step parks on the iteration-cap gate (`exceeded`) for a human rather than failing.
880
+ * A human "request changes" on the companion's gate also re-runs the producer but does
881
+ * NOT consume `attempts` (only the automatic loop is budgeted). Absent for non-companion steps.
882
+ */
883
+ companion: v.optional(v.nullable(v.object({
884
+ /** The quality bar (0..1) the latest verdict's rating must reach; seeded from the pipeline. */
885
+ threshold: v.number(),
886
+ /** The automatic rework budget: once `attempts` reaches this the gate parks for a human (`exceeded`). */
887
+ maxAttempts: v.number(),
888
+ /**
889
+ * How many AUTOMATIC reworks the companion has driven so far (the producer is
890
+ * looped back once per failed verdict). Human "request changes" cycles are not
891
+ * counted. Defaults to 0; once it reaches `maxAttempts` the step parks on the
892
+ * iteration-cap gate (`exceeded`) — an "extra round" raises `maxAttempts` by one.
893
+ */
894
+ attempts: v.optional(v.number(), 0),
895
+ /**
896
+ * One standardized {@link companionVerdictSchema} per grading cycle, in order —
897
+ * the full sequence of correction iterations (the producer is re-run after each
898
+ * rejected verdict), including any human-driven ones. Empty before the first
899
+ * grade; the last entry is the latest.
900
+ */
901
+ verdicts: v.array(companionVerdictSchema),
902
+ /**
903
+ * Set true when the automatic rework budget (`maxAttempts`) was spent with the
904
+ * rating still below the bar: instead of failing the run, the step parks on its
905
+ * approval gate for a human to resolve via the shared iteration-cap surface
906
+ * (one more round / proceed anyway / stop & reset). Cleared once the human grants
907
+ * an extra round (the loop resumes). Absent until/unless the cap is hit.
908
+ */
909
+ exceeded: v.optional(v.boolean()),
910
+ }))),
911
+ /**
912
+ * Live Follow-up companion state while a `coder` step runs/parks: the items the Coder
913
+ * streamed (loose ends / side-tasks / questions), whether the companion is enabled, and
914
+ * the send-back loop budget. Items accrue live as the harness streams them (the blinking
915
+ * companion); at the step's completion the engine parks the run while any item is
916
+ * `pending`, then loops the Coder for any `queued` follow-up / `answered` question. See
917
+ * {@link followUpsStepStateSchema}. Absent for non-`coder` steps / when the companion is off.
918
+ */
919
+ followUps: v.optional(v.nullable(followUpsStepStateSchema)),
920
+ /**
921
+ * Live implementation-fork decision state while a `coder` step runs its optional
922
+ * two-phase flow: the proposer explore job (`proposing`), the human park
923
+ * (`awaiting_choice` / `answering`), the resolved choice (`chosen`), or one of the
924
+ * pass-through terminals (`single_path` / `skipped`). Created lazily by the engine
925
+ * when the phase activates — the config lives on the block + the risk policy, never
926
+ * on the step. Absent for non-`coder` steps / when the phase never activated. See
927
+ * {@link forkDecisionStepStateSchema}.
928
+ */
929
+ forkDecision: v.optional(v.nullable(forkDecisionStepStateSchema)),
930
+ /**
931
+ * Live "Ralph loop" state carried on a `ralph` step: the persistent retry-until-done
932
+ * loop's iteration count, budget, validation command, and per-iteration history. Seeded
933
+ * from the block's per-task agent config at step start, then advanced each iteration by
934
+ * the engine's `RalphController`. Because it rides the run's persisted `detail` blob, both
935
+ * durable drivers + both stale-run sweepers re-drive a mid-loop run from exactly this
936
+ * state after a restart. Absent for non-`ralph` steps. See {@link ralphStepStateSchema}.
937
+ */
938
+ ralph: v.optional(v.nullable(ralphStepStateSchema)),
939
+ /**
940
+ * Transient re-entry marker carried on a parked `coder` step whose fork decision is
941
+ * `answering`: set when the human sends a chat message so the run is signalled to
942
+ * wake and the durable driver, on re-entering, runs the inline chat LLM and appends
943
+ * the assistant reply (the LLM work that must not block the HTTP request). Cleared
944
+ * once that async cycle completes. Documented beside `pendingIncorporation` /
945
+ * `pendingInterview`. Absent when no chat turn is pending.
946
+ */
947
+ pendingForkChat: v.optional(v.nullable(v.object({ messageId: v.string() }))),
948
+ /**
949
+ * Live PR deep-review state carried on a `pr-reviewer` step: the sliced, severity-ordered
950
+ * findings the read-only reviewer produced, the human's curated selection, and how it was
951
+ * resolved. Recorded by the engine when the reviewer container job completes; the run then
952
+ * parks (`awaiting_selection`) for the human to select findings through the dedicated
953
+ * window and resolve. Absent for non-`pr-reviewer` steps. See {@link prReviewStepStateSchema}.
954
+ */
955
+ prReview: v.optional(v.nullable(prReviewStepStateSchema)),
956
+ /**
957
+ * The at-most-once driver marker for the PR-review "post" resolution: set when the human
958
+ * resolves a parked review with `post`, so the durable driver — on re-entry, off the HTTP
959
+ * request — publishes the selected findings as inline PR review comments (via
960
+ * `RepoFiles.createReview`) exactly once. Consumed (cleared + persisted) BEFORE the posting
961
+ * side effect so a Workflows retry/replay can't post the review twice. Cleared once posted.
962
+ */
963
+ pendingPrReviewPost: v.optional(v.nullable(v.boolean())),
964
+ /**
965
+ * Transient rework feedback carried on a PRODUCER step while it is being re-run by
966
+ * a downstream companion (the analogue of an approval's `changes_requested`
967
+ * feedback for the automatic path). Folded into the agent's revision context on the
968
+ * re-run, then cleared. Absent when no companion rework is in flight.
969
+ */
970
+ rework: v.optional(v.nullable(v.object({
971
+ /** The producer's previous proposal the companion challenged. */
972
+ previousProposal: v.string(),
973
+ /** The companion's prose feedback driving the rework. */
974
+ feedback: v.string(),
975
+ /** Optional per-item / per-block challenges to address. */
976
+ comments: v.optional(v.array(stepReviewCommentSchema)),
977
+ }))),
978
+ /**
979
+ * Transient incorporation intent carried on a parked `requirements-review` gate step.
980
+ * Set when the human answers the findings and asks to incorporate: the run is signalled
981
+ * to wake and the durable driver, on re-entering the gate, folds the answers into a
982
+ * document and re-reviews it (the LLM work that used to block the HTTP request). Cleared
983
+ * once that async cycle completes. `feedback` is the human's optional "do it differently"
984
+ * direction (a redo). Absent when no incorporation is pending.
985
+ */
986
+ pendingIncorporation: v.optional(v.nullable(v.object({ feedback: v.optional(v.string()) }))),
987
+ /**
988
+ * Transient recommendation intent carried on a parked `requirements-review` gate step.
989
+ * Set when the human asks the Requirement Writer to suggest answers for a batch of findings
990
+ * (or re-requests one): the run is signalled to wake and the durable driver, on re-entering
991
+ * the gate, runs the Writer per finding — filling in the `pending` placeholder
992
+ * recommendations — then re-parks (recommendations never advance the run). Cleared once that
993
+ * async batch completes. `itemIds` are the findings to recommend for; `note` steers the
994
+ * whole batch. Absent when no recommendation batch is pending.
995
+ */
996
+ pendingRecommendation: v.optional(v.nullable(v.object({ itemIds: v.array(v.string()), note: v.optional(v.string()) }))),
997
+ /**
998
+ * Transient interview intent carried on a parked `initiative-interviewer` gate step. Set
999
+ * when the human has answered the planning questions and asked to continue (or proceed):
1000
+ * the run is signalled to wake and the durable driver, on re-entering the gate, runs the
1001
+ * interviewer LLM again against the answers — asking follow-ups (re-park) or synthesizing
1002
+ * the goal/constraints brief and advancing. `proceed` skips any remaining questions.
1003
+ * Cleared once that async re-entry completes. Absent when no continuation is pending.
1004
+ */
1005
+ pendingInterview: v.optional(v.nullable(v.object({ proceed: v.optional(v.boolean()) }))),
1006
+ /**
1007
+ * Consensus configuration for this step, copied from the pipeline's `consensus`
1008
+ * array at run start. Present (with `enabled: true`) when this step should run
1009
+ * through the multi-model consensus mechanism; read by the consensus executor
1010
+ * (and to decide gating against the block estimate). Absent ⇒ standard agent.
1011
+ * See {@link consensusStepConfigSchema}.
1012
+ */
1013
+ consensus: v.optional(v.nullable(consensusStepConfigSchema)),
1014
+ /**
1015
+ * Estimate-based gating for this step, copied from the pipeline's `gating` array at
1016
+ * run start. When present (with `enabled: true`) the step is skipped at runtime unless
1017
+ * the block's task estimate meets the threshold. Absent ⇒ always run. See
1018
+ * {@link stepGatingSchema}.
1019
+ */
1020
+ gating: v.optional(v.nullable(stepGatingSchema)),
1021
+ /**
1022
+ * Per-step options bag copied from the pipeline's `stepOptions` array at run start (see
1023
+ * {@link stepOptionsSchema}). Absent ⇒ all defaults for this step. Read by the engine —
1024
+ * e.g. the requirements-review gate consults `stepOptions.autoRecommend`.
1025
+ */
1026
+ stepOptions: v.optional(v.nullable(stepOptionsSchema)),
1027
+ /**
1028
+ * True when this step was skipped at runtime because its `gating` was not satisfied
1029
+ * (the task estimate fell below the threshold). The step's `state` is `done` with no
1030
+ * output; the UI renders it as "skipped (gated)". Absent ⇒ the step ran normally.
1031
+ */
1032
+ skipped: v.optional(v.boolean()),
1033
+ /**
1034
+ * Set `true` on a `spec-writer` step that determined the task is purely technical and
1035
+ * produced no business specs (its result's `noBusinessSpecs`). Recorded on the step so
1036
+ * the spec-companion's convergence — the one point both signals coexist — can combine it
1037
+ * with the companion's `technicalCorroborated` verdict to infer the block's `technical`
1038
+ * label. Absent for every other kind / a writer that produced specs.
1039
+ */
1040
+ noBusinessSpecs: v.optional(v.boolean()),
1041
+ /**
1042
+ * Set on a `spec-companion` step from its `technicalCorroborated` verdict (whether it
1043
+ * agreed the task is purely technical). Recorded on the step — not just read off the
1044
+ * live assessment — so the engine can infer the block's `technical` label both on the
1045
+ * companion's automatic convergence AND on a human "proceed" past the iteration cap,
1046
+ * where only the persisted step survives. Absent for every other kind / no opinion.
1047
+ */
1048
+ technicalCorroborated: v.optional(v.boolean()),
1049
+ /** Text the agent produced for this step (when LLM execution is enabled). */
1050
+ output: v.optional(v.string()),
1051
+ /**
1052
+ * The structured JSON a registered CUSTOM kind's agent step returned (the generic
1053
+ * manifest-driven `agent` dispatch's `custom` channel). Recorded so the SPA can render
1054
+ * it in the `generic-structured` result view (and a post-op already consumed it
1055
+ * server-side). Absent for built-in / prose kinds.
1056
+ */
1057
+ custom: v.optional(v.unknown()),
1058
+ /** Identifier of the model that produced `output`, for transparency. */
1059
+ model: v.optional(v.string()),
1060
+ /**
1061
+ * Ids of the prompt-fragment library entries that were folded into this step's
1062
+ * system prompt — the manual selection on the block unioned with the relevance
1063
+ * selector's pick. Recorded for observability and replay-stability; absent when
1064
+ * the fragment-library module is not configured.
1065
+ */
1066
+ selectedFragmentIds: v.optional(v.array(v.string())),
1067
+ /**
1068
+ * The repo-sourced Claude Skill this step was PINNED to at dispatch (a `skill` step; see
1069
+ * `docs/initiatives/repo-skills.md`). Recorded so a run executes a stable version of the
1070
+ * skill even if its source resyncs mid-run, and so a later investigation knows exactly
1071
+ * which skill (and at which commit / manifest blob) ran. `commit` is the source dir's head
1072
+ * commit the resources were fetched at (null if the skill was never synced to a commit);
1073
+ * `sha` is the `SKILL.md` blob sha. Absent for every non-`skill` step.
1074
+ */
1075
+ skillVersion: v.optional(v.object({
1076
+ skillId: v.string(),
1077
+ commit: v.nullable(v.string()),
1078
+ sha: v.string(),
1079
+ })),
1080
+ /**
1081
+ * Identifier of an in-flight asynchronous agent job (a container run polled by
1082
+ * the durable driver). Set while the step is dispatched-but-not-yet-finished so
1083
+ * a Workflows replay re-attaches to the running job instead of starting a new
1084
+ * one; cleared once the job's result is recorded.
1085
+ */
1086
+ jobId: v.optional(v.string()),
1087
+ /**
1088
+ * Epoch ms the step first began executing (transitioned to `working`). Set once
1089
+ * and never overwritten on subsequent state changes, so a re-run/replay keeps the
1090
+ * original start. Absent until the step starts.
1091
+ */
1092
+ startedAt: v.optional(v.nullable(v.number())),
1093
+ /**
1094
+ * Epoch ms the step finished (transitioned to `done`). With {@link startedAt}
1095
+ * this yields the step's execution duration. Absent until the step completes.
1096
+ */
1097
+ finishedAt: v.optional(v.nullable(v.number())),
1098
+ /**
1099
+ * Epoch ms the step parked on a human (an approval gate, a raised decision, or an
1100
+ * iteration-cap gate), freezing its duration clock: while parked, elapsed time stops
1101
+ * accruing — the symmetric counterpart of {@link finishedAt}'s terminal freeze, so a
1102
+ * step waiting on input is not billed for the human's deliberation. Set once on park,
1103
+ * cleared (null) when the step resumes working or finishes. Absent until first parked.
1104
+ */
1105
+ pausedAt: v.optional(v.nullable(v.number())),
1106
+ /**
1107
+ * How many times this step's container was evicted/crashed and recovered by
1108
+ * automatically re-dispatching a fresh container (bounded by
1109
+ * `MAX_EVICTION_RECOVERIES`). Once spent, a further eviction fails the run as
1110
+ * `evicted` rather than looping. Absent/0 until the first eviction.
1111
+ */
1112
+ evictionRecoveries: v.optional(v.number()),
1113
+ /**
1114
+ * How many times this step's container was evicted by *transient infrastructure
1115
+ * churn* — an event the runtime facade flags as not-a-crash (e.g. a deploy
1116
+ * draining the sandbox) — and recovered by re-dispatching a fresh container.
1117
+ * Counted separately from {@link evictionRecoveries} and bounded by a larger
1118
+ * `MAX_TRANSIENT_EVICTION_RECOVERIES`, since such churn can recur several times in
1119
+ * a short window, unlike a crash. Absent/0 until the first transient eviction.
1120
+ */
1121
+ transientEvictionRecoveries: v.optional(v.number()),
1122
+ /**
1123
+ * The service-provisioning config a `deployer` step PINNED when it dispatched its async,
1124
+ * container-backed deploy job, so the later poll/finalize maps the job against the same config
1125
+ * the container was built from — NOT a fresh read of the service frame (which a person may have
1126
+ * edited mid-flight, e.g. flipping it to `infraless`, which would otherwise fail a deploy whose
1127
+ * container already succeeded). Absent for the synchronous raw-manifest path and the undeclared
1128
+ * legacy single-connection path (re-resolution is harmless there). See {@link serviceProvisioningSchema}.
1129
+ */
1130
+ deployProvisioning: v.optional(serviceProvisioningSchema),
1131
+ /**
1132
+ * A `deployer` step fanning out over several service frames (the task's own frame + each
1133
+ * involved-service frame; see the connections initiative) records each frame's TERMINAL
1134
+ * outcome here, keyed by frame block id — so a durable replay knows which frames are already
1135
+ * provisioned and only the remaining ones are dispatched. The in-flight frame is tracked by
1136
+ * {@link deployFrameId} + {@link jobId} until it settles into this map. Absent for a
1137
+ * single-frame deploy that never fanned out. See {@link deployEnvsSchema}.
1138
+ */
1139
+ deployEnvs: v.optional(deployEnvsSchema),
1140
+ /**
1141
+ * The service FRAME the deployer step's currently in-flight deploy job ({@link jobId}) is
1142
+ * provisioning, during a multi-env fan-out — so the poll/finalize maps the settled job onto the
1143
+ * right frame's {@link deployEnvs} entry. Cleared once that frame settles; absent when no deploy
1144
+ * job is in flight or the step never fanned out.
1145
+ */
1146
+ deployFrameId: v.optional(v.string()),
1147
+ /**
1148
+ * The task's OWN (primary) service frame, pinned on the FIRST target resolution of a `deployer`
1149
+ * fan-out and reused on every re-entry/replay. Keeps the primary classification STABLE against a
1150
+ * mid-flight reparent (which would otherwise re-derive a different own frame and flip an
1151
+ * own-service provisioning failure from terminal to a non-terminal peer failure — completing the
1152
+ * run `done` despite a failed deploy). Absent until the first resolution / for a step that never
1153
+ * fanned out.
1154
+ */
1155
+ deployPrimaryFrameId: v.optional(v.string()),
1156
+ });
1157
+ export const executionStatusSchema = v.picklist(['running', 'blocked', 'done', 'paused', 'failed']);
1158
+ /**
1159
+ * Per-run diagnostic context captured for AFTER-THE-FACT investigation of a run (esp. a
1160
+ * failure) — the "where/what did this run actually execute on" facts that were previously
1161
+ * spread across the DB (repo↔service↔installation joins), the harness transcript (model), or
1162
+ * lost entirely (which backend a step ran on). Stamped by the engine at dispatch and refined
1163
+ * on the first poll; it reflects the MOST RECENT container-step dispatch (the step most likely
1164
+ * relevant to a failure), not a per-step history. Rides in the run's `detail` JSON (no dedicated
1165
+ * column), like {@link ExecutionInstance.notes}/`frontendBindings`. Absent on legacy runs and on
1166
+ * runs with no container step (pure inline/gate pipelines). NEVER carries a token or secret.
1167
+ */
1168
+ export const runDiagnosticsSchema = v.object({
1169
+ /** Context of the most recent container-step dispatch. */
1170
+ lastDispatch: v.optional(v.object({
1171
+ /** Index of the dispatched step within the pipeline. */
1172
+ stepIndex: v.number(),
1173
+ /** The step's agent kind (`coder`, `merger`, a custom kind, …). */
1174
+ agentKind: v.string(),
1175
+ /** Resolved model ref `provider:model` (e.g. `anthropic:claude-opus-4-8`); null if unresolved. */
1176
+ model: v.optional(v.nullable(v.string())),
1177
+ /**
1178
+ * Which runner backend the step actually ran on — the datum that distinguishes a native
1179
+ * host-process run from a sandboxed container: `local-native` | `local-container` |
1180
+ * `runner-pool` | `cloudflare-container`. Filled on the first poll (the transport reports
1181
+ * it); absent until then or on an older runtime.
1182
+ */
1183
+ executionBackend: v.optional(v.string()),
1184
+ /** The repo the step operated on. */
1185
+ repo: v.optional(v.object({
1186
+ owner: v.string(),
1187
+ name: v.string(),
1188
+ /** The base branch the work branched from. */
1189
+ baseBranch: v.optional(v.string()),
1190
+ /** VCS provider (`github` | `gitlab`), resolved from the run's repo origin. */
1191
+ provider: v.optional(v.string()),
1192
+ })),
1193
+ /** Epoch ms the dispatch was recorded. */
1194
+ at: v.number(),
1195
+ })),
1196
+ /**
1197
+ * The control-plane (orchestrator) host running the engine — NOT necessarily where the agent
1198
+ * ran (a container step runs elsewhere; see `lastDispatch.executionBackend`). `platform` is the
1199
+ * orchestrator's `process.platform` (e.g. `win32` pins a Windows local deployment — the class
1200
+ * of host that surfaced the native-Windows git-auth break). Best-effort.
1201
+ */
1202
+ host: v.optional(v.object({
1203
+ platform: v.optional(v.string()),
1204
+ })),
1205
+ });
1206
+ export const executionInstanceSchema = v.object({
1207
+ id: v.string(),
1208
+ blockId: v.string(),
1209
+ pipelineId: v.string(),
1210
+ pipelineName: v.string(),
1211
+ steps: v.array(pipelineStepSchema),
1212
+ currentStep: v.number(),
1213
+ status: executionStatusSchema,
1214
+ /**
1215
+ * Structured failure diagnostics when `status` is `failed`; absent/null
1216
+ * otherwise. Lets a failed task surface the same failure banner + retry as a
1217
+ * failed bootstrap (shared {@link agentFailureSchema}).
1218
+ */
1219
+ failure: v.optional(v.nullable(agentFailureSchema)),
1220
+ /**
1221
+ * Failures from the run's PRIOR attempts, oldest→newest. Each retry/restart appends
1222
+ * the then-current {@link failure} here and clears `failure` on the fresh attempt, so
1223
+ * the top failure banner (keyed on `status === 'failed'`) disappears once the task is
1224
+ * restarted while the full error trail stays viewable in the "previous errors" history.
1225
+ * Absent/empty for a run that has never been failed-then-retried.
1226
+ */
1227
+ failureHistory: v.optional(v.array(agentFailureSchema)),
1228
+ /**
1229
+ * Successful outputs from the run's PRIOR attempts that a restart discarded, oldest→newest —
1230
+ * the positive complement of {@link failureHistory}. A restart-from-step resets the chosen
1231
+ * step and every later one, dropping their `output`; those that had already SUCCEEDED are
1232
+ * recorded here (attributed by `stepIndex`) so the step-detail overlay's execution history
1233
+ * surfaces the successful outputs a restart superseded, not only the errors. Bounded in count
1234
+ * and per-entry size so the run's `detail` JSON doesn't bloat. Absent/empty for a run never
1235
+ * restarted past a completed step (a plain retry re-runs only unfinished steps, so it records
1236
+ * nothing).
1237
+ */
1238
+ outputHistory: v.optional(v.array(priorStepOutputSchema)),
1239
+ /**
1240
+ * Non-fatal advisories computed once at run start — today the frontend UI-test flow's
1241
+ * resolved-binding notes ({@link buildFrontendRunNotes}: duplicate env vars, or a partial-live
1242
+ * set of bound services where some fall back to WireMock). Mirrors the harness's own
1243
+ * `buildInfraNotes` but surfaced on the RUN so the SPA renders it in the run/step detail
1244
+ * (distinct from a `failure`, which aborts the run). Absent/empty when there is nothing to
1245
+ * flag. Rides in the `detail` JSON column (no dedicated column), reflecting the start-time
1246
+ * state even after the underlying envs change.
1247
+ */
1248
+ notes: v.optional(v.array(v.string())),
1249
+ /**
1250
+ * The frontend UI-test flow's backend bindings RESOLVED once at run start (env var → the bound
1251
+ * service's live ephemeral URL, or absent ⇒ mocked; see {@link resolveFrontendBindings}). Stamped
1252
+ * on the run so the SPA's run/step detail projects what the run ACTUALLY drove against — a frozen
1253
+ * snapshot that stays truthful after the underlying envs are torn down, rather than re-resolving
1254
+ * against current live state (which for a finished run could disagree with the co-located
1255
+ * start-time {@link notes}). Rides in the `detail` JSON column; absent for a non-frontend run.
1256
+ */
1257
+ frontendBindings: v.optional(v.array(resolvedFrontendBindingSchema)),
1258
+ /**
1259
+ * Internal user id (`usr_*`) of whoever started this run (or retried it). Recorded
1260
+ * so the individual-usage restricted mode can use the initiator's OWN personal
1261
+ * subscription (e.g. Claude) for the run's steps — a personal credential is never
1262
+ * shared, so only its owner's runs may use it. Absent for runs started without a
1263
+ * signed-in user (auth-disabled/local dev) and for legacy runs.
1264
+ */
1265
+ initiatedBy: v.optional(v.nullable(v.string())),
1266
+ /**
1267
+ * Epoch-ms creation time, stamped when the run is first started. Gives a run a stable
1268
+ * creation timestamp independent of when its first step actually starts (the public-API
1269
+ * job view reports it as `createdAt`). Absent on legacy runs persisted before this field.
1270
+ */
1271
+ createdAt: v.optional(v.number()),
1272
+ /**
1273
+ * Optimistic-concurrency token: a monotonic revision of the persisted run row,
1274
+ * bumped on every write. Read back by the repository and used by
1275
+ * `compareAndSwap` so a human-action write (resolve decision / approve /
1276
+ * request changes) that raced another writer is detected and retried on fresh
1277
+ * state instead of silently clobbering it. Defaults to 0 for a run that has
1278
+ * never been persisted. The SPA's execution store also keys its monotonic
1279
+ * reconcile on it, so a lagging snapshot refresh can't regress a run a live
1280
+ * event already advanced.
1281
+ */
1282
+ rev: v.optional(v.number()),
1283
+ /**
1284
+ * After-the-fact investigation context — where/what the run's most recent container step
1285
+ * executed on (backend, model, repo) plus the control-plane host. Rides in the `detail` JSON
1286
+ * (see {@link runDiagnosticsSchema}); absent on legacy runs and pure inline pipelines.
1287
+ */
1288
+ diagnostics: v.optional(runDiagnosticsSchema),
1289
+ });
1290
+ //# sourceMappingURL=execution.js.map