@juicesharp/rpiv-workflow 1.19.1 → 2.0.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.
- package/README.md +81 -8
- package/api.ts +18 -703
- package/audit-ctx.ts +103 -0
- package/audit-rows.ts +154 -0
- package/audit.ts +158 -190
- package/built-ins.ts +40 -45
- package/chain-state.ts +220 -0
- package/command-run.ts +64 -31
- package/command.ts +123 -21
- package/docs/workflow-authoring.md +356 -63
- package/{lifecycle.ts → events.ts} +161 -37
- package/execution-host.ts +75 -0
- package/host.ts +149 -64
- package/index.ts +25 -81
- package/internal-utils.ts +171 -71
- package/internal.ts +22 -1
- package/judge.ts +241 -0
- package/layers.ts +10 -15
- package/load/alias.ts +6 -12
- package/load/cache.ts +9 -6
- package/load/index.ts +27 -106
- package/load/issues.ts +31 -0
- package/load/legacy.ts +102 -0
- package/load/merge.ts +2 -2
- package/load/resolve-default.ts +3 -4
- package/load/shape-guards.ts +3 -6
- package/load/skill-contract-phase.ts +94 -0
- package/loop-constructors.ts +24 -0
- package/loop-def.ts +285 -0
- package/loop-kinds.ts +750 -0
- package/loop-parallel.ts +250 -0
- package/loop-waves.ts +99 -0
- package/loop.ts +330 -0
- package/loops/constructors.ts +334 -0
- package/loops/derivations.ts +65 -0
- package/loops/introspection.ts +184 -0
- package/loops/panel.ts +196 -0
- package/loops/verify.ts +99 -0
- package/messages.ts +249 -156
- package/outcomes/collectors/directory-path.ts +7 -3
- package/outcomes/collectors/index.ts +1 -0
- package/outcomes/collectors/require-opt.ts +11 -0
- package/outcomes/collectors/text-scan.ts +47 -0
- package/outcomes/collectors/tool-call.ts +8 -3
- package/outcomes/collectors/transcript-path.ts +4 -18
- package/outcomes/collectors/union.ts +30 -10
- package/outcomes/collectors/url.ts +9 -14
- package/outcomes/collectors/workspace-diff.ts +21 -14
- package/outcomes/exec.ts +17 -0
- package/outcomes/git-commit.ts +190 -100
- package/outcomes/index.ts +1 -0
- package/outcomes/parsers/json-body.ts +2 -2
- package/outcomes/side-effect.ts +3 -3
- package/output-spec.ts +36 -10
- package/output.ts +98 -20
- package/package.json +27 -11
- package/predicates.ts +11 -8
- package/preview.ts +81 -21
- package/registration.ts +117 -36
- package/routing-dsl.ts +322 -0
- package/routing.ts +48 -2
- package/runner/by-name.ts +2 -1
- package/runner/by-run-id.ts +2 -1
- package/runner/chain-advance.ts +84 -56
- package/runner/errors.ts +10 -0
- package/runner/failure.ts +163 -0
- package/runner/index.ts +7 -13
- package/runner/input-validation.ts +16 -23
- package/runner/preflight.ts +169 -0
- package/runner/resolve-stage.ts +68 -0
- package/runner/resume-entry.ts +121 -0
- package/runner/resume-loop.ts +131 -0
- package/runner/resume.ts +368 -262
- package/runner/run-context.ts +165 -0
- package/runner/run-stage.ts +490 -0
- package/runner/runner.ts +202 -449
- package/runner/script-stage.ts +104 -112
- package/schema-compat.ts +12 -1
- package/semaphore.ts +55 -0
- package/sessions/extraction.ts +146 -81
- package/sessions/halt-routing.ts +195 -0
- package/sessions/index.ts +3 -1
- package/sessions/locate.ts +141 -0
- package/sessions/reattach.ts +71 -0
- package/sessions/sessions.ts +114 -199
- package/sessions/spawn.ts +132 -119
- package/sessions/success-persist.ts +89 -0
- package/skill-contract.ts +22 -25
- package/skill-contracts/composition.ts +86 -37
- package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
- package/skill-contracts/harvest.ts +4 -4
- package/skill-contracts/index.ts +15 -8
- package/skill-contracts/registry.ts +33 -50
- package/stage-def.ts +595 -0
- package/stage-errors.ts +84 -0
- package/stage-identity.ts +56 -0
- package/startup.ts +4 -1
- package/state/index.ts +8 -1
- package/state/names.ts +91 -65
- package/state/paths.ts +20 -0
- package/state/raw.ts +77 -0
- package/state/reads.ts +103 -85
- package/state/resolve.ts +73 -0
- package/state/state.ts +135 -15
- package/state/writes.ts +29 -12
- package/transcript.ts +24 -0
- package/triggers.ts +11 -3
- package/types.ts +290 -78
- package/validate/contract-compat.ts +198 -0
- package/validate/graph.ts +134 -0
- package/validate/issue.ts +328 -0
- package/validate/stage-rules.ts +499 -0
- package/validate-output.ts +82 -7
- package/validate-workflow.ts +57 -759
- package/validation-bounds.ts +35 -0
- package/control-flow.ts +0 -135
- package/fanout.ts +0 -102
- package/iterate.ts +0 -155
- package/load/cache.test.ts +0 -82
- package/load/shape-guards.test.ts +0 -74
- package/outcomes/collectors/directory-path.test.ts +0 -64
- package/outcomes/collectors/tool-call.test.ts +0 -110
- package/outcomes/collectors/transcript-path.test.ts +0 -70
- package/outcomes/collectors/union.test.ts +0 -59
- package/outcomes/collectors/url.test.ts +0 -67
- package/outcomes/collectors/workspace-diff.test.ts +0 -107
- package/outcomes/git-commit.test.ts +0 -194
- package/outcomes/parsers/json-body.test.ts +0 -80
- package/runner/by-name.test.ts +0 -95
- package/runner/by-run-id.test.ts +0 -115
- package/runner/resume-fanout.test.ts +0 -331
- package/runner/resume-fanout.ts +0 -136
- package/runner/resume-iterate.test.ts +0 -444
- package/runner/resume-iterate.ts +0 -111
- package/runner/resume.test.ts +0 -1130
- package/runner/stage-lifecycle.ts +0 -500
package/sessions/extraction.ts
CHANGED
|
@@ -16,17 +16,17 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
import type { StageDef, StageSchema } from "../api.js";
|
|
19
|
-
import {
|
|
19
|
+
import { allocateStageNumber, currentStageRef } from "../audit.js";
|
|
20
|
+
import { lifecycleCtxFromSession } from "../events.js";
|
|
20
21
|
import type { Artifact } from "../handle.js";
|
|
21
|
-
import { assertNever, withTimeout } from "../internal-utils.js";
|
|
22
|
+
import { assertNever, formatError, nowIso, withTimeout } from "../internal-utils.js";
|
|
22
23
|
import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
|
|
23
|
-
import {
|
|
24
|
-
import { ERR_SCHEMA_TIMEOUT, MSG_VALIDATION_RETRY, MSG_VALIDATION_RETRY_PROMPT } from "../messages.js";
|
|
24
|
+
import { ERR_COLLECTOR_THREW, ERR_PARSER_THREW, ERR_SCHEMA_TIMEOUT } from "../messages.js";
|
|
25
25
|
import { sideEffectOutcome } from "../outcomes/index.js";
|
|
26
|
-
import { finalizeOutput, type Output } from "../output.js";
|
|
27
|
-
import type { CollectCtx,
|
|
26
|
+
import { finalizeOutput, type Output, outputMeta } from "../output.js";
|
|
27
|
+
import type { CollectCtx, Outcome } from "../output-spec.js";
|
|
28
28
|
import { type BranchEntry, readBranch } from "../transcript.js";
|
|
29
|
-
import type { StageSession,
|
|
29
|
+
import type { StageSession, WorkflowSessionContext } from "../types.js";
|
|
30
30
|
import {
|
|
31
31
|
DEFAULT_VALIDATION_RETRIES,
|
|
32
32
|
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
@@ -35,24 +35,42 @@ import {
|
|
|
35
35
|
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
36
36
|
MIN_VALIDATION_RETRIES,
|
|
37
37
|
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
38
|
+
runValidationRetryLoop,
|
|
38
39
|
type SchemaValidationFailure,
|
|
39
40
|
type ValidationResult,
|
|
40
41
|
validateOutputData,
|
|
41
42
|
} from "../validate-output.js";
|
|
42
|
-
import {
|
|
43
|
+
import { clampRange } from "../validation-bounds.js";
|
|
44
|
+
import { resendIntoChild } from "./spawn.js";
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The fatal arm shared by every extraction-stage outcome — `{ kind: "fatal";
|
|
48
|
+
* message }`. Declared four times inline before (OutputProduction,
|
|
49
|
+
* RunOutcomeResult, enforceCompletionContract, validateOrFatal); the ok arms
|
|
50
|
+
* genuinely differ (OutputProduction carries a validation-exhausted third arm;
|
|
51
|
+
* validateOrFatal's ok payload is a ValidationResult under `result`, not an
|
|
52
|
+
* Output under `output`), so a single generic `FatalOr<T>` would force a field
|
|
53
|
+
* misnomer — the fatal arm is the part that's actually identical, so it's the
|
|
54
|
+
* thing to name once.
|
|
55
|
+
*/
|
|
56
|
+
type Fatal = { kind: "fatal"; message: string };
|
|
43
57
|
|
|
44
58
|
export type OutputProduction =
|
|
45
59
|
| { kind: "ok"; output: Output }
|
|
46
|
-
|
|
|
60
|
+
| Fatal
|
|
47
61
|
| { kind: "validation-exhausted"; failureSummary: string };
|
|
48
62
|
|
|
49
63
|
/** Retry loop re-produces against the latest branch after each fix request. */
|
|
50
64
|
export async function produceAndValidateOutput(
|
|
51
|
-
ctx:
|
|
65
|
+
ctx: WorkflowSessionContext,
|
|
52
66
|
s: StageSession,
|
|
53
67
|
branch: BranchEntry[],
|
|
54
68
|
branchOffset: number | undefined,
|
|
55
69
|
): Promise<OutputProduction> {
|
|
70
|
+
// Allocate the activation's stage number ONCE, before any output envelope
|
|
71
|
+
// is built — the envelope's `meta.stageNumber`, the eventual audit row
|
|
72
|
+
// (success or failure), and every lifecycle ref share this value.
|
|
73
|
+
s.allocatedStageNumber ??= allocateStageNumber(s.state);
|
|
56
74
|
const outcome = resolveOutcome(s.stage, s.skill);
|
|
57
75
|
const collectCtx = buildCollectCtx(s, branch, branchOffset);
|
|
58
76
|
const finalize = (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => wrapOutput(s, parts);
|
|
@@ -76,7 +94,7 @@ export async function produceAndValidateOutput(
|
|
|
76
94
|
* load time; the runtime throw is defense-in-depth for programmatic
|
|
77
95
|
* embedders that bypassed validation.
|
|
78
96
|
*/
|
|
79
|
-
function resolveOutcome(stage: StageDef, skill: string):
|
|
97
|
+
function resolveOutcome(stage: StageDef, skill: string): Outcome {
|
|
80
98
|
if (stage.outcome) return stage.outcome;
|
|
81
99
|
switch (stage.kind) {
|
|
82
100
|
case "side-effect":
|
|
@@ -114,28 +132,44 @@ function buildCollectCtx(s: StageSession, branch: BranchEntry[], branchOffset: n
|
|
|
114
132
|
}
|
|
115
133
|
|
|
116
134
|
function wrapOutput(s: StageSession, parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }): Output {
|
|
117
|
-
return finalizeOutput(
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
135
|
+
return finalizeOutput(
|
|
136
|
+
parts,
|
|
137
|
+
outputMeta({
|
|
138
|
+
stage: s.stageName,
|
|
139
|
+
skill: s.skill,
|
|
140
|
+
// Pre-allocated by `produceAndValidateOutput` before any finalize runs —
|
|
141
|
+
// no `lastAllocatedStageNumber + 1` peek, no temporal coupling with
|
|
142
|
+
// recordStage.
|
|
143
|
+
stageNumber: s.allocatedStageNumber!,
|
|
144
|
+
ts: nowIso(),
|
|
145
|
+
runId: s.runId,
|
|
146
|
+
}),
|
|
147
|
+
);
|
|
124
148
|
}
|
|
125
149
|
|
|
126
|
-
type RunOutcomeResult = { kind: "ok"; output: Output } |
|
|
150
|
+
type RunOutcomeResult = { kind: "ok"; output: Output } | Fatal;
|
|
127
151
|
|
|
128
152
|
/**
|
|
129
153
|
* The collector → parser pipeline. When `parser` is omitted, the
|
|
130
154
|
* output emits `kind: "artifacts"` with `data = artifacts` — a stage
|
|
131
155
|
* that only needs to enumerate doesn't have to write a parser.
|
|
156
|
+
*
|
|
157
|
+
* `collect`/`parse` are the PRIMARY user extension points, so a throw from
|
|
158
|
+
* either is guarded here and attributed ("collector threw…"), folding into
|
|
159
|
+
* the same fatal arm a tagged `{ kind: "fatal" }` return takes — instead of
|
|
160
|
+
* escaping to the runner's generic catch and reading as a machinery failure.
|
|
132
161
|
*/
|
|
133
162
|
async function runOutcome(
|
|
134
|
-
outcome:
|
|
163
|
+
outcome: Outcome,
|
|
135
164
|
ctx: CollectCtx,
|
|
136
165
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output,
|
|
137
166
|
): Promise<RunOutcomeResult> {
|
|
138
|
-
|
|
167
|
+
let collected: Awaited<ReturnType<typeof outcome.collector.collect>>;
|
|
168
|
+
try {
|
|
169
|
+
collected = await outcome.collector.collect(ctx);
|
|
170
|
+
} catch (e) {
|
|
171
|
+
return { kind: "fatal", message: ERR_COLLECTOR_THREW(ctx.skill, formatError(e)) };
|
|
172
|
+
}
|
|
139
173
|
if (collected.kind === "fatal") return collected;
|
|
140
174
|
|
|
141
175
|
if (!outcome.parser) {
|
|
@@ -145,7 +179,12 @@ async function runOutcome(
|
|
|
145
179
|
};
|
|
146
180
|
}
|
|
147
181
|
|
|
148
|
-
|
|
182
|
+
let parsed: Awaited<ReturnType<typeof outcome.parser.parse>>;
|
|
183
|
+
try {
|
|
184
|
+
parsed = await outcome.parser.parse({ ...ctx, artifacts: collected.artifacts });
|
|
185
|
+
} catch (e) {
|
|
186
|
+
return { kind: "fatal", message: ERR_PARSER_THREW(ctx.skill, formatError(e)) };
|
|
187
|
+
}
|
|
149
188
|
if (parsed.kind === "fatal") return parsed;
|
|
150
189
|
return {
|
|
151
190
|
kind: "ok",
|
|
@@ -168,7 +207,7 @@ function enforceCompletionContract(
|
|
|
168
207
|
stage: StageDef,
|
|
169
208
|
skill: string,
|
|
170
209
|
output: Output,
|
|
171
|
-
): { kind: "ok"; output: Output } |
|
|
210
|
+
): { kind: "ok"; output: Output } | Fatal {
|
|
172
211
|
if (stage.kind === "produces" && output.artifacts.length === 0) {
|
|
173
212
|
return {
|
|
174
213
|
kind: "fatal",
|
|
@@ -181,7 +220,7 @@ function enforceCompletionContract(
|
|
|
181
220
|
/**
|
|
182
221
|
* The schema output is validated against: the stage's own `outputSchema` if it
|
|
183
222
|
* declares one, otherwise the dispatched skill's contract `produces.data`
|
|
184
|
-
* (sourced from the
|
|
223
|
+
* (sourced from the registered-contract registry threaded onto the session).
|
|
185
224
|
*
|
|
186
225
|
* Degrades exactly like the input-side runtime mirror (`ensureContractInputValid`):
|
|
187
226
|
* a non-object / unparseable `produces.data` is treated as absent (no schema),
|
|
@@ -190,7 +229,7 @@ function enforceCompletionContract(
|
|
|
190
229
|
function effectiveOutputSchema(s: StageSession): StageSchema | undefined {
|
|
191
230
|
if (s.stage.outputSchema) return s.stage.outputSchema;
|
|
192
231
|
// `s.skill` is resolved via `resolveSkill(def, stageName)` in `resolveStage`
|
|
193
|
-
// (stage
|
|
232
|
+
// (run-stage.ts), matching the contract map key used by
|
|
194
233
|
// `validate-workflow.ts` and `harvestStageContracts`. The single helper
|
|
195
234
|
// ensures load-time lint and runtime agree on which contract covers the stage.
|
|
196
235
|
const producesData = s.skillContracts?.get(s.skill)?.produces?.data;
|
|
@@ -203,74 +242,102 @@ function shouldValidateOutput(s: StageSession, output: Output): boolean {
|
|
|
203
242
|
}
|
|
204
243
|
|
|
205
244
|
interface RetryDeps {
|
|
206
|
-
outcome:
|
|
245
|
+
outcome: Outcome;
|
|
207
246
|
collectCtx: CollectCtx;
|
|
208
247
|
finalize: (parts: { kind: string; artifacts: readonly Artifact[]; data: unknown }) => Output;
|
|
209
248
|
}
|
|
210
249
|
|
|
211
250
|
async function retryUntilValid(
|
|
212
|
-
ctx:
|
|
251
|
+
ctx: WorkflowSessionContext,
|
|
213
252
|
s: StageSession,
|
|
214
253
|
deps: RetryDeps,
|
|
215
254
|
initial: Output,
|
|
216
255
|
): Promise<OutputProduction> {
|
|
217
256
|
const schema = effectiveOutputSchema(s)!;
|
|
218
|
-
const maxRetries =
|
|
257
|
+
const maxRetries = clampRange(
|
|
258
|
+
s.stage.maxRetries,
|
|
219
259
|
MIN_VALIDATION_RETRIES,
|
|
220
|
-
|
|
260
|
+
DEFAULT_VALIDATION_RETRIES,
|
|
261
|
+
MAX_VALIDATION_RETRIES,
|
|
221
262
|
);
|
|
222
|
-
const timeoutMs =
|
|
263
|
+
const timeoutMs = clampRange(
|
|
264
|
+
s.stage.validateTimeoutMs,
|
|
223
265
|
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
224
|
-
|
|
266
|
+
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
267
|
+
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
225
268
|
);
|
|
226
269
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
270
|
+
// The retry policy is the SHARED `runValidationRetryLoop` engine
|
|
271
|
+
// (validate-output.ts) — the same produce → validate → retry structure the
|
|
272
|
+
// script path runs. The four equivalence cases (invalid+failFast → exhausted;
|
|
273
|
+
// invalid+budget-spent → exhausted; invalid+retryable → retry; any fatal →
|
|
274
|
+
// Fatal) fall out of the engine's three-arm outcome:
|
|
275
|
+
// - `produce(0)` → the already-produced `initial` (produced + contract-
|
|
276
|
+
// checked before this loop opened); `produce(n>0)` → re-read the branch,
|
|
277
|
+
// re-run the collector/parser, re-check the completion contract.
|
|
278
|
+
// - `validate` → `validateOrFatal`, mapping its `Fatal` onto the engine's
|
|
279
|
+
// `{ kind: "aborted"; abort: Fatal }` abort arm.
|
|
280
|
+
// - `onRetry` → `onStageRetry` + `askAgentToFix`; a throw becomes an abort.
|
|
281
|
+
// `failFast` mirrors the script path's stop-flag polarity —
|
|
282
|
+
// `(onInvalid ?? "retry") === "halt"` is byte-identical to today's
|
|
283
|
+
// `onInvalid !== "halt"` loop-continue condition, just expressed as the
|
|
284
|
+
// engine's stop flag. Total productions stay bounded by `maxRetries + 1`.
|
|
285
|
+
const outcome = await runValidationRetryLoop<Output, Fatal>(
|
|
286
|
+
{
|
|
287
|
+
maxRetries,
|
|
288
|
+
failFast: (s.stage.onInvalid ?? "retry") === "halt",
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
produce: async (attempt) => {
|
|
292
|
+
// `produce(0)` returns the already-produced initial — no re-collection,
|
|
293
|
+
// no contract re-check (both ran before the loop opened).
|
|
294
|
+
if (attempt === 0) return { kind: "ok", value: initial };
|
|
295
|
+
const retryBranch = readBranch(ctx);
|
|
296
|
+
const retryCtx: CollectCtx = { ...deps.collectCtx, branch: retryBranch };
|
|
297
|
+
const reRun = await runOutcome(deps.outcome, retryCtx, deps.finalize);
|
|
298
|
+
if (reRun.kind === "fatal") return { kind: "aborted", abort: reRun };
|
|
299
|
+
const contract = enforceCompletionContract(s.stage, s.skill, reRun.output);
|
|
300
|
+
if (contract.kind === "fatal") return { kind: "aborted", abort: contract };
|
|
301
|
+
return { kind: "ok", value: contract.output };
|
|
302
|
+
},
|
|
303
|
+
validate: async (output) => {
|
|
304
|
+
const validation = await validateOrFatal(schema, output.data, s.skill, timeoutMs);
|
|
305
|
+
if (validation.kind === "fatal") return { kind: "aborted", abort: validation };
|
|
306
|
+
return { kind: "ok", result: validation.result };
|
|
307
|
+
},
|
|
308
|
+
onRetry: async (attempt, failures) => {
|
|
309
|
+
// onStageRetry fires before the agent is re-prompted; `attempt` is 1-based.
|
|
310
|
+
// Ref shares the activation's ALLOCATOR number (currentStageRef) so
|
|
311
|
+
// listeners can correlate this retry with the end/error event it
|
|
312
|
+
// belongs to — graph position (`stageIndex + 1`) diverges past any loop.
|
|
313
|
+
await s.lifecycle.fire(ctx, "onStageRetry", currentStageRef(s), attempt, lifecycleCtxFromSession(s));
|
|
314
|
+
try {
|
|
315
|
+
await askAgentToFix(ctx, s, attempt, failures, timeoutMs);
|
|
316
|
+
return { kind: "ok" };
|
|
317
|
+
} catch (e) {
|
|
318
|
+
return { kind: "aborted", abort: { kind: "fatal", message: formatError(e) } };
|
|
319
|
+
}
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
);
|
|
269
323
|
|
|
270
|
-
if (
|
|
271
|
-
|
|
324
|
+
if (outcome.kind === "aborted") return outcome.abort;
|
|
325
|
+
if (outcome.kind === "exhausted") return validationExhausted(outcome.failures);
|
|
326
|
+
return { kind: "ok", output: outcome.value };
|
|
272
327
|
}
|
|
273
328
|
|
|
329
|
+
/**
|
|
330
|
+
* Sent to the AGENT as a follow-up message when an output-schema validation
|
|
331
|
+
* fails — instructs it to re-write the artifact at the same path with a
|
|
332
|
+
* corrected frontmatter. Lives beside its only consumer (this is
|
|
333
|
+
* model-facing prompt text, not a UI constant). `errorLines` is a pre-joined
|
|
334
|
+
* bullet list (one line per failure) so the factory stays single-arg-typed.
|
|
335
|
+
*/
|
|
336
|
+
const MSG_VALIDATION_RETRY_PROMPT = (skill: string, errorLines: string) =>
|
|
337
|
+
`The ${skill} artifact's frontmatter doesn't satisfy the expected output schema. ` +
|
|
338
|
+
"Fix only the fields listed below, then re-write the artifact at the same path (don't move it):\n\n" +
|
|
339
|
+
`${errorLines}`;
|
|
340
|
+
|
|
274
341
|
/**
|
|
275
342
|
* Translate a thrown `validateOutputData` (user-authored schemas may throw
|
|
276
343
|
* synchronously or reject their Promise) into the canonical fatal-extraction
|
|
@@ -283,7 +350,7 @@ async function validateOrFatal(
|
|
|
283
350
|
data: unknown,
|
|
284
351
|
skill: string,
|
|
285
352
|
timeoutMs: number,
|
|
286
|
-
): Promise<{ kind: "ok"; result: ValidationResult } |
|
|
353
|
+
): Promise<{ kind: "ok"; result: ValidationResult } | Fatal> {
|
|
287
354
|
try {
|
|
288
355
|
const result = await withTimeout(
|
|
289
356
|
Promise.resolve(validateOutputData(schema, data)),
|
|
@@ -292,22 +359,20 @@ async function validateOrFatal(
|
|
|
292
359
|
);
|
|
293
360
|
return { kind: "ok", result };
|
|
294
361
|
} catch (e) {
|
|
295
|
-
|
|
296
|
-
return { kind: "fatal", message: `${skill}: ${reason}` };
|
|
362
|
+
return { kind: "fatal", message: `${skill}: ${formatError(e)}` };
|
|
297
363
|
}
|
|
298
364
|
}
|
|
299
365
|
|
|
300
366
|
async function askAgentToFix(
|
|
301
|
-
ctx:
|
|
367
|
+
ctx: WorkflowSessionContext,
|
|
302
368
|
s: StageSession,
|
|
303
369
|
attempt: number,
|
|
304
370
|
failures: SchemaValidationFailure[],
|
|
305
371
|
timeoutMs: number,
|
|
306
372
|
): Promise<void> {
|
|
307
|
-
ctx.ui.notify(MSG_VALIDATION_RETRY(s.skill, attempt), "warning");
|
|
308
373
|
const errorLines = failures.map((f) => ` • ${describeFailure(f)}`).join("\n");
|
|
309
374
|
await withTimeout(
|
|
310
|
-
|
|
375
|
+
resendIntoChild(ctx, MSG_VALIDATION_RETRY_PROMPT(s.skill, errorLines)),
|
|
311
376
|
timeoutMs,
|
|
312
377
|
`${s.skill}: validation retry attempt ${attempt} exceeded ${timeoutMs}ms — agent did not settle`,
|
|
313
378
|
);
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Halt-routing facet — extracted from `sessions.ts`'s HALT HELPERS. Turns a
|
|
3
|
+
* halt reason into the right audit-layer call. `haltStageOrSoftHalt` is the
|
|
4
|
+
* single gate `postStage` dispatches through (a `collectAll` fanout unit
|
|
5
|
+
* soft-halts; everything else fail-fast halts). `haltStageWithValidationFailure`
|
|
6
|
+
* is also exported for the `reattach.ts` companion.
|
|
7
|
+
*
|
|
8
|
+
* `auditFor` lives here (moved from `sessions.ts`) — its only callers are the
|
|
9
|
+
* halt helpers below; relocating it keeps the value-import DAG acyclic (the
|
|
10
|
+
* success-persistence facet in `success-persist.ts` does not use `auditFor`,
|
|
11
|
+
* so no edge from there back here).
|
|
12
|
+
*
|
|
13
|
+
* Companion modules (see `sessions.ts`'s header for the full map):
|
|
14
|
+
* - success-persist.ts — `recordStageSuccess` + `unitEventOf` (the soft-halt
|
|
15
|
+
* lifecycle signal borrows `unitEventOf` from here).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { type AuditCtx, failedArgs, recordStopFailure, recordTerminalFailure, recordUnitHalt } from "../audit.js";
|
|
19
|
+
import { allocateStageNumber } from "../audit-rows.js";
|
|
20
|
+
import { lifecycleCtxFromSession, skillStageRef } from "../events.js";
|
|
21
|
+
import { nowIso } from "../internal-utils.js";
|
|
22
|
+
import { FAIL_VALIDATION_EXHAUSTED, MSG_STAGE_FAILED } from "../messages.js";
|
|
23
|
+
import { failedOutput, type OutputMeta, outputMeta } from "../output.js";
|
|
24
|
+
import type { SessionRef } from "../state/index.js";
|
|
25
|
+
import type { StopSignal } from "../transcript.js";
|
|
26
|
+
import type { StageSession, WorkflowHostContext } from "../types.js";
|
|
27
|
+
import { unitEventOf } from "./success-persist.js";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* A stage's reason-to-halt, tagged by the post-processing arm that produced it.
|
|
31
|
+
* Carries BOTH the fail-fast halt shape (the per-arm record call) and the
|
|
32
|
+
* collect-all soft-halt reason string, so ONE gate decides between them.
|
|
33
|
+
*/
|
|
34
|
+
type HaltReason =
|
|
35
|
+
| { kind: "stop"; stop: Exclude<StopSignal, "stop"> }
|
|
36
|
+
| { kind: "extraction"; message: string }
|
|
37
|
+
| { kind: "validation"; failureSummary: string }
|
|
38
|
+
// A watchdog aborted a runaway tool call (bash) past its per-command timeout. The
|
|
39
|
+
// host surfaces it via `WorkflowSessionContext.toolTimeout`; carries the operator-grade
|
|
40
|
+
// reason string written to the failed row (soft-halt errMsg / terminal errMsg).
|
|
41
|
+
| { kind: "timeout"; reason: string };
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The single collect-all fork. A `collectAll` fanout unit soft-halts (a
|
|
45
|
+
* NON-terminal `collected:true` row + a `failedOutput` sentinel the parallel fold
|
|
46
|
+
* places by index); every other stage takes the arm's fail-fast terminal halt.
|
|
47
|
+
* Replaces the `if (s.collectAll)` that was inlined at all three halt sites.
|
|
48
|
+
*/
|
|
49
|
+
export async function haltStageOrSoftHalt(
|
|
50
|
+
ctx: WorkflowHostContext,
|
|
51
|
+
s: StageSession,
|
|
52
|
+
reason: HaltReason,
|
|
53
|
+
session: SessionRef | null,
|
|
54
|
+
): Promise<void> {
|
|
55
|
+
if (s.collectAll) return softHaltUnit(ctx, s, softHaltReason(s, reason), session);
|
|
56
|
+
return failFastHalt(ctx, s, reason, session);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Collect-all reason text per arm — byte-identical to the prior inline strings. */
|
|
60
|
+
function softHaltReason(s: StageSession, reason: HaltReason): string {
|
|
61
|
+
switch (reason.kind) {
|
|
62
|
+
case "stop":
|
|
63
|
+
return `${s.skill} stopped (${reason.stop})`;
|
|
64
|
+
case "extraction":
|
|
65
|
+
return reason.message;
|
|
66
|
+
case "validation":
|
|
67
|
+
return reason.failureSummary;
|
|
68
|
+
case "timeout":
|
|
69
|
+
return reason.reason;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Fail-fast terminal halt per arm — dispatches to the existing helpers, unchanged. */
|
|
74
|
+
function failFastHalt(
|
|
75
|
+
ctx: WorkflowHostContext,
|
|
76
|
+
s: StageSession,
|
|
77
|
+
reason: HaltReason,
|
|
78
|
+
session: SessionRef | null,
|
|
79
|
+
): Promise<void> {
|
|
80
|
+
switch (reason.kind) {
|
|
81
|
+
case "stop":
|
|
82
|
+
return haltStage(ctx, s, reason.stop, session);
|
|
83
|
+
case "extraction":
|
|
84
|
+
return haltStageWithExtractionError(ctx, s, reason.message, session);
|
|
85
|
+
case "validation":
|
|
86
|
+
return haltStageWithValidationFailure(ctx, s, reason.failureSummary, session);
|
|
87
|
+
case "timeout":
|
|
88
|
+
// A non-fan-out stage whose bash overran the watchdog: terminal "failed" row whose
|
|
89
|
+
// errMsg carries the timeout reason (same shape as an extraction-fatal halt).
|
|
90
|
+
return haltStageWithExtractionError(ctx, s, reason.reason, session);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function haltStage(
|
|
95
|
+
ctx: WorkflowHostContext,
|
|
96
|
+
s: StageSession,
|
|
97
|
+
stop: Exclude<StopSignal, "stop">,
|
|
98
|
+
session: SessionRef | null,
|
|
99
|
+
): Promise<void> {
|
|
100
|
+
await recordStopFailure(ctx, auditFor(s, session), stop, `${s.skill} failed`, s.onFailure);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function haltStageWithExtractionError(
|
|
104
|
+
ctx: WorkflowHostContext,
|
|
105
|
+
s: StageSession,
|
|
106
|
+
message: string,
|
|
107
|
+
session: SessionRef | null,
|
|
108
|
+
): Promise<void> {
|
|
109
|
+
await recordTerminalFailure(
|
|
110
|
+
ctx,
|
|
111
|
+
auditFor(s, session),
|
|
112
|
+
{ status: "failed", notifyMsg: MSG_STAGE_FAILED(s.skill), notifyLevel: "error", errMsg: message },
|
|
113
|
+
s.onFailure,
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Collect-all fanout unit halt: write a NON-terminal failed row, then hand a
|
|
119
|
+
* `failedOutput` sentinel to the continuation (`onSuccess`) so the parallel fold
|
|
120
|
+
* places it by declared index (`foldFanoutCompletion` → `placeFanoutOutput`) and
|
|
121
|
+
* `fanin(...).filter(Boolean)` skips it. The run survives — no `terminate()`. No
|
|
122
|
+
* direct `applyCompletedStage` here (the fold owns the single channel-write — a
|
|
123
|
+
* push here would double-write the slot). Recording + `onSuccess` run on the
|
|
124
|
+
* launcher/observer `ctx` (the same posture as `postStage`).
|
|
125
|
+
*/
|
|
126
|
+
async function softHaltUnit(
|
|
127
|
+
ctx: WorkflowHostContext,
|
|
128
|
+
s: StageSession,
|
|
129
|
+
reason: string,
|
|
130
|
+
session: SessionRef | null,
|
|
131
|
+
): Promise<void> {
|
|
132
|
+
s.allocatedStageNumber ??= allocateStageNumber(s.state);
|
|
133
|
+
recordUnitHalt(ctx, auditFor(s, session), reason); // status:"failed" collected:true row (resume reads errMsg)
|
|
134
|
+
// Fire the soft-halt lifecycle signal (mirrors recordStageSuccess's onUnitEnd) AFTER the row
|
|
135
|
+
// lands. Without it this unit emits NO terminal lifecycle event — recordUnitHalt deliberately
|
|
136
|
+
// skips onStageError ("not a hard fail") and the success-only onUnitEnd never runs — so a lane
|
|
137
|
+
// bridge would leave the sub-row spinning until onWorkflowEnd, where a completed run's sweep
|
|
138
|
+
// paints it ✓ (a failed-but-collected unit mis-rendered as success). The ref carries the PARENT
|
|
139
|
+
// stage name (graph identity), same allocator base as every other ref of this activation.
|
|
140
|
+
await s.lifecycle.fire(
|
|
141
|
+
ctx,
|
|
142
|
+
"onUnitHalt",
|
|
143
|
+
skillStageRef(s.unit!.parent, s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber, s.skill),
|
|
144
|
+
unitEventOf(s),
|
|
145
|
+
reason,
|
|
146
|
+
lifecycleCtxFromSession(s),
|
|
147
|
+
);
|
|
148
|
+
await s.onSuccess(ctx, failedOutput(outputMetaFor(s), reason));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** OutputMeta for a sentinel — same stage number the failed row carries, so the
|
|
152
|
+
* live sentinel and the resume-rebuilt one are byte-identical. */
|
|
153
|
+
function outputMetaFor(s: StageSession): OutputMeta {
|
|
154
|
+
return outputMeta({
|
|
155
|
+
stage: s.stageName,
|
|
156
|
+
skill: s.skill,
|
|
157
|
+
stageNumber: s.allocatedStageNumber ?? s.state.lastAllocatedStageNumber,
|
|
158
|
+
ts: nowIso(),
|
|
159
|
+
runId: s.runId,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Exported to the `reattach.ts` companion — a promotion's validation-exhausted halt is identical to live. */
|
|
164
|
+
export async function haltStageWithValidationFailure(
|
|
165
|
+
ctx: WorkflowHostContext,
|
|
166
|
+
s: StageSession,
|
|
167
|
+
failureSummary: string,
|
|
168
|
+
session: SessionRef | null,
|
|
169
|
+
): Promise<void> {
|
|
170
|
+
await recordTerminalFailure(
|
|
171
|
+
ctx,
|
|
172
|
+
auditFor(s, session),
|
|
173
|
+
failedArgs(FAIL_VALIDATION_EXHAUSTED(s.skill, failureSummary)),
|
|
174
|
+
s.onFailure,
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const auditFor = (s: StageSession, session: SessionRef | null): AuditCtx => ({
|
|
179
|
+
cwd: s.cwd,
|
|
180
|
+
runId: s.runId,
|
|
181
|
+
state: s.state,
|
|
182
|
+
stageName: s.stageName,
|
|
183
|
+
skill: s.skill,
|
|
184
|
+
// The Pi session backing this activation — `null` only for pre-open
|
|
185
|
+
// cancellation (the one writer here that never entered a session).
|
|
186
|
+
session,
|
|
187
|
+
lifecycle: s.lifecycle,
|
|
188
|
+
runIdentity: s.runIdentity,
|
|
189
|
+
// The activation's pre-allocated stage number (set once output production
|
|
190
|
+
// began) — a failure row reuses it instead of burning a second number.
|
|
191
|
+
allocatedStageNumber: s.allocatedStageNumber,
|
|
192
|
+
// Loop units thread their identity onto failure/cancellation rows so failed
|
|
193
|
+
// trailers carry the structured fields the resume drift guard consumes.
|
|
194
|
+
...(s.unit ? { unit: s.unit } : {}),
|
|
195
|
+
});
|
package/sessions/index.ts
CHANGED
|
@@ -4,4 +4,6 @@
|
|
|
4
4
|
* barrel re-exports only the symbols the rest of the package consumes.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
export {
|
|
7
|
+
export { locateSessionFile, pruneOrphanedChildSessions } from "./locate.js";
|
|
8
|
+
export { reattachStageSession } from "./reattach.js";
|
|
9
|
+
export { continueStageSession, runStageSession } from "./sessions.js";
|