@juicesharp/rpiv-workflow 2.6.4 → 2.7.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/api.ts CHANGED
@@ -18,6 +18,9 @@
18
18
  * ./loop-def.ts — the loop vocabulary (LoopDef kinds, JudgedRepetition,
19
19
  * VerifySpec, Unit, contexts, LOOP_KINDS); constructors
20
20
  * stay in loop-constructors.ts
21
+ * ./output-spec.ts — the `Outcome` type (type-only re-export; the wired-up
22
+ * collector/parser pair a stage declares via
23
+ * `StageDef.outcome`)
21
24
  * ./routing-dsl.ts — EdgeFn/EdgeTarget/STOP, defineRoute, gate, the
22
25
  * READS_DATA / ROUTE_NOTE markers
23
26
  */
@@ -1,18 +1,7 @@
1
1
  /**
2
- * Loop constructors + introspection — split into the `loops/` modules behind
3
- * this preserving re-export barrel. The monolith that lived here was
4
- * decomposed into five disjoint facets:
5
- * - `loops/constructors.ts` — `fanout()` / `iterate()` / `assess()` + the
6
- * `LOOP_DEFAULTS` / `VERIFY_LOOP_DEFAULTS` identity tables they consult;
7
- * - `loops/verify.ts` — `verify()` + the `synthesizeVerifyLoop` desugar;
8
- * - `loops/panel.ts` — `panel()` + the canonical fold vocabulary;
9
- * - `loops/introspection.ts` — `describeFlow()` + the `loopSpecOf` projections;
10
- * - `loops/derivations.ts` — `effectiveLoopOf` / `freezesEntryArgsOf` /
11
- * `judgeSlotOf` / `forEachJudgeChannel` (the per-stage consults).
12
- *
13
- * This file keeps the original import path (`./loop-constructors.js`) so the
14
- * existing consumers (9 production + 8 test importers, plus `registration.ts`)
15
- * resolve unchanged — a pure re-export surface, no logic. Skill-agnostic and
2
+ * Preserving re-export barrel over the `loops/` modules — exists solely to
3
+ * keep the original `./loop-constructors.js` import path resolving for
4
+ * existing consumers. A pure re-export surface, no logic; skill-agnostic and
16
5
  * runner-free — safe on `registration`.
17
6
  */
18
7
 
package/loop-waves.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * depends on have filled their slots. A deps-free fanout collapses to a single
10
10
  * level — byte-identical to the pre-wave flat dispatch.
11
11
  *
12
- * Ordering vs grouping: this is NOT clusterSliceDag (built-in-workflows.ts), which
12
+ * Ordering vs grouping: this is NOT clusterSliceDag (built-ins/slices.ts), which
13
13
  * is undirected union-find producing connected-component GROUPS for synth. Waves
14
14
  * need DIRECTED levels — different algorithms over the same edge data.
15
15
  *
@@ -30,24 +30,8 @@ import { panelShapeIssues } from "./panel.js";
30
30
  export const DEFAULT_ASSESS_MAX = 8;
31
31
 
32
32
  /**
33
- * Per-loop-kind identity — the construction-facet twin of `LOOP_STRATEGIES`
34
- * (`loop-kinds.ts`, the per-kind runtime strategy table). Each kind's default
35
- * `onCap`/`result` (and assess's construction `max`) live HERE, consulted by
36
- * every constructor, so a new loop kind or a default change is a single-row
37
- * edit instead of a multi-constructor scatter. Consulted by `effectiveLoopOf`
38
- * (the derivation-authority exemplar) and `freezesEntryArgsOf` (the round-0-arg
39
- * rule) — the two derivations that read it; both live in `derivations.ts` after
40
- * the `loops/` split (they value-import `LOOP_DEFAULTS` from here).
41
- *
42
- * `max` fits the table because `satisfies` (NOT a type annotation) preserves
43
- * the narrow inferred literal type PER KEY (the same property `LOOP_STRATEGIES`
44
- * relies on): `assess.max` infers as `number` (from `DEFAULT_ASSESS_MAX`), while
45
- * `fanout.max`/`iterate.max` infer as `undefined`. The assess constructor
46
- * therefore reads `LOOP_DEFAULTS.assess.max` with NO non-null assertion.
47
- *
48
- * WARNING: if a future change annotates this constant with a type declaration
49
- * instead of `satisfies`, the narrow per-key types are lost and `assess.max`
50
- * widens to `number | undefined` — re-confirm the `satisfies` form is retained.
33
+ * The per-kind defaults row shape — the construction facts each loop kind's
34
+ * row carries in the identity tables (`LOOP_DEFAULTS`, `VERIFY_LOOP_DEFAULTS`).
51
35
  */
