@juicesharp/rpiv-workflow 1.19.0 → 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/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
- }