@juicesharp/rpiv-workflow 1.19.1 → 2.0.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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
@@ -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/control-flow.ts DELETED
@@ -1,135 +0,0 @@
1
- /**
2
- * Control-flow as data — `fanout`/`iterate` made inspectable.
3
- *
4
- * `fanout`/`iterate` are first-class at RUNTIME (the runner drives them) but
5
- * opaque to INTROSPECTION: they're raw functions on `StageDef`, and the pattern
6
- * (what they split over, the cardinality bound, parallel-vs-sequential) lives
7
- * inside a closure. This module makes that pattern inspectable-as-data by
8
- * attaching a declarative `.spec` to the function — the exact mechanism
9
- * `defineRoute`/`gate` use to attach `.targets` (`api.ts`) so reachability checks
10
- * read every branch without executing the predicate.
11
- *
12
- * `fanoutOver(spec)` / `iterateOver(spec)` return the SAME `FanoutFn`/`IterateFn`
13
- * the runner already consumes (zero runner change), carrying a `FanoutSpec`/
14
- * `IterateSpec`. Introspectors read the spec; the runner calls the function.
15
- * A raw `FanoutFn` with no `.spec` stays valid and reads as opaque — same
16
- * degrade posture as a Zod schema being opaque to `extractJsonSchema`, or a
17
- * predicate edge being skipped by edge-compat.
18
- *
19
- * Skill-agnostic: this module ships the spec VOCABULARY (data) only. The actual
20
- * unit detector (e.g. "parse the plan's `phases:` frontmatter") is the consumer-
21
- * supplied `run` function — `rpiv-workflow` ships no conventions.
22
- */
23
-
24
- import type { EdgeFn, FanoutFn, IterateFn, Workflow } from "./api.js";
25
- import { STOP } from "./api.js";
26
-
27
- /**
28
- * How a stage's work is split into units, AS DATA. `by` names the convention
29
- * ("frontmatter-array" | "markdown-heading" | "glob" | "json-path" | a consumer
30
- * tag); `pattern` is its opaque parameter; `meta` carries any extra domain hints.
31
- * The framework never interprets `by`/`pattern` for execution (the `run` fn does)
32
- * — it only surfaces them so an agent can read or emit the pattern. Open + opaque,
33
- * mirroring the contract `meta` bag.
34
- */
35
- export interface UnitSelector {
36
- by: string;
37
- pattern?: string;
38
- meta?: Record<string, unknown>;
39
- }
40
-
41
- /** Common shape of both control-flow specs — the introspectable facet. */
42
- interface ControlFlowSpecBase {
43
- /** The channel / artifact-kind the units are split FROM (a `consumes` signal). */
44
- source?: string;
45
- /** How units are detected (opaque convention). */
46
- unit?: UnitSelector;
47
- /** Cardinality ceiling, surfaced from what used to be a private constant. */
48
- max?: number;
49
- }
50
-
51
- /** Parallel map: all units computed up front, run independent of one another. */
52
- export interface FanoutSpec extends ControlFlowSpecBase {
53
- kind: "fanout";
54
- }
55
-
56
- /** Sequential fold: one unit per call, each seeing the prior units' outputs. */
57
- export interface IterateSpec extends ControlFlowSpecBase {
58
- kind: "iterate";
59
- /** `iterate`'s defining trait — each unit builds on `accumulated`. Always `true`. */
60
- dependsOnPrior: true;
61
- }
62
-
63
- export type ControlFlowSpec = FanoutSpec | IterateSpec;
64
-
65
- /** A `FanoutFn`/`IterateFn` carrying its introspectable spec (cf. `EdgeFn.targets`). */
66
- export type SpeccedFanoutFn = FanoutFn & { spec: FanoutSpec };
67
- export type SpeccedIterateFn = IterateFn & { spec: IterateSpec };
68
-
69
- /**
70
- * Build a fanout that is BOTH executable (the runner calls it) and describable
71
- * (introspectors read `.spec`) — the `defineRoute` pattern for control flow. The
72
- * `run` fn is the consumer-supplied detector; `rpiv-workflow` ships none.
73
- */
74
- export function fanoutOver(spec: Omit<FanoutSpec, "kind"> & { run: FanoutFn }): SpeccedFanoutFn {
75
- const { run, ...rest } = spec;
76
- const fn = run as SpeccedFanoutFn;
77
- fn.spec = { kind: "fanout", ...rest };
78
- return fn;
79
- }
80
-
81
- /** Sequential-fold counterpart. `dependsOnPrior` is implied + fixed to `true`. */
82
- export function iterateOver(spec: Omit<IterateSpec, "kind" | "dependsOnPrior"> & { run: IterateFn }): SpeccedIterateFn {
83
- const { run, ...rest } = spec;
84
- const fn = run as SpeccedIterateFn;
85
- fn.spec = { kind: "iterate", dependsOnPrior: true, ...rest };
86
- return fn;
87
- }
88
-
89
- /** Read a fanout spec off a stage's fanout fn, or `undefined` if raw/opaque. */
90
- export function fanoutSpecOf(fn: FanoutFn | undefined): FanoutSpec | undefined {
91
- return typeof fn === "function" && "spec" in fn ? (fn as SpeccedFanoutFn).spec : undefined;
92
- }
93
-
94
- /** Read an iterate spec off a stage's iterate fn, or `undefined` if raw/opaque. */
95
- export function iterateSpecOf(fn: IterateFn | undefined): IterateSpec | undefined {
96
- return typeof fn === "function" && "spec" in fn ? (fn as SpeccedIterateFn).spec : undefined;
97
- }
98
-
99
- /**
100
- * Per-stage control-flow + edge shape, read entirely from data already attached
101
- * (`.spec`, `.targets`) — no probing. The control-flow analogue of
102
- * `legalNextSkills`: what an analyzing/suggesting agent consumes to render or
103
- * reason about a flow's structure.
104
- */
105
- export interface StageShape {
106
- stage: string;
107
- skill?: string;
108
- control: { mode: "single" | "fanout" | "iterate"; spec?: ControlFlowSpec };
109
- edge: { mode: "linear" | "route" | "terminal"; targets?: readonly string[] };
110
- }
111
-
112
- /** Describe a workflow's structure stage-by-stage from attached metadata alone. */
113
- export function describeFlow(w: Workflow): StageShape[] {
114
- return Object.entries(w.stages).map(([name, stage]) => {
115
- const fanoutSpec = fanoutSpecOf(stage.fanout);
116
- const iterateSpec = iterateSpecOf(stage.iterate);
117
- const control: StageShape["control"] = stage.fanout
118
- ? { mode: "fanout", spec: fanoutSpec }
119
- : stage.iterate
120
- ? { mode: "iterate", spec: iterateSpec }
121
- : { mode: "single" };
122
-
123
- const target = w.edges[name];
124
- let edge: StageShape["edge"];
125
- if (target === undefined || target === STOP) {
126
- edge = { mode: "terminal" };
127
- } else if (typeof target === "string") {
128
- edge = { mode: "linear", targets: [target] };
129
- } else {
130
- edge = { mode: "route", targets: (target as EdgeFn).targets };
131
- }
132
-
133
- return { stage: name, skill: stage.skill, control, edge };
134
- });
135
- }
package/fanout.ts DELETED
@@ -1,102 +0,0 @@
1
- /**
2
- * Fanout iteration. When a stage opts in via `StageDef.fanout`, the runner
3
- * calls the user's `FanoutFn` to get a list of units and iterates one Pi
4
- * session per unit. This module owns the iteration loop; `runner.ts`
5
- * injects its primitives via `FanoutDeps` so the module never imports
6
- * back (cycle-free).
7
- *
8
- * No markdown regex, no per-convention counter, no cap — rpiv-workflow
9
- * stays convention-agnostic. Consumers (rpiv-pi etc.) own the FanoutFn
10
- * body and any safety bounds it needs.
11
- */
12
-
13
- import type { FanoutUnit } from "./api.js";
14
- import { runIdentityOf } from "./audit.js";
15
- import { buildLifecycleContext, skillStageRef } from "./lifecycle.js";
16
- import { MSG_STAGE_COMPLETE, STATUS_FANOUT_UNIT, STATUS_KEY } from "./messages.js";
17
- import type { FanoutSession, RunContext, WorkflowHostContext } from "./types.js";
18
-
19
- export interface FanoutDeps {
20
- runFanoutSession: (ctx: WorkflowHostContext, session: FanoutSession) => Promise<void>;
21
- /**
22
- * Resume the chain after the fanout node's units finish. Receives the
23
- * fanout node's name so the routing layer can look up the outgoing
24
- * edge from it.
25
- */
26
- advanceAfter: (
27
- curCtx: WorkflowHostContext,
28
- completedName: string,
29
- completedIdx: number,
30
- run: RunContext,
31
- ) => Promise<void>;
32
- }
33
-
34
- /**
35
- * `skill` is the bundled skill body (threaded by the runner), not the node
36
- * name. Aliased nodes (e.g. `implement-after-revise` invoking `implement`)
37
- * tag unit rows + prompts with the skill body so audit consumers don't see
38
- * two labels for the same work. Caller verifies node + fanout shape before
39
- * invoking (see `runStage`).
40
- *
41
- * `currentName` is the fanout node's name in the workflow — passed to
42
- * `advanceAfter` once the final unit completes so the routing layer can
43
- * look up the outgoing edge from it.
44
- *
45
- * `units` was already produced by the user's `FanoutFn`; the iteration loop
46
- * walks it in order. `p` is the 1-based index into `units` for the next
47
- * session to run — the continuation-style self-call increments it.
48
- */
49
- export async function runFanout(
50
- curCtx: WorkflowHostContext,
51
- stageIdx: number,
52
- currentName: string,
53
- skill: string,
54
- p: number,
55
- units: readonly FanoutUnit[],
56
- run: RunContext,
57
- deps: FanoutDeps,
58
- ): Promise<void> {
59
- const { cwd, runId, totalStages, state } = run;
60
-
61
- if (p > units.length) {
62
- curCtx.ui.notify(MSG_STAGE_COMPLETE(skill), "info");
63
- await deps.advanceAfter(curCtx, currentName, stageIdx, run);
64
- return;
65
- }
66
-
67
- const unit = units[p - 1]!;
68
- curCtx.ui.setStatus(STATUS_KEY, STATUS_FANOUT_UNIT(stageIdx + 1, totalStages, skill, unit.label));
69
-
70
- const lifecycleCtx = buildLifecycleContext({
71
- cwd,
72
- runId,
73
- workflow: run.workflow.name,
74
- totalStages: run.totalStages,
75
- trigger: run.trigger,
76
- state,
77
- });
78
- await run.lifecycle.fire(
79
- curCtx,
80
- "onFanoutUnitStart",
81
- skillStageRef(currentName, stageIdx + 1, skill),
82
- unit,
83
- p,
84
- lifecycleCtx,
85
- );
86
-
87
- await deps.runFanoutSession(curCtx, {
88
- cwd,
89
- runId,
90
- state,
91
- prompt: `/skill:${skill} ${unit.prompt}`,
92
- stageName: currentName,
93
- skill,
94
- lifecycle: run.lifecycle,
95
- runIdentity: runIdentityOf(run),
96
- unitIndex: p,
97
- label: unit.label,
98
- id: unit.id,
99
- stageIndex: stageIdx,
100
- onSuccess: (freshCtx) => runFanout(freshCtx, stageIdx, currentName, skill, p + 1, units, run, deps),
101
- });
102
- }
package/iterate.ts DELETED
@@ -1,155 +0,0 @@
1
- /**
2
- * Iterate iteration — the sequential, accumulating dual of `fanout.ts`. When a
3
- * stage opts in via `StageDef.iterate`, the runner pulls units one at a time
4
- * (calling the user's `IterateFn` per unit, feeding it the prior units'
5
- * validated `Output`s) and runs one Pi session per unit. Unlike fanout, each
6
- * unit runs the stage's `outcome` collector — it reuses `runStageSession`
7
- * verbatim, so every unit gets the same collector → validate → record →
8
- * accumulate path as a one-shot `produces` stage.
9
- *
10
- * `runner.ts` (via `stage-lifecycle.ts`) injects the runner primitives through
11
- * `IterateDeps` so this module never imports back (cycle-free), mirroring how
12
- * `runFanout` receives `FanoutDeps`.
13
- *
14
- * Two run-wide bounds are the only safety nets: the generator's own `null`
15
- * terminator, and `run.maxIterations` (the backstop for a generator that never
16
- * returns null). No markdown regex, no per-convention counter — rpiv-workflow
17
- * stays convention-agnostic; the `IterateFn` body owns the convention.
18
- *
19
- * Resume contract: `resumeWorkflow` re-enters this pull loop at the next
20
- * not-yet-completed unit by feeding `runIterate` the reconstructed entry artifact
21
- * + accumulated prefix. That REQUIRES the `IterateFn` to be deterministic w.r.t.
22
- * its entry artifact + accumulated outputs — resume guards the one checkable
23
- * boundary (the re-pulled next unit) and trusts the completed prefix by contract.
24
- * See `runner/resume-iterate.ts`.
25
- */
26
-
27
- import type { StageDef } from "./api.js";
28
- import { iterateRowStage, runIdentityOf } from "./audit.js";
29
- import type { Artifact } from "./handle.js";
30
- import { MSG_ITERATE_ZERO_UNITS, MSG_STAGE_COMPLETE, STATUS_ITERATE_UNIT, STATUS_KEY } from "./messages.js";
31
- import type { Output } from "./output.js";
32
- import type { RunContext, StageSession, WorkflowHostContext } from "./types.js";
33
-
34
- export interface IterateDeps {
35
- /**
36
- * Dispatch one unit through the standard stage-session path (collector →
37
- * validate → record → accumulate). The same `runStageSession` a normal
38
- * `produces` stage uses — iterate adds no bespoke session machinery.
39
- */
40
- runStageSession: (ctx: WorkflowHostContext, s: StageSession) => Promise<void>;
41
- /**
42
- * Resume the chain after the iterate node's units finish (generator
43
- * returned null). Receives the iterate node's REAL name so routing looks up
44
- * the outgoing edge from it — the per-unit audit decoration never leaks
45
- * into routing.
46
- */
47
- advanceAfter: (
48
- curCtx: WorkflowHostContext,
49
- completedName: string,
50
- completedIdx: number,
51
- run: RunContext,
52
- ) => Promise<void>;
53
- /** Re-capture the outcome's pre-stage snapshot per unit (each unit is its own produces pass). */
54
- captureSnapshot: (def: StageDef, idx: number, run: RunContext) => Promise<unknown>;
55
- /** Record the terminal failure when the `maxIterations` backstop trips. */
56
- haltIterations: (curCtx: WorkflowHostContext, run: RunContext, stageName: string, count: number) => Promise<void>;
57
- }
58
-
59
- /**
60
- * `skill` is the bundled skill body (threaded by the runner), not the node
61
- * name — aliased nodes tag unit rows + prompts with the skill body so audit
62
- * consumers don't see two labels for the same work.
63
- *
64
- * `currentName` is the iterate node's REAL name in the workflow — passed to
65
- * `advanceAfter` once the generator terminates, and used (undecorated) for
66
- * `state.named` keying via `resolvePublishName`.
67
- *
68
- * `entryArtifact` is the stage-entry primary, FROZEN across every unit (the
69
- * rolling primary advances to each unit's output, but the generator keeps
70
- * seeing its true source — see `IterateContext.artifact`).
71
- *
72
- * `accumulated` carries this stage's prior validated `Output`s in order. The
73
- * continuation-style self-call appends the unit just produced (read from
74
- * `run.state.output`, which `tryRecordStage` sets immediately before
75
- * `onSuccess`).
76
- */
77
- export async function runIterate(
78
- curCtx: WorkflowHostContext,
79
- stageIdx: number,
80
- currentName: string,
81
- skill: string,
82
- def: StageDef,
83
- entryArtifact: Artifact | undefined,
84
- accumulated: readonly Output[],
85
- run: RunContext,
86
- deps: IterateDeps,
87
- ): Promise<void> {
88
- const unit = await def.iterate!({
89
- cwd: run.cwd,
90
- artifact: entryArtifact,
91
- state: run.state,
92
- accumulated,
93
- index: accumulated.length,
94
- });
95
-
96
- // Generator terminated — complete the stage and resume the chain from the
97
- // real node name. A first-call null is the zero-unit no-op: nothing is
98
- // published, the primary stays at the entry artifact — warn (not error) so
99
- // the author notices the empty input. A null after ≥1 unit is a normal
100
- // completion.
101
- if (!unit) {
102
- if (accumulated.length === 0) curCtx.ui.notify(MSG_ITERATE_ZERO_UNITS(skill), "warning");
103
- else curCtx.ui.notify(MSG_STAGE_COMPLETE(skill), "info");
104
- await deps.advanceAfter(curCtx, currentName, stageIdx, run);
105
- return;
106
- }
107
-
108
- // Backstop: the generator wants another unit but we've hit the run-wide
109
- // cap. Halt with a terminal failure (mirrors the backward-jump guard) so a
110
- // runaway generator can't loop forever.
111
- if (accumulated.length >= run.maxIterations) {
112
- await deps.haltIterations(curCtx, run, currentName, accumulated.length);
113
- return;
114
- }
115
-
116
- curCtx.ui.setStatus(STATUS_KEY, STATUS_ITERATE_UNIT(stageIdx + 1, run.totalStages, skill, unit.label));
117
- const snapshot = await deps.captureSnapshot(def, stageIdx, run);
118
-
119
- await deps.runStageSession(curCtx, {
120
- cwd: run.cwd,
121
- runId: run.runId,
122
- state: run.state,
123
- prompt: `/skill:${skill} ${unit.prompt}`,
124
- // Decorated for the JSONL row + status; named keying still resolves to
125
- // outcome.name (mandatory for iterate), so the decoration never splits
126
- // the accumulation slot.
127
- stageName: iterateRowStage(currentName, unit.id ?? unit.label),
128
- skill,
129
- lifecycle: run.lifecycle,
130
- runIdentity: runIdentityOf(run),
131
- stage: def,
132
- skillContracts: run.skillContracts,
133
- stageIndex: stageIdx,
134
- snapshot,
135
- branchOffset: undefined,
136
- onFailure: undefined,
137
- onSuccess: (freshCtx) => {
138
- // `tryRecordStage` set `state.output` to this unit's validated Output
139
- // (and `applyCompletedStage` already pushed it onto state.named) before
140
- // onSuccess fired. Thread it into `accumulated` for the next pull.
141
- const produced = run.state.output!;
142
- return runIterate(
143
- freshCtx,
144
- stageIdx,
145
- currentName,
146
- skill,
147
- def,
148
- entryArtifact,
149
- [...accumulated, produced],
150
- run,
151
- deps,
152
- );
153
- },
154
- });
155
- }
@@ -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
- });
@@ -1,74 +0,0 @@
1
- /**
2
- * Direct unit tests for the loader's small shape guards + formatting
3
- * helpers. `isWorkflow` / `isEnvelope` are exercised transitively through
4
- * `loadWorkflows` integration tests — but `describe` + `formatError`
5
- * have branches that aren't reachable from the integration path
6
- * (`normalizeDefaultExport` handles Arrays before reaching `describe`;
7
- * jiti's `default: true` extraction rewrites `null` / `undefined`
8
- * defaults). These tests pin the contract at the unit level.
9
- */
10
-
11
- import { describe, expect, it } from "vitest";
12
- import { describe as describeValue, formatError, isEnvelope, isWorkflow } from "./shape-guards.js";
13
-
14
- describe("describe", () => {
15
- it("returns 'null' for null", () => {
16
- expect(describeValue(null)).toBe("null");
17
- });
18
-
19
- it("returns 'undefined' for undefined", () => {
20
- expect(describeValue(undefined)).toBe("undefined");
21
- });
22
-
23
- it("returns 'an array' for arrays", () => {
24
- expect(describeValue([])).toBe("an array");
25
- expect(describeValue([1, 2, 3])).toBe("an array");
26
- });
27
-
28
- it("returns the typeof for primitives", () => {
29
- expect(describeValue(42)).toBe("number");
30
- expect(describeValue("hi")).toBe("string");
31
- expect(describeValue(true)).toBe("boolean");
32
- });
33
-
34
- it("returns 'object' for plain objects", () => {
35
- expect(describeValue({})).toBe("object");
36
- });
37
- });
38
-
39
- describe("formatError", () => {
40
- it("returns the message for Error instances", () => {
41
- expect(formatError(new Error("boom"))).toBe("boom");
42
- });
43
-
44
- it("returns the string form for non-Error values", () => {
45
- expect(formatError("nope")).toBe("nope");
46
- expect(formatError(42)).toBe("42");
47
- expect(formatError({ toString: () => "obj" })).toBe("obj");
48
- });
49
- });
50
-
51
- describe("isWorkflow", () => {
52
- it("rejects truthy non-objects on stages/edges", () => {
53
- expect(isWorkflow({ name: "x", start: "y", stages: "foo", edges: 1 })).toBe(false);
54
- expect(isWorkflow({ name: "x", start: "y", stages: {}, edges: [] })).toBe(true);
55
- });
56
-
57
- it("rejects null/undefined", () => {
58
- expect(isWorkflow(null)).toBe(false);
59
- expect(isWorkflow(undefined)).toBe(false);
60
- });
61
- });
62
-
63
- describe("isEnvelope", () => {
64
- it("recognizes an envelope by its workflows array", () => {
65
- expect(isEnvelope({ workflows: [] })).toBe(true);
66
- expect(isEnvelope({ workflows: [{}], default: "x" })).toBe(true);
67
- });
68
-
69
- it("rejects shapes missing workflows", () => {
70
- expect(isEnvelope({})).toBe(false);
71
- expect(isEnvelope(null)).toBe(false);
72
- expect(isEnvelope({ workflows: "not an array" })).toBe(false);
73
- });
74
- });
@@ -1,64 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import type { BranchEntry } from "../../transcript.js";
3
- import { directoryPathCollector } from "./directory-path.js";
4
-
5
- const asst = (text: string): BranchEntry => ({
6
- type: "message",
7
- message: { role: "assistant", content: [{ type: "text", text }] },
8
- });
9
-
10
- const ctxOf = (branch: BranchEntry[]) => ({
11
- cwd: "/tmp",
12
- runId: "test",
13
- stageIndex: 0,
14
- state: {} as never,
15
- branch,
16
- branchOffset: undefined,
17
- snapshot: undefined,
18
- skill: "test",
19
- });
20
-
21
- describe("directoryPathCollector", () => {
22
- it("throws when dir is missing or empty", () => {
23
- // @ts-expect-error — intentional misuse
24
- expect(() => directoryPathCollector({})).toThrow(/dir.*required/);
25
- expect(() => directoryPathCollector({ dir: "" })).toThrow(/dir.*required/);
26
- });
27
-
28
- it("matches files under the directory with any extension when ext omitted", async () => {
29
- const collector = directoryPathCollector({ dir: "docs/adr" });
30
- const ctx = ctxOf([asst("Wrote docs/adr/0042-init.md and docs/adr/notes.txt")]);
31
- const result = await collector.collect(ctx);
32
- expect(result.kind === "ok" && result.artifacts[0]?.handle).toEqual({
33
- kind: "fs",
34
- path: "docs/adr/notes.txt",
35
- });
36
- });
37
-
38
- it("narrows by extension when supplied", async () => {
39
- const collector = directoryPathCollector({ dir: "docs/adr", ext: "md" });
40
- const ctx = ctxOf([asst("Wrote docs/adr/0042-init.md and docs/adr/notes.txt")]);
41
- const result = await collector.collect(ctx);
42
- expect(result.kind === "ok" && result.artifacts[0]?.handle).toEqual({
43
- kind: "fs",
44
- path: "docs/adr/0042-init.md",
45
- });
46
- });
47
-
48
- it("escapes regex metacharacters in dir (e.g. dots in subfolder names)", async () => {
49
- const collector = directoryPathCollector({ dir: ".rpiv/artifacts/research.v2", ext: "md" });
50
- const ctx = ctxOf([asst("Result: .rpiv/artifacts/research.v2/topic.md")]);
51
- const result = await collector.collect(ctx);
52
- expect(result.kind === "ok" && result.artifacts[0]?.handle).toEqual({
53
- kind: "fs",
54
- path: ".rpiv/artifacts/research.v2/topic.md",
55
- });
56
- });
57
-
58
- it("fatals when nothing matches the directory", async () => {
59
- const collector = directoryPathCollector({ dir: "docs/adr", ext: "md" });
60
- const ctx = ctxOf([asst("Wrote elsewhere/file.md")]);
61
- const result = await collector.collect(ctx);
62
- expect(result.kind).toBe("fatal");
63
- });
64
- });