52
36
  interface LoopKindDefaults {
53
37
  /** Construction-default cap policy. fanout/iterate → "halt", assess → "advance". */
@@ -71,9 +55,24 @@ interface LoopKindDefaults {
71
55
 
72
56
  /**
73
57
  * THE per-kind identity table — the single place fanout/iterate/assess default
74
- * `onCap`/`result`/`max` AND the round-0-arg rule are spelled. Modeled on
75
- * `LOOP_STRATEGIES` (`satisfies Record<LoopDef["kind"], …>`); a new loop kind
76
- * added to the union without a row here is a compile error.
58
+ * `onCap`/`result`/`max` AND the round-0-arg rule are spelled: the
59
+ * construction-facet twin of `LOOP_STRATEGIES` (`loop-kinds.ts`, the per-kind
60
+ * runtime strategy table). Consulted by every constructor and by the two
61
+ * derivations that read it — `effectiveLoopOf` and `freezesEntryArgsOf`, both
62
+ * in `derivations.ts` (they value-import `LOOP_DEFAULTS` from here) — so a new
63
+ * loop kind or a default change is a single-row edit instead of a
64
+ * multi-constructor scatter; a new loop kind added to the union without a row
65
+ * here is a compile error.
66
+ *
67
+ * `satisfies` (NOT a type annotation) preserves the narrow inferred literal
68
+ * type PER KEY (the same property `LOOP_STRATEGIES` relies on): `assess.max`
69
+ * infers as `number` (from `DEFAULT_ASSESS_MAX`), while `fanout.max`/
70
+ * `iterate.max` infer as `undefined`. The assess constructor therefore reads
71
+ * `LOOP_DEFAULTS.assess.max` with NO non-null assertion.
72
+ *
73
+ * WARNING: if a future change annotates this constant with a type declaration
74
+ * instead of `satisfies`, the narrow per-key types are lost and `assess.max`
75
+ * widens to `number | undefined` — re-confirm the `satisfies` form is retained.
77
76
  */
78
77
  export const LOOP_DEFAULTS = {
79
78
  fanout: { onCap: "halt", result: "entry", max: undefined, freezesEntryArgs: false },
@@ -293,7 +292,7 @@ export function judgeSlotShapeIssues(slot: unknown): string[] {
293
292
  *
294
293
  * This source stays internal-only: its sole consumer is `assess()`, and it is
295
294
  * deliberately NOT exported from `registration.ts`, while the load gate owns the
296
- * per-code surface the tests pin (`validate-workflow.test.ts:923,928`).
295
+ * per-code surface the tests pin (`validate-workflow.test.ts`).
297
296
  */
298
297
  export function assessShapeIssues(candidate: unknown): string[] {
299
298
  if (!candidate || typeof candidate !== "object") return ["an assess object is required"];
@@ -312,8 +311,7 @@ export function assessShapeIssues(candidate: unknown): string[] {
312
311
  /**
313
312
  * Construction-time positive-int gate for `max`/`concurrency` — the single
314
313
  * spelling of the "integer >= 1" check across all three constructors. Throws
315
- * at construction (the `defineRoute` pattern); byte-identical to the two
316
- * `checkedMax`/`checkedConcurrency` near-twins it collapses.
314
+ * at construction (the `defineRoute` pattern).
317
315
  *
318
316
  * Deliberately NOT unified with the load-gate per-code reports
319
317
  * (`validate/stage-rules.ts` `loop-max-invalid`,
@@ -99,12 +99,6 @@ export function describeFlow(w: Workflow): StageShape[] {
99
99
  // Introspection — one channel for all loop kinds
100
100
  // ===========================================================================
101
101
 
102
- /**
103
- * Pure-data projection of a LoopDef — what `describeFlow`, `preview`, and the
104
- * `checkFanoutSource` lint consume. `judge` summarises the dispatch without
105
- * exposing functions: `prompt: true` means a prompt judge (the text/closure
106
- * itself stays opaque).
107
- */
108
102
  /** Pure-data judge summary — `prompt: true` means a prompt judge (the text/closure stays opaque). */
109
103
  export interface JudgeSpec {
110
104
  skill?: string;
@@ -158,6 +152,11 @@ export function judgeSlotSpecOf(slot: AnyJudge): AnyJudgeSpec {
158
152
  return isPanel(slot) ? panelSpecOf(slot) : judgeSpecOf(slot);
159
153
  }
160
154
 
155
+ /**
156
+ * Pure-data projection of a LoopDef — what `describeFlow`, `preview`, and the
157
+ * `checkFanoutSource` lint consume. `judge` summarises the dispatch without
158
+ * exposing functions.
159
+ */
161
160
  export interface LoopSpec {
162
161
  kind: LoopDef["kind"];
163
162
  source?: string;
package/messages.ts CHANGED
@@ -10,6 +10,8 @@
10
10
  * `/wf` usage strings live in command.ts / preview.ts.
11
11
  */
12
12
 
13
+ import { MAX_NAME_LENGTH } from "./state/index.js";
14
+
13
15
  /**
14
16
  * One structured descriptor per terminal-failure kind — the `toast` (the
15
17
  * one-shot `ctx.ui.notify` line) and the `error` (what lands in
@@ -366,7 +368,7 @@ export const MSG_INTERACTIVE_ONLY = "/wf requires interactive mode";
366
368
  export const MSG_WORKFLOW_THREW = (reason: string) => `/wf: workflow runner failed unexpectedly: ${reason}`;
367
369
 
368
370
  export const MSG_NAME_INVALID = (name: string) =>
369
- `rpiv: invalid name "${name}" — must be 1-64 chars, start with a letter or underscore, only letters, digits, hyphens, underscores`;
371
+ `rpiv: invalid name "${name}" — must be 1-${MAX_NAME_LENGTH} chars, start with a letter or underscore, only letters, digits, hyphens, underscores`;
370
372
 
371
373
  export const MSG_NAME_COLLISION = (name: string, runId: string) => `name '${name}' already used by run ${runId}`;
372
374
 
@@ -104,6 +104,24 @@ async function runGitStatus(cwd: string): Promise<string | undefined> {
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * `git status --porcelain` line grammar — one record per line:
109
+ *
110
+ * <XY><space><path>
111
+ *
112
+ * <XY> — two-character status code (either half may be a space;
113
+ * ` M` is a worktree-only modification)
114
+ * <space> — the one-space separator after the status code
115
+ * <path> — cwd-relative path; renames render as `old -> new`; the
116
+ * path is double-quote wrapped when git cquote-escapes it
117
+ */
118
+ const PORCELAIN_STATUS_CODE_WIDTH = 2;
119
+ const PORCELAIN_PATH_OFFSET = PORCELAIN_STATUS_CODE_WIDTH + 1;
120
+ const PORCELAIN_MIN_LINE_WIDTH = PORCELAIN_PATH_OFFSET + 1;
121
+ const PORCELAIN_RENAME_ARROW = " -> ";
122
+ const PORCELAIN_RENAME_ARROW_WIDTH = PORCELAIN_RENAME_ARROW.length;
123
+ const PORCELAIN_QUOTE = '"';
124
+
107
125
  /**
108
126
  * Parse `git status --porcelain` output: each line is `XY <path>` where
109
127
  * XY is the two-character status code. We key by path and keep the
@@ -113,17 +131,19 @@ async function runGitStatus(cwd: string): Promise<string | undefined> {
113
131
  * downstream collectors / parsers don't usually care about the prior
114
132
  * name and including both halves doubles the artifact count.
115
133
  */
116
- function parsePorcelain(out: string): Map<string, string> {
134
+ export function parsePorcelain(out: string): Map<string, string> {
117
135
  const map = new Map<string, string>();
118
136
  for (const line of out.split("\n")) {
119
- if (line.length < 4) continue;
120
- const code = line.slice(0, 2);
121
- let path = line.slice(3).trim();
137
+ if (line.length < PORCELAIN_MIN_LINE_WIDTH) continue;
138
+ const code = line.slice(0, PORCELAIN_STATUS_CODE_WIDTH);
139
+ let path = line.slice(PORCELAIN_PATH_OFFSET).trim();
122
140
  // Rename: `R old -> new` — take the new name.
123
- const arrow = path.indexOf(" -> ");
124
- if (arrow !== -1) path = path.slice(arrow + 4);
125
- // Strip wrapping quotes (paths with whitespace).
126
- if (path.startsWith('"') && path.endsWith('"')) path = path.slice(1, -1);
141
+ const arrow = path.indexOf(PORCELAIN_RENAME_ARROW);
142
+ if (arrow !== -1) path = path.slice(arrow + PORCELAIN_RENAME_ARROW_WIDTH);
143
+ // Strip wrapping quotes (paths git cquote-escapes).
144
+ if (path.startsWith(PORCELAIN_QUOTE) && path.endsWith(PORCELAIN_QUOTE)) {
145
+ path = path.slice(PORCELAIN_QUOTE.length, -PORCELAIN_QUOTE.length);
146
+ }
127
147
  map.set(path, code);
128
148
  }
129
149
  return map;
package/outcomes/exec.ts CHANGED
@@ -12,6 +12,10 @@ export const execFileAsync = promisify(execFile);
12
12
  /**
13
13
  * Per git command. 5 s is generous for `rev-parse` / `log -1` /
14
14
  * `diff --shortstat` / `status --porcelain` on local repos, short enough
15
- * that a hung network mount can't pin the stage.
15
+ * that a hung network mount can't pin the stage. Mirrors `GIT_EXEC_TIMEOUT_MS`
16
+ * in `packages/rpiv-pi/extensions/rpiv-core/constants.ts` (session-start
17
+ * git-context probe) — same 5 s value, separately owned by design: the
18
+ * five-entry exports map exposes no sanctioned cross-package constant surface,
19
+ * and `sibling-import-graph.test.ts` blocks static sibling edges.
16
20
  */
17
21
  export const GIT_EXEC_TIMEOUT_MS = 5_000;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juicesharp/rpiv-workflow",
3
- "version": "2.6.4",
3
+ "version": "2.7.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",
@@ -112,7 +112,7 @@
112
112
  ]
113
113
  },
114
114
  "dependencies": {
115
- "@juicesharp/rpiv-config": "^2.6.4",
115
+ "@juicesharp/rpiv-config": "^2.7.0",
116
116
  "jiti": "^2.7.0",
117
117
  "typebox": "^1.1.24"
118
118
  },
package/preview.ts CHANGED
@@ -11,11 +11,44 @@ import type { LoadedWorkflows } from "./load/index.js";
11
11
  import { type AnyJudgeSpec, describeFlow, type StageShape } from "./loop-constructors.js";
12
12
  import type { SkillContractMap } from "./skill-contract.js";
13
13
 
14
+ // ===========================================================================
15
+ // Layout constants — module-local; every column width, gap, and ellipsis the
16
+ // formatters emit flows from here (containment precedent: DESC_TRUNCATE_LEN).
17
+ // ===========================================================================
18
+
19
+ /** Truncation ellipsis — the ASCII three-period form; the pinned truncation output forbids the single-glyph variant. */
20
+ const TRUNCATION_ELLIPSIS = "...";
21
+ /** Chars the ellipsis occupies inside the truncation cap. */
22
+ const ELLIPSIS_RESERVE = TRUNCATION_ELLIPSIS.length;
23
+
24
+ /**
25
+ * Description-truncation cap (characters) for the workflow-list view. Test-pinned
26
+ * at `preview.test.ts` ("truncates long descriptions at 50 characters with
27
+ * ellipsis"); the body reserves 3 chars for the trailing "...".
28
+ */
29
+ const DESC_TRUNCATE_LEN = 50;
30
+
31
+ /** Stage-index column width in details rows ("1." … "99." keep column alignment). */
32
+ const STAGE_INDEX_WIDTH = 3;
33
+ /**
34
+ * Stage-kind column width in details rows — layout value carried verbatim (widest
35
+ * current kind tag is 11 chars); coincidental twin of USAGE_HINT_GAP_WIDTH, never
36
+ * unified into one shared constant.
37
+ */
38
+ const STAGE_KIND_WIDTH = 13;
39
+ /** Display-name column width in details rows (stage name plus optional skill attribution). */
40
+ const DISPLAY_NAME_WIDTH = 36;
41
+ /**
42
+ * Gap between `/wf <workflow>` and the hint text in CMD_USAGE_PREVIEW; coincidental
43
+ * twin of STAGE_KIND_WIDTH, never unified into one shared constant.
44
+ */
45
+ const USAGE_HINT_GAP_WIDTH = 13;
46
+
14
47
  /** No-args listing footer — generic usage hint. */
15
48
  export const CMD_USAGE_LIST = "Usage: /wf [workflow] <description>";
16
49
 
17
50
  /** No-args listing footer — preview-mode hint paired with CMD_USAGE_LIST. */
18
- export const CMD_USAGE_PREVIEW = "/wf <workflow> — preview stages";
51
+ export const CMD_USAGE_PREVIEW = `/wf <workflow>${" ".repeat(USAGE_HINT_GAP_WIDTH)}— preview stages`;
19
52
 
20
53
  /** Per-workflow details footer — narrowed to the workflow the user previewed. */
21
54
  export const CMD_USAGE_RUN = (name: string) => `Usage: /wf ${name} <description>`;
@@ -24,17 +57,10 @@ export const CMD_USAGE_RUN = (name: string) => `Usage: /wf ${name} <description>
24
57
  // Public formatters
25
58
  // ===========================================================================
26
59
 
27
- /**
28
- * Description-truncation cap (characters) for the workflow-list view. Test-pinned
29
- * at `preview.test.ts` ("truncates long descriptions at 50 characters with
30
- * ellipsis"); the body reserves 3 chars for the trailing "...".
31
- */
32
- const DESC_TRUNCATE_LEN = 50;
33
-
34
60
  /** Truncate a description to `maxLen` characters, appending "..." if truncated. */
35
61
  function truncateDescription(desc: string, maxLen = DESC_TRUNCATE_LEN): string {
36
62
  if (desc.length <= maxLen) return desc;
37
- return `${desc.slice(0, maxLen - 3)}...`;
63
+ return `${desc.slice(0, maxLen - ELLIPSIS_RESERVE)}${TRUNCATION_ELLIPSIS}`;
38
64
  }
39
65
 
40
66
  /** No-args listing: every loaded workflow, its stage count, and its source. */
@@ -133,8 +159,8 @@ function formatStageRow(
133
159
  shape: StageShape,
134
160
  edgeDeclared: boolean,
135
161
  ): string {
136
- const num = `${idx}.`.padEnd(3);
137
- const decorations = [stage.kind.padEnd(13), stage.sessionPolicy, outcomeTag(stage)];
162
+ const num = `${idx}.`.padEnd(STAGE_INDEX_WIDTH);
163
+ const decorations = [stage.kind.padEnd(STAGE_KIND_WIDTH), stage.sessionPolicy, outcomeTag(stage)];
138
164
  if (stage.inputSchema) decorations.push("in-schema");
139
165
  if (stage.outputSchema) decorations.push("out-schema");
140
166
  if (shape.control.mode !== "single") decorations.push(loopTag(shape.control));
@@ -146,7 +172,7 @@ function formatStageRow(
146
172
  const arrow = formatEdge(shape.edge, edgeDeclared);
147
173
  const trailer = arrow ? ` → ${arrow}` : "";
148
174
 
149
- return ` ${num} ${displayName.padEnd(36)} ${decorations.join(" · ")}${trailer}`;
175
+ return ` ${num} ${displayName.padEnd(DISPLAY_NAME_WIDTH)} ${decorations.join(" · ")}${trailer}`;
150
176
  }
151
177
 
152
178
  /**
@@ -115,12 +115,12 @@ let strikeBudgets: WeakMap<StageSessionContext, StrikeBudget> = new WeakMap();
115
115
  * `recordStageSuccess` (packages/rpiv-workflow/sessions/success-persist.ts:49).
116
116
  */
117
117
  function budgetForConsume(s: StageSessionContext): StrikeBudget {
118
- let b = strikeBudgets.get(s);
119
- if (!b) {
120
- b = { ceiling: s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES, used: 0, reasons: [] };
121
- strikeBudgets.set(s, b);
118
+ let budget = strikeBudgets.get(s);
119
+ if (!budget) {
120
+ budget = { ceiling: s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES, used: 0, reasons: [] };
121
+ strikeBudgets.set(s, budget);
122
122
  }
123
- return b;
123
+ return budget;
124
124
  }
125
125
 
126
126
  /**
@@ -134,10 +134,10 @@ function budgetForConsume(s: StageSessionContext): StrikeBudget {
134
134
  * `push` (the budget initializes `reasons: []`).
135
135
  */
136
136
  export function consumeBashStrike(s: StageSessionContext, reason: string): boolean {
137
- const b = budgetForConsume(s);
138
- if (b.used >= b.ceiling) return false; // exhausted — mutate nothing; caller escalates.
139
- b.used += 1;
140
- b.reasons.push(reason);
137
+ const budget = budgetForConsume(s);
138
+ if (budget.used >= budget.ceiling) return false; // exhausted — mutate nothing; caller escalates.
139
+ budget.used += 1;
140
+ budget.reasons.push(reason);
141
141
  return true;
142
142
  }
143
143
 
@@ -150,9 +150,9 @@ export function consumeBashStrike(s: StageSessionContext, reason: string): boole
150
150
  * the budget's `ceiling` field + this fallback), allocating nothing.
151
151
  */
152
152
  export function bashStrikesRemaining(s: StageSessionContext): number {
153
- const b = strikeBudgets.get(s);
154
- const ceiling = b?.ceiling ?? s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES;
155
- return Math.max(0, ceiling - (b?.used ?? 0));
153
+ const budget = strikeBudgets.get(s);
154
+ const ceiling = budget?.ceiling ?? s.bashTimeoutStrikes ?? BASH_TIMEOUT_STRIKES;
155
+ return Math.max(0, ceiling - (budget?.used ?? 0));
156
156
  }
157
157
 
158
158
  /**
@@ -164,9 +164,9 @@ export function bashStrikesRemaining(s: StageSessionContext): number {
164
164
  * `reasons` lists each consumed strike's host reason, in consumption order.
165
165
  */
166
166
  export function bashTimeoutStrikeHistory(s: StageSessionContext): { count: number; reasons: string[] } | undefined {
167
- const b = strikeBudgets.get(s);
168
- if (!b || b.used <= 0) return undefined;
169
- return { count: b.used, reasons: b.reasons };
167
+ const budget = strikeBudgets.get(s);
168
+ if (!budget || budget.used <= 0) return undefined;
169
+ return { count: budget.used, reasons: budget.reasons };
170
170
  }
171
171
 
172
172
  /**
@@ -2,8 +2,10 @@
2
2
  * Halt-routing facet — extracted from `sessions.ts`'s HALT HELPERS. Turns a
3
3
  * halt reason into the right audit-layer call. `haltStageOrSoftHalt` is the
4
4
  * single gate `postStage` dispatches through (a `collectAll` fanout unit
5
- * soft-halts; everything else fail-fast halts). `haltStageWithValidationFailure`
6
- * is also exported for the `reattach.ts` companion.
5
+ * soft-halts SEMANTIC failures; an infra-death stop hard-fails even there —
6
+ * see `isInfraDeath`; everything else fail-fast halts).
7
+ * `haltStageWithValidationFailure` is also exported for the `reattach.ts`
8
+ * companion.
7
9
  *
8
10
  * `auditFor` lives here (moved from `sessions.ts`) — its only callers are the
9
11
  * halt helpers below; relocating it keeps the value-import DAG acyclic (the
@@ -41,10 +43,47 @@ type HaltReason =
41
43
  | { kind: "timeout"; reason: string };
42
44
 
43
45
  /**
44
- * The single collect-all fork. A `collectAll` fanout unit soft-halts (a
45
- * NON-terminal `collected:true` row + a `failedOutput` sentinel the parallel fold
46
- * places by index); every other stage takes the arm's fail-fast terminal halt.
47
- * Replaces the `if (s.collectAll)` that was inlined at all three halt sites.
46
+ * Stop signals that witness an INFRA death — the child session never delivered
47
+ * a complete agentic pass:
48
+ * - `error` — the SDK/API errored out under the session;
49
+ * - `noResponse` — the model never spoke (the child died before producing
50
+ * anything, e.g. killed at spawn);
51
+ * - `toolUse` — the transcript ENDS on a tool request: an agentic loop
52
+ * truncated mid-flight, the signature of a killed child
53
+ * process (the OOM killer's favourite).
54
+ * `length` is deliberately absent: the model consumed its output budget — a
55
+ * genuine model-behavior outcome an identical retry would likely reproduce, so
56
+ * it stays a collected (semantic) failure for the downstream floors to judge.
57
+ * `aborted` never reaches the stop arm (`classifyAndHandleAbort` owns it and
58
+ * throws `WorkflowAbortError` — no row, slot unfilled, resume re-dispatches).
59
+ */
60
+ const INFRA_DEATH_STOPS: ReadonlySet<StopSignal> = new Set(["error", "noResponse", "toolUse"]);
61
+
62
+ /**
63
+ * True when the halt reason witnesses infrastructure death rather than a
64
+ * judged-bad output. The distinction is load-bearing for collect-all fanout
65
+ * units: a collected soft-halt is a PERMANENT skip — the resume fold rebuilds
66
+ * its `failedOutput` sentinel by `unitIndex` and never re-dispatches the unit
67
+ * (runner/resume.ts `foldFanoutRow`), so collecting a transient infra death
68
+ * turns one OOM'd unit into an unrepairable hole three stages downstream
69
+ * (the slice-design → subplan-check incident). `extraction`/`validation`/
70
+ * `timeout` stay collected: there the skill RAN and its output (or runaway
71
+ * tool call) was judged — an identical retry is not obviously better, and the
72
+ * deterministic floors downstream are the right judge.
73
+ */
74
+ const isInfraDeath = (reason: HaltReason): boolean => reason.kind === "stop" && INFRA_DEATH_STOPS.has(reason.stop);
75
+
76
+ /**
77
+ * The single collect-all fork. A `collectAll` fanout unit soft-halts a
78
+ * SEMANTIC failure (a NON-terminal `collected:true` row + a `failedOutput`
79
+ * sentinel the parallel fold places by index); an infra-death stop takes the
80
+ * fail-fast terminal halt EVEN for collect-all — the trail then carries an
81
+ * UNCOLLECTED failed unit row, the resume fold leaves the slot unfilled, and
82
+ * resume re-dispatches exactly the dead unit. Completed siblings are unharmed:
83
+ * the parallel dispatcher never sibling-cancels a non-`failFast` fanout, and
84
+ * `recordStageSuccess` is not status-gated, so their rows land before the
85
+ * generation settles and the terminated run stops advancing. Every other stage
86
+ * takes the arm's fail-fast terminal halt, unchanged.
48
87
  */
49
88
  export async function haltStageOrSoftHalt(
50
89
  ctx: WorkflowHostContext,
@@ -52,7 +91,7 @@ export async function haltStageOrSoftHalt(
52
91
  reason: HaltReason,
53
92
  session: SessionRef | null,
54
93
  ): Promise<void> {
55
- if (s.collectAll) return softHaltUnit(ctx, s, softHaltReason(s, reason), session);
94
+ if (s.collectAll && !isInfraDeath(reason)) return softHaltUnit(ctx, s, softHaltReason(s, reason), session);
56
95
  return failFastHalt(ctx, s, reason, session);
57
96
  }
58
97
 
@@ -16,6 +16,7 @@ import { closeSync, existsSync, openSync, readdirSync, readSync, rmSync, statSyn
16
16
  import { dirname, join } from "node:path";
17
17
  import type { SessionRef } from "../state/index.js";
18
18
  import { childSessionsDir } from "../state/paths.js";
19
+ import { JSONL_PREFIX_READ_BYTES } from "../state/raw.js";
19
20
 
20
21
  /**
21
22
  * id → on-disk session file. Fail-soft: `null` means "fall back to cold
@@ -118,16 +119,17 @@ function isFile(path: string): boolean {
118
119
  }
119
120
  }
120
121
 
121
- /** Bounded prefix read — session files run to tens of MB; the header is line one. */
122
- const HEADER_PREFIX_BYTES = 8192;
123
-
124
- /** First-line `id` of a Pi session file, or undefined on any read/parse miss. */
122
+ /**
123
+ * First-line `id` of a Pi session file, or undefined on any read/parse miss.
124
+ * One-shot prefix read sized by `JSONL_PREFIX_READ_BYTES` — session files run
125
+ * to tens of MB; the header is line one.
126
+ */
125
127
  function headerIdOf(path: string): string | undefined {
126
128
  let fd: number | undefined;
127
129
  try {
128
130
  fd = openSync(path, "r");
129
- const buf = Buffer.alloc(HEADER_PREFIX_BYTES);
130
- const bytes = readSync(fd, buf, 0, HEADER_PREFIX_BYTES, 0);
131
+ const buf = Buffer.alloc(JSONL_PREFIX_READ_BYTES);
132
+ const bytes = readSync(fd, buf, 0, JSONL_PREFIX_READ_BYTES, 0);
131
133
  const firstLine = buf.toString("utf-8", 0, bytes).split("\n", 1)[0];
132
134
  if (!firstLine) return undefined;
133
135
  const parsed: unknown = JSON.parse(firstLine);
@@ -102,12 +102,16 @@ export async function postStage(
102
102
  const session = readSessionRef(child, offset);
103
103
  const outcome = readSessionOutcome(child, offset);
104
104
  // Abort classification and strike recovery are owned by a single helper that
105
- // returns "continue" when it has handled the turn (strike retry or soft-halt),
106
- // so postStage reaches its happy-path switch only for a clean stop.
105
+ // returns "continue" when it has handled the turn (strike retry or soft-halt).
106
+ // It consults the watchdog verdict for EVERY non-clean stop — a mid-tool abort
107
+ // surfaces as "error"/"toolUse", not "aborted" — so the stop/halt arms below
108
+ // only ever see turns with no live watchdog verdict.
107
109
  if ((await classifyAndHandleAbort(observerCtx, child, s, outcome, session, offset)) === "continue") return;
108
110
  // Every halt below routes through the single `haltStageOrSoftHalt` gate: a
109
111
  // fanout unit marked `collectAll` records a NON-terminal failed row + a sentinel
110
- // slot instead of halting the run; everything else takes the arm's fail-fast
112
+ // slot instead of halting the run — EXCEPT an infra-death stop (error/noResponse/
113
+ // toolUse), which hard-fails even there so resume re-dispatches the dead unit
114
+ // (see `isInfraDeath`, halt-routing.ts); everything else takes the arm's fail-fast
111
115
  // halt. Recording + the continuation run on observerCtx (the launcher) — the per-stage
112
116
  // child is disposed when the stage ends.
113
117
  if (outcome.stop !== "stop")
@@ -147,13 +151,22 @@ const watchdogTimeoutOf = (child: WorkflowSessionContext): { reason: string } |
147
151
 
148
152
  /**
149
153
  * Classify and route an abort. Abort surfaces as a STOP CLASSIFICATION, not a
150
- * promise rejection: `session.abort()` makes the SDK RESOLVE `prompt()` with a
151
- * `stopReason:"aborted"` transcript message, so an aborted in-flight child runs
152
- * straight into here. A genuine abort throws BEFORE haltStage/softHaltUnit/any
153
- * row write so: (a) no `collected:true` row is written (else the resume fold
154
- * marks the unit "don't re-dispatch" → permanent work loss), (b) the parallel
155
- * fold's `isAbortError` branch leaves the slot unfilled, and (c) resume
156
- * re-dispatches the unit cleanly.
154
+ * promise rejection — but NOT always as `stopReason:"aborted"`. An abort landing
155
+ * between turns resolves `prompt()` with an `"aborted"` message; one landing
156
+ * MID-TOOL instead yields an error toolResult ("Command aborted") followed by an
157
+ * EMPTY assistant entry with `stopReason:"error"` (the strangled follow-up API
158
+ * request), or a transcript truncated on the tool request (`"toolUse"`). So the
159
+ * watchdog VERDICT (`toolTimeout()`), not the stop shape, is the authoritative
160
+ * witness that the watchdog aborted this child — it is read for every non-clean
161
+ * stop, BEFORE the aborted-stop shape test. Gating the verdict behind
162
+ * `stop === "aborted"` sent a mid-`npm test` watchdog abort to the caller's stop
163
+ * arm, where `"error"` reads as infra death and hard-failed the unit (run
164
+ * 2026-08-20_14-54-40-4cc2, implement phase-1).
165
+ *
166
+ * A genuine abort throws BEFORE haltStage/softHaltUnit/any row write so: (a) no
167
+ * `collected:true` row is written (else the resume fold marks the unit "don't
168
+ * re-dispatch" → permanent work loss), (b) the parallel fold's `isAbortError`
169
+ * branch leaves the slot unfilled, and (c) resume re-dispatches the unit cleanly.
157
170
  *
158
171
  * Returns `"continue"` once the turn is owned (strike retry or soft-halt),
159
172
  * telling the caller to stop; returns `void` (no abort) so the caller proceeds
@@ -174,20 +187,26 @@ export async function classifyAndHandleAbort(
174
187
  ): Promise<"continue" | undefined> {
175
188
  // Level 1 — genuine run/user abort: the signal fired, so always re-dispatch on resume.
176
189
  if (s.signal?.aborted) throw new WorkflowAbortError();
177
- // Level 2 — not an abort stop: hand back to the caller's happy-path switch.
178
- if (!isAbortedStop(outcome)) return;
179
- // Level 3 — examine a watchdog tool-timeout; an aborted stop with the signal cold
180
- // and no watchdog is a genuine abort that re-dispatches on resume.
190
+ // Level 2 — clean completion: hand back to the caller's happy-path switch. A delivered
191
+ // turn outranks any stale watchdog verdict (the abort raced the completion).
192
+ if (outcome.stop === "stop") return;
193
+ // Level 3 — the watchdog verdict, read for EVERY non-clean stop (see the header: a
194
+ // mid-tool abort surfaces as "error"/"toolUse", not "aborted").
181
195
  const timeout = watchdogTimeoutOf(child);
182
- if (!timeout) throw new WorkflowAbortError();
183
- // Level 4 — a watchdog tool-timeout is recoverable: consume a strike and retry, or
184
- // route exhaustion through the soft-halt gate (collect-all survives; else terminal).
185
- if (consumeBashStrike(s, timeout.reason)) {
186
- await retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
187
- } else {
188
- await haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
196
+ if (timeout) {
197
+ // A watchdog tool-timeout is recoverable: consume a strike and retry, or route
198
+ // exhaustion through the soft-halt gate (collect-all survives; else terminal).
199
+ if (consumeBashStrike(s, timeout.reason)) {
200
+ await retryStageAfterBashStrike(observerCtx, child, s, offset, timeout.reason);
201
+ } else {
202
+ await haltStageOrSoftHalt(observerCtx, s, { kind: "timeout", reason: timeout.reason }, session);
203
+ }
204
+ return "continue";
189
205
  }
190
- return "continue";
206
+ // Level 4 — an aborted stop with the signal cold and no watchdog is a genuine abort
207
+ // (e.g. ESC): throw so no row lands and resume re-dispatches the unit cleanly.
208
+ if (isAbortedStop(outcome)) throw new WorkflowAbortError();
209
+ // Level 5 — a non-clean, non-abort stop with no verdict: the caller's stop arm owns it.
191
210
  }
192
211
 
193
212
  // ===========================================================================
package/state/index.ts CHANGED
@@ -26,6 +26,7 @@ export {
26
26
  isValidName,
27
27
  listArtifacts,
28
28
  listRuns,
29
+ MAX_NAME_LENGTH,
29
30
  namesFilePath,
30
31
  readAllStages,
31
32
  readAllStagesForResume,
package/state/names.ts CHANGED
@@ -43,8 +43,11 @@ export type ClaimResult =
43
43
  // Validation
44
44
  // ---------------------------------------------------------------------------
45
45
 
46
- /** Well-formedness contract for a run name: 1-64 chars, leading letter/underscore. */
47
- export const VALID_NAME = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
46
+ /** The one numeric source of the run-name length policy — names run 1..MAX_NAME_LENGTH characters. */
47
+ export const MAX_NAME_LENGTH = 64;
48
+
49
+ /** Well-formedness contract for a run name: 1-MAX_NAME_LENGTH chars, leading letter/underscore. */
50
+ export const VALID_NAME = new RegExp(`^[a-zA-Z_][a-zA-Z0-9_-]{0,${MAX_NAME_LENGTH - 1}}$`);
48
51
 
49
52
  export function isValidName(name: string): boolean {
50
53
  return VALID_NAME.test(name);
package/state/raw.ts CHANGED
@@ -10,8 +10,12 @@
10
10
  import { closeSync, openSync, readdirSync, readSync } from "node:fs";
11
11
  import { runsDir, stateFilePath } from "./paths.js";
12
12
 
13
- /** Read chunk for the first-line scan. Headers are one short JSON object — one chunk almost always suffices. */
14
- const FIRST_LINE_CHUNK = 8192;
13
+ /**
14
+ * Shared one-shot prefix-read size for JSONL first lines — 8KB covers a header
15
+ * line, so reads stay bounded however large the file. Consumed by the `state/`
16
+ * first-line reader and the `sessions/` header scan.
17
+ */
18
+ export const JSONL_PREFIX_READ_BYTES = 8192;
15
19
  /** Defensive cap: a "first line" longer than this is not a header we'd accept anyway. */
16
20
  const FIRST_LINE_MAX = 256 * 1024;
17
21
 
@@ -38,8 +42,8 @@ export function readFirstJsonlLine(cwd: string, runId: string): unknown {
38
42
  const chunks: Buffer[] = [];
39
43
  let total = 0;
40
44
  while (total < FIRST_LINE_MAX) {
41
- const chunk = Buffer.alloc(FIRST_LINE_CHUNK);
42
- const n = readSync(fd, chunk, 0, FIRST_LINE_CHUNK, total);
45
+ const chunk = Buffer.alloc(JSONL_PREFIX_READ_BYTES);
46
+ const n = readSync(fd, chunk, 0, JSONL_PREFIX_READ_BYTES, total);
43
47
  if (n <= 0) break;
44
48
  const read = chunk.subarray(0, n);
45
49
  const nl = read.indexOf(0x0a);
@@ -49,7 +53,7 @@ export function readFirstJsonlLine(cwd: string, runId: string): unknown {
49
53
  }
50
54
  chunks.push(read);
51
55
  total += n;
52
- if (n < FIRST_LINE_CHUNK) break; // EOF before any newline
56
+ if (n < JSONL_PREFIX_READ_BYTES) break; // EOF before any newline
53
57
  }
54
58
  const line = Buffer.concat(chunks).toString("utf-8").trim();
55
59
  if (!line) return undefined;
package/state/state.ts CHANGED
@@ -292,6 +292,7 @@ export {
292
292
  type ClaimResult,
293
293
  claimName,
294
294
  isValidName,
295
+ MAX_NAME_LENGTH,
295
296
  type NamesIndex,
296
297
  readNamesIndex,
297
298
  rebuildIndex,
package/types.ts CHANGED
@@ -525,10 +525,14 @@ export interface StageSessionContext extends SessionContext {
525
525
  */
526
526
  signal?: AbortSignal;
527
527
  /**
528
- * When true (a collect-all fanout unit), a unit failure soft-halts THIS unit
529
- * (non-terminal failed-output sentinel handed to `onSuccess`) instead of
530
- * terminating the whole run. Set by `buildUnitSession` for non-fail-fast
531
- * fanout; the soft-halt routing lives in `postStage`.
528
+ * When true (a collect-all fanout unit), a SEMANTIC unit failure
529
+ * (extraction/validation/timeout/length) soft-halts THIS unit (non-terminal
530
+ * failed-output sentinel handed to `onSuccess`) instead of terminating the
531
+ * whole run. An infra-death stop (error/noResponse/toolUse — the session
532
+ * never delivered a complete pass) hard-fails even here, so resume
533
+ * re-dispatches the dead unit instead of permanently collecting it (see
534
+ * `isInfraDeath`, sessions/halt-routing.ts). Set by `buildUnitSession` for
535
+ * non-fail-fast fanout; the routing lives in `haltStageOrSoftHalt`.
532
536
  */
533
537
  collectAll?: boolean;
534
538
  /**
@@ -108,7 +108,7 @@ function checkLoopInvariants(stage: StageDef, name: string, report: ReportFn): v
108
108
  // by accepted design (unifying would force a fragile string→code mapping or a
109
109
  // silent message change). This block owns the per-code surface the tests pin —
110
110
  // `assess-judge-shape` / `assess-done-not-function` /
111
- // `assess-feed-forward-not-function` (`validate-workflow.test.ts:923,928`).
111
+ // `assess-feed-forward-not-function` (`validate-workflow.test.ts`).
112
112
  const slot = loop.judge;
113
113
  const shapeIssues = judgeSlotShapeIssues(slot);
114
114
  for (const issue of shapeIssues) {
@@ -16,6 +16,7 @@ export const MAX_VALIDATION_RETRIES = 3;
16
16
  export const DEFAULT_VALIDATION_RETRIES = 1;
17
17
 
18
18
  export const DEFAULT_VALIDATION_RETRY_TIMEOUT_MS = 5 * 60 * 1000;
19
+ /** Hard ceiling for a single validation attempt; mirrors MAX_BASH_TOOL_TIMEOUT_MS in packages/rpiv-pi/extensions/rpiv-core/bash-timeout.ts — same 30-min value, separately owned. */
19
20
  export const MAX_VALIDATION_RETRY_TIMEOUT_MS = 30 * 60 * 1000;
20
21
  export const MIN_VALIDATION_RETRY_TIMEOUT_MS = 1_000;
21
22
 
@@ -14,7 +14,7 @@
14
14
  * which `.gitignore` ignores, and would false-skip the gate):
15
15
  * 1. the default git recipe — `git status --porcelain` + `git diff` (the same
16
16
  * `execFileSync("git", [...], { stdio: ["ignore","pipe","ignore"] })`
17
- * posture built-in-workflows.ts's `writeCommitBaseline` uses);
17
+ * posture built-ins/goal-baseline.ts's `writeCommitBaseline` uses);
18
18
  * 2. `hashArtifactsTree(cwd)` — a recursive walk of `<cwd>/.rpiv/artifacts/`
19
19
  * hashing each file's relative path + contents so a gitignored-only
20
20
  * artifact revision DOES change the digest.
@@ -100,7 +100,7 @@ function readdirRecursively(root: string, excludedTopDirs?: ReadonlySet<string>)
100
100
  /**
101
101
  * Content fingerprint of `cwd`'s working tree — `git status --porcelain` +
102
102
  * `git diff` concatenated with `hashArtifactsTree(cwd)`, then SHA-256 hashed.
103
- * Mirrors built-in-workflows.ts's `writeCommitBaseline` git posture
103
+ * Mirrors built-ins/goal-baseline.ts's `writeCommitBaseline` git posture
104
104
  * (`execFileSync` with stderr ignored so a non-repo cwd degrades silently).
105
105
  *
106
106
  * Returns `undefined` on ANY failure (non-repo / git missing / unreadable