@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
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Runtime preflights for the per-stage pipeline — every check that gates a
3
+ * stage BEFORE its body dispatches. Each check throws `StagePreflightError`
4
+ * on failure; `runStageOrRecordFailure` (run-stage.ts) catches and
5
+ * records the JSONL row. Schema-backed input validation (the two POST-prompt
6
+ * checks) lives beside this in `input-validation.ts`.
7
+ *
8
+ * Checks switch on the resolved `dispatch` mode (resolve-stage.ts) instead
9
+ * of re-probing `def.prompt` — the slot-priority rule lives in one place.
10
+ */
11
+
12
+ import { currentPrimaryArtifact } from "../chain-state.js";
13
+ import { type AnyJudge, panelMembers } from "../judge.js";
14
+ import {
15
+ FAIL_MISSING_ARTIFACT,
16
+ FAIL_MISSING_NAMED_READ,
17
+ FAIL_SKILL_NOT_REGISTERED,
18
+ MSG_STAGE_THREW,
19
+ } from "../messages.js";
20
+ import type { RunContext } from "../types.js";
21
+ import { StagePreflightError } from "./errors.js";
22
+ import type { ResolvedStage } from "./resolve-stage.js";
23
+
24
+ /**
25
+ * The skill-path preflight sequence, in its load-bearing order:
26
+ * 1. ensureUpstreamArtifact — halt: missing inherited artifact.
27
+ * 2. ensureNamedReads — halt: a `reads:` name has no published entry.
28
+ * 3. enforceSessionInvariants — invariant: authoring-time-knowable throws
29
+ * (precede the registry check so the structural violation surfaces
30
+ * regardless of the runtime registry).
31
+ * 4. ensureSkillRegistered — halt: skill not registered in Pi.
32
+ * (Input-schema validation runs after prompt prep — see input-validation.ts.)
33
+ */
34
+ export function runSingleStagePreflights(stage: ResolvedStage, run: RunContext): void {
35
+ ensureUpstreamArtifact(stage, run);
36
+ ensureNamedReads(stage, run);
37
+ enforceSessionInvariants(stage, run);
38
+ ensureSkillRegistered(stage, run);
39
+ }
40
+
41
+ /**
42
+ * The loop ⊕ continue exclusion — runtime mirror of load validation; checked
43
+ * BEFORE the push loop's unit compute (which is itself pinned to run before
44
+ * the remaining loop preflights — a `units()` throw carries its own
45
+ * attribution and must beat any other preflight's halt).
46
+ */
47
+ export function ensureLoopNotContinue(stage: ResolvedStage): void {
48
+ if (stage.def.sessionPolicy !== "continue") return;
49
+ const reason =
50
+ `runStage: stage "${stage.name}" cannot combine loop with sessionPolicy "continue" — ` +
51
+ "each unit requires an isolated session";
52
+ throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
53
+ }
54
+
55
+ /**
56
+ * Loop-stage preflights, run UNIFORMLY for every loop kind (the old
57
+ * shortcuts bypassed them: a ≥1-unit fanout ran none; iterate ran none;
58
+ * assess re-ran two inline):
59
+ * - ensureNamedReads + ensureSkillRegistered for ALL loops (every loop's
60
+ * units dispatch `/skill:<skill>`, and generators read declared channels);
61
+ * - ensureUpstreamArtifact for ASSESS ONLY — the round-0 producer arg is
62
+ * the one loop input that consumes the rolling primary (fanout/iterate
63
+ * unit prompts are author-built; an entry-point loop with no primary is
64
+ * legal for them);
65
+ * - judge-skill registry check for any loop carrying a `.skill` judge.
66
+ */
67
+ export function runLoopPreflights(stage: ResolvedStage, run: RunContext): void {
68
+ const loop = stage.loop!; // mode === "loop" ⇒ resolveStage set it
69
+ ensureNamedReads(stage, run);
70
+ ensureSkillRegistered(stage, run);
71
+ if (loop.kind === "assess") {
72
+ ensureUpstreamArtifact(stage, run);
73
+ ensureJudgeSkillRegistered(loop.judge, stage, run);
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Registry preflight for a judge SLOT (`AnyJudge`) — walks `panelMembers`, so a
79
+ * single judge checks its one `.skill` and a panel checks EVERY member's skill
80
+ * (the first unregistered member halts). `ensureSkillRegistered` only inspects
81
+ * `stage.skill`; this covers the judge dispatch. Fail-soft when
82
+ * `registeredSkills` is undefined (hostless embedder); members without a
83
+ * `.skill` (prompt judges) are skipped.
84
+ */
85
+ export function ensureJudgeSkillRegistered(judge: AnyJudge, stage: ResolvedStage, run: RunContext): void {
86
+ if (run.registeredSkills === undefined) return;
87
+ for (const member of panelMembers(judge)) {
88
+ if (member.skill === undefined) continue;
89
+ if (run.registeredSkills.has(member.skill)) continue;
90
+ const f = FAIL_SKILL_NOT_REGISTERED(member.skill, stage.stageNumber);
91
+ throw new StagePreflightError("halt", member.skill, f.toast, f.error, true);
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Verify `stage.skill` resolves to a Pi-registered skill BEFORE the prompt
97
+ * is dispatched. The workflow runner emits `/skill:<name>` text via
98
+ * `sendUserMessage` (the programmatic path), which goes through
99
+ * `prompt({expandPromptTemplates: false})` — meaning Pi's built-in
100
+ * `_expandSkillCommand` is skipped and `rpiv-args` is the ONLY expander.
101
+ * If the skill isn't registered, `rpiv-args` returns `{action:"continue"}`
102
+ * and the raw `/skill:<name> …` text reaches the LLM as a bare user-message
103
+ * imperative outside the `<skill>...</skill>` contract — silent LLM-prompt
104
+ * corruption with no diagnostic. Catching it here turns that silent failure
105
+ * into a properly-attributed stage halt.
106
+ *
107
+ * Reads the snapshot in `run.registeredSkills` rather than calling
108
+ * `host.getCommands()` mid-run, because Pi marks the `WorkflowHost` handle
109
+ * stale on the first `ctx.newSession()` — the snapshot is built once in
110
+ * `buildRunContext` before any session replaces the outer ctx.
111
+ *
112
+ * Skipped for non-skill dispatch (a prompt stage sends raw text — there is
113
+ * no skill to verify) and when `registeredSkills` is undefined (hostless
114
+ * embedder — same fail-soft posture as the rest of the host-optional
115
+ * surface).
116
+ */
117
+ function ensureSkillRegistered(stage: ResolvedStage, run: RunContext): void {
118
+ if (stage.dispatch !== "skill") return;
119
+ if (!run.registeredSkills) return;
120
+ if (run.registeredSkills.has(stage.skill)) return;
121
+
122
+ const f = FAIL_SKILL_NOT_REGISTERED(stage.skill, stage.stageNumber);
123
+ throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
124
+ }
125
+
126
+ /**
127
+ * The start node consumes the user's brief; subsequent stages MUST inherit
128
+ * an upstream artifactPath. Falling back to originalInput past the start
129
+ * would silently hand a downstream skill the raw feature description.
130
+ *
131
+ * Three opt-outs skip the check:
132
+ * - `inheritsArtifacts: false` (authored via `terminal()`) — stage consumes
133
+ * `originalInput` by design.
134
+ * - `reads: [...]` — stage builds its prompt from the named-publish
135
+ * registry instead of the rolling primary slot; `ensureNamedReads`
136
+ * enforces its own coverage rule.
137
+ * - prompt dispatch — the stage builds its own text and never consumes the
138
+ * rolling primary as an arg (a continue chat turn typically leans on
139
+ * session context, not a handle).
140
+ */
141
+ function ensureUpstreamArtifact(stage: ResolvedStage, run: RunContext): void {
142
+ if (stage.name === run.workflow.start) return;
143
+ if (stage.def.inheritsArtifacts === false) return;
144
+ if (stage.def.reads?.length) return;
145
+ if (stage.dispatch === "prompt") return;
146
+ if (currentPrimaryArtifact(run.state)) return;
147
+ const f = FAIL_MISSING_ARTIFACT(stage.skill, stage.stageNumber);
148
+ throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
149
+ }
150
+
151
+ /**
152
+ * A stage declaring `reads: [...]` must find every name filled in
153
+ * `state.named` before the prompt is built. `validateWorkflow` already
154
+ * confirms the names CAN exist (some upstream stage publishes them); this
155
+ * catches the runtime path where the producer hasn't fired yet — e.g.
156
+ * the stage was placed before its producer in the edge graph.
157
+ */
158
+ function ensureNamedReads(stage: ResolvedStage, run: RunContext): void {
159
+ const reads = stage.def.reads;
160
+ if (!reads?.length) return;
161
+ for (const name of reads) {
162
+ if (run.state.named[name]?.length) continue;
163
+ const f = FAIL_MISSING_NAMED_READ(stage.skill, name, stage.stageNumber);
164
+ throw new StagePreflightError("halt", stage.skill, f.toast, f.error, true);
165
+ }
166
+ }
167
+
168
+ function enforceSessionInvariants(stage: ResolvedStage, run: RunContext): void {
169
+ if (stage.def.sessionPolicy === "continue" && !run.continueHost) {
170
+ const reason = `runStage: stage "${stage.name}" uses sessionPolicy "continue" but no workflow host was provided to runWorkflow`;
171
+ throw new StagePreflightError("invariant", stage.name, MSG_STAGE_THREW(stage.name, reason), reason, false);
172
+ }
173
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Stage resolution — derive a stage's dispatch identity ONCE, at the top of
3
+ * `runStage`, so the rest of the pipeline switches on data instead of
4
+ * re-probing the def's optional slots (`loop`/`verify`/`run`/`prompt`). The
5
+ * old probe-the-optionals ladder needed a "slot ordering (load-bearing)"
6
+ * comment; the ordering now lives in exactly one place (`stageModeOf`).
7
+ */
8
+
9
+ import type { LoopDef, StageDef } from "../api.js";
10
+ import { resolveSkill } from "../chain-state.js";
11
+ import { effectiveLoopOf } from "../loop-constructors.js";
12
+ import type { RunContext } from "../types.js";
13
+
14
+ /**
15
+ * How a stage's BODY is dispatched:
16
+ * - `"script"` — `def.run` is called directly (no session).
17
+ * - `"prompt"` — author-owned raw text is sent (no `/skill:` prefix).
18
+ * - `"skill"` — `/skill:<skill> <args>` is sent.
19
+ * Loop stages dispatch each unit with this same body mode (script is
20
+ * load-rejected on loop stages, so loop bodies are prompt or skill).
21
+ */
22
+ export type StageDispatch = "script" | "prompt" | "skill";
23
+
24
+ /** The top-level dispatch slot `runStage` switches on. */
25
+ export type StageMode = "loop" | StageDispatch;
26
+
27
+ export interface ResolvedStage {
28
+ def: StageDef;
29
+ name: string;
30
+ /** 1-based; for status line + audit row. */
31
+ stageNumber: number;
32
+ /** Label written to JSONL + the status line. */
33
+ skill: string;
34
+ /** Top-level dispatch slot — `"loop"` wins over the body mode. */
35
+ mode: StageMode;
36
+ /** Body dispatch — what one activation (or loop unit) actually sends/runs. */
37
+ dispatch: StageDispatch;
38
+ /** The effective loop spec (incl. a verify desugar); set iff `mode === "loop"`. */
39
+ loop?: LoopDef;
40
+ }
41
+
42
+ /** The ONE slot-priority rule: loop (incl. verify desugar) > script > prompt > skill. */
43
+ function dispatchOf(def: StageDef): StageDispatch {
44
+ if (def.run) return "script";
45
+ if (def.prompt !== undefined) return "prompt";
46
+ return "skill";
47
+ }
48
+
49
+ export function resolveStage(currentName: string, idx: number, run: RunContext): ResolvedStage {
50
+ const def = run.workflow.stages[currentName];
51
+ if (!def) {
52
+ // validateWorkflow should catch this; defensive for tests bypassing validation.
53
+ throw new Error(`runStage: stage "${currentName}" referenced by edges but missing from workflow.stages`);
54
+ }
55
+ const loop = effectiveLoopOf(def);
56
+ const dispatch = dispatchOf(def);
57
+ // `skill` defaults to the record key; `resolveSkill` is the shared derivation
58
+ // the load-time contract lookups also use, so runtime and load can't disagree.
59
+ return {
60
+ def,
61
+ name: currentName,
62
+ stageNumber: idx + 1,
63
+ skill: resolveSkill(def, currentName),
64
+ mode: loop ? "loop" : dispatch,
65
+ dispatch,
66
+ loop,
67
+ };
68
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Resume entry selection — translate a reconstructed trail (`resume.ts`)
3
+ * into the chain re-entry thunk `resumeWorkflow` hands to `executeRun`, plus
4
+ * the refusal-reason rendering for a reconstruct that declined. Companion to
5
+ * `resume-loop.ts` (which owns the loop-trailer arm's dispatch).
6
+ */
7
+
8
+ import {
9
+ ERR_RESUME_MALFORMED_ROW,
10
+ ERR_RESUME_NO_ROWS,
11
+ ERR_RESUME_STAGE_GONE,
12
+ ERR_RESUME_VERSION_MISMATCH,
13
+ } from "../messages.js";
14
+ import { STATE_SCHEMA_VERSION } from "../state/index.js";
15
+ import type { RunContext, WorkflowHostContext } from "../types.js";
16
+ import { recordEntryThrow } from "./failure.js";
17
+ import type { ReconstructResult } from "./resume.js";
18
+ import { recordLoopDriftFailure, resumeLoopStage } from "./resume-loop.js";
19
+ import { advance, buildLoopDeps, resumeStageWithSession, runStageOrRecordFailure } from "./run-stage.js";
20
+
21
+ /**
22
+ * Pick the chain re-entry thunk from the trail trailer. Dispatch keys on the
23
+ * STRUCTURED `parent` field — no string matching, no per-primitive arms:
24
+ * - fold-detected drift → record the parent-attributed terminal failure
25
+ * (zero dispatch; lifecycle bracketing identical to every other entry);
26
+ * - trailing unit row → re-enter the loop with the fold's cursor;
27
+ * - completed normal trailer → route onward (finished run hits stop ⇒ no-op);
28
+ * - failed/aborted trailer → session-backed rows try promotion/reattach
29
+ * (`resumeStageWithSession`); sessionless rows re-run cold (today's
30
+ * behavior). Dispatch keys on the STRUCTURED `session` field, mirroring
31
+ * the `parent !== undefined` arm.
32
+ */
33
+ export function selectResumeEntry(
34
+ ctx: WorkflowHostContext,
35
+ recon: Extract<ReconstructResult, { ok: true }>,
36
+ run: RunContext,
37
+ ): () => Promise<unknown> {
38
+ if (recon.drift) {
39
+ const { parent, errMsg } = recon.drift;
40
+ return () => recordLoopDriftFailure(ctx, run, parent, errMsg);
41
+ }
42
+
43
+ // The fold's reconstructed chain index — NOT `stageNumber - 1`: the
44
+ // allocator counts every row including loop units, so past any loop the
45
+ // two diverge (a 10-unit loop would resume showing "stage 14/5").
46
+ const last = recon.rows[recon.rows.length - 1]!;
47
+ const idx = recon.lastChainIndex; // status-line / routing index; JSONL number comes from the allocator
48
+
49
+ if (last.parent !== undefined) {
50
+ // `recon.trailing` is set by construction: the fold always produces a
51
+ // trailing point for an open generation, and a unit-row trailer means
52
+ // the generation is open.
53
+ return () =>
54
+ guardResumeEntry(ctx, last.parent!, run, () =>
55
+ resumeLoopStage(ctx, recon.trailing!, idx, run, buildLoopDeps()),
56
+ );
57
+ }
58
+ if (last.status === "completed") {
59
+ // route onward; finished run ⇒ hits stop ⇒ no-op
60
+ return () => guardResumeEntry(ctx, last.stage, run, () => advance(ctx, last.stage, idx, run));
61
+ }
62
+ // failed/aborted trailer — session-backed rows try promotion/reattach,
63
+ // sessionless rows re-run cold (today's behavior).
64
+ return last.session !== null
65
+ ? () => resumeStageWithSession(ctx, last, idx, run)
66
+ : () => runStageOrRecordFailure(ctx, last.stage, idx, run);
67
+ }
68
+
69
+ /**
70
+ * Resume-entry counterpart of `runStageOrRecordFailure`'s catch. The live
71
+ * chain reaches user fns (loop `next`/`done`/`feedForward`, judge prompts,
72
+ * route predicates) only under that catch; the resume-loop and route-onward
73
+ * entry thunks call the same fns directly, so a throw would otherwise escape
74
+ * `executeRun` as a raw rejection — `onWorkflowEnd` never fires and the
75
+ * caller loses the result envelope.
76
+ */
77
+ async function guardResumeEntry(
78
+ curCtx: WorkflowHostContext,
79
+ name: string,
80
+ run: RunContext,
81
+ entry: () => Promise<unknown>,
82
+ ): Promise<void> {
83
+ try {
84
+ await entry();
85
+ } catch (e) {
86
+ await recordEntryThrow(curCtx, name, run, e);
87
+ }
88
+ }
89
+
90
+ export function resumeRefusalError(recon: Extract<ReconstructResult, { ok: false }>, workflow: string): string {
91
+ switch (recon.reason) {
92
+ case "no-rows":
93
+ return ERR_RESUME_NO_ROWS(recon.detail);
94
+ case "stage-gone":
95
+ return ERR_RESUME_STAGE_GONE(recon.detail, workflow);
96
+ case "malformed-row":
97
+ return ERR_RESUME_MALFORMED_ROW(recon.detail);
98
+ case "version-mismatch":
99
+ return ERR_RESUME_VERSION_MISMATCH(recon.detail, STATE_SCHEMA_VERSION);
100
+ }
101
+ }