@juicesharp/rpiv-workflow 1.20.0 → 2.1.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 (111) hide show
  1. package/README.md +98 -545
  2. package/api.ts +1 -1
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +18 -0
  5. package/audit.ts +119 -164
  6. package/built-ins.ts +26 -6
  7. package/chain-state.ts +119 -68
  8. package/command-run.ts +35 -30
  9. package/command.ts +10 -4
  10. package/docs/embedding.md +341 -0
  11. package/docs/workflow-authoring.md +70 -16
  12. package/docs/workflow-basics.md +125 -10
  13. package/events.ts +44 -4
  14. package/execution-host.ts +75 -0
  15. package/host.ts +137 -82
  16. package/internal-utils.ts +89 -3
  17. package/internal.ts +1 -0
  18. package/judge.ts +23 -11
  19. package/load/alias.ts +3 -3
  20. package/load/index.ts +15 -1
  21. package/load/issues.ts +2 -2
  22. package/load/legacy.ts +2 -2
  23. package/load/resolve-default.ts +3 -4
  24. package/load/skill-contract-phase.ts +1 -1
  25. package/loop-constructors.ts +19 -618
  26. package/loop-def.ts +60 -15
  27. package/loop-kinds.ts +319 -62
  28. package/loop-parallel.ts +250 -0
  29. package/loop-waves.ts +99 -0
  30. package/loop.ts +106 -80
  31. package/loops/constructors.ts +334 -0
  32. package/loops/derivations.ts +65 -0
  33. package/loops/introspection.ts +184 -0
  34. package/loops/panel.ts +196 -0
  35. package/loops/verify.ts +99 -0
  36. package/messages.ts +58 -33
  37. package/outcomes/collectors/index.ts +1 -0
  38. package/outcomes/collectors/text-scan.ts +47 -0
  39. package/outcomes/collectors/transcript-path.ts +2 -15
  40. package/outcomes/collectors/union.ts +2 -1
  41. package/outcomes/collectors/url.ts +2 -14
  42. package/outcomes/collectors/workspace-diff.ts +1 -1
  43. package/outcomes/git-commit.ts +57 -6
  44. package/output-spec.ts +1 -1
  45. package/output.ts +59 -1
  46. package/package.json +19 -6
  47. package/preview.ts +18 -18
  48. package/registration.ts +11 -4
  49. package/routing-dsl.ts +53 -41
  50. package/routing.ts +46 -0
  51. package/runner/chain-advance.ts +30 -17
  52. package/runner/errors.ts +7 -30
  53. package/runner/failure.ts +67 -13
  54. package/runner/input-validation.ts +8 -5
  55. package/runner/preflight.ts +17 -21
  56. package/runner/resume-entry.ts +23 -3
  57. package/runner/resume-loop.ts +50 -29
  58. package/runner/resume.ts +96 -10
  59. package/runner/run-context.ts +20 -16
  60. package/runner/run-stage.ts +125 -91
  61. package/runner/runner.ts +163 -69
  62. package/runner/script-stage.ts +23 -29
  63. package/schema-compat.ts +1 -2
  64. package/semaphore.ts +55 -0
  65. package/sessions/extraction.ts +103 -60
  66. package/sessions/halt-routing.ts +195 -0
  67. package/sessions/index.ts +2 -2
  68. package/sessions/locate.ts +60 -9
  69. package/sessions/reattach.ts +28 -20
  70. package/sessions/sessions.ts +103 -191
  71. package/sessions/spawn.ts +132 -119
  72. package/sessions/success-persist.ts +89 -0
  73. package/skill-contracts/composition.ts +8 -10
  74. package/skill-contracts/harvest.ts +3 -2
  75. package/skill-contracts/registry.ts +1 -1
  76. package/stage-def.ts +115 -47
  77. package/stage-errors.ts +84 -0
  78. package/stage-identity.ts +56 -0
  79. package/startup.ts +1 -0
  80. package/state/paths.ts +11 -3
  81. package/state/raw.ts +2 -3
  82. package/state/resolve.ts +3 -3
  83. package/state/state.ts +26 -3
  84. package/state/writes.ts +1 -1
  85. package/types.ts +97 -43
  86. package/validate/contract-compat.ts +16 -11
  87. package/validate/graph.ts +10 -1
  88. package/validate/issue.ts +20 -6
  89. package/validate/stage-rules.ts +139 -60
  90. package/validate-output.ts +27 -20
  91. package/validate-workflow.ts +5 -3
  92. package/validation-bounds.ts +35 -0
  93. package/docs/cover.png +0 -0
  94. package/docs/cover.svg +0 -120
  95. package/load/cache.test.ts +0 -82
  96. package/load/shape-guards.test.ts +0 -77
  97. package/outcomes/collectors/directory-path.test.ts +0 -64
  98. package/outcomes/collectors/tool-call.test.ts +0 -112
  99. package/outcomes/collectors/transcript-path.test.ts +0 -70
  100. package/outcomes/collectors/union.test.ts +0 -113
  101. package/outcomes/collectors/url.test.ts +0 -67
  102. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  103. package/outcomes/git-commit.test.ts +0 -240
  104. package/outcomes/parsers/json-body.test.ts +0 -80
  105. package/runner/by-name.test.ts +0 -95
  106. package/runner/by-run-id.test.ts +0 -115
  107. package/runner/header-write-failure.test.ts +0 -64
  108. package/runner/resume-loop.test.ts +0 -1410
  109. package/runner/resume-session.test.ts +0 -400
  110. package/runner/resume.test.ts +0 -1805
  111. package/sessions/locate.test.ts +0 -77
