@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/types.ts CHANGED
@@ -27,6 +27,7 @@ import type { Artifact } from "./handle.js";
27
27
  import type { WorkflowHost, WorkflowHostContext } from "./host.js";
28
28
  import type { LifecycleDispatcher } from "./lifecycle.js";
29
29
  import type { Output } from "./output.js";
30
+ import type { SkillContractMap } from "./skill-contract.js";
30
31
  import type { RunTrigger } from "./triggers.js";
31
32
 
32
33
  // Re-export the host port so runtime layers can pull `RunContext`,
@@ -128,6 +129,22 @@ export interface RunContext {
128
129
  * fail-soft posture as the rest of the host-optional surface).
129
130
  */
130
131
  registeredSkills?: ReadonlySet<string>;
132
+ /**
133
+ * Snapshot of the declared/injected skill-contract registry, taken once in
134
+ * `buildRunContext` (mirrors `registeredSkills`). This is the
135
+ * declared/injected registry — NOT the harvested-merged
136
+ * `LoadedWorkflows.skillContracts` — because both runtime uses only add
137
+ * value over a declared contract:
138
+ * - `ensureContractInputValid` mirrors a declared `consumes.data` that
139
+ * lacks a stage `inputSchema` (a harvested `consumes.data` is the
140
+ * stage's own `inputSchema` re-derived, already covered by
141
+ * `ensureInputValid`);
142
+ * - `effectiveOutputSchema` (threaded onto `StageSession`) sources a
143
+ * declared `produces.data` as the output schema when the stage carries
144
+ * no `outputSchema` of its own.
145
+ * Fail-soft: both degrade (no validation, never throw) when absent.
146
+ */
147
+ skillContracts?: SkillContractMap;
131
148
  /**
132
149
  * Pi `ExtensionAPI` handle, retained as the FALLBACK send-path for
133
150
  * continue-policy stages — used only when the live inner ctx lacks
@@ -209,6 +226,14 @@ export interface SessionContext {
209
226
 
210
227
  export interface StageSession extends SessionContext {
211
228
  stage: StageDef;
229
+ /**
230
+ * Declared/injected skill-contract registry, threaded from
231
+ * `RunContext.skillContracts` at session construction. Lets output
232
+ * validation fall back to the dispatched skill's `produces.data` when the
233
+ * stage carries no `outputSchema` of its own. Fail-soft: absent for
234
+ * programmatic embedders that opt out of contract registration.
235
+ */
236
+ skillContracts?: SkillContractMap;
212
237
  /** 0-based stage index within this run — for status display + JSONL stage number. */
213
238
  stageIndex: number;
214
239
  /** Pre-stage snapshot value (undefined if the stage's `outcome` has no `snapshot`). */
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import type { StageSchema } from "./api.js";
9
+ import { extractJsonSchema, isJsonSchemaObject, type JsonSchemaObject } from "./json-schema.js";
9
10
 
10
11
  // ---------------------------------------------------------------------------
11
12
  // Types
@@ -19,6 +20,17 @@ export interface SchemaValidationFailure {
19
20
  /** typeof / "array" / "null" / "undefined" of the offending value. */
20
21
  actual: string;
21
22
  message: string;
23
+ /**
24
+ * The actual offending value at `path`, resolved from the input data.
25
+ * `undefined` when the field is absent (e.g. a missing required property).
26
+ */
27
+ value?: unknown;
28
+ /**
29
+ * The values the schema permits at `path` (`enum`, or a single-element list
30
+ * for `const`), recovered from the JSON-Schema-as-data when the schema is
31
+ * introspectable. `undefined` for non-enum constraints or opaque schemas.
32
+ */
33
+ allowed?: readonly unknown[];
22
34
  }
23
35
 
