@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 +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
|
@@ -13,17 +13,14 @@ import type { PromptFn, StageDef } from "../api.js";
|
|
|
13
13
|
import { auditCtxFor, notifyPartialArtifacts, recordTerminalFailure, runIdentityOf } from "../audit.js";
|
|
14
14
|
import { runFanout } from "../fanout.js";
|
|
15
15
|
import { handleToString } from "../handle.js";
|
|
16
|
-
import { currentPrimaryArtifact,
|
|
16
|
+
import { currentPrimaryArtifact, resolveSkill } from "../internal-utils.js";
|
|
17
17
|
import { runIterate } from "../iterate.js";
|
|
18
18
|
import { skillStageRef } from "../lifecycle.js";
|
|
19
19
|
import {
|
|
20
|
-
ERR_INPUT_VALIDATION_FAILED,
|
|
21
20
|
ERR_ITERATIONS_EXHAUSTED,
|
|
22
21
|
ERR_MISSING_ARTIFACT,
|
|
23
22
|
ERR_MISSING_NAMED_READ,
|
|
24
|
-
ERR_SCHEMA_TIMEOUT,
|
|
25
23
|
ERR_SKILL_NOT_REGISTERED,
|
|
26
|
-
MSG_INPUT_VALIDATION_FAILED,
|
|
27
24
|
MSG_ITERATIONS_EXHAUSTED,
|
|
28
25
|
MSG_MISSING_ARTIFACT,
|
|
29
26
|
MSG_MISSING_NAMED_READ,
|
|
@@ -35,14 +32,8 @@ import {
|
|
|
35
32
|
import { runFanoutSession, runStageSession } from "../sessions/index.js";
|
|
36
33
|
import { readBranch } from "../transcript.js";
|
|
37
34
|
import type { RunContext, WorkflowHostContext } from "../types.js";
|
|
38
|
-
import {
|
|
39
|
-
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
40
|
-
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
41
|
-
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
42
|
-
type ValidationResult,
|
|
43
|
-
validateOutputData,
|
|
44
|
-
} from "../validate-output.js";
|
|
45
35
|
import { advanceChain } from "./chain-advance.js";
|
|
36
|
+
import { ensureContractInputValid, ensureInputValid } from "./input-validation.js";
|
|
46
37
|
import { lifecycleCtxFor } from "./runner.js";
|
|
47
38
|
import { runScript } from "./script-stage.js";
|
|
48
39
|
|
|
@@ -245,6 +236,7 @@ export async function runStage(
|
|
|
245
236
|
lifecycle: run.lifecycle,
|
|
246
237
|
runIdentity: runIdentityOf(run),
|
|
247
238
|
stage: stage.def,
|
|
239
|
+
skillContracts: run.skillContracts,
|
|
248
240
|
stageIndex: idx,
|
|
249
241
|
snapshot,
|
|
250
242
|
continueHost: run.continueHost,
|
|
@@ -260,9 +252,9 @@ function resolveStage(currentName: string, idx: number, run: RunContext): Resolv
|
|
|
260
252
|
// validateWorkflow should catch this; defensive for tests bypassing validation.
|
|
261
253
|
throw new Error(`runStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
|
|
262
254
|
}
|
|
263
|
-
// `skill` defaults to the record key
|
|
264
|
-
//
|
|
265
|
-
return { def, name: currentName, stageNumber: idx + 1, skill: def
|
|
255
|
+
// `skill` defaults to the record key; `resolveSkill` is the shared derivation
|
|
256
|
+
// the load-time contract lookups also use, so runtime and load can't disagree.
|
|
257
|
+
return { def, name: currentName, stageNumber: idx + 1, skill: resolveSkill(def, currentName) };
|
|
266
258
|
}
|
|
267
259
|
|
|
268
260
|
/**
|
|
@@ -479,59 +471,6 @@ function computeBranchOffset(curCtx: WorkflowHostContext, def: StageDef): number
|
|
|
479
471
|
return readBranch(curCtx).length;
|
|
480
472
|
}
|
|
481
473
|
|
|
482
|
-
async function ensureInputValid(stage: ResolvedStage, run: RunContext): Promise<void> {
|
|
483
|
-
if (!stage.def.inputSchema || run.state.output?.data === undefined) return;
|
|
484
|
-
const timeoutMs = clampValidateTimeoutMs(stage.def.validateTimeoutMs);
|
|
485
|
-
const prevSkill = run.state.output.meta.stage || "unknown";
|
|
486
|
-
|
|
487
|
-
let result: ValidationResult;
|
|
488
|
-
try {
|
|
489
|
-
result = await withTimeout(
|
|
490
|
-
Promise.resolve(validateOutputData(stage.def.inputSchema, run.state.output.data)),
|
|
491
|
-
timeoutMs,
|
|
492
|
-
ERR_SCHEMA_TIMEOUT("inputSchema", timeoutMs),
|
|
493
|
-
);
|
|
494
|
-
} catch (e) {
|
|
495
|
-
// Async schema rejected, or schema timed out. Same fatal-extraction
|
|
496
|
-
// posture as the outputSchema seam — surface as a halt-class
|
|
497
|
-
// StagePreflightError so the row attribution and notify message
|
|
498
|
-
// match every other preflight failure.
|
|
499
|
-
const reason = e instanceof Error ? e.message : String(e);
|
|
500
|
-
throw new StagePreflightError(
|
|
501
|
-
"halt",
|
|
502
|
-
stage.skill,
|
|
503
|
-
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
504
|
-
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, reason),
|
|
505
|
-
true,
|
|
506
|
-
);
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
if (result.valid) return;
|
|
510
|
-
|
|
511
|
-
const failureSummary = result.failures.map((f) => `${f.path}: ${f.message}`).join("; ");
|
|
512
|
-
throw new StagePreflightError(
|
|
513
|
-
"halt",
|
|
514
|
-
stage.skill,
|
|
515
|
-
MSG_INPUT_VALIDATION_FAILED(stage.skill, prevSkill),
|
|
516
|
-
ERR_INPUT_VALIDATION_FAILED(stage.skill, prevSkill, failureSummary),
|
|
517
|
-
true,
|
|
518
|
-
);
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
/**
|
|
522
|
-
* Mirror of the clamp in extraction.ts:retryUntilValid. Same defense-in-depth
|
|
523
|
-
* posture: validateWorkflow rejects out-of-range values at load, but
|
|
524
|
-
* programmatic callers that embed runWorkflow can bypass it; clamping here
|
|
525
|
-
* means a misconfigured stage degrades to the spec-default behavior instead
|
|
526
|
-
* of firing a 100 ms timeout before a real I/O probe gets a chance to settle.
|
|
527
|
-
*/
|
|
528
|
-
function clampValidateTimeoutMs(raw: number | undefined): number {
|
|
529
|
-
return Math.max(
|
|
530
|
-
MIN_VALIDATION_RETRY_TIMEOUT_MS,
|
|
531
|
-
Math.min(raw ?? DEFAULT_VALIDATION_RETRY_TIMEOUT_MS, MAX_VALIDATION_RETRY_TIMEOUT_MS),
|
|
532
|
-
);
|
|
533
|
-
}
|
|
534
|
-
|
|
535
474
|
export async function captureStageSnapshot(def: StageDef, idx: number, run: RunContext): Promise<unknown> {
|
|
536
475
|
const snapshot = def.outcome?.collector.snapshot;
|
|
537
476
|
if (!snapshot) return undefined;
|
|
@@ -557,4 +496,5 @@ const PRE_PROMPT_CHECKS: readonly PreflightCheck[] = [
|
|
|
557
496
|
|
|
558
497
|
const POST_PROMPT_CHECKS: readonly PreflightCheck[] = [
|
|
559
498
|
{ name: "ensureInputValid", kind: "halt", run: ensureInputValid },
|
|
499
|
+
{ name: "ensureContractInputValid", kind: "halt", run: ensureContractInputValid },
|
|
560
500
|
];
|
package/schema-compat.ts
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conservative structural compatibility of JSON Schema producer → consumer.
|
|
3
|
+
*
|
|
4
|
+
* The bridge + introspection helpers stay in json-schema.ts; this module owns
|
|
5
|
+
* the compat engine and nothing else. The engine
|
|
6
|
+
* flags DEFINITE mismatches (no false positives) — everything else returns
|
|
7
|
+
* `{ ok: true }` (not provably incompatible).
|
|
8
|
+
*
|
|
9
|
+
* NOTE: the closed-object rule rarely fires for TypeBox/harvested schemas
|
|
10
|
+
* (`Type.Object` doesn't emit `additionalProperties: false`); it's reachable
|
|
11
|
+
* mainly for hand-authored frontmatter that explicitly closes the object. The
|
|
12
|
+
* per-field type/enum/const rules are what catch most real producer↔consumer drift.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { deepEqual } from "./internal-utils.js";
|
|
16
|
+
import type { JsonSchemaObject } from "./json-schema.js";
|
|
17
|
+
import type { SchemaCompatResult } from "./skill-contract.js";
|
|
18
|
+
|
|
19
|
+
/** The set of JSON-Schema `type`s a schema allows (string or string[]), or undefined if untyped. */
|
|
20
|
+
function typeSet(schema: JsonSchemaObject): Set<string> | undefined {
|
|
21
|
+
const t = schema.type;
|
|
22
|
+
if (typeof t === "string") return new Set([t]);
|
|
23
|
+
if (Array.isArray(t) && t.every((x) => typeof x === "string")) return new Set(t as string[]);
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Two sets share no member. */
|
|
28
|
+
function disjoint(a: ReadonlySet<unknown>, b: ReadonlySet<unknown>): boolean {
|
|
29
|
+
for (const x of a) if (b.has(x)) return false;
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `integer` is a subtype of `number` — widen so the two never read as disjoint. */
|
|
34
|
+
function widenNumeric(s: Set<string>): Set<string> {
|
|
35
|
+
return s.has("integer") ? new Set([...s, "number"]) : s;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Rule 1 — a producer that CLOSES its object (`additionalProperties: false`) and
|
|
40
|
+
* omits a field the consumer `requires` provably never emits it. `undefined` when
|
|
41
|
+
* the producer is open or emits every required field.
|
|
42
|
+
*/
|
|
43
|
+
function closedProducerOmitsRequired(
|
|
44
|
+
producer: JsonSchemaObject,
|
|
45
|
+
producerProps: Record<string, JsonSchemaObject>,
|
|
46
|
+
required: readonly string[],
|
|
47
|
+
): SchemaCompatResult | undefined {
|
|
48
|
+
if (producer.additionalProperties !== false) return undefined;
|
|
49
|
+
for (const key of required) {
|
|
50
|
+
if (!(key in producerProps)) {
|
|
51
|
+
return { ok: false, reason: `consumer requires "${key}" but producer (closed object) never emits it` };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Rule 2 — producer and consumer pin disjoint `type` sets for the shared field. */
|
|
58
|
+
function fieldTypeConflict(key: string, p: JsonSchemaObject, c: JsonSchemaObject): SchemaCompatResult | undefined {
|
|
59
|
+
const pt = typeSet(p);
|
|
60
|
+
const ct = typeSet(c);
|
|
61
|
+
if (pt && ct && disjoint(widenNumeric(pt), widenNumeric(ct))) {
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
reason: `field "${key}": producer emits ${[...pt].join("|")} but consumer expects ${[...ct].join("|")}`,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Rule 3 — producer and consumer both restrict to `enum`, and the two enums are disjoint. */
|
|
71
|
+
function fieldEnumConflict(key: string, p: JsonSchemaObject, c: JsonSchemaObject): SchemaCompatResult | undefined {
|
|
72
|
+
if (!Array.isArray(p.enum) || !Array.isArray(c.enum)) return undefined;
|
|
73
|
+
const pe = new Set(p.enum.map((v) => JSON.stringify(v)));
|
|
74
|
+
const ce = new Set(c.enum.map((v) => JSON.stringify(v)));
|
|
75
|
+
if (disjoint(pe, ce)) return { ok: false, reason: `field "${key}": producer enum is disjoint from consumer enum` };
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Rule 4 — producer and consumer both pin a `const`, and the two constants
|
|
81
|
+
* differ. Compares with `deepEqual` (key-order-independent) to match the
|
|
82
|
+
* `registerSkillContracts` collision check (registry.ts) — `JSON.stringify`
|
|
83
|
+
* is insertion-order dependent, so `{ a, b }` vs `{ b, a }` would register as
|
|
84
|
+
* identical yet read as incompatible here.
|
|
85
|
+
*/
|
|
86
|
+
function fieldConstConflict(key: string, p: JsonSchemaObject, c: JsonSchemaObject): SchemaCompatResult | undefined {
|
|
87
|
+
if ("const" in p && "const" in c && !deepEqual(p.const, c.const)) {
|
|
88
|
+
return {
|
|
89
|
+
ok: false,
|
|
90
|
+
reason: `field "${key}": producer const ${JSON.stringify(p.const)} ≠ consumer const ${JSON.stringify(c.const)}`,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Conservative structural compatibility of a producer's output schema against a
|
|
98
|
+
* consumer's input schema. Deliberately NOT a full JSON-Schema subtype engine —
|
|
99
|
+
* it only flags DEFINITE mismatches (no false positives). For each field present
|
|
100
|
+
* in BOTH `properties` it reports a conflict when:
|
|
101
|
+
* 1. their allowed `type` sets are disjoint — covers `type` arrays like
|
|
102
|
+
* `["string","null"]`, and treats `integer` as a `number` so `integer`↔
|
|
103
|
+
* `number` is never falsely flagged;
|
|
104
|
+
* 2. both restrict to an `enum` and the two enums are disjoint (by JSON value)
|
|
105
|
+
* — the producer can only emit values the consumer never accepts;
|
|
106
|
+
* 3. both pin a `const` and the two constants differ (by JSON value).
|
|
107
|
+
* Plus: a CLOSED producer object (`additionalProperties: false`) that omits a
|
|
108
|
+
* field the consumer `requires` — provably never emitted. Everything else (open
|
|
109
|
+
* producers, untyped fields, nested objects, `$ref`, oneOf/anyOf) returns
|
|
110
|
+
* `{ ok: true }` — not provably incompatible. Non-object roots aren't compared.
|
|
111
|
+
*/
|
|
112
|
+
export function isSchemaCompatible(producer: JsonSchemaObject, consumer: JsonSchemaObject): SchemaCompatResult {
|
|
113
|
+
if (producer.type !== "object" || consumer.type !== "object") {
|
|
114
|
+
// Non-object roots: compare root type when both sides declare one.
|
|
115
|
+
// Scalars like { type: "string" } vs { type: "array" } are provably
|
|
116
|
+
// incompatible; when either side omits `type`, degrade to ok (unprovable).
|
|
117
|
+
if (typeof producer.type === "string" && typeof consumer.type === "string" && producer.type !== consumer.type) {
|
|
118
|
+
return {
|
|
119
|
+
ok: false,
|
|
120
|
+
reason: `root type mismatch: producer is "${producer.type}", consumer is "${consumer.type}"`,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
return { ok: true };
|
|
124
|
+
}
|
|
125
|
+
const producerProps = (producer.properties as Record<string, JsonSchemaObject> | undefined) ?? {};
|
|
126
|
+
const consumerProps = (consumer.properties as Record<string, JsonSchemaObject> | undefined) ?? {};
|
|
127
|
+
const required = Array.isArray(consumer.required) ? (consumer.required as string[]) : [];
|
|
128
|
+
|
|
129
|
+
const omission = closedProducerOmitsRequired(producer, producerProps, required);
|
|
130
|
+
if (omission) return omission;
|
|
131
|
+
|
|
132
|
+
for (const key of Object.keys(consumerProps)) {
|
|
133
|
+
const p = producerProps[key];
|
|
134
|
+
const c = consumerProps[key];
|
|
135
|
+
if (!p || !c) continue;
|
|
136
|
+
const conflict = fieldTypeConflict(key, p, c) ?? fieldEnumConflict(key, p, c) ?? fieldConstConflict(key, p, c);
|
|
137
|
+
if (conflict) return conflict;
|
|
138
|
+
}
|
|
139
|
+
return { ok: true };
|
|
140
|
+
}
|
package/sessions/extraction.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { StageDef, StageSchema } from "../api.js";
|
|
|
19
19
|
import { nowIso } from "../audit.js";
|
|
20
20
|
import type { Artifact } from "../handle.js";
|
|
21
21
|
import { assertNever, withTimeout } from "../internal-utils.js";
|
|
22
|
+
import { isJsonSchemaObject, jsonSchemaToStandard } from "../json-schema.js";
|
|
22
23
|
import { buildLifecycleContext, skillStageRef } from "../lifecycle.js";
|
|
23
24
|
import { ERR_SCHEMA_TIMEOUT, MSG_VALIDATION_RETRY, MSG_VALIDATION_RETRY_PROMPT } from "../messages.js";
|
|
24
25
|
import { sideEffectOutcome } from "../outcomes/index.js";
|
|
@@ -29,6 +30,7 @@ import type { StageSession, WorkflowHostContext } from "../types.js";
|
|
|
29
30
|
import {
|
|
30
31
|
DEFAULT_VALIDATION_RETRIES,
|
|
31
32
|
DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
|
|
33
|
+
describeFailure,
|
|
32
34
|
MAX_VALIDATION_RETRIES,
|
|
33
35
|
MAX_VALIDATION_RETRY_TIMEOUT_MS,
|
|
34
36
|
MIN_VALIDATION_RETRIES,
|
|
@@ -60,7 +62,7 @@ export async function produceAndValidateOutput(
|
|
|
60
62
|
const initialOutput = enforceCompletionContract(s.stage, s.skill, first.output);
|
|
61
63
|
if (initialOutput.kind === "fatal") return initialOutput;
|
|
62
64
|
|
|
63
|
-
if (!shouldValidateOutput(s
|
|
65
|
+
if (!shouldValidateOutput(s, initialOutput.output)) return initialOutput;
|
|
64
66
|
|
|
65
67
|
return retryUntilValid(ctx, s, { outcome, collectCtx, finalize }, initialOutput.output);
|
|
66
68
|
}
|
|
@@ -176,8 +178,28 @@ function enforceCompletionContract(
|
|
|
176
178
|
return { kind: "ok", output };
|
|
177
179
|
}
|
|
178
180
|
|
|
179
|
-
|
|
180
|
-
|
|
181
|
+
/**
|
|
182
|
+
* The schema output is validated against: the stage's own `outputSchema` if it
|
|
183
|
+
* declares one, otherwise the dispatched skill's contract `produces.data`
|
|
184
|
+
* (sourced from the declared/injected registry threaded onto the session).
|
|
185
|
+
*
|
|
186
|
+
* Degrades exactly like the input-side runtime mirror (`ensureContractInputValid`):
|
|
187
|
+
* a non-object / unparseable `produces.data` is treated as absent (no schema),
|
|
188
|
+
* never thrown. Returns `undefined` when neither source supplies a schema.
|
|
189
|
+
*/
|
|
190
|
+
function effectiveOutputSchema(s: StageSession): StageSchema | undefined {
|
|
191
|
+
if (s.stage.outputSchema) return s.stage.outputSchema;
|
|
192
|
+
// `s.skill` is resolved via `resolveSkill(def, stageName)` in `resolveStage`
|
|
193
|
+
// (stage-lifecycle.ts), matching the contract map key used by
|
|
194
|
+
// `validate-workflow.ts` and `harvestStageContracts`. The single helper
|
|
195
|
+
// ensures load-time lint and runtime agree on which contract covers the stage.
|
|
196
|
+
const producesData = s.skillContracts?.get(s.skill)?.produces?.data;
|
|
197
|
+
if (!isJsonSchemaObject(producesData)) return undefined;
|
|
198
|
+
return jsonSchemaToStandard(producesData);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function shouldValidateOutput(s: StageSession, output: Output): boolean {
|
|
202
|
+
return !!(effectiveOutputSchema(s) && output.data !== undefined);
|
|
181
203
|
}
|
|
182
204
|
|
|
183
205
|
interface RetryDeps {
|
|
@@ -192,7 +214,7 @@ async function retryUntilValid(
|
|
|
192
214
|
deps: RetryDeps,
|
|
193
215
|
initial: Output,
|
|
194
216
|
): Promise<OutputProduction> {
|
|
195
|
-
const schema = s
|
|
217
|
+
const schema = effectiveOutputSchema(s)!;
|
|
196
218
|
const maxRetries = Math.max(
|
|
197
219
|
MIN_VALIDATION_RETRIES,
|
|
198
220
|
Math.min(s.stage.maxRetries ?? DEFAULT_VALIDATION_RETRIES, MAX_VALIDATION_RETRIES),
|
|
@@ -283,7 +305,7 @@ async function askAgentToFix(
|
|
|
283
305
|
timeoutMs: number,
|
|
284
306
|
): Promise<void> {
|
|
285
307
|
ctx.ui.notify(MSG_VALIDATION_RETRY(s.skill, attempt), "warning");
|
|
286
|
-
const errorLines = failures.map((f) => ` • ${f
|
|
308
|
+
const errorLines = failures.map((f) => ` • ${describeFailure(f)}`).join("\n");
|
|
287
309
|
await withTimeout(
|
|
288
310
|
handlerFor(s.stage.sessionPolicy).send(ctx, MSG_VALIDATION_RETRY_PROMPT(s.skill, errorLines), s.continueHost),
|
|
289
311
|
timeoutMs,
|
|
@@ -292,6 +314,6 @@ async function askAgentToFix(
|
|
|
292
314
|
}
|
|
293
315
|
|
|
294
316
|
function validationExhausted(failures: SchemaValidationFailure[]): OutputProduction {
|
|
295
|
-
const failureSummary = failures.map(
|
|
317
|
+
const failureSummary = failures.map(describeFailure).join("; ");
|
|
296
318
|
return { kind: "validation-exhausted", failureSummary };
|
|
297
319
|
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill contract data model.
|
|
3
|
+
*
|
|
4
|
+
* A contract declares what a skill consumes and produces, as data — the
|
|
5
|
+
* keystone that lets an agent reason about composition without scanning prose.
|
|
6
|
+
* The contract is the SKILL's property (declared once in its frontmatter),
|
|
7
|
+
* injected into this framework via `registerSkillContracts` / a provider
|
|
8
|
+
* (see `skill-contracts.ts`). This package never reads skill files or parses
|
|
9
|
+
* YAML — the primary consumer (rpiv-pi) supplies already-parsed contracts.
|
|
10
|
+
*
|
|
11
|
+
* Three field tiers, by who understands them:
|
|
12
|
+
* - data channel (`consumes.data` / `produces.data`, JSON Schema) — the ONLY
|
|
13
|
+
* channel this framework adjudicates; JSON Schema is consumer-neutral.
|
|
14
|
+
* - framework-native structure (`produces.kind`, `consumes.reads`) — derived
|
|
15
|
+
* from `StageDef`, typed because the framework owns these concepts.
|
|
16
|
+
* - opaque consumer metadata (`meta`) — domain tags the framework stores and
|
|
17
|
+
* surfaces but NEVER interprets (e.g. an `artifactKind` / handle-kind under
|
|
18
|
+
* whatever model a consumer uses). A consumer whose skills emit raw JSON,
|
|
19
|
+
* API-sourced artifacts, or many-artifacts-per-skill puts that here without
|
|
20
|
+
* the framework needing to know the shape.
|
|
21
|
+
* Every channel is optional — a pure chat side-effect declares none.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { JsonSchemaObject } from "./json-schema.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Result of a conservative structural compatibility check between a producer's
|
|
28
|
+
* output schema and a consumer's input schema. Co-located with
|
|
29
|
+
* `CompositionComparator` (which returns this type) so the contract vocabulary
|
|
30
|
+
* is self-contained — consumers don't need to reach into `json-schema.ts` or
|
|
31
|
+
* `schema-compat.ts` for the result type.
|
|
32
|
+
*/
|
|
33
|
+
export interface SchemaCompatResult {
|
|
34
|
+
ok: boolean;
|
|
35
|
+
reason?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Where a contract came from, in descending authority. `declared` = the skill's
|
|
40
|
+
* own frontmatter (truth); `harvested` = derived from how workflow stages use
|
|
41
|
+
* the skill (a cross-check / lint); `inferred` = future JSONL/LLM sources
|
|
42
|
+
* (deferred). Absence (no contract at all) is modelled by the skill simply not
|
|
43
|
+
* being present in the registry — there is no `missing` source.
|
|
44
|
+
*/
|
|
45
|
+
export type ContractSource = "declared" | "harvested" | "inferred";
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A named-channel reference a skill reads (`reads:` / `state.named`). v1 records
|
|
49
|
+
* the reference exists but does NOT schema-check it — named-channel compat is
|
|
50
|
+
* deferred. Any per-read domain tags (kind, artifactKind, …) live in `meta`,
|
|
51
|
+
* opaque to the framework.
|
|
52
|
+
*/
|
|
53
|
+
export interface ConsumesReadSpec {
|
|
54
|
+
meta?: Record<string, unknown>;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* What a skill consumes: an optional typed input `data` schema (the only
|
|
59
|
+
* framework-adjudicated channel), optional framework-native named-channel
|
|
60
|
+
* references (`reads`), and an opaque `meta` bag for consumer domain tags
|
|
61
|
+
* (e.g. a required `artifactKind` under the consumer's own model).
|
|
62
|
+
*/
|
|
63
|
+
export interface ConsumesSpec {
|
|
64
|
+
data?: JsonSchemaObject;
|
|
65
|
+
reads?: Record<string, ConsumesReadSpec>;
|
|
66
|
+
meta?: Record<string, unknown>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* What a skill produces: the stage `kind` (`StageKind`-shaped —
|
|
71
|
+
* `"produces" | "side-effect"` — for harvested contracts; a free-form `string`
|
|
72
|
+
* for declared ones, since frontmatter is untrusted and the framework never
|
|
73
|
+
* validates it), an optional typed output `data` schema (the only
|
|
74
|
+
* framework-adjudicated channel), and an opaque `meta` bag for consumer domain
|
|
75
|
+
* tags (e.g. the emitted `artifactKind` under the consumer's own model).
|
|
76
|
+
*/
|
|
77
|
+
export interface ProducesSpec {
|
|
78
|
+
kind: string;
|
|
79
|
+
data?: JsonSchemaObject;
|
|
80
|
+
meta?: Record<string, unknown>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* A skill's contract. `consumes` / `produces` are each optional (a skill may be
|
|
85
|
+
* a pure chat side-effect). `source` records provenance — its only role today is
|
|
86
|
+
* the `/wf` coverage banner's declared-vs-harvested tally.
|
|
87
|
+
*/
|
|
88
|
+
export interface SkillContract {
|
|
89
|
+
consumes?: ConsumesSpec;
|
|
90
|
+
produces?: ProducesSpec;
|
|
91
|
+
source: ContractSource;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Registry shape: resolved post-alias skill name → contract. */
|
|
95
|
+
export type SkillContractMap = ReadonlyMap<string, SkillContract>;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* A consumer-supplied adjudicator for one named channel's `meta` compatibility.
|
|
99
|
+
* The framework INVOKES it but never reads inside `meta` — the channel's
|
|
100
|
+
* ontology lives entirely with the consumer. Registered per channel
|
|
101
|
+
* via `registerCompositionComparator(channelName, comparator)` and consulted by
|
|
102
|
+
* the three adjudication points (`canCompose`/`legalNextSkills`,
|
|
103
|
+
* `checkEdgeSchemaCompat`, `ensureContractInputValid`) for any consumer
|
|
104
|
+
* declaring `consumes.reads[channelName]`. Conservative by contract: return
|
|
105
|
+
* `{ ok: true }` whenever there is nothing to compare (absent meta on either
|
|
106
|
+
* side) so a missing tag degrades, never HALTs.
|
|
107
|
+
*/
|
|
108
|
+
export type CompositionComparator = (
|
|
109
|
+
produces: ProducesSpec,
|
|
110
|
+
consumes: ConsumesSpec,
|
|
111
|
+
channelName: string,
|
|
112
|
+
) => SchemaCompatResult;
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Composition queries — can one skill's output feed another's input?
|
|
3
|
+
*
|
|
4
|
+
* Conservative structural compatibility checks using `isSchemaCompatible` for
|
|
5
|
+
* the data channel and per-channel `CompositionComparator` for named-channel
|
|
6
|
+
* reads. Returns `{ ok: true }` when either schema is absent/opaque
|
|
7
|
+
* (not provably incompatible).
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { isSchemaCompatible } from "../schema-compat.js";
|
|
11
|
+
import type { SchemaCompatResult, SkillContractMap } from "../skill-contract.js";
|
|
12
|
+
import { getCompositionComparators } from "./registries.js";
|
|
13
|
+
import { getSkillContracts } from "./registry.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Can a producer skill's `produces.data` feed a consumer skill's `consumes.data`?
|
|
17
|
+
* Conservative (via `isSchemaCompatible`): returns `{ ok: true }` when either
|
|
18
|
+
* schema is absent/opaque (not provably incompatible).
|
|
19
|
+
*
|
|
20
|
+
* IMPORTANT: the default `contracts` is the GLOBAL registry
|
|
21
|
+
* (`getSkillContracts()`), which holds only `declared` + `injected` contracts —
|
|
22
|
+
* NOT the `harvested` ones, which exist solely on `LoadedWorkflows.skillContracts`
|
|
23
|
+
* (built per load, never written back to the global). So the zero-arg call sees a
|
|
24
|
+
* weaker map than the loader's own edge-compat pass and will degrade to
|
|
25
|
+
* `{ ok: true }` for any harvest-only skill. For the effective (declared ⊕
|
|
26
|
+
* harvested) view an agent should pass `loaded.skillContracts` explicitly.
|
|
27
|
+
*/
|
|
28
|
+
export function canCompose(
|
|
29
|
+
producerSkill: string,
|
|
30
|
+
consumerSkill: string,
|
|
31
|
+
contracts: SkillContractMap = getSkillContracts(),
|
|
32
|
+
): SchemaCompatResult {
|
|
33
|
+
const producerContract = contracts.get(producerSkill);
|
|
34
|
+
const consumerContract = contracts.get(consumerSkill);
|
|
35
|
+
// Data channel: a provable data mismatch is decisive.
|
|
36
|
+
const producerData = producerContract?.produces?.data;
|
|
37
|
+
const consumerData = consumerContract?.consumes?.data;
|
|
38
|
+
if (producerData && consumerData) {
|
|
39
|
+
const dataCompat = isSchemaCompatible(producerData, consumerData);
|
|
40
|
+
if (!dataCompat.ok) return dataCompat;
|
|
41
|
+
}
|
|
42
|
+
// Named-channel (reads) compat: consult per-channel comparators for the
|
|
43
|
+
// consumer's declared reads channels. Degrades to `{ ok: true }` when no comparator
|
|
44
|
+
// is registered or the producer has no `produces` spec. Only adjudicates channels
|
|
45
|
+
// where the consumer has explicitly declared a meta requirement (readSpec.meta
|
|
46
|
+
// present) — without it there is no kind to compare, and invoking the comparator
|
|
47
|
+
// for a channel the producer may not publish would be a false-reject risk for
|
|
48
|
+
// multi-channel consumers like `revise` (reads ["plans","reviews"]).
|
|
49
|
+
const produces = producerContract?.produces;
|
|
50
|
+
const consumes = consumerContract?.consumes;
|
|
51
|
+
if (produces && consumes?.reads) {
|
|
52
|
+
const comparators = getCompositionComparators();
|
|
53
|
+
for (const channel of Object.keys(consumes.reads)) {
|
|
54
|
+
const comparator = comparators.get(channel);
|
|
55
|
+
if (!comparator) continue;
|
|
56
|
+
const readSpec = consumes.reads[channel];
|
|
57
|
+
if (!readSpec?.meta) continue; // no declared kind requirement — degrade
|
|
58
|
+
const compat = comparator(produces, consumes, channel);
|
|
59
|
+
if (!compat.ok) return compat;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return { ok: true };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Every known skill whose `consumes` is not provably incompatible with `skill`'s
|
|
67
|
+
* `produces` — the generator's search-space narrowing. Sorted for determinism.
|
|
68
|
+
* Same default-map caveat as `canCompose`: pass `loaded.skillContracts` for
|
|
69
|
+
* the effective (declared ⊕ harvested) view, else only declared/injected skills
|
|
70
|
+
* are considered. Conservative by design — absent/opaque schemas count as
|
|
71
|
+
* compatible, so this excludes only PROVABLE data-channel mismatches.
|
|
72
|
+
*/
|
|
73
|
+
export function legalNextSkills(skill: string, contracts: SkillContractMap = getSkillContracts()): string[] {
|
|
74
|
+
const next: string[] = [];
|
|
75
|
+
for (const candidate of contracts.keys()) {
|
|
76
|
+
if (canCompose(skill, candidate, contracts).ok) next.push(candidate);
|
|
77
|
+
}
|
|
78
|
+
return next.sort();
|
|
79
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Harvest — derive skill contracts from how workflow stages USE a skill.
|
|
3
|
+
*
|
|
4
|
+
* The harvested contract is a best-effort cross-check / gap-fill source.
|
|
5
|
+
* Lower authority than a declared frontmatter contract: the loader merges
|
|
6
|
+
* declared OVER harvested. The harvestable surface is the `data` channel
|
|
7
|
+
* (via `extractJsonSchema` on the stage's input/output schemas) plus the
|
|
8
|
+
* framework-native `kind`/`reads`; the opaque `meta` bag is declared-only.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Workflow } from "../api.js";
|
|
12
|
+
import { resolveSkill } from "../internal-utils.js";
|
|
13
|
+
import { extractJsonSchema } from "../json-schema.js";
|
|
14
|
+
import { isDispatchingStage } from "../load/alias.js";
|
|
15
|
+
import type { ConsumesSpec, ProducesSpec, SkillContract } from "../skill-contract.js";
|
|
16
|
+
import { getSkillContracts } from "./registry.js";
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Derive a best-effort `harvested` contract per dispatched skill from how
|
|
20
|
+
* workflow stages USE it — the cross-check / gap-fill source. Lower authority
|
|
21
|
+
* than a declared frontmatter contract: the loader merges declared OVER
|
|
22
|
+
* harvested. The harvestable surface is the `data` channel (via `extractJsonSchema`
|
|
23
|
+
* on the stage's input/output schemas) plus the framework-native `kind`/`reads`;
|
|
24
|
+
* the opaque `meta` bag (e.g. artifactKind) is declared-only — a collector is an
|
|
25
|
+
* opaque function the framework can't introspect. When multiple stages
|
|
26
|
+
* dispatch one skill with divergent schemas, last-writer wins for v1
|
|
27
|
+
* (polymorphic union / drift detection deferred). Reuses `isDispatchingStage`
|
|
28
|
+
* — the shared predicate the alias remap + no-op warning already agree on.
|
|
29
|
+
*
|
|
30
|
+
* LIMITATION: the `data` channel only harvests from schemas that expose
|
|
31
|
+
* their JSON Schema as data — i.e. `typeboxSchema(...)` (and `jsonSchemaToStandard`
|
|
32
|
+
* raw wraps). A stage authored with Zod / Valibot / Arktype has an OPAQUE
|
|
33
|
+
* `~standard` (no `jsonSchema` Converter), so `extractJsonSchema` returns
|
|
34
|
+
* `undefined` and that stage contributes no harvested `data` — only `kind`/`reads`.
|
|
35
|
+
* Such a consumer gets the full benefit by DECLARING contracts (any source) instead
|
|
36
|
+
* of relying on harvest. This is inherent to Standard-Schema adoption, not a bug;
|
|
37
|
+
* it's surfaced (not silent) so authors know why a Zod stage shows no `data`.
|
|
38
|
+
*/
|
|
39
|
+
export function harvestStageContracts(workflows: readonly Workflow[]): Map<string, SkillContract> {
|
|
40
|
+
const harvested = new Map<string, SkillContract>();
|
|
41
|
+
for (const w of workflows) {
|
|
42
|
+
for (const [stageName, stage] of Object.entries(w.stages)) {
|
|
43
|
+
if (!isDispatchingStage(stage)) continue; // only /skill: stages dispatch a contract-bearing skill
|
|
44
|
+
const skill = resolveSkill(stage, stageName);
|
|
45
|
+
const producesData = extractJsonSchema(stage.outputSchema);
|
|
46
|
+
const consumesData = extractJsonSchema(stage.inputSchema);
|
|
47
|
+
const reads = stage.reads?.length ? Object.fromEntries(stage.reads.map((r) => [r, {}])) : undefined;
|
|
48
|
+
const produces: ProducesSpec | undefined =
|
|
49
|
+
stage.kind === "produces" || producesData
|
|
50
|
+
? { kind: stage.kind, ...(producesData ? { data: producesData } : {}) } // real StageKind ("produces" | "side-effect")
|
|
51
|
+
: undefined;
|
|
52
|
+
const consumes: ConsumesSpec | undefined =
|
|
53
|
+
consumesData || reads
|
|
54
|
+
? { ...(consumesData ? { data: consumesData } : {}), ...(reads ? { reads } : {}) }
|
|
55
|
+
: undefined;
|
|
56
|
+
if (!produces && !consumes) continue;
|
|
57
|
+
harvested.set(skill, {
|
|
58
|
+
source: "harvested",
|
|
59
|
+
...(produces ? { produces } : {}),
|
|
60
|
+
...(consumes ? { consumes } : {}),
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return harvested;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Build the effective registry the loader hands to validation + the runner:
|
|
69
|
+
* `harvested` gap-fill first, then `declared`/injected contracts override per
|
|
70
|
+
* skill (declared outranks harvested). Returns a NEW map — never mutates the
|
|
71
|
+
* shared global registry returned by `getSkillContracts()`. Co-located with
|
|
72
|
+
* `harvestStageContracts` because the merge precedence is contract-domain logic,
|
|
73
|
+
* not loader plumbing.
|
|
74
|
+
*/
|
|
75
|
+
export function buildEffectiveContracts(workflows: readonly Workflow[]): Map<string, SkillContract> {
|
|
76
|
+
const effective = new Map(harvestStageContracts(workflows));
|
|
77
|
+
for (const [name, contract] of getSkillContracts()) effective.set(name, contract);
|
|
78
|
+
return effective;
|
|
79
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill-contract registry public surface. Internally split into four focused
|
|
3
|
+
* modules (see `registry.ts`'s header for the module map); this barrel
|
|
4
|
+
* re-exports only the symbols the rest of the package consumes.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export { canCompose, legalNextSkills } from "./composition.js";
|
|
8
|
+
|
|
9
|
+
export { buildEffectiveContracts, harvestStageContracts } from "./harvest.js";
|
|
10
|
+
export {
|
|
11
|
+
getCompositionComparators,
|
|
12
|
+
getOutcomeDerivers,
|
|
13
|
+
type OutcomeDeriverFn,
|
|
14
|
+
registerCompositionComparator,
|
|
15
|
+
registerOutcomeDeriver,
|
|
16
|
+
} from "./registries.js";
|
|
17
|
+
export {
|
|
18
|
+
drainSkillContractCollisions,
|
|
19
|
+
drainSkillContractProviderErrors,
|
|
20
|
+
flushSkillContractProviders,
|
|
21
|
+
getSkillContracts,
|
|
22
|
+
registerSkillContracts,
|
|
23
|
+
registerSkillContractsProvider,
|
|
24
|
+
} from "./registry.js";
|
|
25
|
+
|
|
26
|
+
import { __resetRegistries } from "./registries.js";
|
|
27
|
+
import { __resetRegistry } from "./registry.js";
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Test reset (wired into repo-wide setup). Clears the registry, pending lazy
|
|
31
|
+
* providers, recorded failures + collisions, ownership map, comparator + deriver
|
|
32
|
+
* registries, and the flush latch so the next case starts clean.
|
|
33
|
+
*/
|
|
34
|
+
export function __resetSkillContracts(): void {
|
|
35
|
+
__resetRegistry();
|
|
36
|
+
__resetRegistries();
|
|
37
|
+
}
|