@juicesharp/rpiv-workflow 1.18.2 → 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 CHANGED
@@ -11,6 +11,8 @@ import { findWorkflow, type Issue, loadWorkflows } from "./load/index.js";
11
11
  import {
12
12
  MSG_INTERACTIVE_ONLY,
13
13
  MSG_LOAD_ABORTED,
14
+ MSG_NAME_IGNORED_ON_RESUME,
15
+ MSG_NAME_INVALID,
14
16
  MSG_NO_WORKFLOWS_REGISTERED,
15
17
  MSG_RESUME_USAGE,
16
18
  MSG_WORKFLOW_NOT_FOUND,
@@ -18,6 +20,7 @@ import {
18
20
  } from "./messages.js";
19
21
  import { formatWorkflowDetails, formatWorkflowList } from "./preview.js";
20
22
  import { resumeWorkflowByRunId, runWorkflow } from "./runner/index.js";
23
+ import { isValidName } from "./state/index.js";
21
24
 
22
25
  // ---------------------------------------------------------------------------
23
26
  // Orchestrator
@@ -36,11 +39,19 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
36
39
  const parsed = parseArgs(args, { workflowNames, default: loaded.default });
37
40
 
38
41
  if (parsed.kind === "resume") {
42
+ if (parsed.droppedName !== undefined) {
43
+ ctx.ui.notify(MSG_NAME_IGNORED_ON_RESUME, "warning");
44
+ }
39
45
  await handleResume(host, ctx, parsed.ref);
40
46
  return;
41
47
  }
42
48
 
43
- const { workflow: workflowName, input } = parsed;
49
+ const { workflow: workflowName, input, name } = parsed;
50
+
51
+ if (name !== undefined && !isValidName(name)) {
52
+ ctx.ui.notify(MSG_NAME_INVALID(name), "error");
53
+ return;
54
+ }
44
55
 
45
56
  if (!input) {
46
57
  const trimmed = args.trim();
@@ -78,7 +89,17 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
78
89
  // thrown predicate or invariant could still bubble. Catch so Pi's
79
90
  // dispatcher doesn't print a raw stack.
80
91
  try {
81
- await runWorkflow(ctx, { workflow, input, host, trigger: { kind: "command", name: "wf" } });
92
+ const result = await runWorkflow(ctx, {
93
+ workflow,
94
+ input,
95
+ host,
96
+ trigger: { kind: "command", name: "wf" },
97
+ name,
98
+ });
99
+ // Surface pre-flight rejections (collision, etc.) — no runId means no JSONL on disk.
100
+ if (!result.success && result.runId === undefined && result.error) {
101
+ ctx.ui.notify(result.error, "error");
102
+ }
82
103
  } catch (e) {
83
104
  const reason = e instanceof Error ? e.message : String(e);
84
105
  ctx.ui.notify(MSG_WORKFLOW_THREW(reason), "error");
@@ -89,13 +110,13 @@ export async function handleWorkflowCommand(host: WorkflowHost, args: string, ct
89
110
  // Resume handler
90
111
  // ---------------------------------------------------------------------------
91
112
 
92
- async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, runId: string): Promise<void> {
93
- if (!runId) {
113
+ async function handleResume(host: WorkflowHost, ctx: WorkflowHostContext, ref: string): Promise<void> {
114
+ if (!ref) {
94
115
  ctx.ui.notify(MSG_RESUME_USAGE, "error");
95
116
  return;
96
117
  }
97
118
  try {
98
- const result = await resumeWorkflowByRunId(ctx, runId, { host });
119
+ const result = await resumeWorkflowByRunId(ctx, ref, { host });
99
120
  // A failure with no runId is a no-JSONL refusal (run-id didn't resolve,
100
121
  // load error, workflow gone, or an unreconstructable trail) — nothing else
101
122
  // surfaces it, so notify here. An in-run failure carries a runId and was
package/command.ts CHANGED
@@ -27,7 +27,11 @@ export function registerWorkflowCommand(host: WorkflowHost): void {
27
27
  // Arg parsing (pure; exported for tests + consumed by ./command-run.js)
28
28
  // ---------------------------------------------------------------------------
29
29
 
30
- export type ParsedCommand = { kind: "run"; workflow: string; input: string } | { kind: "resume"; ref: string };
30
+ const NAME_FLAG = /--name\s+([^\s]+)/;
31
+
32
+ export type ParsedCommand =
33
+ | { kind: "run"; workflow: string; input: string; name?: string }
34
+ | { kind: "resume"; ref: string; droppedName?: string };
31
35
 
32
36
  /**
33
37
  * First token is a workflow name iff recognised; otherwise the whole arg is
@@ -43,15 +47,24 @@ export function parseArgs(
43
47
  args: string,
44
48
  loaded: { workflowNames: ReadonlySet<string>; default: string | undefined },
45
49
  ): ParsedCommand {
46
- const trimmed = args.trim();
50
+ let trimmed = args.trim();
51
+ let name: string | undefined;
52
+
53
+ // Extract --name <slug> flag and strip it before further parsing.
54
+ const nameMatch = NAME_FLAG.exec(trimmed);
55
+ if (nameMatch) {
56
+ name = nameMatch[1];
57
+ trimmed = trimmed.replace(NAME_FLAG, "").trim();
58
+ }
47
59
 
48
60
  if (trimmed.startsWith("@")) {
49
- // First token after the sigil is the ref; ignore any trailing tokens for now.
50
- return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "" };
61
+ // @resume — name has no meaning here; carry it as `droppedName` so the
62
+ // command layer can warn instead of silently dropping it.
63
+ return { kind: "resume", ref: trimmed.slice(1).trim().split(/\s+/)[0] ?? "", droppedName: name };
51
64
  }
52
65
 
53
66
  if (!trimmed) {
54
- return { kind: "run", workflow: loaded.default ?? "", input: "" };
67
+ return { kind: "run", workflow: loaded.default ?? "", input: "", name };
55
68
  }
56
69
 
57
70
  const firstSpace = trimmed.indexOf(" ");
@@ -59,8 +72,8 @@ export function parseArgs(
59
72
 
60
73
  if (loaded.workflowNames.has(firstToken)) {
61
74
  const remaining = firstSpace === -1 ? "" : trimmed.slice(firstSpace + 1).trim();
62
- return { kind: "run", workflow: firstToken, input: remaining };
75
+ return { kind: "run", workflow: firstToken, input: remaining, name };
63
76
  }
64
77
 
65
- return { kind: "run", workflow: loaded.default ?? "", input: trimmed };
78
+ return { kind: "run", workflow: loaded.default ?? "", input: trimmed, name };
66
79
  }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Control-flow as data — `fanout`/`iterate` made inspectable.
3
+ *
4
+ * `fanout`/`iterate` are first-class at RUNTIME (the runner drives them) but
5
+ * opaque to INTROSPECTION: they're raw functions on `StageDef`, and the pattern
6
+ * (what they split over, the cardinality bound, parallel-vs-sequential) lives
7
+ * inside a closure. This module makes that pattern inspectable-as-data by
8
+ * attaching a declarative `.spec` to the function — the exact mechanism
9
+ * `defineRoute`/`gate` use to attach `.targets` (`api.ts`) so reachability checks
10
+ * read every branch without executing the predicate.
11
+ *
12
+ * `fanoutOver(spec)` / `iterateOver(spec)` return the SAME `FanoutFn`/`IterateFn`
13
+ * the runner already consumes (zero runner change), carrying a `FanoutSpec`/
14
+ * `IterateSpec`. Introspectors read the spec; the runner calls the function.
15
+ * A raw `FanoutFn` with no `.spec` stays valid and reads as opaque — same
16
+ * degrade posture as a Zod schema being opaque to `extractJsonSchema`, or a
17
+ * predicate edge being skipped by edge-compat.
18
+ *
19
+ * Skill-agnostic: this module ships the spec VOCABULARY (data) only. The actual
20
+ * unit detector (e.g. "parse the plan's `phases:` frontmatter") is the consumer-
21
+ * supplied `run` function — `rpiv-workflow` ships no conventions.
22
+ */
23
+
24
+ import type { EdgeFn, FanoutFn, IterateFn, Workflow } from "./api.js";
25
+ import { STOP } from "./api.js";
26
+
27
+ /**
28
+ * How a stage's work is split into units, AS DATA. `by` names the convention
29
+ * ("frontmatter-array" | "markdown-heading" | "glob" | "json-path" | a consumer
30
+ * tag); `pattern` is its opaque parameter; `meta` carries any extra domain hints.
31
+ * The framework never interprets `by`/`pattern` for execution (the `run` fn does)
32
+ * — it only surfaces them so an agent can read or emit the pattern. Open + opaque,
33
+ * mirroring the contract `meta` bag.
34
+ */
35
+ export interface UnitSelector {
36
+ by: string;
37
+ pattern?: string;
38
+ meta?: Record<string, unknown>;
39
+ }
40
+
41
+ /** Common shape of both control-flow specs — the introspectable facet. */
42
+ interface ControlFlowSpecBase {
43
+ /** The channel / artifact-kind the units are split FROM (a `consumes` signal). */
44
+ source?: string;
45
+ /** How units are detected (opaque convention). */
46
+ unit?: UnitSelector;
47
+ /** Cardinality ceiling, surfaced from what used to be a private constant. */
48
+ max?: number;
49
+ }
50
+
51
+ /** Parallel map: all units computed up front, run independent of one another. */
52
+ export interface FanoutSpec extends ControlFlowSpecBase {
53
+ kind: "fanout";
54
+ }
55
+
56
+ /** Sequential fold: one unit per call, each seeing the prior units' outputs. */
57
+ export interface IterateSpec extends ControlFlowSpecBase {
58
+ kind: "iterate";
59
+ /** `iterate`'s defining trait — each unit builds on `accumulated`. Always `true`. */
60
+ dependsOnPrior: true;
61
+ }
62
+
63
+ export type ControlFlowSpec = FanoutSpec | IterateSpec;
64
+
65
+ /** A `FanoutFn`/`IterateFn` carrying its introspectable spec (cf. `EdgeFn.targets`). */
66
+ export type SpeccedFanoutFn = FanoutFn & { spec: FanoutSpec };
67
+ export type SpeccedIterateFn = IterateFn & { spec: IterateSpec };
68
+
69
+ /**
70
+ * Build a fanout that is BOTH executable (the runner calls it) and describable
71
+ * (introspectors read `.spec`) — the `defineRoute` pattern for control flow. The
72
+ * `run` fn is the consumer-supplied detector; `rpiv-workflow` ships none.
73
+ */
74
+ export function fanoutOver(spec: Omit<FanoutSpec, "kind"> & { run: FanoutFn }): SpeccedFanoutFn {
75
+ const { run, ...rest } = spec;
76
+ const fn = run as SpeccedFanoutFn;
77
+ fn.spec = { kind: "fanout", ...rest };
78
+ return fn;
79
+ }
80
+
81
+ /** Sequential-fold counterpart. `dependsOnPrior` is implied + fixed to `true`. */
82
+ export function iterateOver(spec: Omit<IterateSpec, "kind" | "dependsOnPrior"> & { run: IterateFn }): SpeccedIterateFn {
83
+ const { run, ...rest } = spec;
84
+ const fn = run as SpeccedIterateFn;
85
+ fn.spec = { kind: "iterate", dependsOnPrior: true, ...rest };
86
+ return fn;
87
+ }
88
+
89
+ /** Read a fanout spec off a stage's fanout fn, or `undefined` if raw/opaque. */
90
+ export function fanoutSpecOf(fn: FanoutFn | undefined): FanoutSpec | undefined {
91
+ return typeof fn === "function" && "spec" in fn ? (fn as SpeccedFanoutFn).spec : undefined;
92
+ }
93
+
94
+ /** Read an iterate spec off a stage's iterate fn, or `undefined` if raw/opaque. */
95
+ export function iterateSpecOf(fn: IterateFn | undefined): IterateSpec | undefined {
96
+ return typeof fn === "function" && "spec" in fn ? (fn as SpeccedIterateFn).spec : undefined;
97
+ }
98
+
99
+ /**
100
+ * Per-stage control-flow + edge shape, read entirely from data already attached
101
+ * (`.spec`, `.targets`) — no probing. The control-flow analogue of
102
+ * `legalNextSkills`: what an analyzing/suggesting agent consumes to render or
103
+ * reason about a flow's structure.
104
+ */
105
+ export interface StageShape {
106
+ stage: string;
107
+ skill?: string;
108
+ control: { mode: "single" | "fanout" | "iterate"; spec?: ControlFlowSpec };
109
+ edge: { mode: "linear" | "route" | "terminal"; targets?: readonly string[] };
110
+ }
111
+
112
+ /** Describe a workflow's structure stage-by-stage from attached metadata alone. */
113
+ export function describeFlow(w: Workflow): StageShape[] {
114
+ return Object.entries(w.stages).map(([name, stage]) => {
115
+ const fanoutSpec = fanoutSpecOf(stage.fanout);
116
+ const iterateSpec = iterateSpecOf(stage.iterate);
117
+ const control: StageShape["control"] = stage.fanout
118
+ ? { mode: "fanout", spec: fanoutSpec }
119
+ : stage.iterate
120
+ ? { mode: "iterate", spec: iterateSpec }
121
+ : { mode: "single" };
122
+
123
+ const target = w.edges[name];
124
+ let edge: StageShape["edge"];
125
+ if (target === undefined || target === STOP) {
126
+ edge = { mode: "terminal" };
127
+ } else if (typeof target === "string") {
128
+ edge = { mode: "linear", targets: [target] };
129
+ } else {
130
+ edge = { mode: "route", targets: (target as EdgeFn).targets };
131
+ }
132
+
133
+ return { stage: name, skill: stage.skill, control, edge };
134
+ });
135
+ }
package/internal-utils.ts CHANGED
@@ -42,15 +42,58 @@ export function resolvePublishName(def: StageDef, stageName: string): string {
42
42
  return def.outcome?.name ?? stageName;
43
43
  }
44
44
 
45
+ /**
46
+ * Resolve a stage's effective skill — the contract-registry key. Twin of
47
+ * `resolvePublishName`. Single source of truth so the runtime resolution
48
+ * (`resolveStage`) and the load-time lookups (`validate-workflow.ts`) key the
49
+ * registry identically and can't drift.
50
+ */
51
+ export function resolveSkill(def: StageDef, stageName: string): string {
52
+ return def.skill ?? stageName;
53
+ }
54
+
55
+ /**
56
+ * Create a lazily-initialised global-slot getter anchored on a `Symbol.for` key.
57
+ * The returned function reads from `globalThis` on every call, initialising the
58
+ * slot on first access. The indirection through `globalThis` (rather than
59
+ * module-local state) ensures a single shared slot even when Pi loads this
60
+ * module more than once (e.g. once for the extension entry, once via a
61
+ * sibling's cross-package import).
62
+ *
63
+ * Usage: `const getRegistry = globalSlot(KEY, () => new Map());`
64
+ * Then: `getRegistry()` returns the lazily-created Map.
65
+ */
66
+ export function globalSlot<T>(key: symbol, init: () => T): () => T {
67
+ return () => {
68
+ const g = globalThis as Record<symbol, unknown>;
69
+ let value = g[key] as T | undefined;
70
+ if (value === undefined) {
71
+ value = init();
72
+ g[key] = value;
73
+ }
74
+ return value;
75
+ };
76
+ }
77
+
78
+ /** Thrown by `withTimeout` when the caller passes a `SchemaTimeoutError`
79
+ * instance as the message. Lets consumers distinguish timeout errors from
80
+ * inner-promise rejections via `instanceof` instead of string-identity
81
+ * comparison. */
82
+ export class SchemaTimeoutError extends Error {}
83
+
45
84
  /**
46
85
  * Race a promise against `ms`. The inner promise is NOT cancelled — Pi's
47
86
  * `ctx.waitForIdle()` has no abort signal today; the dangling promise becomes
48
87
  * inert when the next stage's `newSession` replaces the ctx.
88
+ *
89
+ * When `message` is a string, a plain `Error` is thrown on timeout
90
+ * (backward-compatible). When `message` is an `Error` (e.g.
91
+ * `SchemaTimeoutError`), it is thrown directly so `instanceof` checks work.
49
92
  */
50
- export async function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {
93
+ export async function withTimeout<T>(promise: Promise<T>, ms: number, message: string | Error): Promise<T> {
51
94
  let timer: ReturnType<typeof setTimeout> | undefined;
52
95
  const timeout = new Promise<never>((_, reject) => {
53
- timer = setTimeout(() => reject(new Error(message)), ms);
96
+ timer = setTimeout(() => reject(typeof message === "string" ? new Error(message) : message), ms);
54
97
  });
55
98
  try {
56
99
  return await Promise.race([promise, timeout]);
@@ -102,3 +145,31 @@ export function applyCompletedStage(state: RunState, def: StageDef, stageName: s
102
145
  export function resolveUnderCwd(cwd: string, p: string): string {
103
146
  return isAbsolute(p) ? p : join(cwd, p);
104
147
  }
148
+
149
+ /**
150
+ * Structural (key-order-independent) deep equality. Used by the
151
+ * cross-owner collision check in `skill-contracts.ts` (later
152
+ * `skill-contracts/registry.ts`) so two semantically-identical contracts
153
+ * built by different code paths (or with different YAML key order) don't
154
+ * read as divergent — `JSON.stringify` is insertion-order dependent and
155
+ * would raise a spurious collision warning. Contracts are plain JSON data
156
+ * (no functions/symbols/Dates), so a recursive value compare is sufficient
157
+ * and total.
158
+ */
159
+ export function deepEqual(a: unknown, b: unknown): boolean {
160
+ if (a === b) return true;
161
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
162
+ const aArr = Array.isArray(a);
163
+ const bArr = Array.isArray(b);
164
+ if (aArr !== bArr) return false;
165
+ if (aArr && bArr) {
166
+ if (a.length !== b.length) return false;
167
+ return a.every((x, i) => deepEqual(x, b[i]));
168
+ }
169
+ const aObj = a as Record<string, unknown>;
170
+ const bObj = b as Record<string, unknown>;
171
+ const aKeys = Object.keys(aObj);
172
+ const bKeys = Object.keys(bObj);
173
+ if (aKeys.length !== bKeys.length) return false;
174
+ return aKeys.every((k) => Object.hasOwn(bObj, k) && deepEqual(aObj[k], bObj[k]));
175
+ }
package/internal.ts CHANGED
@@ -4,8 +4,8 @@
4
4
  * Exports below are NOT part of the package's authoring or embedding
5
5
  * contract. They exist solely for:
6
6
  *
7
- * - rpiv-pi's `[I3]` regression test that exercises `recordStage`
8
- * directly (asserting the JSONL append + stageNumber monotonicity).
7
+ * - rpiv-pi's regression test that exercises `recordStage` directly
8
+ * (asserting the JSONL append + stageNumber monotonicity).
9
9
  * - `test/setup.ts`'s per-worker `beforeEach` reset of module-level
10
10
  * singleton state (the built-in workflow registry, the jiti import
11
11
  * cache).
@@ -25,3 +25,10 @@ export { recordStage } from "./audit.js";
25
25
  export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins.js";
26
26
  export { __resetLifecycleRegistry } from "./lifecycle.js";
27
27
  export { __resetLoadCache } from "./load/cache.js";
28
+ export {
29
+ __resetSkillContracts,
30
+ flushSkillContractProviders,
31
+ getCompositionComparators,
32
+ getSkillContracts,
33
+ harvestStageContracts,
34
+ } from "./skill-contracts/index.js";
package/iterate.ts CHANGED
@@ -129,6 +129,7 @@ export async function runIterate(
129
129
  lifecycle: run.lifecycle,
130
130
  runIdentity: runIdentityOf(run),
131
131
  stage: def,
132
+ skillContracts: run.skillContracts,
132
133
  stageIndex: stageIdx,
133
134
  snapshot,
134
135
  branchOffset: undefined,
package/json-schema.ts ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Raw-JSON-Schema ↔ Standard Schema bridge + introspection helpers.
3
+ *
4
+ * Makes schemas inspectable AS DATA, not just executable validators. Two
5
+ * directions:
6
+ *
7
+ * - `jsonSchemaToStandard(schema)` wraps a plain JSON-Schema-shaped object
8
+ * (a skill's frontmatter `consumes.data` / `produces.data`) into a Standard
9
+ * Schema v1 backed by TypeBox `Value.Check` — droppable into the same
10
+ * `~standard.validate` seam `validate-output.ts` consumes, AND carrying the
11
+ * spec `jsonSchema` Converter so the captured schema round-trips back out.
12
+ * - `hasJsonSchema(schema)` / `extractJsonSchema(schema, target?)` feature-detect
13
+ * and pull the JSON Schema off ANY `~standard` value (TypeBox- or raw-wrapped).
14
+ * The edge-compat checker uses them; opaque schemas (Zod/Valibot without
15
+ * the Converter) degrade to `undefined` and the caller skips + warns.
16
+ *
17
+ * No new dependency: `typebox@1.1.39` is keyword-driven, so `Value.Check`
18
+ * validates a raw JSON Schema object with zero normalization.
19
+ */
20
+
21
+ import type { StandardJSONSchemaV1, StandardSchemaV1 } from "@standard-schema/spec";
22
+ import type { TSchema } from "typebox";
23
+ import { Value } from "typebox/value";
24
+
25
+ /** A JSON-Schema-shaped object — the canonical contract data format. */
26
+ export type JsonSchemaObject = Record<string, unknown>;
27
+
28
+ /**
29
+ * Runtime guard that a value is a plain (non-null, non-array) object — the
30
+ * minimum shape a JSON Schema must have. The framework treats INJECTED contracts
31
+ * as untrusted: any caller that feeds a `consumes.data` / `produces.data` into
32
+ * the keyword engine guards with this first, so a malformed contract (a string /
33
+ * array / null where a schema was expected) DEGRADES instead of throwing into a
34
+ * load or a run.
35
+ */
36
+ export function isJsonSchemaObject(value: unknown): value is JsonSchemaObject {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+
40
+ /**
41
+ * The intersection a `~standard` value carries when it exposes its JSON Schema
42
+ * as data: the validate surface (`StandardSchemaV1`) PLUS the introspection
43
+ * Converter (`StandardJSONSchemaV1`). `typeboxSchema` and `jsonSchemaToStandard`
44
+ * both return this; third-party schemas (Zod/Valibot) satisfy only the former.
45
+ */
46
+ export type JsonSchemaCapable<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &
47
+ StandardJSONSchemaV1<Input, Output>;
48
+
49
+ /** Targets whose dialect our structural subset serialises to identically. */
50
+ const SUPPORTED_TARGETS = new Set<string>(["draft-2020-12", "draft-07"]);
51
+
52
+ /**
53
+ * Build the spec-conformant `jsonSchema` Converter for a captured schema. The
54
+ * captured value is already a clean JSON Schema (TypeBox v1 schemas have zero
55
+ * symbol keys; frontmatter schemas are plain objects), so `input`/`output` both
56
+ * return it — validation-only schemas have no input≠output transform. Supports
57
+ * `draft-2020-12` + `draft-07` (the spec's strongly-recommended pair), identical
58
+ * over our structural subset; other targets throw per the spec.
59
+ */
60
+ export function jsonSchemaConverter(schema: JsonSchemaObject): StandardJSONSchemaV1.Converter {
61
+ const convert = (options: StandardJSONSchemaV1.Options): JsonSchemaObject => {
62
+ if (!SUPPORTED_TARGETS.has(options.target)) {
63
+ throw new Error(
64
+ `jsonSchema: unsupported target "${options.target}" (supported: ${[...SUPPORTED_TARGETS].join(", ")})`,
65
+ );
66
+ }
67
+ return schema;
68
+ };
69
+ return { input: convert, output: convert };
70
+ }
71
+
72
+ /**
73
+ * Shared `Value.Check` + `Value.Errors` → Standard Schema `Issue[]` mapping.
74
+ * Both `jsonSchemaToStandard` and `typeboxSchema` (typebox-adapter.ts) call
75
+ * this so validation failures are reported identically regardless of which
76
+ * wrapper was used. Returns `{ value }` on success, `{ issues }` on failure.
77
+ */
78
+ export function validateToJsonSchemaIssues(schema: TSchema | JsonSchemaObject, value: unknown) {
79
+ if (Value.Check(schema, value)) return { value };
80
+ const issues = [...Value.Errors(schema, value)].map((err) => ({
81
+ message: err.message || `${err.keyword} validation failed at ${err.instancePath || "root"}`,
82
+ path: err.instancePath ? err.instancePath.split("/").filter(Boolean) : undefined,
83
+ }));
84
+ return { issues };
85
+ }
86
+
87
+ /**
88
+ * Wrap a raw JSON-Schema-shaped object into a Standard Schema v1 that BOTH
89
+ * validates (via `Value.Check`) and exposes the schema as data (the Converter).
90
+ * Delegates to the shared `validateToJsonSchemaIssues` helper so both this
91
+ * wrapper and `typeboxSchema` report failures identically by construction.
92
+ */
93
+ export function jsonSchemaToStandard(schema: JsonSchemaObject): JsonSchemaCapable {
94
+ return {
95
+ "~standard": {
96
+ version: 1,
97
+ vendor: "rpiv-json-schema",
98
+ validate: (value: unknown) => validateToJsonSchemaIssues(schema, value),
99
+ jsonSchema: jsonSchemaConverter(schema),
100
+ },
101
+ };
102
+ }
103
+
104
+ /**
105
+ * True when a `~standard` value exposes its JSON Schema as data (carries the
106
+ * `jsonSchema` Converter). TypeBox- and raw-wrapped schemas pass; Zod/Valibot/
107
+ * ArkType schemas — which implement only `~standard.validate` — do not.
108
+ */
109
+ export function hasJsonSchema(schema: StandardSchemaV1 | undefined): schema is JsonSchemaCapable {
110
+ if (!schema) return false;
111
+ const std = (schema as Partial<JsonSchemaCapable>)["~standard"] as Partial<StandardJSONSchemaV1.Props> | undefined;
112
+ return typeof std?.jsonSchema?.output === "function";
113
+ }
114
+
115
+ /**
116
+ * Pull the JSON Schema back off a `~standard` value as data, or `undefined`
117
+ * when the schema is opaque (no Converter) or the Converter throws for the
118
+ * requested target. The edge-compat checker calls this and skips + warns
119
+ * on `undefined`. Defaults to `draft-2020-12` — the TypeBox-native dialect.
120
+ */
121
+ export function extractJsonSchema(
122
+ schema: StandardSchemaV1 | undefined,
123
+ target: StandardJSONSchemaV1.Target = "draft-2020-12",
124
+ ): JsonSchemaObject | undefined {
125
+ if (!hasJsonSchema(schema)) return undefined;
126
+ try {
127
+ return schema["~standard"].jsonSchema.output({ target });
128
+ } catch {
129
+ return undefined;
130
+ }
131
+ }
package/load/alias.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * Declarative skill-name remapping, applied once at load time.
3
3
  *
4
4
  * `aliasSkills(w, aliases)` rewrites every dispatching stage whose effective
5
- * skill (`stage.skill ?? stageName`) has an alias entry, materialising the
5
+ * skill (resolved via `resolveSkill(stage, stageName)`) has an alias entry, materialising the
6
6
  * `skill` field on stages that relied on the stage-key default. Because the
7
7
  * remap happens in the loader — before validation and before the runner ever
8
8
  * sees the workflow — `/wf` preview, JSONL audit, and the runtime
@@ -21,6 +21,7 @@
21
21
  */
22
22
 
23
23
  import type { StageDef, Workflow } from "../api.js";
24
+ import { resolveSkill } from "../internal-utils.js";
24
25
  import type { LayerOutcome, LoadAccumulator } from "./merge.js";
25
26
 
26
27
  /**
@@ -40,7 +41,7 @@ export function aliasSkills(w: Workflow, aliases: Record<string, string>): Workf
40
41
  const stages: typeof w.stages = {};
41
42
  for (const [name, stage] of Object.entries(w.stages)) {
42
43
  const dispatches = isDispatchingStage(stage); // only /skill: stages
43
- const effective = stage.skill ?? name;
44
+ const effective = resolveSkill(stage, name);
44
45
  const target = aliases[effective];
45
46
  if (dispatches && target && target !== effective) {
46
47
  stages[name] = { ...stage, skill: target }; // materialise implicit skill
@@ -88,7 +89,7 @@ export function applySkillAliases(
88
89
  const dispatchedBefore = new Set<string>();
89
90
  for (const w of acc.workflowMap.values()) {
90
91
  for (const [stageName, stage] of Object.entries(w.stages)) {
91
- if (isDispatchingStage(stage)) dispatchedBefore.add(stage.skill ?? stageName);
92
+ if (isDispatchingStage(stage)) dispatchedBefore.add(resolveSkill(stage, stageName));
92
93
  }
93
94
  }
94
95
  for (const [name, w] of acc.workflowMap) acc.workflowMap.set(name, aliasSkills(w, merged));
package/load/index.ts CHANGED
@@ -56,6 +56,14 @@ import type { Workflow } from "../api.js";
56
56
  import { flushBuiltInProviders, getBuiltIns } from "../built-ins.js";
57
57
  import type { ConfigLayer } from "../layers.js";
58
58
  import { LEGACY_OVERLAY_NOTICE, LEGACY_RUNS_NOTICE, LEGACY_USER_CONFIG_NOTICE } from "../messages.js";
59
+ import type { SkillContractMap } from "../skill-contract.js";
60
+ import {
61
+ buildEffectiveContracts,
62
+ drainSkillContractCollisions,
63
+ drainSkillContractProviderErrors,
64
+ flushSkillContractProviders,
65
+ getOutcomeDerivers,
66
+ } from "../skill-contracts/index.js";
59
67
  import { validateWorkflow, type WorkflowValidationIssue } from "../validate-workflow.js";
60
68
  import { applySkillAliases } from "./alias.js";
61
69
  import { type LoadAccumulator, loadLayer } from "./merge.js";
@@ -103,6 +111,12 @@ export interface LoadedWorkflows {
103
111
  * the remap.
104
112
  */
105
113
  skillAliases: Readonly<Record<string, string>>;
114
+ /**
115
+ * Effective skill-contract registry: injected `declared` contracts merged
116
+ * OVER `harvested` ones (derived from stage usage). Required field, empty
117
+ * `Map` when no contract was declared or harvestable.
118
+ */
119
+ skillContracts: SkillContractMap;
106
120
  }
107
121
 
108
122
  // ===========================================================================
@@ -132,6 +146,11 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
132
146
  // defer constructing definitions to first `/wf` (the earliest reader).
133
147
  await flushBuiltInProviders();
134
148
 
149
+ // Flush skill-contract providers beside the built-in flush. Same provider+flush
150
+ // idiom; contract providers read the filesystem / parse frontmatter (failure-prone),
151
+ // so each throw is recorded (drained below) rather than propagated.
152
+ await flushSkillContractProviders();
153
+
135
154
  const acc: LoadAccumulator = {
136
155
  issues: [],
137
156
  workflowMap: new Map(),
@@ -140,6 +159,22 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
140
159
  };
141
160
  const layers: ConfigLayer[] = getBuiltIns().length > 0 ? ["built-in"] : [];
142
161
 
162
+ // Surface any provider failure as a LoadIssue rather than swallowing it —
163
+ // loader still never throws, but a buggy provider is now visible in loaded.issues.
164
+ for (const err of drainSkillContractProviderErrors()) {
165
+ acc.issues.push({
166
+ kind: "load",
167
+ layer: "built-in",
168
+ message: `skill-contract provider failed: ${err instanceof Error ? err.message : String(err)}`,
169
+ severity: "warning",
170
+ });
171
+ }
172
+ // Surface cross-owner contract collisions — last-writer still wins, but the
173
+ // divergence is no longer silent.
174
+ for (const message of drainSkillContractCollisions()) {
175
+ acc.issues.push({ kind: "load", layer: "built-in", message, severity: "warning" });
176
+ }
177
+
143
178
  for (const w of getBuiltIns()) {
144
179
  acc.workflowMap.set(w.name, w);
145
180
  acc.sources.set(w.name, "built-in");
@@ -168,6 +203,30 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
168
203
  // declared the key — see `applySkillAliases` in `./alias.ts`.
169
204
  const skillAliases = applySkillAliases(acc, userOutcome, projectOutcome);
170
205
 
206
+ // Build the effective registry BEFORE the validation loop, so checkEdgeSchemaCompat
207
+ // sees it. Returns a NEW map (harvested gap-fill first, declared overriding
208
+ // per skill) — never mutates the shared global registry.
209
+ const skillContracts = buildEffectiveContracts([...acc.workflowMap.values()]);
210
+
211
+ // Invoke registered outcome derivers (e.g. rpiv-pi's BUCKET_BY_KIND resolver)
212
+ // so `produces` stages that don't declare an explicit `outcome` get one wired
213
+ // from the contract registry before validation checks
214
+ // `produces-without-outcome`.
215
+ for (const deriver of getOutcomeDerivers()) {
216
+ try {
217
+ deriver(acc.workflowMap.values(), skillContracts, (message, severity) => {
218
+ acc.issues.push({ kind: "load", layer: "built-in", severity, message });
219
+ });
220
+ } catch (err) {
221
+ acc.issues.push({
222
+ kind: "load",
223
+ layer: "built-in",
224
+ severity: "error",
225
+ message: `outcome deriver failed: ${err instanceof Error ? err.message : String(err)}`,
226
+ });
227
+ }
228
+ }
229
+
171
230
  // Validate every merged workflow once. Validation runs even on built-in so
172
231
  // that a future built-in regression surfaces in the same channel as user
173
232
  // errors. Each issue is attributed to the exact file the surviving workflow
@@ -176,7 +235,8 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
176
235
  for (const w of acc.workflowMap.values()) {
177
236
  const layer = acc.sources.get(w.name) ?? "built-in";
178
237
  const path = acc.sourcePaths.get(w.name);
179
- for (const v of validateWorkflow(w)) acc.issues.push({ ...v, kind: "validation", layer, path });
238
+ for (const v of validateWorkflow(w, { skillContracts }))
239
+ acc.issues.push({ ...v, kind: "validation", layer, path });
180
240
  }
181
241
 
182
242
  const defaultName = resolveDefault(projectOutcome.configDefault, userOutcome.configDefault, acc);
@@ -188,6 +248,7 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
188
248
  layers,
189
249
  issues: acc.issues,
190
250
  skillAliases,
251
+ skillContracts,
191
252
  };
192
253
  }
193
254