@@ -12,21 +12,22 @@
12
12
  */
13
13
 
14
14
  import { LOOP_KINDS, ON_INVALID_VALUES, SESSION_POLICIES, STAGE_KINDS, type StageDef, type Workflow } from "../api.js";
15
- import { resolvePublishName } from "../chain-state.js";
16
- import { type AnyJudge, isPanel, judgeShapeIssues } from "../judge.js";
15
+ import { type AnyJudge, isPanel } from "../judge.js";
17
16
  import {
18
- judgeSlotOf,
17
+ forEachJudgeChannel,
18
+ judgeSlotShapeIssues,
19
19
  loopSpecOf,
20
- panelShapeIssues,
21
20
  panelVerdictChannel,
22
21
  verifyShapeIssues,
23
22
  } from "../loop-constructors.js";
23
+ import { readName } from "../stage-def.js";
24
+ import { resolvePublishName } from "../stage-identity.js";
24
25
  import {
25
26
  MAX_VALIDATION_RETRIES,
26
27
  MAX_VALIDATION_RETRY_TIMEOUT_MS,
27
28
  MIN_VALIDATION_RETRIES,
28
29
  MIN_VALIDATION_RETRY_TIMEOUT_MS,
29
- } from "../validate-output.js";
30
+ } from "../validation-bounds.js";
30
31
  import type { IssueReporter, ReportFn } from "./issue.js";
31
32
 
32
33
  /**
@@ -69,6 +70,20 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
69
70
  if (loop.max !== undefined && (!Number.isInteger(loop.max) || loop.max < 1)) {
70
71
  report("loop-max-invalid", { max: loop.max });
71
72
  }
73
+ if (
74
+ loop.kind === "fanout" &&
75
+ loop.concurrency !== undefined &&
76
+ (!Number.isInteger(loop.concurrency) || loop.concurrency < 1)
77
+ ) {
78
+ report("loop-concurrency-invalid", { concurrency: loop.concurrency });
79
+ }
80
+ if (
81
+ loop.kind === "fanout" &&
82
+ loop.depArtifactFlag !== undefined &&
83
+ (typeof loop.depArtifactFlag !== "string" || loop.depArtifactFlag.trim().length === 0)
84
+ ) {
85
+ report("loop-dep-flag-invalid", { depArtifactFlag: loop.depArtifactFlag });
86
+ }
72
87
  // Pull loops + assess run the stage's outcome collector per unit.
73
88
  if ((loop.kind === "iterate" || loop.kind === "assess") && stage.kind !== "produces") {
74
89
  report("loop-requires-produces", { kind: loop.kind });
@@ -84,11 +99,22 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
84
99
 
85
100
  if (loop.kind !== "assess") return;
86
101
 
87
- // Judge shape — SAME rule sources as the judge()/panel() factories (no
88
- // wording drift). The slot is an `AnyJudge`: a panel routes through
89
- // `panelShapeIssues`, a single judge through `judgeShapeIssues`.
102
+ // Judge shape — SAME rule source as the judge()/panel() factories (no
103
+ // wording drift). The slot is an `AnyJudge`, routed through the shared
104
+ // `judgeSlotShapeIssues` (the panel-vs-single dispatch spelled once, here
105
+ // and in the assess/verify construction paths).
106
+ //
107
+ // This block is the LOAD-GATE half of the (intentionally dual) assess shape
108
+ // validation — see the rationale of record on `assessShapeIssues` in
109
+ // `loop-constructors.ts`. The judge/panel shape above is shared verbatim; the
110
+ // ONLY duplication is the two trivial `done`/`feedForward`
111
+ // `typeof !== "function"` predicates below, kept here AND in `assessShapeIssues`
112
+ // by accepted design (unifying would force a fragile string→code mapping or a
113
+ // silent message change). This block owns the per-code surface the tests pin —
114
+ // `assess-judge-shape` / `assess-done-not-function` /
115
+ // `assess-feed-forward-not-function` (`validate-workflow.test.ts:923,928`).
90
116
  const slot = loop.judge;
91
- const shapeIssues = slot && isPanel(slot) ? panelShapeIssues(slot) : judgeShapeIssues(slot);
117
+ const shapeIssues = judgeSlotShapeIssues(slot);
92
118
  for (const issue of shapeIssues) {
93
119
  report("assess-judge-shape", { issue });
94
120
  }
@@ -105,12 +131,13 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
105
131
 
106
132
  /**
107
133
  * Verdict-channel collisions for a judge SLOT (`AnyJudge`) — workflow-level
108
- * because it needs the producer's publish identity (`stage.outcome?.name ??
109
- * name`). A single judge owns ONE verdict channel; a PANEL owns one channel per
110
- * member PLUS the folded-verdict channel, and every one of them must be
111
- * distinct from the others and from the producer's own slot, or two sessions
112
- * clobber a single `state.named` entry. The SHAPE is checked separately through
113
- * the matching rule source; this is purely the channel-namespace rule.
134
+ * because it needs the producer's publish identity
135
+ * (`resolvePublishName(stage, name)`). A single judge owns ONE verdict channel;
136
+ * a PANEL owns one channel per member PLUS the folded-verdict channel, and every
137
+ * one of them must be distinct from the others and from the producer's own
138
+ * slot, or two sessions clobber a single `state.named` entry. The SHAPE is
139
+ * checked separately through the matching rule source; this is purely the
140
+ * channel-namespace rule.
114
141
  *
115
142
  * `singleCode` (assess- vs verify-worded) is the only per-site difference; the
116
143
  * panel codes are site-independent.
@@ -123,7 +150,7 @@ function checkVerdictChannels(
123
150
  report: ReportFn,
124
151
  ): void {
125
152
  if (!slot) return;
126
- const producer = stage.outcome?.name ?? name;
153
+ const producer = resolvePublishName(stage, name);
127
154
  if (!isPanel(slot)) {
128
155
  if (slot.outcome?.name && slot.outcome.name === producer) {
129
156
  report(singleCode, { channel: slot.outcome.name });
@@ -185,41 +212,58 @@ function checkVerifyInvariants(stage: StageDef, name: string, report: ReportFn):
185
212
  checkVerdictChannels(v.judge, name, stage, "verify-verdict-channel-collision", report);
186
213
  }
187
214
 
215
+ /**
216
+ * ONE range probe — collapses `checkRetryBounds`/`checkTimeoutBounds`. Optional-
217
+ * field early-out → range predicate → `{value, min, max}` report. The bounds
218
+ * constants already live first-class at each call site, so the probe carries
219
+ * zero information not expressible as parameters.
220
+ */
221
+ function checkRange(
222
+ report: ReportFn,
223
+ code: "max-retries-out-of-range" | "validate-timeout-out-of-range",
224
+ value: number | undefined,
225
+ min: number,
226
+ max: number,
227
+ ): void {
228
+ if (value === undefined) return;
229
+ if (value < min || value > max) report(code, { value, min, max });
230
+ }
231
+
232
+ /**
233
+ * ONE enum probe — collapses the three same-shape `{value, allowed}` guards in
234
+ * `checkStageEnums` (onInvalid / kind / sessionPolicy). NOTE: `loop-kind-unknown`
235
+ * (`checkLoopInvariants`) is intentionally NOT unified — it reports `{kind,
236
+ * allowed}` (different param key) and carries an early `return` after the report
237
+ * (kind-specific rules would misfire on an unknown kind); forcing it through this
238
+ * helper would touch the public issue-param shape for marginal gain.
239
+ */
240
+ function checkEnum(
241
+ report: ReportFn,
242
+ code: "on-invalid-unknown" | "stage-kind-unknown" | "session-policy-unknown",
243
+ value: string | undefined,
244
+ allowed: readonly string[],
245
+ ): void {
246
+ if (value !== undefined && !allowed.includes(value)) report(code, { value, allowed: allowed.join(", ") });
247
+ }
248
+
188
249
  function checkRetryBounds(stage: StageDef, report: ReportFn): void {
189
- if (stage.maxRetries === undefined) return;
190
- if (stage.maxRetries < MIN_VALIDATION_RETRIES || stage.maxRetries > MAX_VALIDATION_RETRIES) {
191
- report("max-retries-out-of-range", {
192
- value: stage.maxRetries,
193
- min: MIN_VALIDATION_RETRIES,
194
- max: MAX_VALIDATION_RETRIES,
195
- });
196
- }
250
+ checkRange(report, "max-retries-out-of-range", stage.maxRetries, MIN_VALIDATION_RETRIES, MAX_VALIDATION_RETRIES);
197
251
  }
