@juicesharp/rpiv-workflow 1.18.1 → 1.19.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/command-run.ts +26 -5
- package/command.ts +20 -7
- package/control-flow.ts +135 -0
- package/internal-utils.ts +73 -2
- package/internal.ts +9 -2
- package/iterate.ts +1 -0
- package/json-schema.ts +131 -0
- package/load/alias.ts +4 -3
- package/load/index.ts +62 -1
- package/messages.ts +15 -4
- package/package.json +8 -2
- package/preview.ts +19 -0
- package/registration.ts +39 -0
- package/runner/by-run-id.ts +22 -21
- package/runner/chain-advance.ts +3 -2
- package/runner/index.ts +2 -0
- package/runner/input-validation.ts +173 -0
- package/runner/resume-fanout.ts +2 -2
- package/runner/resume-iterate.ts +2 -1
- package/runner/runner.ts +43 -2
- package/runner/script-stage.ts +2 -2
- package/runner/stage-lifecycle.ts +7 -67
- package/schema-compat.ts +140 -0
- package/sessions/extraction.ts +28 -6
- package/skill-contract.ts +112 -0
- package/skill-contracts/composition.ts +79 -0
- package/skill-contracts/harvest.ts +79 -0
- package/skill-contracts/index.ts +37 -0
- package/skill-contracts/registries.ts +93 -0
- package/skill-contracts/registry.ts +164 -0
- package/startup.ts +6 -0
- package/state/index.ts +9 -0
- package/state/names.ts +174 -0
- package/state/paths.ts +4 -0
- package/state/reads.ts +29 -5
- package/state/state.ts +16 -1
- package/typebox-adapter.ts +17 -16
- package/types.ts +25 -0
- package/validate-output.ts +101 -4
- package/validate-workflow.ts +179 -12
package/messages.ts
CHANGED
|
@@ -61,9 +61,9 @@ export const ERR_VALIDATION_FAILED = (skill: string, failures: string) =>
|
|
|
61
61
|
* line per failure) so the factory stays single-arg-typed.
|
|
62
62
|
*/
|
|
63
63
|
export const MSG_VALIDATION_RETRY_PROMPT = (skill: string, errorLines: string) =>
|
|
64
|
-
`The
|
|
65
|
-
"
|
|
66
|
-
|
|
64
|
+
`The ${skill} artifact's frontmatter doesn't satisfy the expected output schema. ` +
|
|
65
|
+
"Fix only the fields listed below, then re-write the artifact at the same path (don't move it):\n\n" +
|
|
66
|
+
`${errorLines}`;
|
|
67
67
|
|
|
68
68
|
export const MSG_INPUT_VALIDATION_FAILED = (currentSkill: string, prevSkill: string) =>
|
|
69
69
|
`✗ ${currentSkill} input validation failed — upstream ${prevSkill} produced invalid data`;
|
|
@@ -209,7 +209,7 @@ export const MSG_RESUME_ITERATE_MISMATCH = (stage: string) =>
|
|
|
209
209
|
// load-gate → find); returned in the envelope before resumeWorkflow is reached
|
|
210
210
|
// ---------------------------------------------------------------------------
|
|
211
211
|
|
|
212
|
-
export const MSG_RESUME_USAGE = "rpiv: usage — /wf @<run-id>";
|
|
212
|
+
export const MSG_RESUME_USAGE = "rpiv: usage — /wf @<run-id | name | path-to.jsonl>";
|
|
213
213
|
export const MSG_RUN_NOT_FOUND = (ref: string) => `rpiv: no run found for "${ref}"`;
|
|
214
214
|
export const MSG_RESUME_WORKFLOW_GONE = (workflow: string, ref: string) =>
|
|
215
215
|
`rpiv: run "${ref}" used workflow "${workflow}", which is no longer registered`;
|
|
@@ -222,6 +222,17 @@ export const MSG_INTERACTIVE_ONLY = "/wf requires interactive mode";
|
|
|
222
222
|
|
|
223
223
|
export const MSG_WORKFLOW_THREW = (reason: string) => `/wf: workflow runner failed unexpectedly: ${reason}`;
|
|
224
224
|
|
|
225
|
+
export const MSG_NAME_INVALID = (name: string) =>
|
|
226
|
+
`rpiv: invalid name "${name}" — must be 1-64 chars, start with a letter or underscore, only letters, digits, hyphens, underscores`;
|
|
227
|
+
|
|
228
|
+
export const MSG_NAME_COLLISION = (name: string, runId: string) => `name '${name}' already used by run ${runId}`;
|
|
229
|
+
|
|
230
|
+
export const MSG_NAME_INDEX_WRITE_FAILED = (name: string) =>
|
|
231
|
+
`/wf: could not persist name "${name}" to the names index — run aborted (no run started). Check filesystem permissions for .rpiv/workflows/runs/`;
|
|
232
|
+
|
|
233
|
+
export const MSG_NAME_IGNORED_ON_RESUME =
|
|
234
|
+
"/wf: --name has no effect on @resume (the ref already identifies the run) — ignoring it";
|
|
235
|
+
|
|
225
236
|
export const MSG_LOAD_ABORTED = (count: number) =>
|
|
226
237
|
`/wf: ${count} ${count === 1 ? "config error" : "config errors"} — see warnings above (fix and re-run)`;
|
|
227
238
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juicesharp/rpiv-workflow",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.19.0",
|
|
4
4
|
"description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
|
@@ -39,11 +39,14 @@
|
|
|
39
39
|
"built-ins.ts",
|
|
40
40
|
"command.ts",
|
|
41
41
|
"command-run.ts",
|
|
42
|
+
"control-flow.ts",
|
|
42
43
|
"extension.ts",
|
|
43
44
|
"registration.ts",
|
|
44
45
|
"fanout.ts",
|
|
45
46
|
"handle.ts",
|
|
46
47
|
"host.ts",
|
|
48
|
+
"json-schema.ts",
|
|
49
|
+
"schema-compat.ts",
|
|
47
50
|
"internal-utils.ts",
|
|
48
51
|
"iterate.ts",
|
|
49
52
|
"layers.ts",
|
|
@@ -55,6 +58,8 @@
|
|
|
55
58
|
"outcomes/",
|
|
56
59
|
"predicates.ts",
|
|
57
60
|
"preview.ts",
|
|
61
|
+
"skill-contract.ts",
|
|
62
|
+
"skill-contracts/",
|
|
58
63
|
"routing.ts",
|
|
59
64
|
"runner/",
|
|
60
65
|
"startup.ts",
|
|
@@ -75,6 +80,7 @@
|
|
|
75
80
|
".": "./index.ts",
|
|
76
81
|
"./startup": "./startup.ts",
|
|
77
82
|
"./registration": "./registration.ts",
|
|
83
|
+
"./runner": "./runner/index.ts",
|
|
78
84
|
"./internal": "./internal.ts"
|
|
79
85
|
},
|
|
80
86
|
"pi": {
|
|
@@ -83,7 +89,7 @@
|
|
|
83
89
|
]
|
|
84
90
|
},
|
|
85
91
|
"dependencies": {
|
|
86
|
-
"@juicesharp/rpiv-config": "^1.
|
|
92
|
+
"@juicesharp/rpiv-config": "^1.19.0",
|
|
87
93
|
"jiti": "^2.7.0"
|
|
88
94
|
},
|
|
89
95
|
"peerDependencies": {
|
package/preview.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { StageDef, Workflow } from "./api.js";
|
|
|
9
9
|
import { type ConfigLayer, renderConfigLayer } from "./layers.js";
|
|
10
10
|
import type { LoadedWorkflows } from "./load/index.js";
|
|
11
11
|
import { CMD_USAGE_LIST, CMD_USAGE_PREVIEW, CMD_USAGE_RUN } from "./messages.js";
|
|
12
|
+
import type { SkillContractMap } from "./skill-contract.js";
|
|
12
13
|
|
|
13
14
|
// ===========================================================================
|
|
14
15
|
// Public formatters
|
|
@@ -53,12 +54,14 @@ export function formatWorkflowList(loaded: LoadedWorkflows): string {
|
|
|
53
54
|
});
|
|
54
55
|
|
|
55
56
|
const aliasBanner = formatAliasBanner(loaded.skillAliases);
|
|
57
|
+
const contractsBanner = formatContractsBanner(loaded.skillContracts);
|
|
56
58
|
return [
|
|
57
59
|
"Available workflows:",
|
|
58
60
|
"",
|
|
59
61
|
...rows,
|
|
60
62
|
"",
|
|
61
63
|
...(aliasBanner ? [aliasBanner] : []),
|
|
64
|
+
...(contractsBanner ? [contractsBanner] : []),
|
|
62
65
|
formatLayerBanner(loaded.layers),
|
|
63
66
|
CMD_USAGE_LIST,
|
|
64
67
|
CMD_USAGE_PREVIEW,
|
|
@@ -163,3 +166,19 @@ function formatAliasBanner(aliases: Readonly<Record<string, string>>): string |
|
|
|
163
166
|
if (entries.length === 0) return undefined;
|
|
164
167
|
return `Skill aliases in effect: ${entries.map(([from, to]) => `${from} → ${to}`).join(", ")}`;
|
|
165
168
|
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* "Skill contracts: 3 declared, 2 harvested" — coverage summary shown when any
|
|
172
|
+
* contract is in effect. Surfaces how many skills carry a declared (frontmatter)
|
|
173
|
+
* vs harvested (usage-derived) contract so a reader knows the registry's tier.
|
|
174
|
+
*/
|
|
175
|
+
function formatContractsBanner(contracts: SkillContractMap): string | undefined {
|
|
176
|
+
if (contracts.size === 0) return undefined;
|
|
177
|
+
let declared = 0;
|
|
178
|
+
let harvested = 0;
|
|
179
|
+
for (const c of contracts.values()) {
|
|
180
|
+
if (c.source === "declared") declared++;
|
|
181
|
+
else if (c.source === "harvested") harvested++;
|
|
182
|
+
}
|
|
183
|
+
return `Skill contracts: ${declared} declared, ${harvested} harvested`;
|
|
184
|
+
}
|
package/registration.ts
CHANGED
|
@@ -42,6 +42,20 @@ export {
|
|
|
42
42
|
type Workflow,
|
|
43
43
|
} from "./api.js";
|
|
44
44
|
export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
|
|
45
|
+
export {
|
|
46
|
+
type ControlFlowSpec,
|
|
47
|
+
describeFlow,
|
|
48
|
+
type FanoutSpec,
|
|
49
|
+
fanoutOver,
|
|
50
|
+
fanoutSpecOf,
|
|
51
|
+
type IterateSpec,
|
|
52
|
+
iterateOver,
|
|
53
|
+
iterateSpecOf,
|
|
54
|
+
type SpeccedFanoutFn,
|
|
55
|
+
type SpeccedIterateFn,
|
|
56
|
+
type StageShape,
|
|
57
|
+
type UnitSelector,
|
|
58
|
+
} from "./control-flow.js";
|
|
45
59
|
export {
|
|
46
60
|
type Artifact,
|
|
47
61
|
type ArtifactHandle,
|
|
@@ -52,6 +66,13 @@ export {
|
|
|
52
66
|
url,
|
|
53
67
|
} from "./handle.js";
|
|
54
68
|
export type { WorkflowHost, WorkflowHostContext, WorkflowSessionContext } from "./host.js";
|
|
69
|
+
// Only the contract data types are public — they're referenced by kept public
|
|
70
|
+
// signatures (`JsonSchemaCapable` ← `typeboxSchema`, `JsonSchemaObject` ←
|
|
71
|
+
// `ConsumesSpec`/`ProducesSpec.data`, `SchemaCompatResult` ← `canCompose`). The
|
|
72
|
+
// low-level json-schema and schema-compat FUNCTIONS stay package-private (no
|
|
73
|
+
// consumer needs them); internal callers import them from their source modules
|
|
74
|
+
// directly.
|
|
75
|
+
export type { JsonSchemaCapable, JsonSchemaObject } from "./json-schema.js";
|
|
55
76
|
export { type LifecycleContext, type LifecycleListeners, registerLifecycle, type StageRef } from "./lifecycle.js";
|
|
56
77
|
export type { ConfigLayer, Issue, LoadedWorkflows, LoadIssue, OverlayPaths } from "./load/index.js";
|
|
57
78
|
export { aliasSkills, loadWorkflows, projectOverlayPaths, userOverlayPaths } from "./load/index.js";
|
|
@@ -94,6 +115,24 @@ export type {
|
|
|
94
115
|
} from "./output.js";
|
|
95
116
|
export { defineCollector, defineParser } from "./output-spec.js";
|
|
96
117
|
export { eq, gt, gte, lt, lte, type Predicate } from "./predicates.js";
|
|
118
|
+
export type {
|
|
119
|
+
ConsumesReadSpec,
|
|
120
|
+
ConsumesSpec,
|
|
121
|
+
ContractSource,
|
|
122
|
+
ProducesSpec,
|
|
123
|
+
SchemaCompatResult,
|
|
124
|
+
SkillContract,
|
|
125
|
+
SkillContractMap,
|
|
126
|
+
} from "./skill-contract.js";
|
|
127
|
+
export {
|
|
128
|
+
canCompose,
|
|
129
|
+
legalNextSkills,
|
|
130
|
+
type OutcomeDeriverFn,
|
|
131
|
+
registerCompositionComparator,
|
|
132
|
+
registerOutcomeDeriver,
|
|
133
|
+
registerSkillContracts,
|
|
134
|
+
registerSkillContractsProvider,
|
|
135
|
+
} from "./skill-contracts/index.js";
|
|
97
136
|
export {
|
|
98
137
|
listArtifacts,
|
|
99
138
|
listRuns,
|
package/runner/by-run-id.ts
CHANGED
|
@@ -11,23 +11,19 @@
|
|
|
11
11
|
* Naming: the suffix names the identifier the caller hands in.
|
|
12
12
|
* `runWorkflowByName` resolves a *workflow* by name (you're starting a run, so
|
|
13
13
|
* you say which workflow); `resumeWorkflowByRunId` resolves a specific past
|
|
14
|
-
* *run* by its
|
|
15
|
-
*
|
|
16
|
-
* under `<cwd>/.rpiv/workflows/runs/` — exactly what `listRuns()` returns on
|
|
17
|
-
* `RunSummary.runId`. (When `resolveRun` later grows symbolic resolution —
|
|
18
|
-
* `@latest`, relative refs — the parameter can widen to a `ref`; today it is a
|
|
19
|
-
* plain run-id and the name says so.)
|
|
14
|
+
* *run* by its reference — a human-readable name (assigned via `--name`) or a
|
|
15
|
+
* literal run-id slug. `resolveRun` handles both.
|
|
20
16
|
*
|
|
21
17
|
* The run header already names its workflow, so the lookup is free — the caller
|
|
22
|
-
* supplies only the
|
|
18
|
+
* supplies only the reference.
|
|
23
19
|
*
|
|
24
20
|
* Contract mirrors `command.ts`'s former resume guards so the programmatic path
|
|
25
|
-
* and the `/wf @<
|
|
26
|
-
* 1.
|
|
27
|
-
* 2. error-severity load issues
|
|
28
|
-
*
|
|
29
|
-
* 3. header's workflow no longer loaded
|
|
30
|
-
* 4. otherwise
|
|
21
|
+
* and the `/wf @<ref>` path never diverge:
|
|
22
|
+
* 1. ref doesn't resolve to a run → failure envelope (`MSG_RUN_NOT_FOUND`)
|
|
23
|
+
* 2. error-severity load issues → refuse (a broken overlay may
|
|
24
|
+
* mis-resolve the workflow) (`MSG_LOAD_ABORTED`)
|
|
25
|
+
* 3. header's workflow no longer loaded → failure envelope (`MSG_RESUME_WORKFLOW_GONE`)
|
|
26
|
+
* 4. otherwise → delegate to `resumeWorkflow`
|
|
31
27
|
*
|
|
32
28
|
* Pure, like `runWorkflowByName` and `resumeWorkflow`: every expected failure is
|
|
33
29
|
* returned in the `RunWorkflowResult` envelope, never thrown and never
|
|
@@ -52,11 +48,16 @@ import { type ResumeWorkflowOptions, type RunWorkflowResult, resumeWorkflow } fr
|
|
|
52
48
|
export type ResumeWorkflowByRunIdOptions = Omit<ResumeWorkflowOptions, "workflow" | "header" | "ref">;
|
|
53
49
|
|
|
54
50
|
/**
|
|
55
|
-
* Resolve `
|
|
51
|
+
* Resolve `ref` to a run header, load the merged overlay for `ctx.cwd`, find
|
|
56
52
|
* the run's workflow, and resume it.
|
|
57
53
|
*
|
|
54
|
+
* const result = await resumeWorkflowByRunId(ctx, "my-ref", { host });
|
|
55
|
+
* // or with a literal run-id:
|
|
58
56
|
* const result = await resumeWorkflowByRunId(ctx, "2026-06-03_07-30-00-ab12", { host });
|
|
59
|
-
*
|
|
57
|
+
*
|
|
58
|
+
* `ref` may be either a human-readable name (assigned via `--name`) or a
|
|
59
|
+
* literal run-id slug. Resolution is handled by `resolveRun` — callers pass
|
|
60
|
+
* whatever the user supplied after the `@` sigil.
|
|
60
61
|
*
|
|
61
62
|
* Pass `opts` to thread a `host` (required for continue-policy stages),
|
|
62
63
|
* `lifecycle` listeners, or the iteration caps — same semantics as
|
|
@@ -64,12 +65,12 @@ export type ResumeWorkflowByRunIdOptions = Omit<ResumeWorkflowOptions, "workflow
|
|
|
64
65
|
*/
|
|
65
66
|
export async function resumeWorkflowByRunId(
|
|
66
67
|
ctx: WorkflowHostContext,
|
|
67
|
-
|
|
68
|
+
ref: string,
|
|
68
69
|
opts?: ResumeWorkflowByRunIdOptions,
|
|
69
70
|
): Promise<RunWorkflowResult> {
|
|
70
|
-
const header = resolveRun(ctx.cwd,
|
|
71
|
+
const header = resolveRun(ctx.cwd, ref);
|
|
71
72
|
if (!header) {
|
|
72
|
-
return { stagesCompleted: 0, success: false, error: MSG_RUN_NOT_FOUND(
|
|
73
|
+
return { stagesCompleted: 0, success: false, error: MSG_RUN_NOT_FOUND(ref) };
|
|
73
74
|
}
|
|
74
75
|
|
|
75
76
|
const loaded = await loadWorkflows(ctx.cwd);
|
|
@@ -84,9 +85,9 @@ export async function resumeWorkflowByRunId(
|
|
|
84
85
|
|
|
85
86
|
const workflow = findWorkflow(loaded, header.workflow);
|
|
86
87
|
if (!workflow) {
|
|
87
|
-
return { stagesCompleted: 0, success: false, error: MSG_RESUME_WORKFLOW_GONE(header.workflow,
|
|
88
|
+
return { stagesCompleted: 0, success: false, error: MSG_RESUME_WORKFLOW_GONE(header.workflow, ref) };
|
|
88
89
|
}
|
|
89
90
|
|
|
90
|
-
// `ref` is the run-id here — it surfaces in `trigger.meta.resumedFrom`.
|
|
91
|
-
return resumeWorkflow(ctx, { workflow, header, ref
|
|
91
|
+
// `ref` is the run-id or name here — it surfaces in `trigger.meta.resumedFrom`.
|
|
92
|
+
return resumeWorkflow(ctx, { workflow, header, ref, ...opts });
|
|
92
93
|
}
|
package/runner/chain-advance.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { auditCtxFor, nowIso, recordTerminalFailure } from "../audit.js";
|
|
12
|
+
import { resolveSkill } from "../internal-utils.js";
|
|
12
13
|
import { skillStageRef } from "../lifecycle.js";
|
|
13
14
|
import {
|
|
14
15
|
ERR_BACKWARD_JUMP_EXHAUSTED,
|
|
@@ -45,7 +46,7 @@ export async function advanceChain(
|
|
|
45
46
|
return;
|
|
46
47
|
}
|
|
47
48
|
|
|
48
|
-
const fromRef = skillStageRef(currentName, idx + 1, run.workflow.stages[currentName]
|
|
49
|
+
const fromRef = skillStageRef(currentName, idx + 1, resolveSkill(run.workflow.stages[currentName]!, currentName));
|
|
49
50
|
|
|
50
51
|
if (result.kind === "stop") {
|
|
51
52
|
await run.lifecycle.fire(curCtx, "onRoute", fromRef, "stop", lifecycleCtxFor(run));
|
|
@@ -122,7 +123,7 @@ function auditRoutingDecision(
|
|
|
122
123
|
* global pool that drains across unrelated loops.
|
|
123
124
|
*
|
|
124
125
|
* Trip attribution targets `nextName` (the stage the guard refused to
|
|
125
|
-
* re-enter), not the just-completed stage.
|
|
126
|
+
* re-enter), not the just-completed stage.
|
|
126
127
|
*/
|
|
127
128
|
async function checkBackwardJumpGuard(
|
|
128
129
|
curCtx: WorkflowHostContext,
|
package/runner/index.ts
CHANGED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Input-validation preflights for the runner's per-stage pipeline.
|
|
3
|
+
*
|
|
4
|
+
* Two validators run as `POST_PROMPT_CHECKS` in `stage-lifecycle.ts`:
|
|
5
|
+
* - `ensureInputValid` — validates upstream output against the stage's
|
|
6
|
+
* declared `inputSchema`.
|
|
7
|
+
* - `ensureContractInputValid` — validates upstream output against the
|
|
8
|
+
* skill contract's `consumes.data` schema (the gap `ensureInputValid`
|
|
9
|
+
* leaves when the stage has no `inputSchema`).
|
|
10
|
+
*
|
|
11
|
+
* Both share a common validate-and-throw pipeline, factored into
|
|
12
|
+
* `validateOrThrow`. The difference is error policy: `ensureInputValid`
|
|
13
|
+
* halts on any validation error; `ensureContractInputValid` degrades
|
|
14
|
+
* (returns) when the contract schema itself throws (author defect),
|
|
15
|
+
* halting only on timeouts.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { SchemaTimeoutError, withTimeout } from "../internal-utils.js";
|
|
19
|
+
import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
|
|
20
|
+
import { ERR_INPUT_VALIDATION_FAILED, ERR_SCHEMA_TIMEOUT, MSG_INPUT_VALIDATION_FAILED } from "../messages.js";
|
|
21
|
+
import type { RunContext } from "../types.js";
|
|
22
|
+
import {
|
|
23
|
+
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
24
|
+
describeFailure,
|
|
25
|
+
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
26
|
+
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
27
|
+
type ValidationResult,
|
|
28
|
+
validateOutputData,
|
|
29
|
+
} from "../validate-output.js";
|
|
30
|
+
import type { ResolvedStage } from "./stage-lifecycle.js";
|
|
31
|
+
import { StagePreflightError } from "./stage-lifecycle.js";
|
|
32
|
+
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
// Shared helper
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Error policy for `validateOrThrow`:
|
|
39
|
+
* - `"halt-on-any"` — any validation error or throw halts the stage.
|
|
40
|
+
* Used by `ensureInputValid` (stage-owned schemas are trusted).
|
|
41
|
+
* - `"degrade-on-non-timeout"` — timeout halts the stage; other throws
|
|
42
|
+
* degrade (return). Used by `ensureContractInputValid` (contract schemas
|
|
43
|
+
* are consumer-authored and may contain unsupported keywords).
|
|
44
|
+
*/
|
|
45
|
+
type ErrorPolicy = "halt-on-any" | "degrade-on-non-timeout";
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Shared core of both input validators: validate `data` against `schema`
|
|
49
|
+
* within `timeoutMs`, throwing `StagePreflightError` on failure.
|
|
50
|
+
*
|
|
51
|
+
* The `errorPolicy` parameter controls the catch-path behaviour:
|
|
52
|
+
* - `"halt-on-any"`: `withTimeout` receives a string error message.
|
|
53
|
+
* Any catch → `StagePreflightError` (halt).
|
|
54
|
+
* - `"degrade-on-non-timeout"`: `withTimeout` receives a
|
|
55
|
+
* `SchemaTimeoutError` instance. On catch, only a timeout is re-thrown
|
|
56
|
+
* as `StagePreflightError`; other errors (contract schema evaluation
|
|
57
|
+
* failures) cause a silent return (degrade), so an unparseable contract
|
|
58
|
+
* doesn't kill a legitimate run.
|
|
59
|
+
*/
|
|
60
|
+
async function validateOrThrow(
|
|
61
|
+
schema: Parameters<typeof validateOutputData>[0],
|
|
62
|
+
data: unknown,
|
|
63
|
+
stage: ResolvedStage,
|
|
64
|
+
prevSkill: string,
|
|
65
|
+
timeoutMs: number,
|
|
66
|
+
errorPolicy: ErrorPolicy,
|
|
67
|
+
): Promise<void> {
|
|
68
|
+
const timeoutError =
|
|
69
|
+
errorPolicy === "degrade-on-non-timeout"
|
|
70
|
+
? new SchemaTimeoutError(ERR_SCHEMA_TIMEOUT("inputSchema", timeoutMs))
|
|
71
|
+
: ERR_SCHEMA_TIMEOUT("inputSchema", timeoutMs);
|
|
72
|
+
|
|
73
|
+
let result: ValidationResult;
|
|
74
|
+
try {
|
|
75
|
+
result = await withTimeout(Promise.resolve(validateOutputData(schema, data)), timeoutMs, timeoutError);
|
|
76
|
+
} catch (e) {
|
|
77
|
+
if (errorPolicy === "degrade-on-non-timeout" && !(e instanceof SchemaTimeoutError)) return;
|
|
78
|
+
const reason = e instanceof Error ? e.message : String(e);
|
|
79
|
+
throw new StagePreflightError(
|
|
80
|
+
"halt",
|
|
81
|
+
stage.skill,
|
|
82
|
+
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
83
|
+
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, reason),
|
|
84
|
+
true,
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (result.valid) return;
|
|
89
|
+
|
|
90
|
+
const failureSummary = result.failures.map(describeFailure).join("; ");
|
|
91
|
+
throw new StagePreflightError(
|
|
92
|
+
"halt",
|
|
93
|
+
stage.skill,
|
|
94
|
+
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
95
|
+
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, failureSummary),
|
|
96
|
+
true,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
// Timeout clamp
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Clamp `validateTimeoutMs` to the allowed range. Mirror of the clamp in
|
|
106
|
+
* `extraction.ts:retryUntilValid`. Same defense-in-depth posture:
|
|
107
|
+
* `validateWorkflow` rejects out-of-range values at load, but programmatic
|
|
108
|
+
* callers that embed `runWorkflow` can bypass it; clamping here means a
|
|
109
|
+
* misconfigured stage degrades to the spec-default behavior instead of
|
|
110
|
+
* firing a 100 ms timeout before a real I/O probe gets a chance to settle.
|
|
111
|
+
*/
|
|
112
|
+
function clampValidateTimeoutMs(raw: number | undefined): number {
|
|
113
|
+
return Math.max(
|
|
114
|
+
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
115
|
+
Math.min(raw ?? DEFAULT_VALIDATION_RETRY_TIMEOUT_MS, MAX_VALIDATION_RETRY_TIMEOUT_MS),
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// ---------------------------------------------------------------------------
|
|
120
|
+
// Public validators
|
|
121
|
+
// ---------------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Validate upstream output against the stage's declared `inputSchema`.
|
|
125
|
+
* Runs as a `POST_PROMPT_CHECK` in the skill pipeline and directly before
|
|
126
|
+
* `runScript` in the script-stage shortcut.
|
|
127
|
+
*
|
|
128
|
+
* Any validation failure or async schema error → `StagePreflightError`
|
|
129
|
+
* (halt-class). The stage author owns `inputSchema`; if it throws, that's
|
|
130
|
+
* a runtime bug worth halting for.
|
|
131
|
+
*/
|
|
132
|
+
export async function ensureInputValid(stage: ResolvedStage, run: RunContext): Promise<void> {
|
|
133
|
+
if (!stage.def.inputSchema || run.state.output?.data === undefined) return;
|
|
134
|
+
const timeoutMs = clampValidateTimeoutMs(stage.def.validateTimeoutMs);
|
|
135
|
+
const prevSkill = run.state.output.meta.stage || "unknown";
|
|
136
|
+
await validateOrThrow(stage.def.inputSchema, run.state.output.data, stage, prevSkill, timeoutMs, "halt-on-any");
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Runtime mirror of `checkEdgeSchemaCompat` for the LINEAR `data` channel.
|
|
141
|
+
* When the consumer declares `consumes.data` but the stage has no
|
|
142
|
+
* `inputSchema`, validate upstream `output.data` against the contract
|
|
143
|
+
* schema — the gap `ensureInputValid` leaves. A clean failure HALTS
|
|
144
|
+
* (load-time only warns, being schema-vs-schema). Degrades (returns)
|
|
145
|
+
* when `consumes.data` is not a plain-object schema or the keyword engine
|
|
146
|
+
* throws (author defect), and when there's no registry / contract /
|
|
147
|
+
* `consumes.data`, an `inputSchema`, a raw `prompt`, or upstream data.
|
|
148
|
+
*
|
|
149
|
+
* NAMED-channel (`reads:`) validity is a complete LOAD-TIME guarantee
|
|
150
|
+
* (`checkReadsChannelCompat`), not checked here — a `reads:` stage consumes
|
|
151
|
+
* from `state.named`, never the rolling primary, so it returns early
|
|
152
|
+
* (mirroring the `ensureUpstreamArtifact` reads guard) rather than validating
|
|
153
|
+
* the unrelated primary `output.data` against its `consumes.data`.
|
|
154
|
+
*/
|
|
155
|
+
export async function ensureContractInputValid(stage: ResolvedStage, run: RunContext): Promise<void> {
|
|
156
|
+
if (stage.def.prompt !== undefined) return;
|
|
157
|
+
if (stage.def.inputSchema) return; // ensureInputValid owns the stage-schema path
|
|
158
|
+
// A `reads:` stage's input comes from `state.named`, not the rolling primary
|
|
159
|
+
// `output.data` — adjudicating that primary against this stage's `consumes.data`
|
|
160
|
+
// would check the wrong source. Named-channel compat is load-time-only
|
|
161
|
+
// (`checkReadsChannelCompat`); mirror `ensureUpstreamArtifact`'s reads guard.
|
|
162
|
+
if (stage.def.reads?.length) return;
|
|
163
|
+
const contract = run.skillContracts?.get(stage.skill);
|
|
164
|
+
|
|
165
|
+
if (run.state.output?.data === undefined) return;
|
|
166
|
+
const consumesData = contract?.consumes?.data;
|
|
167
|
+
// Untrusted injected contract — degrade (never HALT) on a non-object schema.
|
|
168
|
+
if (!isJsonSchemaObject(consumesData)) return;
|
|
169
|
+
const schema = jsonSchemaToStandard(consumesData);
|
|
170
|
+
const timeoutMs = clampValidateTimeoutMs(stage.def.validateTimeoutMs);
|
|
171
|
+
const prevSkill = run.state.output.meta.stage || "unknown";
|
|
172
|
+
await validateOrThrow(schema, run.state.output.data, stage, prevSkill, timeoutMs, "degrade-on-non-timeout");
|
|
173
|
+
}
|
package/runner/resume-fanout.ts
CHANGED
|
@@ -27,7 +27,7 @@ import type { FanoutUnit, StageDef } from "../api.js";
|
|
|
27
27
|
import { auditCtxFor, recordTerminalFailure } from "../audit.js";
|
|
28
28
|
import type { FanoutDeps } from "../fanout.js";
|
|
29
29
|
import { runFanout } from "../fanout.js";
|
|
30
|
-
import { currentPrimaryArtifact } from "../internal-utils.js";
|
|
30
|
+
import { currentPrimaryArtifact, resolveSkill } from "../internal-utils.js";
|
|
31
31
|
import { skillStageRef } from "../lifecycle.js";
|
|
32
32
|
import { ERR_RESUME_FANOUT_MISMATCH, MSG_RESUME_FANOUT_MISMATCH } from "../messages.js";
|
|
33
33
|
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
@@ -52,7 +52,7 @@ export async function resumeFanoutStage(
|
|
|
52
52
|
deps: FanoutDeps,
|
|
53
53
|
): Promise<void> {
|
|
54
54
|
const def = run.workflow.stages[parent]!; // caller verified parent is a fanout stage
|
|
55
|
-
const skill = def
|
|
55
|
+
const skill = resolveSkill(def, parent); // mirror resolveStage; aliased nodes tag rows with the skill body
|
|
56
56
|
const units = await recomputeUnits(def, run);
|
|
57
57
|
|
|
58
58
|
if (fanoutPrefixDrifted(parent, completedDecorated, units)) {
|
package/runner/resume-iterate.ts
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
|
|
22
22
|
import type { IterateUnit, StageDef } from "../api.js";
|
|
23
23
|
import { auditCtxFor, iterateRowStage, recordTerminalFailure } from "../audit.js";
|
|
24
|
+
import { resolveSkill } from "../internal-utils.js";
|
|
24
25
|
import type { IterateDeps } from "../iterate.js";
|
|
25
26
|
import { runIterate } from "../iterate.js";
|
|
26
27
|
import { skillStageRef } from "../lifecycle.js";
|
|
@@ -49,7 +50,7 @@ export async function resumeIterateStage(
|
|
|
49
50
|
deps: IterateDeps,
|
|
50
51
|
): Promise<void> {
|
|
51
52
|
const def = run.workflow.stages[parent]!; // caller verified parent is an iterate stage
|
|
52
|
-
const skill = def
|
|
53
|
+
const skill = resolveSkill(def, parent); // mirror resolveStage; aliased nodes tag rows with the skill body
|
|
53
54
|
|
|
54
55
|
// Pre-pull the next unit ONCE to branch: drift-guard + already-complete no-op.
|
|
55
56
|
const next = await pullNextUnit(def, point, run);
|
package/runner/runner.ts
CHANGED
|
@@ -39,13 +39,17 @@ import {
|
|
|
39
39
|
ERR_RESUME_NO_ROWS,
|
|
40
40
|
ERR_RESUME_STAGE_GONE,
|
|
41
41
|
ERR_WORKFLOW_ABORTED,
|
|
42
|
+
MSG_NAME_COLLISION,
|
|
43
|
+
MSG_NAME_INDEX_WRITE_FAILED,
|
|
44
|
+
MSG_NAME_INVALID,
|
|
42
45
|
MSG_STAGE_THREW,
|
|
43
46
|
MSG_WORKFLOW_ABORTED,
|
|
44
47
|
MSG_WORKFLOW_COMPLETE,
|
|
45
48
|
STATUS_KEY,
|
|
46
49
|
} from "../messages.js";
|
|
47
50
|
import { runFanoutSession, runStageSession } from "../sessions/index.js";
|
|
48
|
-
import {
|
|
51
|
+
import { getSkillContracts } from "../skill-contracts/index.js";
|
|
52
|
+
import { type ClaimResult, claimName, generateRunId, writeHeader } from "../state/index.js";
|
|
49
53
|
import type { WorkflowHeader } from "../state/state.js";
|
|
50
54
|
import { DEFAULT_TRIGGER, type RunTrigger } from "../triggers.js";
|
|
51
55
|
import type { RunContext, RunState } from "../types.js";
|
|
@@ -122,6 +126,12 @@ export interface RunWorkflowOptions {
|
|
|
122
126
|
* mid-stage.
|
|
123
127
|
*/
|
|
124
128
|
signal?: AbortSignal;
|
|
129
|
+
/**
|
|
130
|
+
* Human-readable alias for this run. Stored in the JSONL header and the
|
|
131
|
+
* sidecar names.json index. Rejected if already in use — the error
|
|
132
|
+
* identifies the conflicting runId.
|
|
133
|
+
*/
|
|
134
|
+
name?: string;
|
|
125
135
|
}
|
|
126
136
|
|
|
127
137
|
export interface RunWorkflowResult {
|
|
@@ -199,6 +209,18 @@ async function executeRun(
|
|
|
199
209
|
// runWorkflow — workflow entry point
|
|
200
210
|
// ---------------------------------------------------------------------------
|
|
201
211
|
|
|
212
|
+
/** Map a failed `claimName` outcome to its user-facing message. */
|
|
213
|
+
function nameClaimError(name: string, claim: Extract<ClaimResult, { ok: false }>): string {
|
|
214
|
+
switch (claim.reason) {
|
|
215
|
+
case "invalid":
|
|
216
|
+
return MSG_NAME_INVALID(name);
|
|
217
|
+
case "collision":
|
|
218
|
+
return MSG_NAME_COLLISION(name, claim.runId);
|
|
219
|
+
case "write-failed":
|
|
220
|
+
return MSG_NAME_INDEX_WRITE_FAILED(name);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
202
224
|
/**
|
|
203
225
|
* Each subsequent `newSession()` is invoked on the freshCtx returned by the
|
|
204
226
|
* previous withSession — never on a captured outer ctx (which Pi invalidates
|
|
@@ -221,7 +243,22 @@ export async function runWorkflow(ctx: WorkflowHostContext, options: RunWorkflow
|
|
|
221
243
|
const runId = generateRunId();
|
|
222
244
|
const trigger = options.trigger ?? DEFAULT_TRIGGER;
|
|
223
245
|
|
|
224
|
-
|
|
246
|
+
// Reserve the name (validate → collision → persist) through the state
|
|
247
|
+
// layer's single door, BEFORE the JSONL header so the collision guard's
|
|
248
|
+
// truth-source can never lag the header. Nothing is written on failure.
|
|
249
|
+
if (options.name) {
|
|
250
|
+
const claim = claimName(cwd, options.name, runId);
|
|
251
|
+
if (!claim.ok) return { stagesCompleted: 0, success: false, error: nameClaimError(options.name, claim) };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
writeHeader(cwd, {
|
|
255
|
+
runId,
|
|
256
|
+
workflow: workflow.name,
|
|
257
|
+
input: options.input,
|
|
258
|
+
ts: nowIso(),
|
|
259
|
+
trigger,
|
|
260
|
+
name: options.name,
|
|
261
|
+
});
|
|
225
262
|
|
|
226
263
|
const run = buildRunContext(cwd, workflow, options, {
|
|
227
264
|
runId,
|
|
@@ -354,6 +391,10 @@ function buildRunContext(
|
|
|
354
391
|
state: identity.state,
|
|
355
392
|
visited: identity.visited,
|
|
356
393
|
registeredSkills: options.host ? snapshotRegisteredSkills(options.host) : undefined,
|
|
394
|
+
// Defensive COPY (not the live global Map) so a later registerSkillContracts
|
|
395
|
+
// call cannot mutate this run's snapshot mid-run — parity with the fresh-Set
|
|
396
|
+
// copy snapshotRegisteredSkills makes.
|
|
397
|
+
skillContracts: new Map(getSkillContracts()),
|
|
357
398
|
continueHost: options.host,
|
|
358
399
|
maxBackwardJumps: options.maxBackwardJumps ?? MAX_BACKWARD_JUMPS,
|
|
359
400
|
maxIterations: options.maxIterations ?? MAX_ITERATIONS,
|
package/runner/script-stage.ts
CHANGED
|
@@ -45,7 +45,7 @@ import {
|
|
|
45
45
|
} from "../messages.js";
|
|
46
46
|
import { finalizeOutput, type Output } from "../output.js";
|
|
47
47
|
import type { RunContext, RunState, WorkflowHostContext } from "../types.js";
|
|
48
|
-
import { DEFAULT_VALIDATION_RETRIES, validateOutputData } from "../validate-output.js";
|
|
48
|
+
import { DEFAULT_VALIDATION_RETRIES, describeFailure, validateOutputData } from "../validate-output.js";
|
|
49
49
|
import { advanceChain } from "./chain-advance.js";
|
|
50
50
|
import { lifecycleCtxFor } from "./runner.js";
|
|
51
51
|
import type { ResolvedStage } from "./stage-lifecycle.js";
|
|
@@ -94,7 +94,7 @@ export async function runScript(
|
|
|
94
94
|
if (stage.def.kind === "produces" && stage.def.outputSchema) {
|
|
95
95
|
const validation = await Promise.resolve(validateOutputData(stage.def.outputSchema, output.data));
|
|
96
96
|
if (!validation.valid) {
|
|
97
|
-
const failureSummary = validation.failures.map(
|
|
97
|
+
const failureSummary = validation.failures.map(describeFailure).join("; ");
|
|
98
98
|
if (attempt > maxRetries || onInvalid === "halt") {
|
|
99
99
|
await recordTerminalFailure(curCtx, scriptAuditCtx(run, stage), {
|
|
100
100
|
status: "failed",
|