@juicesharp/rpiv-workflow 2.3.1 → 2.5.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.
package/docs/embedding.md CHANGED
@@ -150,7 +150,7 @@ const result = await runWorkflow(ctx, { // ctx: WorkflowHostContext
150
150
  | `input` | `string` | required — passed to the start stage as its argument |
151
151
  | `host` | `WorkflowHost` | none; used for the skill-registration preflight snapshot |
152
152
  | `maxIterations` | `number` | `32` — run-wide cap on loop units of every kind |
153
- | `maxBackwardJumps` | `number` | `2` per destination stage |
153
+ | `maxBackwardJumps` | `number` | `3` per destination stage |
154
154
  | `trigger` | `RunTrigger` | `{ kind: "programmatic" }` |
155
155
  | `lifecycle` | `LifecycleListeners` | none |
156
156
  | `signal` | `AbortSignal` | none |
@@ -338,4 +338,5 @@ Row **writes** are runner-owned. Readers are public:
338
338
  | `readHeader(cwd, runId)` | The run's header row |
339
339
  | `readLastStage(cwd, runId)` | The most recent stage row |
340
340
  | `listArtifacts(cwd, runId)` | Every artifact the run recorded |
341
+ | `summarizeRun(cwd, runId)` | A `RunRecap \| undefined` (terminal `outcome` + display-string `artifacts` + `workflow` projected from the trail; `outcome` is `"completed"` for a `collected:true` collect-all halt) — `undefined` when the run has no stage rows |
341
342
  | `runFileFor(cwd, run)` | The absolute path of the run's JSONL file. `run` is anything carrying `runId` — a `RunSummary` or `WorkflowHeader` |
@@ -195,7 +195,7 @@ Two backstops bound every run regardless of what a workflow declares:
195
195
  | Cap | Default | Effect |
196
196
  | --- | --- | --- |
197
197
  | `maxIterations` | `32` | Run-wide ceiling on loop units of every kind. The effective loop cap is `min(loop.max, run.maxIterations)` |
198
- | Backward-jump budget | `2` per destination stage | At most 3 executions of any one stage across decision-edge loop-backs |
198
+ | Backward-jump budget | `3` per destination stage | At most 4 executions of any one stage across decision-edge loop-backs |
199
199
 
200
200
  ## Trusting overlay files
201
201
 
package/internal.ts CHANGED
@@ -35,6 +35,10 @@ export { __resetBuiltIns, flushBuiltInProviders, getBuiltIns } from "./built-ins
35
35
  export { __resetLifecycleRegistry } from "./events.js";
36
36
  export { __resetWorkflowExecutionHost } from "./execution-host.js";
37
37
  export { __resetLoadCache } from "./load/cache.js";
38
+ // Read-and-clear a gate's stop-pick note — test fixtures assert the reason a
39
+ // bespoke `defineRoute` gate attached via `setRouteNote`; production consumption
40
+ // stays inside the runner's routing audit.
41
+ export { takeRouteNote } from "./routing-dsl.js";
38
42
  export { __resetStrikeBudgets } from "./sessions/bash-strikes.js";
39
43
  export {
40
44
  __resetSkillContracts,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.3.1",
3
+ "version": "2.5.0",
4
4
  "description": "Pi extension. Chain skills into typed multi-stage workflows with audited JSONL state, predicate routing, and per-stage output validation. Skill-agnostic — bring your own skills.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -111,7 +111,7 @@
111
111
  ]
112
112
  },
113
113
  "dependencies": {
114
- "@juicesharp/rpiv-config": "^2.3.1",
114
+ "@juicesharp/rpiv-config": "^2.5.0",
115
115
  "jiti": "^2.7.0",
116
116
  "typebox": "^1.1.24"
117
117
  },
package/registration.ts CHANGED
@@ -52,6 +52,7 @@ export {
52
52
  type StageKind,
53
53
  type StageRead,
54
54
  type StageSchema,
55
+ setRouteNote,
55
56
  terminal,
56
57
  type Unit,
57
58
  type UnitRole,
@@ -205,6 +206,7 @@ export {
205
206
  type LoopCapRow,
206
207
  listArtifacts,
207
208
  listRuns,
209
+ type RunRecap,
208
210
  type RunSummary,
209
211
  readHeader,
210
212
  readLastStage,
@@ -216,6 +218,7 @@ export {
216
218
  runFileFor,
217
219
  type SessionRef,
218
220
  STATE_SCHEMA_VERSION,
221
+ summarizeRun,
219
222
  type WorkflowHeader,
220
223
  type WorkflowStage,
221
224
  } from "./state/index.js";
package/routing-dsl.ts CHANGED
@@ -125,9 +125,10 @@ export function defineRoute(targets: readonly string[], fn: EdgePredicate, opts?
125
125
  * the edge (same tick — single-threaded, no other decision can interleave)
126
126
  * and persists it on the `RoutingDecision` row's `note`.
127
127
  *
128
- * Framework plumbing, not authoring surface — NOT re-exported from
129
- * `registration.ts`. `Symbol.for` so it survives import boundaries, matching
130
- * `READS_DATA`.
128
+ * The SYMBOL is framework plumbing — NOT re-exported from `registration.ts`;
129
+ * bespoke `defineRoute` gates attach notes through `setRouteNote` (the
130
+ * authoring-surface dual of `takeRouteNote`), which IS re-exported. `Symbol.for`
131
+ * so it survives import boundaries, matching `READS_DATA`.
131
132
  */
132
133
  export const ROUTE_NOTE: unique symbol = Symbol.for("rpiv.workflow.routeNote");
133
134
 
@@ -141,6 +142,20 @@ export function takeRouteNote(fn: EdgeFn): string | undefined {
141
142
  return note;
142
143
  }
143
144
 
145
+ /**
146
+ * Attach a note to an `EdgeFn`'s CURRENT pick — the authoring-surface dual of
147
+ * `takeRouteNote`, for bespoke `defineRoute` gates (`gate`/`match` attach their
148
+ * own no-match diagnostics internally). Call it inside the predicate, on the
149
+ * route about to be returned from — the routing audit reads-and-clears the note
150
+ * in the same tick and persists it on the `RoutingDecision` row, where
151
+ * `summarizeRun` surfaces it as a stopped run's reason. A note set on a pick
152
+ * the audit never reads (e.g. under a test harness) is simply overwritten by
153
+ * the next call.
154
+ */
155
+ export function setRouteNote(fn: EdgeFn, note: string): void {
156
+ markSymbol(fn, ROUTE_NOTE, note);
157
+ }
158
+
144
159
  /**
145
160
  * Matches the keys JS engines hoist and reorder ahead of string keys
146
161
  * (canonical array indices). `gate` evaluates branches in declaration order,
package/startup.ts CHANGED
@@ -16,3 +16,4 @@ export {
16
16
  registerSkillContracts,
17
17
  registerSkillContractsProvider,
18
18
  } from "./skill-contracts/index.js";
19
+ export { summarizeRun } from "./state/index.js";
package/state/index.ts CHANGED
@@ -9,6 +9,7 @@ export type {
9
9
  LoopCapRow,
10
10
  NamesIndex,
11
11
  RoutingDecision,
12
+ RunRecap,
12
13
  RunSummary,
13
14
  SessionRef,
14
15
  StageStatus,
@@ -40,5 +41,6 @@ export {
40
41
  runsDir,
41
42
  STATE_SCHEMA_VERSION,
42
43
  stateFilePath,
44
+ summarizeRun,
43
45
  VALID_NAME,
44
46
  } from "./state.js";
package/state/reads.ts CHANGED
@@ -17,11 +17,19 @@
17
17
  */
18
18
 
19
19
  import { existsSync, readFileSync } from "node:fs";
20
- import type { Artifact } from "../handle.js";
20
+ import { type Artifact, handleToString } from "../handle.js";
21
21
  import { formatError } from "../internal-utils.js";
22
22
  import { stateFilePath } from "./paths.js";
23
23
  import { enumerateRunIds, readFirstJsonlLine } from "./raw.js";
24
- import type { LoopCapRow, RoutingDecision, RunSummary, WorkflowHeader, WorkflowStage } from "./state.js";
24
+ import type {
25
+ LoopCapRow,
26
+ RoutingDecision,
27
+ RunRecap,
28
+ RunSummary,
29
+ StageStatus,
30
+ WorkflowHeader,
31
+ WorkflowStage,
32
+ } from "./state.js";
25
33
 
26
34
  /**
27
35
  * Reads every line, filters by shape (not position). Header has no
@@ -171,26 +179,22 @@ export function readLoopCaps(cwd: string, runId: string): LoopCapRow[] {
171
179
  return readJsonlRows(cwd, runId, isLoopCapRow);
172
180
  }
173
181
 
174
- /**
175
- * Project a run's stage rows to the (stage, artifact) pairs that
176
- * actually carried at least one artifact. One entry per artifact —
177
- * stages with multi-artifact collectors expand to N entries. Used by
178
- * `notifyPartialArtifacts` for the failure recap and by past-runs UIs
179
- * (the `listRuns` API) for run summaries.
180
- *
181
- * `stage` is the workflow stage's record key (always present); `skill`
182
- * is the Pi skill body when this row recorded a skill stage (absent
183
- * for script stages).
184
- *
185
- * Reads from `output.artifacts` (single source); rows without an
186
- * output, or with an empty artifacts list, contribute nothing.
187
- */
188
182
  export function listArtifacts(
189
183
  cwd: string,
190
184
  runId: string,
191
185
  ): Array<{ stage: string; skill?: string; artifact: Artifact }> {
186
+ return stagesToArtifacts(readAllStages(cwd, runId));
187
+ }
188
+
189
+ /**
190
+ * The single stage→artifacts iteration, shared by `listArtifacts` and
191
+ * `summarizeRun`'s artifact projection. One entry per artifact in trail order;
192
+ * stages with multi-artifact collectors expand to N entries. Rows without an
193
+ * `output`, or with an empty artifacts list, contribute nothing.
194
+ */
195
+ function stagesToArtifacts(stages: WorkflowStage[]): Array<{ stage: string; skill?: string; artifact: Artifact }> {
192
196
  const out: Array<{ stage: string; skill?: string; artifact: Artifact }> = [];
193
- for (const s of readAllStages(cwd, runId)) {
197
+ for (const s of stages) {
194
198
  const artifacts = s.output?.artifacts;
195
199
  if (!artifacts) continue;
196
200
  for (const artifact of artifacts) out.push({ stage: s.stage, skill: s.skill, artifact });
@@ -198,6 +202,91 @@ export function listArtifacts(
198
202
  return out;
199
203
  }
200
204
 
205
+ /**
206
+ * On-disk `StageStatus` → recap outcome. The lone translation is
207
+ * `"skipped"`→`"cancelled"`: `"skipped"` is the FROZEN on-disk marker a
208
+ * `recordCancellation` row carries (see `StageStatus`), while the recap reads
209
+ * the canonical in-memory outcome. The other three statuses pass through
210
+ * unchanged. Frozen + exhaustive over `StageStatus`, so a new status breaks
211
+ * the record at compile time.
212
+ *
213
+ * Applied AFTER the `collected:true` filter — `recapOutcomeOf` checks that
214
+ * marker first and short-circuits to `"completed"` (see its doc).
215
+ */
216
+ const STAGE_TO_RECAP_OUTCOME: Readonly<Record<StageStatus, RunRecap["outcome"]>> = {
217
+ completed: "completed",
218
+ failed: "failed",
219
+ skipped: "cancelled",
220
+ aborted: "aborted",
221
+ };
222
+
223
+ /**
224
+ * Terminal outcome for the LAST stage row of a run. A `collected:true` marker
225
+ * distinguishes a NON-terminal collect-all fanout unit halt: the run survived
226
+ * the halted unit (its output was rebuilt into a `failedOutput` sentinel), so
227
+ * the recap reads `"completed"` rather than the halted unit's on-disk terminal
228
+ * status. Every other row falls through to `STAGE_TO_RECAP_OUTCOME`.
229
+ */
230
+ function recapOutcomeOf(last: WorkflowStage): RunRecap["outcome"] {
231
+ if (last.collected === true) return "completed";
232
+ return STAGE_TO_RECAP_OUTCOME[last.status];
233
+ }
234
+
235
+ /**
236
+ * The trail's routed-stop terminator, when present: the LAST well-formed row is
237
+ * a `RoutingDecision` with `decision: "stop"` (the literal mirrors routing-dsl's
238
+ * `STOP` — not imported so state/ stays a leaf). Only a routed stop leaves the
239
+ * routing row as the trail's tail: static string edges never audit, a natural
240
+ * chain end appends its terminal stage row after any routing row, and a resume
241
+ * appends new stage rows behind a prior stop. Fail-soft via `readParsedRows`.
242
+ */
243
+ function trailingRoutingStop(cwd: string, runId: string): RoutingDecision | undefined {
244
+ const rows = readParsedRows(cwd, runId);
245
+ const last = rows[rows.length - 1];
246
+ return isRoutingDecision(last) && last.decision === "stop" ? last : undefined;
247
+ }
248
+
249
+ /**
250
+ * Terminal-state projection of one run's JSONL trail — the post-mortem recap a lane
251
+ * renders on end-of-run. Returns `undefined` when no stage row exists (no terminal row
252
+ * ⇒ outcome unrecoverable from the trail). `failureReason` is set only for a
253
+ * non-completed outcome with a present `last.errMsg`, so a collected halt's errMsg
254
+ * never leaks into a completed recap. Fail-soft by inheritance — never throws.
255
+ *
256
+ * A run whose trail ENDS with a routed `stop` (see `trailingRoutingStop`) is
257
+ * refined from `"completed"` to `"stopped"`: the runner reports a gate-routed
258
+ * stop as ordinary completion, but a stop-on-fail gate firing before the
259
+ * chain's natural end is not a success reading. The reason is the stopping
260
+ * edge's persisted `note` when it attached one (`gate`/`match` no-match
261
+ * diagnostics, `setRouteNote` on bespoke gates), else the bare stage name — a
262
+ * note-less trail still names WHERE the run stopped. The refinement only
263
+ * applies over a completed last stage row: a failed/aborted/cancelled tail
264
+ * keeps its own outcome + errMsg (and by write order such a tail follows any
265
+ * routing row anyway).
266
+ */
267
+ export function summarizeRun(cwd: string, runId: string): RunRecap | undefined {
268
+ const stages = readAllStages(cwd, runId);
269
+ if (stages.length === 0) return undefined;
270
+ const last = stages[stages.length - 1];
271
+ const outcome = recapOutcomeOf(last);
272
+ const header = readHeader(cwd, runId);
273
+ const recap: RunRecap = {
274
+ outcome,
275
+ artifacts: stagesToArtifacts(stages).map(({ artifact }) => handleToString(artifact.handle)),
276
+ workflow: header?.workflow,
277
+ };
278
+ if (outcome !== "completed" && last.errMsg !== undefined) recap.failureReason = last.errMsg;
279
+ if (outcome === "completed") {
280
+ const stop = trailingRoutingStop(cwd, runId);
281
+ if (stop) {
282
+ recap.outcome = "stopped";
283
+ recap.failureReason =
284
+ stop.note !== undefined ? `stopped at ${stop.fromStage}: ${stop.note}` : `stopped at ${stop.fromStage}`;
285
+ }
286
+ }
287
+ return recap;
288
+ }
289
+
201
290
  // ---------------------------------------------------------------------------
202
291
  // Past-runs enumeration (header-only)
203
292
  // ---------------------------------------------------------------------------
package/state/state.ts CHANGED
@@ -218,6 +218,58 @@ export interface RunSummary {
218
218
  name?: string;
219
219
  }
220
220
 
221
+ /**
222
+ * Terminal-state projection of one run's JSONL trail — the post-mortem recap
223
+ * a lane renders on end-of-run (computed by `summarizeRun`). Flat (NOT a
224
+ * discriminated union mirroring `RunTermination`): `failureReason` is optional
225
+ * because it is sourced from `WorkflowStage.errMsg`, which is optional on the
226
+ * persisted row and unenforced by `isWorkflowStage` — a union requiring it on
227
+ * non-completed arms would assert a guarantee legacy/truncated trails do not
228
+ * make. Does NOT extend `RunSummary` (different projection: terminal state
229
+ * vs. header/start state).
230
+ *
231
+ * `outcome` is the recap outcome set ("completed" / "stopped" / "failed" /
232
+ * "cancelled" / "aborted") — a subset of a host's lane-status vocabulary with
233
+ * NO "running" member, since a recap only exists for a terminal run.
234
+ * `summarizeRun` derives it from the on-disk `StageStatus` via the lone
235
+ * `"skipped"`→`"cancelled"` translation (see `STAGE_TO_RECAP_OUTCOME`); the
236
+ * other three pass through. `"stopped"` never comes from a stage status: it is
237
+ * the routed-stop refinement of `"completed"` — the trail's LAST row is a
238
+ * `RoutingDecision` with `decision: "stop"`, i.e. a gate terminated the run
239
+ * before its linear chain reached a natural end (a stop-on-fail preset's red
240
+ * gate). The runner itself reports such a run "completed"; only the recap
241
+ * distinguishes it, so hosts can surface "stopped at <gate>" instead of a
242
+ * success reading.
243
+ */
244
+ export interface RunRecap {
245
+ outcome: "completed" | "stopped" | "failed" | "cancelled" | "aborted";
246
+ /**
247
+ * One display string per artifact, in trail order, projected through
248
+ * `handleToString` (`fs`→path, `url`→href, `opaque`→id, `inline`→byte
249
+ * length). Includes artifacts from stages that completed before a later
250
+ * failure (NO `status === "completed"` filter — `summarizeRun` projects via
251
+ * `listArtifacts`, which reads every stage row). `[]` when no stage carried
252
+ * artifacts.
253
+ */
254
+ artifacts: string[];
255
+ /**
256
+ * Reason a non-completed run terminated — sourced from the LAST stage row's
257
+ * `errMsg`, which mirrors the in-memory `state.termination.error` set by
258
+ * `recordFatalFailure` / `recordCancellation` (present only on
259
+ * `"failed" | "aborted" | "skipped"`-translated rows). Optional because
260
+ * `errMsg` is optional on the persisted row: a legacy/truncated trail may
261
+ * carry no reason even on a terminal row.
262
+ */
263
+ failureReason?: string;
264
+ /**
265
+ * Workflow name (matches `Workflow.name` at run-time) projected from the
266
+ * header. `undefined` when the header row is missing or malformed (a
267
+ * degraded trail with stage rows still returns a recap; the gap surfaces
268
+ * explicitly so a caller renders the outcome without the name).
269
+ */
270
+ workflow?: string;
271
+ }
272
+
221
273
  export interface RoutingDecision {
222
274
  type: "routing";
223
275
  fromStageIndex: number;
@@ -256,6 +308,7 @@ export {
256
308
  readLastStage,
257
309
  readLoopCaps,
258
310
  readRoutingDecisions,
311
+ summarizeRun,
259
312
  } from "./reads.js";
260
313
  export { resolveRun } from "./resolve.js";
261
314
  export { appendHeader, appendLoopCap, appendRoutingDecision, appendStage } from "./writes.js";