198
252
 
199
253
  function checkTimeoutBounds(stage: StageDef, report: ReportFn): void {
200
- if (stage.validateTimeoutMs === undefined) return;
201
- if (
202
- stage.validateTimeoutMs < MIN_VALIDATION_RETRY_TIMEOUT_MS ||
203
- stage.validateTimeoutMs > MAX_VALIDATION_RETRY_TIMEOUT_MS
204
- ) {
205
- report("validate-timeout-out-of-range", {
206
- value: stage.validateTimeoutMs,
207
- min: MIN_VALIDATION_RETRY_TIMEOUT_MS,
208
- max: MAX_VALIDATION_RETRY_TIMEOUT_MS,
209
- });
210
- }
254
+ checkRange(
255
+ report,
256
+ "validate-timeout-out-of-range",
257
+ stage.validateTimeoutMs,
258
+ MIN_VALIDATION_RETRY_TIMEOUT_MS,
259
+ MAX_VALIDATION_RETRY_TIMEOUT_MS,
260
+ );
211
261
  }
212
262
 
213
263
  function checkStageEnums(stage: StageDef, report: ReportFn): void {
214
- if (stage.onInvalid !== undefined && !(ON_INVALID_VALUES as readonly string[]).includes(stage.onInvalid)) {
215
- report("on-invalid-unknown", { value: stage.onInvalid, allowed: ON_INVALID_VALUES.join(", ") });
216
- }
217
- if (!(STAGE_KINDS as readonly string[]).includes(stage.kind)) {
218
- report("stage-kind-unknown", { value: stage.kind, allowed: STAGE_KINDS.join(", ") });
219
- }
220
- if (!(SESSION_POLICIES as readonly string[]).includes(stage.sessionPolicy)) {
221
- report("session-policy-unknown", { value: stage.sessionPolicy, allowed: SESSION_POLICIES.join(", ") });
222
- }
264
+ checkEnum(report, "on-invalid-unknown", stage.onInvalid, ON_INVALID_VALUES);
265
+ checkEnum(report, "stage-kind-unknown", stage.kind, STAGE_KINDS);
266
+ checkEnum(report, "session-policy-unknown", stage.sessionPolicy, SESSION_POLICIES);
223
267
  if (stage.kind === "produces" && !stage.outcome && !stage.run) {
224
268
  report("produces-without-outcome");
225
269
  }
@@ -347,9 +391,9 @@ function checkScriptStageInvariants(stage: StageDef, report: ReportFn): void {
347
391
  * judge verdict channels from `loop` (assess) and `verify` — judge sessions
348
392
  * run as `produces` and publish to `judge.outcome.name` (`judgeStageDef`). A
349
393
  * PANEL slot publishes one channel per member verdict plus the folded verdict
350
- * (`panelVerdictChannel`). The old produces-only scan missed verdict channels,
351
- * so a downstream `reads: ["<verdict>"]` falsely errored at load while the
352
- * runtime `ensureNamedReads` preflight would have passed.
394
+ * (`panelVerdictChannel`). The scan includes verdict channels, so a downstream
395
+ * `reads: ["<verdict>"]` doesn't falsely error at load while the runtime
396
+ * `ensureNamedReads` preflight would pass.
353
397
  *
354
398
  * Computed ONCE by the orchestrator and threaded to both consumers
355
399
  * (`checkReadsReferences`, `checkFanoutSource`).
@@ -358,16 +402,9 @@ export function publishedNamesOf(w: Workflow): Set<string> {
358
402
  const published = new Set<string>();
359
403
  for (const [name, stage] of Object.entries(w.stages)) {
360
404
  if (stage.kind === "produces") published.add(resolvePublishName(stage, name));
361
- const slot = judgeSlotOf(stage);
362
- if (!slot) continue;
363
- if (isPanel(slot)) {
364
- // A panel publishes one channel per MEMBER verdict plus the folded
365
- // verdict (`<stage>-panel` or the author's `outcome.name`).
366
- for (const m of slot.members) if (m?.outcome?.name) published.add(m.outcome.name);
367
- published.add(panelVerdictChannel(slot, name));
368
- } else if (slot.outcome?.name) {
369
- published.add(slot.outcome.name);
370
- }
405
+ // Every judge channel (single judge, panel members, AND the folded verdict)
406
+ // counts for reachability — shared walk with the contract-compat index.
407
+ forEachJudgeChannel(stage, name, (channel) => published.add(channel));
371
408
  }
372
409
  return published;
373
410
  }
@@ -388,8 +425,9 @@ export function checkReadsReferences(w: Workflow, published: ReadonlySet<string>
388
425
  if (!stage.reads?.length) continue;
389
426
  const report = r.forStage(name);
390
427
  for (const read of stage.reads) {
391
- if (published.has(read)) continue;
392
- report("reads-unpublished", { channel: read });
428
+ const channel = readName(read);
429
+ if (published.has(channel)) continue;
430
+ report("reads-unpublished", { channel });
393
431
  }
394
432
  }
395
433
  }
@@ -414,7 +452,48 @@ export function checkFanoutSource(w: Workflow, published: ReadonlySet<string>, r
414
452
  const spec = loopSpecOf(stage.loop);
415
453
  const source = spec?.source;
416
454
  if (!source || published.has(source)) continue; // no source / satisfied → degrade
417
- if (stage.reads?.includes(source)) continue; // checkReadsReferences owns this channel
455
+ if (stage.reads?.some((read) => readName(read) === source)) continue; // checkReadsReferences owns this channel
418
456
  r.forStage(name)("loop-source-unpublished", { verb: LOOP_VERB[spec.kind], source });
419
457
  }
420
458
  }