24
36
  export interface ValidationResult {
@@ -54,9 +66,9 @@ export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
54
66
  export function validateOutputData(schema: StageSchema, data: unknown): ValidationResult | Promise<ValidationResult> {
55
67
  const result = schema["~standard"].validate(data);
56
68
  if (result instanceof Promise) {
57
- return result.then((resolved) => buildResult(resolved, data));
69
+ return result.then((resolved) => buildResult(resolved, data, schema));
58
70
  }
59
- return buildResult(result, data);
71
+ return buildResult(result, data, schema);
60
72
  }
61
73
 
62
74
  function buildResult(
@@ -67,17 +79,26 @@ function buildResult(
67
79
  }[];
68
80
  },
69
81
  data: unknown,
82
+ schema: StageSchema,
70
83
  ): ValidationResult {
71
84
  if (!result.issues) {
72
85
  return { valid: true, failures: [] };
73
86
  }
87
+ // Recover the schema AS DATA once (validator-agnostic; `undefined` for opaque
88
+ // schemas) so each failure can name the values it actually permits.
89
+ const rootSchema = extractJsonSchema(schema);
74
90
  const failures: SchemaValidationFailure[] = result.issues.map((issue) => {
75
91
  const path = issue.path ? formatStandardPath(issue.path) : ".";
92
+ const value = resolveInstanceValue(data, path);
93
+ const node = rootSchema ? resolveSchemaNode(rootSchema, path) : undefined;
94
+ const allowed = node ? allowedValues(node) : undefined;
76
95
  return {
77
96
  path,
78
- expected: "schema",
79
- actual: describeType(resolveInstanceValue(data, path)),
97
+ expected: node ? schemaKeyword(node) : "schema",
98
+ actual: describeType(value),
80
99
  message: issue.message,
100
+ value,
101
+ ...(allowed ? { allowed } : {}),
81
102
  };
82
103
  });
83
104
  return { valid: false, failures };
@@ -108,10 +129,86 @@ function resolveInstanceValue(data: unknown, instancePath: string): unknown {
108
129
  return cur;
109
130
  }
110
131
 
132
+ // ---------------------------------------------------------------------------
133
+ // Failure formatting
134
+ // ---------------------------------------------------------------------------
135
+
136
+ /**
137
+ * Render a failure as one actionable line: the field, the constraint it
138
+ * violated, and — when recoverable — the values the schema allows and the
139
+ * value the data actually carried. Falls back to the raw validator message
140
+ * when the schema is opaque (Zod/Valibot without a Converter) or the failure
141
+ * isn't an enum/const mismatch.
142
+ *
143
+ * status: must be one of "in-progress", "in-review", "ready" — got "done"
144
+ * phase_count: must be an integer — got "3"
145
+ * status: must have required property (field missing)
146
+ */
147
+ export function describeFailure(f: SchemaValidationFailure): string {
148
+ const field = f.path === "." ? "(root)" : f.path.replace(/^\//, "").replace(/\//g, ".");
149
+ if (f.allowed && f.allowed.length > 0) {
150
+ const allowed = f.allowed.map((v) => JSON.stringify(v)).join(", ");
151
+ const got = f.value === undefined ? "(field missing)" : `got ${JSON.stringify(f.value)}`;
152
+ return `${field}: must be one of ${allowed} — ${got}`;
153
+ }
154
+ // Non-enum failure: keep the validator's own message, append the offending
155
+ // value only when it's a primitive (an object/array dump adds noise, and a
156
+ // `required` failure resolves to the whole parent object).
157
+ const got = isPrimitive(f.value) ? ` — got ${JSON.stringify(f.value)}` : "";
158
+ return `${field}: ${f.message}${got}`;
159
+ }
160
+
161
+ function isPrimitive(value: unknown): boolean {
162
+ return value === null || (typeof value !== "object" && typeof value !== "undefined" && typeof value !== "function");
163
+ }
164
+
111
165
  // ---------------------------------------------------------------------------
112
166
  // Helpers
113
167
  // ---------------------------------------------------------------------------
114
168
 
169
+ /**
170
+ * Walk a JSON Schema by an instance path (`/status`, `/phases/0/n`) to the
171
+ * sub-schema that governs the offending value. Handles the shapes a frontmatter
172
+ * contract uses — object `properties` and array `items` (single-schema, not
173
+ * tuple) — and degrades to `undefined` on `$ref`/`anyOf`/`allOf` or any segment
174
+ * it can't follow, so an unrecoverable node simply yields no enum enrichment.
175
+ */
176
+ function resolveSchemaNode(root: JsonSchemaObject, path: string): JsonSchemaObject | undefined {
177
+ if (path === "." || path === "") return root;
178
+ let node: JsonSchemaObject | undefined = root;
179
+ for (const seg of path.split("/").filter(Boolean)) {
180
+ if (!node) return undefined;
181
+ const props: unknown = node.properties;
182
+ if (isJsonSchemaObject(props) && isJsonSchemaObject(props[seg])) {
183
+ node = props[seg];
184
+ continue;
185
+ }
186
+ // Array index → the `items` schema (single-schema form only).
187
+ if (/^\d+$/.test(seg) && isJsonSchemaObject(node.items)) {
188
+ node = node.items;
189
+ continue;
190
+ }
191
+ return undefined;
192
+ }
193
+ return node;
194
+ }
195
+
196
+ /** The values a schema node permits: its `enum`, or `[const]` for a const node. */
197
+ function allowedValues(node: JsonSchemaObject): readonly unknown[] | undefined {
198
+ if (Array.isArray(node.enum)) return node.enum;
199
+ if ("const" in node) return [node.const];
200
+ return undefined;
201
+ }
202
+
203
+ /** A short keyword for the `expected` field — the node's `type`, or `enum`/`const`. */
204
+ function schemaKeyword(node: JsonSchemaObject): string {
205
+ if (Array.isArray(node.enum)) return "enum";
206
+ if ("const" in node) return "const";
207
+ if (typeof node.type === "string") return node.type;
208
+ if (Array.isArray(node.type)) return node.type.join("|");
209
+ return "schema";
210
+ }
211
+
115
212
  function describeType(value: unknown): string {
116
213
  if (value === null) return "null";
117
214
  if (value === undefined) return "undefined";
@@ -12,6 +12,12 @@
12
12
  * to halt on any error and surface warnings non-fatally.
13
13
  *
14
14
  * No I/O, no throws — purely a graph walk + predicate probe.
15
+ *
16
+ * Enforcement layers (where each contract channel is adjudicated):
17
+ * - reads / wiring → LOAD-TIME, complete (`checkReadsChannelCompat`, all
18
+ * publishers, errors on signed mismatch — all stage kinds).
19
+ * - linear `data` + `status` → RUNTIME (`ensureContractInputValid`).
20
+ * - produces self-check → PRODUCE-TIME (`extraction.ts:effectiveOutputSchema`).
15
21
  */
16
22
 
17
23
  import {
@@ -24,7 +30,13 @@ import {
24
30
  type StageDef,
25
31
  type Workflow,
26
32
  } from "./api.js";
33
+ import { fanoutSpecOf, iterateSpecOf } from "./control-flow.js";
34
+ import { resolvePublishName, resolveSkill } from "./internal-utils.js";
35
+ import { extractJsonSchema } from "./json-schema.js";
27
36
  import type { ConfigLayer } from "./layers.js";
37
+ import { isSchemaCompatible } from "./schema-compat.js";
38
+ import type { ProducesSpec, SkillContractMap } from "./skill-contract.js";
39
+ import { getCompositionComparators } from "./skill-contracts/index.js";
28
40
  import {
29
41
  MAX_VALIDATION_RETRIES,
30
42
  MAX_VALIDATION_RETRY_TIMEOUT_MS,
@@ -59,7 +71,10 @@ export interface WorkflowValidationIssue {
59
71
  * Validate one workflow. Aggregates all issues; never short-circuits. Caller
60
72
  * decides what's fatal — `severity === "error"` is the runner-blocking set.
61
73
  */
62
- export function validateWorkflow(workflow: Workflow): WorkflowValidationIssue[] {
74
+ export function validateWorkflow(
75
+ workflow: Workflow,
76
+ opts?: { skillContracts?: SkillContractMap },
77
+ ): WorkflowValidationIssue[] {
63
78
  const issues: WorkflowValidationIssue[] = [];
64
79
 
65
80
  checkWorkflowName(workflow, issues);
@@ -77,8 +92,11 @@ export function validateWorkflow(workflow: Workflow): WorkflowValidationIssue[]
77
92
  const hasUnenumerableEdge = issues.some((i) => /\.targets` metadata/.test(i.message));
78
93
  if (!hasUnenumerableEdge) checkReachability(workflow, issues);
79
94
  checkStageSemantics(workflow, issues);
80
- checkPredicateSchemas(workflow, issues);
95
+ checkPredicateSchemas(workflow, issues, opts?.skillContracts);
81
96
  checkReadsReferences(workflow, issues);
97
+ checkFanoutSource(workflow, issues);
98
+ checkEdgeSchemaCompat(workflow, issues, opts?.skillContracts);
99
+ checkReadsChannelCompat(workflow, issues, opts?.skillContracts);
82
100
 
83
101
  return issues;
84
102
  }
@@ -333,7 +351,7 @@ function checkIterateInvariants(w: Workflow, name: string, stage: StageDef, issu
333
351
  * skill or sending raw text — `skill` defaulting to the record key does
334
352
  * NOT trip this, only an explicitly-set `skill`);
335
353
  * - mutually exclusive with `fanout`/`iterate` in v1 (chat fan-out is a
336
- * deferred composition — see the design's §3 non-goals);
354
+ * deferred composition);
337
355
  * - mutually exclusive with `reads` — a skill stage's `reads` auto-builds a
338
356
  * labelled-flag arg, but a prompt stage's text is author-owned; rather than
339
357
  * give `reads` two meanings, require the prompt to read `state.named`
@@ -534,6 +552,41 @@ function checkReadsReferences(w: Workflow, issues: WorkflowValidationIssue[]): v
534
552
  }
535
553
  }
536
554
 
555
+ /**
556
+ * Load-time fanout/iterate source check (Phase 3 — control-flow as data). A stage
557
+ * whose `fanout`/`iterate` carries a declarative `.spec` (via `fanoutOver`/
558
+ * `iterateOver`) with a `source` channel must have that channel published by some
559
+ * `produces` stage in this workflow — otherwise the stage splits over a channel
560
+ * nothing fills. Same publisher model as `checkReadsReferences`
561
+ * (`stage.outcome?.name ?? <record-key>`).
562
+ *
563
+ * WARNS (never errors): `source` is an introspective hint, and a raw/opaque fanout
564
+ * (no `.spec`) or a spec without `source` degrades silently — mirrors the
565
+ * edge-compat posture. When the source is already in the stage's `reads`,
566
+ * `checkReadsReferences` owns it (errors) — skip to avoid double-reporting. The
567
+ * additive value is the `iterate`/closure-sourced case, which declares no `reads:`
568
+ * and is otherwise unchecked.
569
+ */
570
+ function checkFanoutSource(w: Workflow, issues: WorkflowValidationIssue[]): void {
571
+ const published = new Set<string>();
572
+ for (const [name, stage] of Object.entries(w.stages)) {
573
+ if (stage.kind === "produces") published.add(stage.outcome?.name ?? name);
574
+ }
575
+ for (const [name, stage] of Object.entries(w.stages)) {
576
+ const spec = fanoutSpecOf(stage.fanout) ?? iterateSpecOf(stage.iterate);
577
+ const source = spec?.source;
578
+ if (!source || published.has(source)) continue; // opaque / no source / satisfied → degrade
579
+ if (stage.reads?.includes(source)) continue; // checkReadsReferences owns this channel
580
+ issues.push(
581
+ warning(
582
+ w.name,
583
+ name,
584
+ `stage "${name}" ${spec.kind === "fanout" ? "fans out" : "iterates"} over source "${source}" but no produces stage in this workflow publishes it`,
585
+ ),
586
+ );
587
+ }
588
+ }
589
+
537
590
  /**
538
591
  * Route edges that read `output.data[field]` (i.e. `defineRoute(...)` with
539
592
  * the default `readsData: true`, `gate(...)`, and any future factory that
@@ -542,23 +595,137 @@ function checkReadsReferences(w: Workflow, issues: WorkflowValidationIssue[]): v
542
595
  * the validation-retry loop never runs and the route may read an undefined
543
596
  * field — routing decisions silently default.
544
597
  *
598
+ * A stage carrying no `outputSchema` is still covered when its dispatched
599
+ * skill declares a contract `produces.data` — output validation sources that
600
+ * schema at runtime (`effectiveOutputSchema` in extraction.ts), so the route
601
+ * fires on validated data. Such stages are exempt from this lint.
602
+ *
545
603
  * Routes authored via `defineRoute(targets, fn, { readsData: false })`
546
604
  * consult only `state` or `output.meta` and carry no marker — exempt from
547
605
  * this lint.
548
606
  */
549
- function checkPredicateSchemas(w: Workflow, issues: WorkflowValidationIssue[]): void {
607
+ function checkPredicateSchemas(
608
+ w: Workflow,
609
+ issues: WorkflowValidationIssue[],
610
+ skillContracts: SkillContractMap | undefined,
611
+ ): void {
550
612
  for (const [from, target] of Object.entries(w.edges)) {
551
613
  if (typeof target === "string") continue;
552
614
  if (!marksReadsData(target)) continue;
553
615
  const stage = w.stages[from];
554
- if (stage && !stage.outputSchema) {
555
- issues.push(
556
- warning(
557
- w.name,
558
- from,
559
- `route edge from "${from}" reads output.data but the stage has no outputSchema — routing may fire on un-validated data`,
560
- ),
561
- );
616
+ if (!stage || stage.outputSchema) continue;
617
+ // Contract-sourced output schema covers the stage like its own `outputSchema`
618
+ // would — mirror `effectiveOutputSchema`'s fallback (same `resolveSkill` key).
619
+ const contractData = skillContracts?.get(resolveSkill(stage, from))?.produces?.data;
620
+ if (contractData) continue;
621
+ issues.push(
622
+ warning(
623
+ w.name,
624
+ from,
625
+ `route edge from "${from}" reads output.data but the stage has no outputSchema — routing may fire on un-validated data`,
626
+ ),
627
+ );
628
+ }
629
+ }
630
+
631
+ /**
632
+ * Load-time compat for the LINEAR `data` channel: for each string edge from→to,
633
+ * compare the producer's `produces.data` to the consumer's `consumes.data`
634
+ * (registry-sourced, falling back to the stage's own output/input schema). Warns
635
+ * on a definite mismatch; degrades on predicate/STOP edges and opaque schemas.
636
+ *
637
+ * Edge-local is correct here — the rolling primary flows along edges. The
638
+ * many-to-one NAMED (`reads`) channel is handled by `checkReadsChannelCompat`.
639
+ * Runtime mirror: `ensureContractInputValid`.
640
+ */
641
+ function checkEdgeSchemaCompat(
642
+ w: Workflow,
643
+ issues: WorkflowValidationIssue[],
644
+ skillContracts: SkillContractMap | undefined,
645
+ ): void {
646
+ for (const [from, target] of Object.entries(w.edges)) {
647
+ if (typeof target !== "string" || target === STOP) continue; // degrade on predicate/STOP edges
648
+ const fromStage = w.stages[from];
649
+ const toStage = w.stages[target];
650
+ if (!fromStage || !toStage) continue; // unknown stages already reported by edge-target checks
651
+ const producerContract = skillContracts?.get(resolveSkill(fromStage, from));
652
+ const consumerContract = skillContracts?.get(resolveSkill(toStage, target));
653
+
654
+ const producer = producerContract?.produces?.data ?? extractJsonSchema(fromStage.outputSchema);
655
+ const consumer = consumerContract?.consumes?.data ?? extractJsonSchema(toStage.inputSchema);
656
+ if (producer && consumer) {
657
+ const compat = isSchemaCompatible(producer, consumer);
658
+ if (!compat.ok) {
659
+ issues.push(
660
+ warning(w.name, from, `edge "${from}" → "${target}": schema incompatibility — ${compat.reason}`),
661
+ );
662
+ }
663
+ }
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Load-time named-channel (`reads`) compat — the COMPLETE authoring gate for
669
+ * `reads:` wiring. For each consumer with `consumes.reads`, adjudicate
670
+ * against EVERY `produces` stage that publishes the channel
671
+ * (`resolvePublishName === channel`), not just the edge predecessor — named
672
+ * channels are many-to-one (loop-backs, non-adjacent producers). The publisher
673
+ * set is statically computable.
674
+ *
675
+ * ERRORS on a clean comparator incompatibility between two SIGNED contracts —
676
+ * the "mechanically reject invalid wirings" guarantee, uniform across all stage
677
+ * kinds, which is why no runtime reads gate is needed. Degrades (never errors)
678
+ * when either side is unsigned, no comparator is registered, the channel isn't
679
+ * declared, or the comparator throws. "No publisher at all" is
680
+ * `checkReadsReferences`'s job, not this one's.
681
+ */
682
+ function checkReadsChannelCompat(
683
+ w: Workflow,
684
+ issues: WorkflowValidationIssue[],
685
+ skillContracts: SkillContractMap | undefined,
686
+ ): void {
687
+ if (!skillContracts) return;
688
+ const comparators = getCompositionComparators();
689
+ if (comparators.size === 0) return; // no adjudicators registered
690
+
691
+ // Index signed publishers by channel. `kind === "produces"` mirrors the
692
+ // runtime publish rule (`applyCompletedStage`).
693
+ const publishersByChannel = new Map<string, Array<{ stage: string; produces: ProducesSpec }>>();
694
+ for (const [name, stage] of Object.entries(w.stages)) {
695
+ if (stage.kind !== "produces") continue;
696
+ const produces = skillContracts.get(resolveSkill(stage, name))?.produces;
697
+ if (!produces) continue; // unsigned producer — degrade
698
+ const channel = resolvePublishName(stage, name);
699
+ const list = publishersByChannel.get(channel);
700
+ if (list) list.push({ stage: name, produces });
701
+ else publishersByChannel.set(channel, [{ stage: name, produces }]);
702
+ }
703
+
704
+ for (const [consumerName, consumer] of Object.entries(w.stages)) {
705
+ if (!consumer.reads?.length) continue;
706
+ const consumes = skillContracts.get(resolveSkill(consumer, consumerName))?.consumes;
707
+ if (!consumes?.reads) continue; // unsigned consumer — degrade
708
+ for (const channel of consumer.reads) {
709
+ const comparator = comparators.get(channel);
710
+ if (!comparator || !consumes.reads[channel]) continue; // no adjudicator / undeclared channel — degrade
711
+ const publishers = publishersByChannel.get(channel);
712
+ if (!publishers) continue; // "no publisher at all" is checkReadsReferences's job
713
+ for (const { stage: producerName, produces } of publishers) {
714
+ let compat: { ok: boolean; reason?: string };
715
+ try {
716
+ compat = comparator(produces, consumes, channel);
717
+ } catch {
718
+ continue; // comparator threw — author defect, degrade
719
+ }
720
+ if (compat.ok) continue;
721
+ issues.push(
722
+ error(
723
+ w.name,
724
+ consumerName,
725
+ `stage "${consumerName}" reads channel "${channel}" but publisher "${producerName}" is incompatible — ${compat.reason ?? "named-channel meta incompatibility"}`,
726
+ ),
727
+ );
728
+ }
562
729
  }
563
730
  }
564
731
  }