@juicesharp/rpiv-workflow 1.19.1 → 1.20.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.
Files changed (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
package/judge.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Judge — the first-class model-judge concept. A `Judge` names a dispatchable
3
+ * grading session: a **skill** (`/skill:<judge.skill> <producerHandle>`, the
4
+ * latest producer artifact auto-injected as the input handle) or a raw
5
+ * **prompt** (the author embeds the handle/output themselves). Exactly one of
6
+ * `skill` / `prompt` is the dispatch discriminator — enforced at CONSTRUCTION
7
+ * by `judge()` (the `defineRoute` pattern: invalid shapes are unrepresentable
8
+ * past the factory).
9
+ *
10
+ * A judge session runs as a `produces`-kind session so its verdict is
11
+ * VALIDATED by `outcome` and published into its own dedicated
12
+ * `state.named[outcome.name]` channel. What the verdict DECIDES lives on the
13
+ * consuming site, not here: the `assess()` constructor adds `done(verdict)`;
14
+ * the per-stage `verify` field reuses `done(verdict)` as its pass gate; `panel()` will compose
15
+ * N judges with a vote fold. Keeping the termination predicate off `Judge`
16
+ * is what makes the concept reusable across all three.
17
+ *
18
+ * Leaf module — type-only imports; safe on the runner-free `registration`
19
+ * surface (siblings register built-ins without dragging the runner in).
20
+ */
21
+
22
+ import type { Artifact } from "./handle.js";
23
+ import type { Output, RunView } from "./output.js";
24
+ import type { Outcome } from "./output-spec.js";
25
+
26
+ /** Context handed to a dynamic `Judge.prompt`. */
27
+ export interface JudgeContext {
28
+ cwd: string;
29
+ /** Latest producer output (also the session's input handle). */
30
+ output: Output;
31
+ /** Frozen stage-entry primary, referenceable; the author embeds it if wanted. */
32
+ entryArtifact: Artifact | undefined;
33
+ state: RunView;
34
+ /** 0-based round index. */
35
+ round: number;
36
+ }
37
+
38
+ /** A judge's dynamic prompt — receives the producer output + round context. */
39
+ export type JudgePromptFn = (ctx: JudgeContext) => string | Promise<string>;
40
+
41
+ /**
42
+ * An `Outcome` whose `name` is REQUIRED — a judge's verdict must publish
43
+ * to its own dedicated `state.named` channel, so the optional-`name` outcome
44
+ * shape isn't enough here.
45
+ */
46
+ export interface NamedOutcome extends Outcome {
47
+ name: string;
48
+ }
49
+
50
+ /**
51
+ * Fields shared by both judge dispatch arms.
52
+ *
53
+ * `outcome` validates the verdict and names its dedicated `state.named`
54
+ * channel (its `.name` must differ from the producer outcome's; that
55
+ * collision needs the producer's identity, so it stays a workflow-level
56
+ * check in `validateWorkflow`).
57
+ *
58
+ * ≥1-ARTIFACT CONSTRAINT: the collector MUST materialize at least one
59
+ * artifact (e.g. a JSON verdict file whose parser yields `{ done, feedback }`).
60
+ * A judge session whose collector returns zero artifacts is a **fatal halt**
61
+ * via `enforceCompletionContract` — no retry, no soft-stop.
62
+ */
63
+ interface JudgeBase {
64
+ outcome: NamedOutcome;
65
+ }
66
+
67
+ /** Skill dispatch: `/skill:<skill> <producerHandle>` (handle auto-injected). */
68
+ export interface SkillJudge extends JudgeBase {
69
+ skill: string;
70
+ /** Structurally absent — skill XOR prompt (both is ambiguous). */
71
+ prompt?: never;
72
+ }
73
+
74
+ /**
75
+ * Raw-prompt dispatch: the session receives only the prompt text, so the
76
+ * author embeds the producer handle/output themselves (via `JudgeContext`
77
+ * for the dynamic form).
78
+ */
79
+ export interface PromptJudge extends JudgeBase {
80
+ prompt: string | JudgePromptFn;
81
+ /** Structurally absent — skill XOR prompt (both is ambiguous). */
82
+ skill?: never;
83
+ }
84
+
85
+ /**
86
+ * The reusable judge shape — a union over the two dispatch arms, so
87
+ * skill-XOR-prompt and the named verdict outcome are violations the type
88
+ * system rejects on typed call sites, not just runtime checks. Authored via
89
+ * the `judge()` factory; a hand-rolled object literal (jiti-loaded configs
90
+ * erase TS types) is re-checked defensively at load time by
91
+ * `validateWorkflow` through the same `judgeShapeIssues` rule source —
92
+ * which is why the runtime checks stay.
93
+ */
94
+ export type Judge = SkillJudge | PromptJudge;
95
+
96
+ /**
97
+ * A fold reduces the N member verdicts of a `PanelJudge` to the panel's
98
+ * decision DATA — `unknown` here because the *shape* is path-dependent
99
+ * (canonical `PANEL_VERDICT` vs. a custom author schema), validated downstream
100
+ * by the panel's `outcome`. The fold is pure (the replay contract leans on
101
+ * this: live + resume both recompute it from the durable member rows).
102
+ */
103
+ export type FoldFn = (verdicts: readonly Output[]) => unknown;
104
+
105
+ /**
106
+ * N independent judges plus a vote `fold` — the adversarial-verification
107
+ * generalization of a single `Judge` (Cohere PoLL: a jury beats a self-agreeing
108
+ * judge). `kind: "panel"` is the discriminator; a single `Judge` carries no
109
+ * `kind`, so `isPanel` distinguishes them structurally.
110
+ *
111
+ * `members` is `Judge[]` — each a full `SkillJudge | PromptJudge`, so the whole
112
+ * judge surface (skill XOR prompt, named verdict outcome, dispatch) is reused
113
+ * per member with zero new vocabulary. Nesting is rejected at construction
114
+ * (`members` is NOT `AnyJudge[]`).
115
+ *
116
+ * `outcome` is the canonical-vs-custom switch: ABSENT ⇒ the built-in
117
+ * `PANEL_VERDICT` shape on the `<stage>-panel` channel (sugar fold); PRESENT ⇒
118
+ * the author's schema + channel (raw fold). The two are kept disjoint by a hard
119
+ * XOR enforced by the `panel()` factory (Phase 2) — never both.
120
+ */
121
+ export interface PanelJudge {
122
+ kind: "panel";
123
+ members: readonly Judge[];
124
+ fold: FoldFn;
125
+ outcome?: NamedOutcome;
126
+ }
127
+
128
+ /**
129
+ * The slot type every judge SITE (`assess`, `verify`, any future judge phase)
130
+ * accepts — a plain `Judge` OR a `PanelJudge`. A single judge is the panel of
131
+ * one: sites reference the judge opaquely and let `panelMembers` expand it, so
132
+ * widening this slot is the ONLY signature change panel support imposes.
133
+ */
134
+ export type AnyJudge = Judge | PanelJudge;
135
+
136
+ /** Discriminate a `PanelJudge` from a single `Judge` (singles carry no `kind`). */
137
+ export const isPanel = (j: AnyJudge): j is PanelJudge => (j as PanelJudge).kind === "panel";
138
+
139
+ /**
140
+ * THE expander — the single place a judge value becomes its member list. A
141
+ * panel yields its `members`; a single judge yields `[judge]` (the panel of
142
+ * one). Every member-walking site (preflight skill registration, introspection,
143
+ * the judge-phase dispatch) routes through this, so single-judge behavior is
144
+ * the degenerate case of the general path by construction.
145
+ */
146
+ export const panelMembers = (j: AnyJudge): readonly Judge[] => (isPanel(j) ? j.members : [j]);
147
+
148
+ /** The sugar-fold constructors — the canonical folds (`majority`/`all`/`any`). */
149
+ export type CanonicalFoldName = "majority" | "all" | "any";
150
+
151
+ /**
152
+ * Brand carrying the SUGAR-fold name (`majority`/`all`/`any`) so consumers can
153
+ * (a) tell a canonical fold from a raw author closure — the structural signal
154
+ * behind the §4 XOR (sugar ⊕ `outcome`) — and (b) report WHICH fold it is in
155
+ * the introspection summary (`panelSpecOf`). `Symbol.for` so it survives
156
+ * `import` boundaries cleanly, matching the `READS_DATA` / `ROUTE_NOTE`
157
+ * precedent.
158
+ *
159
+ * Framework plumbing, not authoring surface — the sugar constructors brand;
160
+ * `panelShapeIssues` / `validateWorkflow` / `panelSpecOf` read. NOT re-exported
161
+ * from `registration.ts`, like `ROUTE_NOTE`.
162
+ */
163
+ export const CANONICAL_FOLD: unique symbol = Symbol.for("rpiv.workflow.canonicalFold");
164
+
165
+ /** True iff `fold` was produced by a sugar constructor (carries the `CANONICAL_FOLD` brand). */
166
+ export function marksCanonicalFold(fold: FoldFn): boolean {
167
+ return canonicalFoldName(fold) !== undefined;
168
+ }
169
+
170
+ /** The sugar constructor that produced `fold` (`majority`/`all`/`any`), or `undefined` for a raw author closure. */
171
+ export function canonicalFoldName(fold: FoldFn): CanonicalFoldName | undefined {
172
+ return (fold as unknown as Record<symbol, CanonicalFoldName | undefined>)[CANONICAL_FOLD];
173
+ }
174
+
175
+ /** Attach the `CANONICAL_FOLD` brand (the sugar name) and return the fold — the ONE write site (sugar constructors). */
176
+ export function brandCanonicalFold(name: CanonicalFoldName, fold: FoldFn): FoldFn {
177
+ (fold as unknown as Record<symbol, CanonicalFoldName>)[CANONICAL_FOLD] = name;
178
+ return fold;
179
+ }
180
+
181
+ /**
182
+ * Single rule source for the judge shape. Returns human-readable violations
183
+ * (empty array = valid). `judge()` throws on the first; `validateWorkflow`
184
+ * maps each to a load issue for hand-rolled literals that bypassed the
185
+ * factory. Takes `unknown` ON PURPOSE: the type system already rejects these
186
+ * shapes on typed call sites (the `Judge` union), so everything reaching this
187
+ * checker is an untyped jiti-loaded literal.
188
+ */
189
+ export function judgeShapeIssues(candidate: unknown): string[] {
190
+ if (!candidate || typeof candidate !== "object") return ["a judge object is required"];
191
+ const j = candidate as { skill?: unknown; prompt?: unknown; outcome?: { name?: unknown } };
192
+ const issues: string[] = [];
193
+ if (!j.outcome?.name) {
194
+ issues.push("judge.outcome must carry a `name` so the verdict publishes to its own named channel");
195
+ }
196
+ const hasSkill = j.skill !== undefined;
197
+ const hasPrompt = j.prompt !== undefined;
198
+ if (hasSkill && hasPrompt) {
199
+ issues.push("judge sets both `skill` and `prompt` — choose one dispatch (skill XOR prompt)");
200
+ }
201
+ if (!hasSkill && !hasPrompt) {
202
+ issues.push("judge sets neither `skill` nor `prompt` — one is required to dispatch the judge");
203
+ }
204
+ return issues;
205
+ }
206
+
207
+ /**
208
+ * Promote a judge literal to a validated `Judge` — identity passthrough that
209
+ * throws on an invalid shape, so a `judge(...)`-authored value is correct by
210
+ * construction (cf. `defineRoute`). Composes into `assess({ judge: judge({...}) })`
211
+ * today and `panel(judge({...}), judge({...}))` in the follow-up.
212
+ */
213
+ export function judge(spec: Judge): Judge {
214
+ const issues = judgeShapeIssues(spec);
215
+ if (issues.length > 0) throw new Error(`judge(): ${issues[0]}`);
216
+ return spec;
217
+ }
218
+
219
+ /**
220
+ * Resolve a static or dynamic `Judge.prompt`. A dynamic prompt may be async.
221
+ * (Moved from loop.ts — the ONE resolver for every Judge dispatch site.)
222
+ */
223
+ export async function resolveJudgePrompt(
224
+ prompt: string | ((ctx: JudgeContext) => string | Promise<string>),
225
+ ctx: JudgeContext,
226
+ ): Promise<string> {
227
+ if (typeof prompt === "string") return prompt;
228
+ return prompt(ctx);
229
+ }
package/layers.ts CHANGED
@@ -8,26 +8,21 @@
8
8
  * eliminates the silent-drift risk of two parallel string-literal unions.
9
9
  */
10
10
 
11
- import { assertNever } from "./internal-utils.js";
12
-
13
11
  export type ConfigLayer = "built-in" | "user" | "project";
14
12
 
15
13
  /**
16
14
  * Single source for layer → display string. Wrap every interpolation site
17
15
  * (`${layer}` in template strings, banner builders, issue prefixes) in this
18
- * helper so adding a new `ConfigLayer` value surfaces as a compile error at
19
- * every consumer, not just at the loader's switch. The current display
20
- * form is the layer name verbatim — keep that invariant if you change it.
16
+ * helper; the `satisfies Record<ConfigLayer, string>` makes adding a new
17
+ * `ConfigLayer` value a compile error here. The current display form is the
18
+ * layer name verbatim — keep that invariant if you change it.
21
19
  */
20
+ const CONFIG_LAYER_LABELS = {
21
+ "built-in": "built-in",
22
+ user: "user",
23
+ project: "project",
24
+ } satisfies Record<ConfigLayer, string>;
25
+
22
26
  export function renderConfigLayer(layer: ConfigLayer): string {
23
- switch (layer) {
24
- case "built-in":
25
- return "built-in";
26
- case "user":
27
- return "user";
28
- case "project":
29
- return "project";
30
- default:
31
- return assertNever(layer);
32
- }
27
+ return CONFIG_LAYER_LABELS[layer];
33
28
  }
package/load/alias.ts CHANGED
@@ -20,20 +20,14 @@
20
20
  * slot) is never mutated in place; a changed workflow is a new frozen copy.