459
+
460
+ /**
461
+ * Channels published by a `fanout()` stage — the producer walk of
462
+ * `publishedNamesOf`, narrowed to fanout loops. Built once and threaded to
463
+ * `checkFanoutReadHint`.
464
+ *
465
+ * The `stage.kind === "produces"` clause is LOAD-BEARING — only a COLLECTING
466
+ * fanout (produces kind) accumulates per-unit Outputs into a named channel; an
467
+ * `acts()` fanout (`kind: "side-effect"`) publishes nothing, so its name would
468
+ * be a false fanout channel. rpiv-pi's built-ins carry fanout loops on
469
+ * `acts()` implement stages while the "plans" channel they read is published by
470
+ * a separate `produces()` stage — relaxing this predicate would fire the hint
471
+ * across every shipped built-in and break the sibling package's zero-warning
472
+ * release gate.
473
+ */
474
+ export function fanoutPublishedChannels(w: Workflow): Set<string> {
475
+ const channels = new Set<string>();
476
+ for (const [name, stage] of Object.entries(w.stages)) {
477
+ if (loopSpecOf(stage.loop)?.kind === "fanout" && stage.kind === "produces") {
478
+ channels.add(resolvePublishName(stage, name));
479
+ }
480
+ }
481
+ return channels;
482
+ }
483
+
484
+ /**
485
+ * Soft nudge: a bare-string read of a channel that a fanout fills reads only the
486
+ * last unit's output (`array.at(-1)`). Almost always the author meant `fanin()`
487
+ * — the fanout-and-synthesize barrier. WARNS (never errors): latest-only is
488
+ * legal. `fanin()` reads are already opted in (object form) — skipped.
489
+ */
490
+ export function checkFanoutReadHint(w: Workflow, fanoutChannels: ReadonlySet<string>, r: IssueReporter): void {
491
+ for (const [name, stage] of Object.entries(w.stages)) {
492
+ if (!stage.reads?.length) continue;
493
+ const report = r.forStage(name);
494
+ for (const read of stage.reads) {
495
+ if (typeof read !== "string") continue; // already opted in via fanin()
496
+ if (fanoutChannels.has(read)) report("reads-latest-from-fanout", { channel: read });
497
+ }
498
+ }
499
+ }
@@ -42,13 +42,17 @@ export interface ValidationResult {
42
42
  // Constants
43
43
  // ---------------------------------------------------------------------------
44
44
 
45
- export const MIN_VALIDATION_RETRIES = 1;
46
- export const MAX_VALIDATION_RETRIES = 3;
47
- export const DEFAULT_VALIDATION_RETRIES = 1;
48
-
49
- export const DEFAULT_VALIDATION_RETRY_TIMEOUT_MS = 5 * 60 * 1000;
50
- export const MAX_VALIDATION_RETRY_TIMEOUT_MS = 30 * 60 * 1000;
51
- export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
45
+ // The policy bounds live in the dependency-free `validation-bounds.ts` leaf so
46
+ // the load-time validator can read them without importing this runtime module;
47
+ // re-exported here so this module's runtime callers keep a single import.
48
+ export {
49
+ DEFAULT_VALIDATION_RETRIES,
50
+ DEFAULT_VALIDATION_RETRY_TIMEOUT_MS,
51
+ MAX_VALIDATION_RETRIES,
52
+ MAX_VALIDATION_RETRY_TIMEOUT_MS,
53
+ MIN_VALIDATION_RETRIES,
54
+ MIN_VALIDATION_RETRY_TIMEOUT_MS,
55
+ } from "./validation-bounds.js";
52
56
 
53
57
  /**
54
58
  * Thrown by `withTimeout` (internal-utils.ts) when the caller passes a
@@ -65,7 +69,7 @@ export class SchemaTimeoutError extends Error {}
65
69
  // ---------------------------------------------------------------------------
66
70
 
67
71
  /**
68
- * Hooks for `runValidationRetryLoop`. `H` is the caller's halt payload — a
72
+ * Hooks for `runValidationRetryLoop`. `H` is the caller's abort payload — a
69
73
  * tagged value that aborts the loop immediately (extraction's fatal arm; the
70
74
  * script path's already-recorded failure marker). Throws are NOT caught:
71
75
  * they propagate to the caller's own catch posture (the runner's single
@@ -73,47 +77,50 @@ export class SchemaTimeoutError extends Error {}
73
77
  */
74
78
  export interface RetryLoopHooks<T, H> {
75
79
  /** Produce attempt `n` (0-based; 0 = the initial production). */
76
- produce(attempt: number): Promise<{ ok: true; value: T } | { ok: false; halt: H }>;
80
+ produce(attempt: number): Promise<{ kind: "ok"; value: T } | { kind: "aborted"; abort: H }>;
77
81
  /** Validate one produced value. */
78
- validate(value: T): Promise<{ ok: true; result: ValidationResult } | { ok: false; halt: H }>;
82
+ validate(value: T): Promise<{ kind: "ok"; result: ValidationResult } | { kind: "aborted"; abort: H }>;
79
83
  /** Between a failed validation and the next produce. `attempt` is 1-based. */
80
- onRetry(attempt: number, failures: SchemaValidationFailure[]): Promise<{ ok: true } | { ok: false; halt: H }>;
84
+ onRetry(
85
+ attempt: number,
86
+ failures: SchemaValidationFailure[],
87
+ ): Promise<{ kind: "ok" } | { kind: "aborted"; abort: H }>;
81
88
  }
82
89
 
83
90
  export type RetryLoopOutcome<T, H> =
84
91
  | { kind: "ok"; value: T }
85
92
  | { kind: "exhausted"; failures: SchemaValidationFailure[] }
86
- | { kind: "halt"; halt: H };
93
+ | { kind: "aborted"; abort: H };
87
94
 
88
95
  /**
89
96
  * THE produce → validate → retry policy loop, shared by the skill path
90
97
  * (extraction.ts — re-prompts the agent between attempts) and the script
91
98
  * path (script-stage.ts — re-invokes the function). One structure: produce,
92
- * validate, and while invalid — stop on `haltOnInvalid` or a spent budget
99
+ * validate, and while invalid — stop on `failFast` or a spent budget
93
100
  * (`"exhausted"`), otherwise fire the retry hook and go again. Total
94
101
  * productions are bounded by `maxRetries + 1`.
95
102
  */
96
103
  export async function runValidationRetryLoop<T, H>(
97
- policy: { maxRetries: number; haltOnInvalid: boolean },
104
+ policy: { maxRetries: number; failFast: boolean },
98
105
  hooks: RetryLoopHooks<T, H>,
99
106
  ): Promise<RetryLoopOutcome<T, H>> {
100
107
  let attempt = 0;
101
108
  let produced = await hooks.produce(attempt);
102
- if (!produced.ok) return { kind: "halt", halt: produced.halt };
109
+ if (produced.kind !== "ok") return { kind: "aborted", abort: produced.abort };
103
110
  let validation = await hooks.validate(produced.value);
104
- if (!validation.ok) return { kind: "halt", halt: validation.halt };
111
+ if (validation.kind !== "ok") return { kind: "aborted", abort: validation.abort };
105
112
 
106
113
  while (!validation.result.valid) {
107
- if (policy.haltOnInvalid || attempt >= policy.maxRetries) {
114
+ if (policy.failFast || attempt >= policy.maxRetries) {
108
115
  return { kind: "exhausted", failures: validation.result.failures };
109
116
  }
110
117
  attempt++;
111
118
  const retried = await hooks.onRetry(attempt, validation.result.failures);
112
- if (!retried.ok) return { kind: "halt", halt: retried.halt };
119
+ if (retried.kind !== "ok") return { kind: "aborted", abort: retried.abort };
113
120
  produced = await hooks.produce(attempt);
114
- if (!produced.ok) return { kind: "halt", halt: produced.halt };
121
+ if (produced.kind !== "ok") return { kind: "aborted", abort: produced.abort };
115
122
  validation = await hooks.validate(produced.value);
116
- if (!validation.ok) return { kind: "halt", halt: validation.halt };
123
+ if (validation.kind !== "ok") return { kind: "aborted", abort: validation.abort };
117
124
  }
118
125
  return { kind: "ok", value: produced.value };
119
126
  }
@@ -35,9 +35,11 @@ import {
35
35
  } from "./validate/graph.js";
36
36
  import { issueReporter, type WorkflowValidationIssue } from "./validate/issue.js";
37
37
  import {
38
+ checkFanoutReadHint,
38
39
  checkFanoutSource,
39
40
  checkReadsReferences,
40
41
  checkStageSemantics,
42
+ fanoutPublishedChannels,
41
43
  publishedNamesOf,
42
44
  } from "./validate/stage-rules.js";
43
45
 
@@ -66,16 +68,16 @@ export function validateWorkflow(
66
68
  checkMissingEdges(workflow, r);
67
69
  // Skip reachability when an EdgeFn lacks `.targets` — the BFS would emit
68
70
  // "unreachable from start" cascades whose root cause is the metadata error
69
- // already reported. Gated on the issue CODE (machine-readable — the
70
- // message-regex this replaced was finding C5).
71
+ // already reported. Gated on the issue CODE (machine-readable).
71
72
  if (!issues.some((i) => i.code === "edge-fn-no-targets")) checkReachability(workflow, r);
72
73
 
73
74
  checkStageSemantics(workflow, r);
74
75
 
75
- // The publisher set is computed ONCE and threaded to both consumers (D10).
76
+ // The publisher set is computed ONCE and threaded to both consumers.
76
77
  const published = publishedNamesOf(workflow);
77
78
  checkReadsReferences(workflow, published, r);
78
79
  checkFanoutSource(workflow, published, r);
80
+ checkFanoutReadHint(workflow, fanoutPublishedChannels(workflow), r);
79
81
 
80
82
  checkPredicateSchemas(workflow, r, opts?.skillContracts);
81
83
  checkEdgeSchemaCompat(workflow, r, opts?.skillContracts);
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Output-validation policy bounds — the retry-count and per-attempt timeout
3
+ * clamps shared by the RUNTIME retry loop (`validate-output.ts`,
4
+ * `sessions/extraction.ts`, `runner/input-validation.ts`) and the LOAD-TIME
5
+ * stage-rule validator (`validate/stage-rules.ts`).
6
+ *
7
+ * A dependency-free LEAF (zero imports) so `validate/` can read the bounds
8
+ * WITHOUT importing `validate-output.ts`, which also houses the runtime
9
+ * `runValidationRetryLoop` engine — a definition-context module should not pull
10
+ * a runtime control loop onto its dependency graph just to read six numbers.
11
+ * `validate-output.ts` re-exports these so its runtime callers keep one import.
12
+ */
13
+
14
+ export const MIN_VALIDATION_RETRIES = 1;
15
+ export const MAX_VALIDATION_RETRIES = 3;
16
+ export const DEFAULT_VALIDATION_RETRIES = 1;
17
+
18
+ export const DEFAULT_VALIDATION_RETRY_TIMEOUT_MS = 5 * 60 * 1000;
19
+ export const MAX_VALIDATION_RETRY_TIMEOUT_MS = 30 * 60 * 1000;
20
+ export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
21
+
22
+ /**
23
+ * Clamp `raw` to `[min, max]`, defaulting to `def` when `raw` is `undefined`.
24
+ * The ONE runtime-clamp idiom shared by the runtime retry loop
25
+ * (`sessions/extraction.ts:retryUntilValid` — retries + timeout) and the input
26
+ * preflight (`runner/input-validation.ts:clampValidateTimeoutMs` — timeout).
27
+ * Same defense-in-depth posture as the load-time `checkRange`: `validateWorkflow`
28
+ * rejects out-of-range values at load, but programmatic callers that embed
29
+ * `runWorkflow` can bypass it; clamping here means a misconfigured stage degrades
30
+ * to the spec-default behavior instead of firing a 100ms timeout before a real
31
+ * I/O probe gets a chance to settle.
32
+ */
33
+ export function clampRange(raw: number | undefined, min: number, def: number, max: number): number {
34
+ return Math.max(min, Math.min(raw ?? def, max));
35
+ }
package/docs/cover.png DELETED
Binary file
package/docs/cover.svg DELETED
@@ -1,120 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 800" role="img" aria-label="rpiv-workflow — Chain Pi skills into typed multi-stage workflows" preserveAspectRatio="xMidYMid meet">
2
- <title>rpiv-workflow — Chain Pi skills into typed multi-stage workflows</title>
3
- <defs>
4
- <style>
5
- .mono { font-family: 'JetBrains Mono', 'Fira Code', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
6
- .serif { font-family: 'Iowan Old Style', 'Hoefler Text', Charter, 'Source Serif Pro', Georgia, serif; }
7
- .ink { fill: #ede6d3; }
8
- .text-quiet { fill: #a8a29e; }
9
- .text-distant { fill: #9c968d; }
10
- .ochre { fill: #a8896c; }
11
- .sage { fill: #8a9580; }
12
- .sage-deep { fill: #5e6b56; }
13
- </style>
14
- <radialGradient id="wash-ochre" cx="25%" cy="10%" r="65%">
15
- <stop offset="0%" stop-color="#a8896c" stop-opacity="0.10"/>
16
- <stop offset="100%" stop-color="#a8896c" stop-opacity="0"/>
17
- </radialGradient>
18
- <radialGradient id="wash-sage" cx="85%" cy="90%" r="55%">
19
- <stop offset="0%" stop-color="#8a9580" stop-opacity="0.07"/>
20
- <stop offset="100%" stop-color="#8a9580" stop-opacity="0"/>
21
- </radialGradient>
22
-
23
- </defs>
24
-
25
- <rect width="1280" height="800" fill="#1c1a17"/>
26
- <rect width="1280" height="800" fill="url(#wash-ochre)"/>
27
- <rect width="1280" height="800" fill="url(#wash-sage)"/>
28
-
29
- <g fill="none" stroke="#8a9580" stroke-linecap="round" opacity="0.45">
30
- <path d="M1120 60 q36 -52 88 -60 q40 -5 68 14" stroke-width="1.1"/>
31
- <path d="M1140 80 q28 -18 60 -14 q24 3 42 14" stroke-width="0.7" opacity="0.6"/>
32
- <circle cx="1210" cy="32" r="2" opacity="0.5"/>
33
- <circle cx="1160" cy="60" r="1.4" opacity="0.4"/>
34
- </g>
35
-
36
- <text class="mono text-distant" x="80" y="64" font-size="11" letter-spacing="0.18em">PI AGENT EXTENSION</text>
37
-
38
- <text class="serif ink" x="80" y="152" font-size="80" font-weight="700" letter-spacing="-2.5">rpiv<tspan class="ochre">-</tspan>workflow</text>
39
- <text class="mono text-quiet" x="80" y="196" font-size="19" letter-spacing="0.2">Chain Pi skills into typed multi-stage workflows.</text>
40
-
41
- <line x1="80" y1="228" x2="1200" y2="228" stroke="#2e2b27" stroke-width="1"/>
42
-
43
- <rect x="80" y="264" width="1120" height="440" rx="3" fill="#1c1a17" stroke="#3a3631" stroke-width="1"/>
44
-
45
- <!-- Main timeline (research → plan → review → gate → commit → stop) -->
46
- <line x1="200" y1="468" x2="800" y2="468" stroke="#a8896c" stroke-width="2"/>
47
- <line x1="836" y1="468" x2="1000" y2="468" stroke="#a8896c" stroke-width="2"/>
48
- <line x1="1000" y1="468" x2="1124" y2="468" stroke="#a8896c" stroke-width="2"/>
49
- <path d="M1114 459 L1128 468 L1114 477" fill="none" stroke="#a8896c" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>
50
-
51
- <!-- Loopback edge: gate → (down) → (left) → plan -->
52
- <path d="M800 484 Q800 580 720 580 L480 580 Q400 580 400 500 L400 484"
53
- fill="none" stroke="#5e6b56" stroke-width="1.6" stroke-dasharray="4 4" stroke-linecap="round"/>
54
- <path d="M392 494 L400 480 L408 494" fill="none" stroke="#5e6b56" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"/>
55
-
56
- <!-- Loopback label -->
57
- <text class="mono sage" x="600" y="572" font-size="11" letter-spacing="0.18em" text-anchor="middle" font-weight="700">REVISE &#183; blockers &gt; 0</text>
58
-
59
- <!-- Branch label on straight path to commit -->
60
- <text class="mono text-distant" x="900" y="456" font-size="11" letter-spacing="0.16em" text-anchor="middle">blockers == 0</text>
61
-
62
- <!-- Node 01: Research (produces) -->
63
- <g transform="translate(200 468)">
64
- <circle r="14" fill="#1c1a17" stroke="#a8896c" stroke-width="2"/>
65
- <circle r="5" fill="#a8896c"/>
66
- <text class="mono text-distant" x="0" y="-36" font-size="11" letter-spacing="0.12em" text-anchor="middle">01 &#183; produces</text>
67
- <text class="mono ink" x="0" y="52" font-size="15" letter-spacing="0.12em" text-anchor="middle" font-weight="700">RESEARCH</text>
68
- </g>
69
-
70
- <!-- Node 02: Plan (produces) -->
71
- <g transform="translate(400 468)">
72
- <circle r="14" fill="#1c1a17" stroke="#a8896c" stroke-width="2"/>
73
- <circle r="5" fill="#a8896c"/>
74
- <text class="mono text-distant" x="0" y="-36" font-size="11" letter-spacing="0.12em" text-anchor="middle">02 &#183; produces</text>
75
- <text class="mono ink" x="0" y="52" font-size="15" letter-spacing="0.12em" text-anchor="middle" font-weight="700">PLAN</text>
76
- </g>
77
-
78
- <!-- Node 03: Review (produces, emits blockers count) -->
79
- <g transform="translate(600 468)">
80
- <circle r="14" fill="#1c1a17" stroke="#a8896c" stroke-width="2"/>
81
- <circle r="5" fill="#a8896c"/>
82
- <text class="mono text-distant" x="0" y="-36" font-size="11" letter-spacing="0.12em" text-anchor="middle">03 &#183; produces</text>
83
- <text class="mono ink" x="0" y="52" font-size="15" letter-spacing="0.12em" text-anchor="middle" font-weight="700">REVIEW</text>
84
- </g>
85
-
86
- <!-- Node 04: Gate (predicate routing — diamond) -->
87
- <g transform="translate(800 468)">
88
- <polygon points="0,-18 18,0 0,18 -18,0" fill="#1c1a17" stroke="#8a9580" stroke-width="2"/>
89
- <circle r="3.5" fill="#8a9580"/>
90
- <text class="mono text-distant" x="0" y="-40" font-size="11" letter-spacing="0.12em" text-anchor="middle">04 &#183; gate</text>
91
- <text class="mono sage" x="0" y="54" font-size="15" letter-spacing="0.12em" text-anchor="middle" font-weight="700">blockers_count</text>
92
- </g>
93
-
94
- <!-- Node 05: Commit (acts) -->
95
- <g transform="translate(1000 468)">
96
- <circle r="16" fill="#1c1a17" stroke="#8a9580" stroke-width="2"/>
97
- <circle r="6" fill="#8a9580"/>
98
- <text class="mono text-distant" x="0" y="-38" font-size="11" letter-spacing="0.12em" text-anchor="middle">05 &#183; acts</text>
99
- <text class="mono sage" x="0" y="54" font-size="15" letter-spacing="0.12em" text-anchor="middle" font-weight="700">COMMIT</text>
100
- </g>
101
-
102
- <!-- Stop terminator -->
103
- <g transform="translate(1140 468)">
104
- <rect x="-6" y="-9" width="12" height="18" fill="#5e6b56" stroke="#5e6b56" stroke-width="1"/>
105
- <text class="mono text-distant" x="0" y="34" font-size="11" letter-spacing="0.18em" text-anchor="middle">STOP</text>
106
- </g>
107
-
108
- <!-- Caption -->
109
- <text class="mono text-distant" x="640" y="660" font-size="12" letter-spacing="0.2em" text-anchor="middle">TYPED STAGES &#183; PREDICATE ROUTING &#183; TS SCRIPTING &#183; .rpiv/workflows/</text>
110
-
111
- <line x1="80" y1="740" x2="1200" y2="740" stroke="#2e2b27" stroke-width="1"/>
112
-
113
- <text class="mono text-distant" x="80" y="776" font-size="12" letter-spacing="0.12em">
114
- <tspan class="ochre" font-weight="700">&#9612; rpiv-workflow</tspan>
115
- <tspan dx="12">&#9474;</tspan>
116
- <tspan dx="12" class="sage">/wf &#183; defineWorkflow() &#183; gate()</tspan>
117
- <tspan dx="12">&#9474;</tspan>
118
- <tspan dx="12">npm:@juicesharp/rpiv-workflow</tspan>
119
- </text>
120
- </svg>
@@ -1,82 +0,0 @@
1
- /**
2
- * Direct tests for the mtime-keyed jiti import cache. Exercises both the
3
- * cache-miss path (fresh `jiti.import`) and the cache-hit path (returns
4
- * the stored parsed value without re-evaluating top-level code).
5
- *
6
- * `loadWorkflows` integration tests cover the cache miss every time
7
- * (each `loadWorkflows` call hits the file once); the cache-hit branch
8
- * only fires when the same path is imported twice within one
9
- * `__resetLoadCache()` boundary, which `test/setup.ts:beforeEach`
10
- * normally prevents. These tests opt out of the global reset by calling
11
- * `cachedImport` directly.
12
- */
13
-
14
- import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
15
- import { tmpdir } from "node:os";
16
- import { join } from "node:path";
17
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
18
- import { __resetLoadCache, cachedImport } from "./cache.js";
19
-
20
- const TMP_ROOT = mkdtempSync(join(tmpdir(), "rpiv-workflow-cache-"));
21
-
22
- beforeEach(() => {
23
- __resetLoadCache();
24
- });
25
-
26
- afterEach(() => {
27
- __resetLoadCache();
28
- });
29
-
30
- // One-shot cleanup so we don't leak the tmp directory.
31
- process.on("exit", () => {
32
- rmSync(TMP_ROOT, { recursive: true, force: true });
33
- });
34
-
35
- const writeFixture = (name: string, body: string): string => {
36
- const path = join(TMP_ROOT, name);
37
- writeFileSync(path, body, "utf-8");
38
- return path;
39
- };
40
-
41
- describe("cachedImport", () => {
42
- it("returns the parsed default export on first call (cache miss)", async () => {
43
- const path = writeFixture("miss.ts", "export default 'first';\n");
44
- const value = await cachedImport(path);
45
- expect(value).toBe("first");
46
- });
47
-
48
- it("returns the cached value when mtime is unchanged (cache hit)", async () => {
49
- const path = writeFixture("hit.ts", "export default { v: 1 };\n");
50
- const first = await cachedImport(path);
51
- const second = await cachedImport(path);
52
- // Same reference — proves the second call short-circuited via the cache
53
- // (a re-evaluated `jiti.import` would return a freshly-allocated object).
54
- expect(second).toBe(first);
55
- });
56
-
57
- it("re-imports when mtime advances (edit invalidates the cache)", async () => {
58
- const path = writeFixture("edit.ts", "export default 'v1';\n");
59
- const first = await cachedImport(path);
60
- expect(first).toBe("v1");
61
-
62
- // Rewrite + bump mtime far enough that the cache key changes even on
63
- // coarse-mtime filesystems.
64
- writeFileSync(path, "export default 'v2';\n", "utf-8");
65
- const future = new Date(Date.now() + 60_000);
66
- utimesSync(path, future, future);
67
-
68
- const second = await cachedImport(path);
69
- expect(second).toBe("v2");
70
- });
71
-
72
- it("__resetLoadCache forces a fresh re-import on the next call", async () => {
73
- const path = writeFixture("reset.ts", "export default { tag: 'x' };\n");
74
- const first = await cachedImport(path);
75
- __resetLoadCache();
76
- const second = await cachedImport(path);
77
- // Different references prove the reset cleared the entry — jiti returned
78
- // a freshly-evaluated object.
79
- expect(second).not.toBe(first);
80
- expect(second).toEqual(first);
81
- });
82
- });