21
21
  */
22
22
 
23
- import type { StageDef, Workflow } from "../api.js";
24
- import { resolveSkill } from "../internal-utils.js";
23
+ import type { Workflow } from "../api.js";
24
+ import { isDispatchingStage, resolveSkill } from "../chain-state.js";
25
25
  import type { LayerOutcome, LoadAccumulator } from "./merge.js";
26
26
 
27
- /**
28
- * A stage dispatches a `/skill:<name>` exactly when it carries neither a `run`
29
- * (script body) nor a `prompt` (raw-text body). `fanout`/`iterate` stages carry
30
- * neither, so they ARE dispatching stages. Single source of truth shared by the
31
- * alias remap below (which stages to rewrite) and the no-op-alias warning in
32
- * `applySkillAliases` (which skills count as "dispatched") — the two must agree.
33
- */
34
- export function isDispatchingStage(stage: StageDef): boolean {
35
- return stage.run == null && stage.prompt == null;
36
- }
27
+ // `isDispatchingStage` lives beside `resolveSkill` in chain-state.ts (the
28
+ // validator and harvest consume it without reaching into load/); re-exported
29
+ // here for existing consumers of the old path.
30
+ export { isDispatchingStage } from "../chain-state.js";
37
31
 
38
32
  export function aliasSkills(w: Workflow, aliases: Record<string, string>): Workflow {
39
33
  if (!aliases || Object.keys(aliases).length === 0) return w;
package/load/cache.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  /**
2
- * mtime-keyed jiti import cache. jiti's own caches are disabled so `/reload`
3
- * picks up edits without restart; this wrapper layers a stat-driven cache
4
- * on top so unchanged overlays don't re-evaluate top-level code on every
5
- * `/wf` invocation.
2
+ * mtime-keyed jiti import cache. jiti's MODULE cache is disabled so `/reload`
3
+ * picks up edits without restart; its fs TRANSFORM cache stays on (the
4
+ * default) — entries are content-hash validated, so an edited overlay can
5
+ * never be served stale, and fresh sessions skip the ~70ms/file Babel
6
+ * re-transform. This wrapper layers a stat-driven cache on top so unchanged
7
+ * overlays don't re-evaluate top-level code on every `/wf` invocation.
6
8
  *
7
9
  * The `jiti` instance lives here so the cache and the underlying importer
8
10
  * co-locate. Other loader modules import `cachedImport` — none touches
@@ -18,9 +20,10 @@ import { statSync } from "node:fs";
18
20
  import { createJiti } from "jiti";
19
21
 
20
22
  const jiti = createJiti(import.meta.url, {
21
- // Bypass jiti's module cache so /reload picks up edits without restart.
23
+ // Module cache OFF so /reload picks up edits without restart. The fs
24
+ // transform cache (default ON) is deliberately kept: it is content-hash
25
+ // validated (edit-safe) and saves ~70ms/file of Babel work per session.
22
26
  moduleCache: false,
23
- fsCache: false,
24
27
  });
25
28
 
26
29
  const overlayCache = new Map<string, { mtimeMs: number; parsed: unknown }>();
package/load/index.ts CHANGED
@@ -42,33 +42,29 @@
42
42
  * (the config file + pack files) before running `/wf`.
43
43
  *
44
44
  * Module map:
45
+ * ./issues.ts — LoadIssue + Issue (the layer/path-attributed wrapper)
46
+ * ./skill-contract-phase.ts — provider flush/drain + effective registry + derivers
45
47
  * ./paths.ts — OverlayPaths + per-layer path helpers
46
- * ./shape-guards.ts — isWorkflow, isEnvelope, describe, formatError
48
+ * ./shape-guards.ts — isWorkflow, isEnvelope, describe
47
49
  * ./normalize.ts — normalizeDefaultExport + NormalizeResult
48
50
  * ./merge.ts — LoadAccumulator, LayerOutcome, loadLayer, mergeOverlay, loadError
51
+ * ./legacy.ts — legacy-layout advisories (notices + probes)
49
52
  * ./resolve-default.ts — resolveDefault (first-workflow fallback)
50
53
  * ./cache.ts — mtime-keyed jiti import cache + __resetLoadCache
51
54
  */
52
55
 
53
- import { existsSync, readdirSync } from "node:fs";
54
- import { dirname, join } from "node:path";
55
56
  import type { Workflow } from "../api.js";
56
57
  import { flushBuiltInProviders, getBuiltIns } from "../built-ins.js";
57
58
  import type { ConfigLayer } from "../layers.js";
58
- import { LEGACY_OVERLAY_NOTICE, LEGACY_RUNS_NOTICE, LEGACY_USER_CONFIG_NOTICE } from "../messages.js";
59
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";
67
- import { validateWorkflow, type WorkflowValidationIssue } from "../validate-workflow.js";
60
+ import { validateWorkflow } from "../validate-workflow.js";
68
61
  import { applySkillAliases } from "./alias.js";
62
+ import type { Issue } from "./issues.js";
63
+ import { pushLegacyNotices } from "./legacy.js";
69
64
  import { type LoadAccumulator, loadLayer } from "./merge.js";
70
- import { type OverlayPaths, projectOverlayPaths, userOverlayPaths } from "./paths.js";
65
+ import { projectOverlayPaths, userOverlayPaths } from "./paths.js";
71
66
  import { resolveDefault } from "./resolve-default.js";
67
+ import { applySkillContractPhase } from "./skill-contract-phase.js";
72
68
 
73
69
  // ===========================================================================
74
70
  // Public types
@@ -77,19 +73,10 @@ import { resolveDefault } from "./resolve-default.js";
77
73
  export type { ConfigLayer } from "../layers.js";
78
74
  export { aliasSkills } from "./alias.js";
79
75
  export { __resetLoadCache } from "./cache.js";
76
+ export type { Issue, LoadIssue, LoadIssueOrigin } from "./issues.js";
80
77
  export type { OverlayPaths } from "./paths.js";
81
78
  export { projectOverlayPaths, userOverlayPaths } from "./paths.js";
82
79
 
83
- export interface LoadIssue {
84
- kind: "load";
85
- layer: ConfigLayer;
86
- path?: string;
87
- severity: "error" | "warning";
88
- message: string;
89
- }
90
-
91
- export type Issue = LoadIssue | (WorkflowValidationIssue & { kind: "validation"; layer: ConfigLayer; path?: string });
92
-
93
80
  export interface LoadedWorkflows {
94
81
  workflows: readonly Workflow[];
95
82
  /**
@@ -112,7 +99,7 @@ export interface LoadedWorkflows {
112
99
  */
113
100
  skillAliases: Readonly<Record<string, string>>;
114
101
  /**
115
- * Effective skill-contract registry: injected `declared` contracts merged
102
+ * Effective skill-contract registry: registered (`declared`-source) contracts merged
116
103
  * OVER `harvested` ones (derived from stage usage). Required field, empty
117
104
  * `Map` when no contract was declared or harvestable.
118
105
  */
@@ -146,11 +133,6 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
146
133
  // defer constructing definitions to first `/wf` (the earliest reader).
147
134
  await flushBuiltInProviders();
148
135
 
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
-
154
136
  const acc: LoadAccumulator = {
155
137
  issues: [],
156
138
  workflowMap: new Map(),
@@ -159,22 +141,6 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
159
141
  };
160
142
  const layers: ConfigLayer[] = getBuiltIns().length > 0 ? ["built-in"] : [];
161
143
 
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
-
178
144
  for (const w of getBuiltIns()) {
179
145
  acc.workflowMap.set(w.name, w);
180
146
  acc.sources.set(w.name, "built-in");
@@ -203,29 +169,11 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
203
169
  // declared the key — see `applySkillAliases` in `./alias.ts`.
204
170
  const skillAliases = applySkillAliases(acc, userOutcome, projectOutcome);
205
171
 
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
- }
172
+ // Skill-contract phase: flush providers, surface their failures +
173
+ // collisions (attributed to "framework", not a config layer), build the
174
+ // effective registry, run outcome derivers on per-load stage copies. Must
175
+ // precede validation — see `./skill-contract-phase.ts`.
176
+ const skillContracts = await applySkillContractPhase(acc);
229
177
 
230
178
  // Validate every merged workflow once. Validation runs even on built-in so
231
179
  // that a future built-in regression surfaces in the same channel as user
@@ -251,44 +199,3 @@ export async function loadWorkflows(cwd: string): Promise<LoadedWorkflows> {
251
199
  skillContracts,
252
200
  };
253
201
  }
254
-
255
- /**
256
- * Push the three independent legacy-migration advisories. Each is a `"warning"`
257
- * (never blocks the run) and each probes a distinct stale layout the unified
258
- * `.rpiv/workflows/` move left behind:
259
- * - project dashed dir `<cwd>/.rpiv-workflow/` → config.ts + packs/
260
- * - orphaned run JSONLs `<cwd>/.rpiv/workflows/*.jsonl` → runs/
261
- * - user-layer rename `~/.config/rpiv-workflow/workflows.config.ts` → config.ts
262
- */
263
- function pushLegacyNotices(cwd: string, userPaths: OverlayPaths, acc: LoadAccumulator): void {
264
- if (existsSync(join(cwd, ".rpiv-workflow"))) {
265
- acc.issues.push({ kind: "load", layer: "project", severity: "warning", message: LEGACY_OVERLAY_NOTICE(cwd) });
266
- }
267
-
268
- if (hasOrphanedRunFiles(cwd)) {
269
- acc.issues.push({ kind: "load", layer: "project", severity: "warning", message: LEGACY_RUNS_NOTICE(cwd) });
270
- }
271
-
272
- const userDir = dirname(userPaths.configFile);
273
- if (existsSync(join(userDir, "workflows.config.ts"))) {
274
- acc.issues.push({
275
- kind: "load",
276
- layer: "user",
277
- severity: "warning",
278
- message: LEGACY_USER_CONFIG_NOTICE(userDir),
279
- });
280
- }
281
- }
282
-
283
- /**
284
- * True when `<cwd>/.rpiv/workflows/` holds top-level `*.jsonl` run files written
285
- * before the `runs/` relocation. `readdirSync` lists only immediate entries, so
286
- * files already inside `runs/` never match. A missing / unreadable dir → false.
287
- */
288
- function hasOrphanedRunFiles(cwd: string): boolean {
289
- try {
290
- return readdirSync(join(cwd, ".rpiv", "workflows")).some((f) => f.endsWith(".jsonl"));
291
- } catch {
292
- return false;
293
- }
294
- }
package/load/issues.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The loader's issue vocabulary — a LEAF module so `merge.ts` (and any other
3
+ * pipeline stage) can name the `Issue` shape without importing the
4
+ * orchestrator back (the one back-edge the load pipeline used to have, G4).
5
+ *
6
+ * `layer`/`path` attribution lives ONLY here: `validateWorkflow` knows
7
+ * nothing about config layers; the loader is the seam that has both
8
+ * `workflowSources` and the issue list in scope, so it wraps each validation
9
+ * issue with the layer/path of the file the surviving workflow came from.
10
+ */
11
+
12
+ import type { ConfigLayer } from "../layers.js";
13
+ import type { WorkflowValidationIssue } from "../validate/issue.js";
14
+
15
+ /**
16
+ * Where a load issue originated: one of the config layers, or `"framework"`
17
+ * — the loader's own machinery (skill-contract providers, outcome derivers,
18
+ * collision tracking). The framework origin is honest attribution for
19
+ * errors no config file caused; `"built-in"` used to be the dumping ground.
20
+ */
21
+ export type LoadIssueOrigin = ConfigLayer | "framework";
22
+
23
+ export interface LoadIssue {
24
+ kind: "load";
25
+ layer: LoadIssueOrigin;
26
+ path?: string;
27
+ severity: "error" | "warning";
28
+ message: string;
29
+ }
30
+
31
+ export type Issue = LoadIssue | (WorkflowValidationIssue & { kind: "validation"; layer: ConfigLayer; path?: string });
package/load/legacy.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Legacy-layout migration advisories — the notice strings AND the probes
3
+ * that fire them (moved here from messages.ts + load/index.ts, M8: the
4
+ * migration shell snippets are a loader concern, not UI constants).
5
+ *
6
+ * Each advisory is a `"warning"` (never blocks the run) probing a distinct
7
+ * stale layout the unified `.rpiv/workflows/` move left behind. Sunset
8
+ * target ~3 release cycles post-1.0 — remove each `existsSync` gate, its
9
+ * message constant, and the co-located test case together.
10
+ */
11
+
12
+ import { existsSync, readdirSync } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import type { LoadAccumulator } from "./merge.js";
15
+ import type { OverlayPaths } from "./paths.js";
16
+
17
+ /**
18
+ * Legacy `.rpiv-workflow/` overlay directory detected at load time. The
19
+ * package moved project config under the unified `.rpiv/workflows/` tree
20
+ * (config.ts + packs/) alongside run state. The old directory is NO LONGER
21
+ * read — this notice points the user at the new location and the one-line
22
+ * `mv` migration. Emitted as a load WARNING (advisory, non-blocking).
23
+ *
24
+ * The embedded shell is `;`-sequenced (not `&&`-chained) and each move is
25
+ * guarded (`[ -f … ]` for the config, `find … 2>/dev/null` for the packs) so
26
+ * the terminal `rm -rf` ALWAYS runs — a config-only legacy dir (no `workflows/`
27
+ * subdir) no longer halts the chain and re-fires this warning forever.
28
+ */
29
+ export const LEGACY_OVERLAY_NOTICE = (cwd: string): string =>
30
+ `rpiv-workflow: detected legacy \`${join(cwd, ".rpiv-workflow")}\` — project config now lives at ` +
31
+ "`.rpiv/workflows/config.ts` + `.rpiv/workflows/packs/` and is the only location read. " +
32
+ "Move it: `mkdir -p .rpiv/workflows/packs; " +
33
+ "[ -f .rpiv-workflow/workflows.config.ts ] && mv .rpiv-workflow/workflows.config.ts .rpiv/workflows/config.ts; " +
34
+ "find .rpiv-workflow/workflows -name '*.ts' -exec mv {} .rpiv/workflows/packs/ \\; 2>/dev/null; " +
35
+ "rm -rf .rpiv-workflow` " +
36
+ "(the old directory is ignored). " +
37
+ "Note: `.rpiv/workflows/` is commonly gitignored (it holds run state), so the moved " +
38
+ "`config.ts` + `packs/` may be silently uncommittable — add `!.rpiv/workflows/config.ts` and " +
39
+ "`!.rpiv/workflows/packs/` to your `.gitignore` to version-control team workflow config.";
40
+
41
+ /**
42
+ * Orphaned run JSONLs detected directly under `.rpiv/workflows/` at load time.
43
+ * Run state moved one level down into `.rpiv/workflows/runs/`; files written by
44
+ * an older version still sit at the parent and are no longer enumerated by
45
+ * `listRuns` (so `/wf` past-run inspection silently can't see them). Emitted as
46
+ * a load WARNING (advisory, non-blocking) — the files are orphaned, not deleted.
47
+ */
48
+ export const LEGACY_RUNS_NOTICE = (cwd: string): string =>
49
+ `rpiv-workflow: detected legacy run files directly under \`${join(cwd, ".rpiv", "workflows")}\` — ` +
50
+ "run state now lives in `.rpiv/workflows/runs/` and these top-level `*.jsonl` files are no longer " +
51
+ "read by `/wf`. Move them: `mkdir -p .rpiv/workflows/runs && mv .rpiv/workflows/*.jsonl .rpiv/workflows/runs/`.";
52
+
53
+ /**
54
+ * Legacy user-layer config filename (`workflows.config.ts`) detected at load
55
+ * time. The user overlay's inner name was aligned with the project layer
56
+ * (`config.ts`) and is the ONLY name read — a stale `workflows.config.ts` would
57
+ * otherwise silently stop contributing its aliases / default / overlay
58
+ * workflows. Mirrors `LEGACY_OVERLAY_NOTICE` at the user layer. Load WARNING.
59
+ */
60
+ export const LEGACY_USER_CONFIG_NOTICE = (dir: string): string =>
61
+ `rpiv-workflow: detected legacy \`${join(dir, "workflows.config.ts")}\` — the user-layer config now lives at ` +
62
+ `\`${join(dir, "config.ts")}\` and is the only name read. ` +
63
+ `Move it: \`mv ${join(dir, "workflows.config.ts")} ${join(dir, "config.ts")}\` (the old name is ignored).`;
64
+
65
+ /**
66
+ * Push the three independent legacy-migration advisories:
67
+ * - project dashed dir `<cwd>/.rpiv-workflow/` → config.ts + packs/
68
+ * - orphaned run JSONLs `<cwd>/.rpiv/workflows/*.jsonl` → runs/
69
+ * - user-layer rename `~/.config/rpiv-workflow/workflows.config.ts` → config.ts
70
+ */
71
+ export function pushLegacyNotices(cwd: string, userPaths: OverlayPaths, acc: LoadAccumulator): void {
72
+ if (existsSync(join(cwd, ".rpiv-workflow"))) {
73
+ acc.issues.push({ kind: "load", layer: "project", severity: "warning", message: LEGACY_OVERLAY_NOTICE(cwd) });
74
+ }
75
+
76
+ if (hasOrphanedRunFiles(cwd)) {
77
+ acc.issues.push({ kind: "load", layer: "project", severity: "warning", message: LEGACY_RUNS_NOTICE(cwd) });
78
+ }
79
+
80
+ const userDir = dirname(userPaths.configFile);
81
+ if (existsSync(join(userDir, "workflows.config.ts"))) {
82
+ acc.issues.push({
83
+ kind: "load",
84
+ layer: "user",
85
+ severity: "warning",
86
+ message: LEGACY_USER_CONFIG_NOTICE(userDir),
87
+ });
88
+ }
89
+ }
90
+
91
+ /**
92
+ * True when `<cwd>/.rpiv/workflows/` holds top-level `*.jsonl` run files written
93
+ * before the `runs/` relocation. `readdirSync` lists only immediate entries, so
94
+ * files already inside `runs/` never match. A missing / unreadable dir → false.
95
+ */
96
+ function hasOrphanedRunFiles(cwd: string): boolean {
97
+ try {
98
+ return readdirSync(join(cwd, ".rpiv", "workflows")).some((f) => f.endsWith(".jsonl"));
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
package/load/merge.ts CHANGED
@@ -16,12 +16,12 @@
16
16
  import { existsSync, readdirSync } from "node:fs";
17
17
  import { join } from "node:path";
18
18
  import type { Workflow } from "../api.js";
19
+ import { formatError } from "../internal-utils.js";
19
20
  import type { ConfigLayer } from "../layers.js";
20
21
  import { cachedImport } from "./cache.js";
21
- import type { Issue } from "./index.js";
22
+ import type { Issue } from "./issues.js";
22
23
  import { type FileKind, normalizeDefaultExport, type ParsedConfig } from "./normalize.js";
23
24
  import type { OverlayPaths } from "./paths.js";
24
- import { formatError } from "./shape-guards.js";
25
25
 
26
26
  /**
27
27
  * Mutable bag of state threaded through `loadLayer` → `loadOverlayFile`