@juicesharp/rpiv-pi 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.
@@ -24,6 +24,7 @@ import {
24
24
  defineRoute,
25
25
  defineWorkflow,
26
26
  directoryPathCollector,
27
+ type EdgeFn,
27
28
  eq,
28
29
  type FanoutContext,
29
30
  fanin,
@@ -40,11 +41,29 @@ import {
40
41
  produces,
41
42
  type RunView,
42
43
  type ScriptContext,
44
+ setRouteNote,
43
45
  type Unit,
44
46
  type Workflow,
45
47
  } from "@juicesharp/rpiv-workflow/registration";
46
- import { StagePreflightError } from "@juicesharp/rpiv-workflow/runner";
47
48
  import { rpivBucketOutcome } from "./artifact-collector.js";
49
+ import {
50
+ countHeadingsOutsideFences,
51
+ FILE_LINE_CITATION_RE,
52
+ type FsArtifact,
53
+ fencedSpans,
54
+ forEachLineOutsideFences,
55
+ haltPreflight,
56
+ latestFsArtifact,
57
+ MAX_PHASES,
58
+ type PhaseRecord,
59
+ readArtifactFile,
60
+ type StructureFinding,
61
+ TEST_PATH_RE,
62
+ VERDICT_DIR,
63
+ VERDICT_FAIL_SCORE,
64
+ VERDICT_PASS_SCORE,
65
+ writeStructureVerdict,
66
+ } from "./built-ins/index.js";
48
67
 
49
68
  // The code-review stage's output schema is no longer declared here — every
50
69
  // code-review stage sources it from the skill's contract `produces.data`
@@ -53,18 +72,6 @@ import { rpivBucketOutcome } from "./artifact-collector.js";
53
72
  // per workflow. Every workflow with a `code-review` stage — polish AND vet —
54
73
  // routes on the same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
55
74
 
56
- /**
57
- * A plan's structured `phases:` frontmatter array — the machine-readable phase
58
- * enumeration a plan-producing skill (`blueprint`, `plan`) derives from its
59
- * `## Phase N:` body headings — is what drives `implement` fanout. The
60
- * convention lives here; rpiv-workflow knows nothing about phases.
61
- *
62
- * Cap: a plan declaring more than 32 phases throws. The rpiv-pi planning skills
63
- * cap around 8 phases in practice; 32 leaves headroom for stretch plans without
64
- * letting a pathological (or hostile) plan drive an unbounded fanout loop.
65
- */
66
- const MAX_PHASES = 32;
67
-
68
75
  /**
69
76
  * `## Phase N:` headings — the source of truth a plan's `phases:` frontmatter
70
77
  * array is derived from. Used to verify that derived array, not to enumerate
@@ -72,103 +79,6 @@ const MAX_PHASES = 32;
72
79
  */
73
80
  const PLAN_PHASE_RE = /^## Phase (\d+):/gm;
74
81
 
75
- /**
76
- * A fence-opening line: optional leading whitespace then 3+ backticks or 3+
77
- * tildes (the CommonMark info-string delimiter). Single source of truth every
78
- * fence-aware scan shares.
79
- */
80
- const FENCE_LINE_RE = /^\s*(`{3,}|~{3,})/;
81
-
82
- /**
83
- * Whether `line` CLOSES the fence whose opener recorded `fenceChar` and
84
- * `fenceLen`. CommonMark: a closing fence uses the SAME char (``` ``` ``` does not
85
- * close `~~~`) and is at least as long (a 4-backtick opener needs 4+ to close),
86
- * with only that char plus optional trailing whitespace on the line. `fence` is
87
- * the current line's `RegExpExecArray` match (narrowed from the guarded
88
- * `.exec()` result).
89
- */
90
- const closesFence = (line: string, fence: RegExpExecArray, fenceChar: string, fenceLen: number): boolean => {
91
- const len = fence[1].length;
92
- return fence[1][0] === fenceChar && len >= fenceLen && line.trim().length === len;
93
- };
94
-
95
- /**
96
- * Visit every line of `content` that sits OUTSIDE fenced code blocks, calling
97
- * `visit(line, index)` with the line text and its 0-based index in
98
- * `content.split("\n")`. A `## Phase N:` / `## Slice N:` / `### Phase N —` / a
99
- * `#### N. path` inside a ``` or ~~~ fence is example/fixture text — a meta-plan
100
- * (one whose subject is the pipeline) legitimately embeds the pipeline's own
101
- * plan/slice fixtures — not a structural heading or declared write, so a naive
102
- * line scan would false-count it. Mirrors the fence-aware boundary scan in
103
- * skills/_shared/stitch-elaborations.mjs. Fence-opener and fence-closer lines
104
- * are skipped (never visited); `index` advances once per line (including skipped
105
- * fence lines) so it stays aligned with any caller's own `content.split("\n")`
106
- * array.
107
- */
108
- const forEachLineOutsideFences = (content: string, visit: (line: string, index: number) => void): void => {
109
- let inFence = false;
110
- let fenceLen = 0;
111
- let fenceChar = "";
112
- let index = 0;
113
- for (const line of content.split("\n")) {
114
- const fence = FENCE_LINE_RE.exec(line);
115
- if (fence) {
116
- if (!inFence) {
117
- inFence = true;
118
- fenceLen = fence[1].length;
119
- fenceChar = fence[1][0];
120
- } else if (closesFence(line, fence, fenceChar, fenceLen)) {
121
- inFence = false;
122
- fenceLen = 0;
123
- fenceChar = "";
124
- }
125
- } else if (!inFence) {
126
- visit(line, index);
127
- }
128
- index++;
129
- }
130
- };
131
-
132
- /**
133
- * Count lines matching `re` (a `^…` heading pattern) that sit OUTSIDE fenced code
134
- * blocks. Fence-awareness lives on `forEachLineOutsideFences` (a naive `matchAll`
135
- * counts fenced examples and false-throws the derived-array staleness guard);
136
- * the per-line `lineRe` drops the source's `g`/`m` flags so `lastIndex` can't drift.
137
- */
138
- const countHeadingsOutsideFences = (content: string, re: RegExp): number => {
139
- const lineRe = new RegExp(re.source); // per-line test; drop g/m so lastIndex can't drift
140
- let count = 0;
141
- forEachLineOutsideFences(content, (line) => {
142
- if (lineRe.test(line)) count++;
143
- });
144
- return count;
145
- };
146
-
147
- /**
148
- * One parsed entry of a plan's `phases:` array. `entry` carries the whole raw
149
- * frontmatter object, so a consumer can read fields beyond `{ n, title }`
150
- * without this parser knowing about them.
151
- */
152
- interface PhaseRecord {
153
- entry: Record<string, unknown>;
154
- /** From `entry.n`, falling back to the 1-based array position. */
155
- n: number;
156
- /** From `entry.title`, or "" when absent. */
157
- title: string;
158
- /** 0-based position in the array. */
159
- index: number;
160
- /** Total phases in this plan. */
161
- total: number;
162
- }
163
-
164
- /** Read an artifact file, resolving a workflow-relative path against `cwd`. */
165
- const readArtifactFile = (path: string, cwd: string): string =>
166
- readFileSync(isAbsolute(path) ? path : join(cwd, path), "utf-8");
167
-
168
- /** Build the halting `StagePreflightError` shape every phase fanout/iterate guard `throw`s. */
169
- const haltPreflight = (who: string, summary: string, detail: string): StagePreflightError =>
170
- new StagePreflightError("halt", who, summary, detail, true);
171
-
172
82
  /**
173
83
  * Parse a plan's `phases:` frontmatter into records, derive-checked against the
174
84
  * body's `## Phase N:` headings — the source of truth both the single-plan
@@ -214,10 +124,6 @@ const planPhaseRecords = (content: string, who: string, path: string): readonly
214
124
  });
215
125
  };
216
126
 
217
- /** Latest `fs`-handle artifact most recently published under `name` (undefined if none). */
218
- const latestFsArtifact = (state: RunView, name: string): Artifact | undefined =>
219
- state.named[name]?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
220
-
221
127
  /**
222
128
  * Read the latest plan published to the named `"plans"` channel and parse its
223
129
  * `phases:` frontmatter into records — the shared read/halt body both
@@ -257,17 +163,6 @@ const readPlanPhaseRecords = (
257
163
  return { records, promptPath };
258
164
  };
259
165
 
260
- /**
261
- * An `Artifact` narrowed to its `fs`-handle variant — the plan-path-carrying
262
- * shape the scope checks key the verdict path + `artifact` field off. Annotates
263
- * a captured artifact ACROSS loop iterations so the `if (a.handle.kind !== "fs")
264
- * continue` guard's narrowing carries to the post-loop `latest.handle.path` read
265
- * (the file's idiom — `designPathsBySlice` reads `.path` inside its own
266
- * same-scope guard; this loop captures the artifact across iterations, so the
267
- * narrowed type annotates the capture).
268
- */
269
- type FsArtifact = Artifact & { handle: { kind: "fs"; path: string } };
270
-
271
166
  /**
272
167
  * Union the per-phase `files:` write-set declared across the FULL `plans`
273
168
  * channel history. vet's review-fix loop appends a DISTINCT non-superseding fix
@@ -656,7 +551,7 @@ const polishWorkflow = defineWorkflow({
656
551
  validate: "code-review",
657
552
  // Backward edge: code-review → blueprint re-plans (implement needs a plan).
658
553
  // The iterate stage re-runs over every review phase; bounded by the
659
- // runner's default maxBackwardJumps (2 → up to 3 review iterations).
554
+ // runner's default maxBackwardJumps (3 → up to 4 review iterations).
660
555
  "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
661
556
  commit: "stop",
662
557
  },
@@ -719,6 +614,19 @@ const PLAN_DIMENSIONS = [
719
614
  "architecture-fit",
720
615
  ] as const;
721
616
 
617
+ /**
618
+ * The FIXED three-dimension roster ship's grade panel grades — the bespoke,
619
+ * tier-independent counterpart of `PLAN_DIMENSIONS`. Ship is a lightweight
620
+ * preset: it front-loads `research` (so `architecture-fit` always has its
621
+ * `--context`) and grades a trimmed, always-on set regardless of run shape.
622
+ * `SHIP_DIMENSION_FANOUT` and `shipGatePasses` bind this roster DIRECTLY — no
623
+ * `gateRoster(gateTier(...))` wrap — so a single-phase ship run still grades
624
+ * `architecture-fit`, the dimension a tiered gate would drop in the light
625
+ * roster. Order mirrors `PLAN_DIMENSIONS` (goal-anchored dimensions first,
626
+ * fit last) so the emitted units stay stable.
627
+ */
628
+ export const SHIP_DIMENSIONS = ["completeness", "correctness", "architecture-fit"] as const;
629
+
722
630
  /** Bucket directory the goal capture writes into — build's verbatim-brief channel. */
723
631
  const GOAL_DIR = ".rpiv/artifacts/goal";
724
632
 
@@ -907,6 +815,30 @@ const scopeExcess = (dirty: readonly string[], baseline: readonly string[], decl
907
815
  */
908
816
  const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
909
817
 
818
+ /**
819
+ * ship's research front-load — a LEANER grounding than build's `/skill:research`
820
+ * pass. Bypasses the research skill and bounds the agent to at most TWO targeted
821
+ * `codebase-analyzer` dispatches (sequentially — never parallel, never
822
+ * `run_in_background`) to map only what a lightweight single-phase plan needs to
823
+ * be correct: entry points, the relevant module's shape, and the conventions the
824
+ * implement lane must match. The agent then `Write`s a grounding doc under
825
+ * `.rpiv/artifacts/research/`, where the research bucket collector harvests it —
826
+ * the grade panel's architecture-fit dimension threads it as `--context` exactly
827
+ * as build's research artifact does. A prompt stage (no skill), so the stage
828
+ * name `research` drives outcome derivation (research contract → `research`
829
+ * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
830
+ * text, not dispatch, is what differs.
831
+ */
832
+ const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
833
+ [
834
+ "Ground this brief for a lightweight ship plan.",
835
+ "Do NOT dispatch /skill:research. Instead dispatch at most TWO targeted codebase-analyzer subagents (sequentially — never parallel, never run_in_background) to map only what a single-phase plan needs to be correct: entry points, the relevant module's shape, and the conventions the implement lane must match.",
836
+ "",
837
+ `Brief: ${state.originalInput}`,
838
+ "",
839
+ "Then Write a grounding doc under .rpiv/artifacts/research/ (timestamped filename) carrying the findings, and stop.",
840
+ ].join("\n");
841
+
910
842
  /** `## Slice N:` headings — the source of truth a slice map's `slices:` array is derived from. */
911
843
  const SLICE_HEADING_RE = /^## Slice (\d+):/gm;
912
844
 
@@ -1096,28 +1028,6 @@ const sliceCovers = (entry: Record<string, unknown>): string[] => {
1096
1028
  return Array.isArray(raw) ? raw.filter((c): c is string => typeof c === "string") : [];
1097
1029
  };
1098
1030
 
1099
- /** The verdict directory the deterministic checks and the LLM grade panel share. */
1100
- const VERDICT_DIR = ".rpiv/artifacts/verdicts";
1101
- /** Binary verdict score: a clean pass. The gate keys off `severity`, never this number. */
1102
- const VERDICT_PASS_SCORE = 100;
1103
- /** Binary verdict score: at least one finding. The gate keys off `severity`, never this number. */
1104
- const VERDICT_FAIL_SCORE = 0;
1105
-
1106
- /**
1107
- * A `path:line` (or `path:line-line`) citation in an artifact's prose. Requires a
1108
- * dotted extension so timestamps (`17:13:27`), ratios, and bare `Slice 2:` labels
1109
- * never match — only file references with a real extension are verified.
1110
- *
1111
- * A citation may START with a single dot (`.github/workflows/ci.yml:12`,
1112
- * `.eslintrc.js:3`) — without it, dot-dirs and dotfiles were captured with the
1113
- * dot stripped and guaranteed to fail the floor as a mangled path. The leading
1114
- * dot is taken only when the preceding char is not a word char or another dot
1115
- * (`(?<![\w.])`), and a dotless start only at a word boundary (`(?<!\w)`), so a
1116
- * prose ellipsis (`...packages/x.ts:5`) still yields `packages/x.ts`, never
1117
- * `...packages/x.ts`.
1118
- */
1119
- const FILE_LINE_CITATION_RE = /((?:(?<![\w.])\.)?(?<!\w)[\w][\w./-]*\.[a-zA-Z][a-zA-Z0-9]{0,4}):(\d+)(?:-(\d+))?/g;
1120
-
1121
1031
  /**
1122
1032
  * Verify every `file:line` citation in `body` resolves against the working tree:
1123
1033
  * the cited file must exist AND carry at least the cited line (a range's high end).
@@ -1254,41 +1164,6 @@ const resolveCitationPath = (
1254
1164
  return undefined;
1255
1165
  };
1256
1166
 
1257
- /**
1258
- * Character-offset spans of fenced code blocks (delimiter lines included), an
1259
- * unterminated fence running to end-of-text. Mirrors the `inFence`/`fenceLen`
1260
- * toggle `countHeadingsOutsideFences` carries so every fence-aware scan agrees
1261
- * on the same boundaries.
1262
- */
1263
- const fencedSpans = (content: string): [number, number][] => {
1264
- const spans: [number, number][] = [];
1265
- let inFence = false;
1266
- let fenceLen = 0;
1267
- let fenceChar = "";
1268
- let spanStart = 0;
1269
- let offset = 0;
1270
- for (const line of content.split("\n")) {
1271
- const lineEnd = offset + line.length + 1; // +1 for the split-consumed \n
1272
- const fence = FENCE_LINE_RE.exec(line);
1273
- if (fence) {
1274
- if (!inFence) {
1275
- inFence = true;
1276
- fenceLen = fence[1].length;
1277
- fenceChar = fence[1][0];
1278
- spanStart = offset;
1279
- } else if (closesFence(line, fence, fenceChar, fenceLen)) {
1280
- inFence = false;
1281
- fenceLen = 0;
1282
- fenceChar = "";
1283
- spans.push([spanStart, lineEnd]);
1284
- }
1285
- }
1286
- offset = lineEnd;
1287
- }
1288
- if (inFence) spans.push([spanStart, offset]);
1289
- return spans;
1290
- };
1291
-
1292
1167
  /** Example-path namespaces the skill prompts use in illustrative citations
1293
1168
  * (`path/to/file.ext:12`, `packages/x/y.ts:42`). Artifacts quote — and models
1294
1169
  * imitate — these examples in unfenced prose, where the fence skip cannot
@@ -1360,59 +1235,9 @@ const verifyCitations = (body: string, cwd: string): { detail: string; where: st
1360
1235
  return findings;
1361
1236
  };
1362
1237
 
1363
- /** A structure-dimension finding — the shared shape the deterministic verdict
1364
- * checks emit (`detail` is the actionable message, `where` locates the defect). */
1365
- type StructureFinding = { detail: string; where: string };
1366
-
1367
1238
  /** A dispatched sub-plan basename with its `_cluster-<k>` ordinal resolved. */
1368
1239
  type DispatchedCluster = { path: string; k: number };
1369
1240
 
1370
- /** An `fs` artifact handle (the only handle kind the verdict checks operate on). */
1371
- type FsHandle = { kind: "fs"; path: string };
1372
-
1373
- /**
1374
- * Write the shared `{ dimension: "structure" }` verdict and publish it on an fs
1375
- * artifact. The three deterministic structure checks (`sliceStructureCheck`,
1376
- * `subplanCoverageCheck`, `planCitationCheck`) all emit the SAME verdict shape
1377
- * and basename-keyed JSON write, so it lives here once. `who` is the channel
1378
- * prefix folded into the basename (so a re-run OVERWRITES its own slot —
1379
- * idempotent across fix/reslice/re-dispatch rounds); `handle` is the artifact
1380
- * the check inspected (serialized into `data.artifact` and basename-keyed).
1381
- *
1382
- * The `severity: pass ? "none" : "high"` floor is load-bearing: the gate routes
1383
- * via `allDimensionsPass`/`subplanGatePasses`, whose severity floor silently
1384
- * passes a `pass:false` verdict rated `low`/`none`; a structural defect MUST
1385
- * rate `high` or it ships. The `score` is the binary verdict scale (100 = clean,
1386
- * 0 = finding; the gate keys off `severity`, never this number).
1387
- *
1388
- * `extra` lets a caller stamp additional gate-readable fields onto the verdict
1389
- * data (and the persisted JSON, so the trail records them) — currently only
1390
- * `sliceStructureCheck`'s `citeDischarged` stamp.
1391
- */
1392
- const writeStructureVerdict = (
1393
- who: string,
1394
- handle: FsHandle,
1395
- findings: StructureFinding[],
1396
- cwd: string,
1397
- extra?: Record<string, unknown>,
1398
- ): Omit<Output, "meta"> => {
1399
- const pass = findings.length === 0;
1400
- const data = {
1401
- dimension: "structure",
1402
- pass,
1403
- score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
1404
- severity: pass ? "none" : "high",
1405
- artifact: handleToString(handle),
1406
- findings,
1407
- feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
1408
- ...extra,
1409
- };
1410
- const rel = join(VERDICT_DIR, `${who}__${basename(handle.path, ".md")}.json`);
1411
- mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
1412
- writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
1413
- return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
1414
- };
1415
-
1416
1241
  /**
1417
1242
  * A citation string occurs LIVE in the slice-map text — outside fenced spans
1418
1243
  * and not as half of an `old→new` refresh-note pair. A re-slice's revision
@@ -2321,25 +2146,18 @@ const reconciliationRecords = (
2321
2146
  return { directives, malformed };
2322
2147
  };
2323
2148
 
2324
- /**
2325
- * The reconcile write-restriction's static allowlist — a conservative test-path
2326
- * classifier. A directive may apply its `find → replace` ONLY to a co-located test
2327
- * file (`*.test.{ts,tsx,js,jsx}`); any other target is flagged and left untouched
2328
- * (fail-closed: golden masters, fixtures, `*.t.ts`, and production sources are NOT
2329
- * auto-applied). Narrow by design — do not widen it to compensate for a weak
2330
- * directive (correctness rests on this neither false-failing a legit test edit
2331
- * nor false-allowing a non-test target).
2332
- */
2333
- const TEST_PATH_RE = /\.test\.[tj]sx?$/;
2334
2149
  const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
2335
2150
 
2336
2151
  /**
2337
2152
  * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
2338
2153
  * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
2339
2154
  * finding, left untouched, fail-closed). A present `find` is replaced exactly
2340
- * once (`String.replace`, first match); an absent `find` whose `replace` is ALSO
2341
- * absent is a finding (reconcile does not guess); an absent `find` whose `replace`
2342
- * is already present is the idempotent-re-run no-op (a prior successful apply, no
2155
+ * once (`String.replace`, first match); an absent `find` whose `replace` is empty
2156
+ * is the idempotent-re-run no-op for a deletion (find-absent is the deletion's
2157
+ * success condition — the directive was already applied, no finding, no write); an
2158
+ * absent `find` whose non-empty `replace` is ALSO absent is a finding (reconcile
2159
+ * does not guess); an absent `find` whose non-empty `replace` is already present is
2160
+ * the idempotent-re-run no-op for a substitution (a prior successful apply, no
2343
2161
  * finding, no write). Paths resolve through `cwd` (`isAbsolute` short-circuit else
2344
2162
  * `join(cwd, target)`). Fail-soft: a read/apply throw degrades to a finding naming
2345
2163
  * the target, never a terminal throw. Returns findings in DIRECTIVE order and
@@ -2370,6 +2188,11 @@ const applyReconciliationDirectives = (
2370
2188
  // directive was already applied (e.g. a vet review-fix loop re-running
2371
2189
  // reconcile). Treated as satisfied — reconcile must not fail on its own
2372
2190
  // prior successful apply.
2191
+ } else if (d.replace === "") {
2192
+ // Idempotent re-run of a deletion: the find is gone and the replacement is
2193
+ // empty ⇒ find-absent is the deletion's success condition (a prior successful
2194
+ // apply removed it). Treated as satisfied — reconcile must not fail on its
2195
+ // own prior successful apply (e.g. a validate-fix loop re-running reconcile).
2373
2196
  } else {
2374
2197
  findings.push({
2375
2198
  detail: `reconcile: directive find substring not present in ${d.target} (and the replacement is absent — not already applied) — the expected text to replace is absent; the directive is stale or the test no longer matches`,
@@ -3097,6 +2920,45 @@ const CODE_DIMENSION_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-v
3097
2920
  const PLAN_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "plan-verdicts", { confirm: true });
3098
2921
  const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-verdicts", { confirm: true });
3099
2922
 
2923
+ /**
2924
+ * Ship's grade panel — a bespoke `fanout({...})` mirroring `gradePanelFanout`'s
2925
+ * body but binding the roster to `SHIP_DIMENSIONS` DIRECTLY (no
2926
+ * `gateRoster(gateTier(...))` wrap) and dropping the confirm / `priorChannel`
2927
+ * / surgical-fix machinery ship's single-pass grade does not carry. Kept: the
2928
+ * `latestFsArtifact` guard (no plan → no units), the dimension-keyed
2929
+ * `--context` (architecture-fit only, sourced from the front-loaded `research`
2930
+ * artifact), the `--goal` flag for `GOAL_DIMENSIONS` (completeness/
2931
+ * correctness), and the `freshVerdicts` / `latestVerdictPerDimension` /
2932
+ * `dimensionsToRegrade` carry-forward so a re-grade emits only still-pending
2933
+ * dimensions. Tier-independence is structural: the roster never shrinks, so a
2934
+ * light run still grades `architecture-fit`.
2935
+ */
2936
+ export const SHIP_DIMENSION_FANOUT = fanout({
2937
+ source: "plans",
2938
+ unit: { by: "dimension-list", pattern: "dimensions" },
2939
+ max: SHIP_DIMENSIONS.length,
2940
+ units: ({ state }) => {
2941
+ const doc = latestFsArtifact(state, "plans");
2942
+ if (doc?.handle.kind !== "fs") return [];
2943
+ const target = handleToString(doc.handle);
2944
+ const research = latestFsArtifact(state, "research");
2945
+ const contextFlag = research?.handle.kind === "fs" ? ` --context ${handleToString(research.handle)}` : "";
2946
+ const goal = latestFsArtifact(state, "goal");
2947
+ const goalFlag = goal?.handle.kind === "fs" ? ` --goal ${handleToString(goal.handle)}` : "";
2948
+ // Tier-independent roster: SHIP_DIMENSIONS verbatim — never gateRoster(gateTier(...)).
2949
+ const roster = SHIP_DIMENSIONS;
2950
+ const latest = latestVerdictPerDimension(freshVerdicts(state.named["ship-verdicts"], target));
2951
+ const risks = planAuthoredRisks(state, "plans");
2952
+ const pending = dimensionsToRegrade(roster, latest, risks);
2953
+ const carryForward = pending.length > 0 ? pending : roster;
2954
+ return carryForward.map((d) => ({
2955
+ prompt: `--dimension ${d} --artifact ${target}${d === "architecture-fit" ? contextFlag : ""}${GOAL_DIMENSIONS.has(d) ? goalFlag : ""}`,
2956
+ label: d,
2957
+ id: `plans-dim-${d}`,
2958
+ }));
2959
+ },
2960
+ });
2961
+
3100
2962
  /**
3101
2963
  * Fold the per-dimension verdicts into a gate decision: keep the latest verdict
3102
2964
  * per dimension (verdicts accumulate across fix loops), require all-pass.
@@ -3375,6 +3237,21 @@ const codeGatePasses = (state: RunView): boolean => {
3375
3237
  );
3376
3238
  };
3377
3239
 
3240
+ /**
3241
+ * Ship's grade gate — the tier-independent fold over `SHIP_DIMENSIONS` reading
3242
+ * the `ship-verdicts` channel. Satisfied when every ship dimension passes
3243
+ * (severity-floored) AND every plan-authored risk flag is ruled pass. Unlike
3244
+ * `planGatePasses`/`codeGatePasses` it folds NO deterministic cite channel —
3245
+ * ship's `plan-cite-check` gate is routed at its own edge — and binds the
3246
+ * roster to `SHIP_DIMENSIONS` verbatim (never `gateRoster(gateTier(...))`), so
3247
+ * the gate consults the same fixed set the panel graded.
3248
+ */
3249
+ export const shipGatePasses = (state: RunView): boolean => {
3250
+ const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
3251
+ const risks = planAuthoredRisks(state, "plans");
3252
+ return allDimensionsPass(fresh, SHIP_DIMENSIONS) && allRiskFlagsPass(fresh, risks);
3253
+ };
3254
+
3378
3255
  /**
3379
3256
  * Confirm-before-block: a dimension's FIRST blocking verdict against the
3380
3257
  * current artifact gets ONE independent second judgment before it buys a fix
@@ -3437,6 +3314,12 @@ const planVerdictOutcome = verdictOutcome("plan-verdicts");
3437
3314
  // slice-verdicts / plan-verdicts / code-verdicts parallel.
3438
3315
  const codeVerdictOutcome = verdictOutcome("code-verdicts");
3439
3316
 
3317
+ // Ship's grade panel writes its verdicts to a DISTINCT channel (same
3318
+ // directory, different artifact basenames) so they never mix with build's
3319
+ // plan/code verdicts — named for the workflow, completing the slice-verdicts
3320
+ // / plan-verdicts / code-verdicts / ship-verdicts parallel.
3321
+ export const shipVerdictOutcome = verdictOutcome("ship-verdicts");
3322
+
3440
3323
  /**
3441
3324
  * Absolute path to rpiv-pi's bundled deterministic stitch script. Resolved off
3442
3325
  * this module's own URL so it points inside the installed package at runtime
@@ -3576,7 +3459,7 @@ const vetWorkflow = defineWorkflow({
3576
3459
  // UNCHANGED. The scope-check inserts before validate, so a failing scope
3577
3460
  // verdict halts before re-review, and a passing one flows into validate and
3578
3461
  // back to code-review exactly as today. Bounded by the runner's default
3579
- // maxBackwardJumps (2 → at most 3 review iterations).
3462
+ // maxBackwardJumps (3 → at most 4 review iterations).
3580
3463
  validate: "code-review",
3581
3464
  commit: "stop",
3582
3465
  },
@@ -3788,6 +3671,15 @@ const buildWorkflow = defineWorkflow({
3788
3671
  // `from` form suppresses the READS_DATA outputSchema lint.
3789
3672
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
3790
3673
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
3674
+ // Repair arm the validate gate dispatches on a `verdict: "fail"`. `acts()`
3675
+ // (not `produces()`) because remediate is `side-effect`/`code-mutation` (the
3676
+ // tools twin of `implement`: re-runs verification commands via `Bash(*)` and
3677
+ // edits the working tree) — NOT produced-validating and NOT routed-on (its
3678
+ // edge is deterministic), so it owns no outcome. `reads: ["plans","validation"]`
3679
+ // ⇒ `stageEntryArgs` derives `--plans <plan> --validation <latest-report>`;
3680
+ // `validation` is validate's own publish bucket, so validate-fix always reads
3681
+ // the latest failing report.
3682
+ "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"] }),
3791
3683
  commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
3792
3684
  },
3793
3685
  edges: {
@@ -3810,7 +3702,7 @@ const buildWorkflow = defineWorkflow({
3810
3702
  { readsData: false },
3811
3703
  ),
3812
3704
  // Design-readiness gate BEFORE any design. Structure + design-readiness pass⇒ design; any fails ⇒
3813
- // slice-fix and loop back. Bounded by the runner's maxBackwardJumps (default 2).
3705
+ // slice-fix and loop back. Bounded by the runner's maxBackwardJumps (default 3).
3814
3706
  "slice-grade": defineRoute(
3815
3707
  ["slice-design", "slice-fix"],
3816
3708
  ({ state }) => (sliceGatePasses(state) ? "slice-design" : "slice-fix"),
@@ -3940,15 +3832,186 @@ const buildWorkflow = defineWorkflow({
3940
3832
  // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
3941
3833
  reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
3942
3834
  // Gate commit on validate's own verdict — an unconditional `validate → commit`
3943
- // let a `verdict: fail` (incomplete goal coverage) commit anyway. `match` with
3944
- // no fallback commits ONLY on an explicit `verdict: "pass"`; every other value
3945
- // (a `fail`, or a missing verdict) routes to STOP — a failed validation halts
3946
- // WITHOUT committing, leaving the report on disk for the user. Safe by
3947
- // construction: the sole path to commit is an explicit pass, so un-anticipated
3948
- // data can never route INTO commit. Sourced from validate's published verdict
3949
- // channel (`from: "validation"` — the bucket its contract's `artifactKind`
3950
- // derives) — a prompt stage owns its message and can't inherit its contract's
3951
- // output schema, so route on the channel, not the raw (un-validated) stage output.
3835
+ // let a `verdict: fail` (incomplete goal coverage) commit anyway. Now the
3836
+ // gate splits: `pass` ⇒ commit; `fail` ⇒ validate-fix (the repair arm above,
3837
+ // which re-runs the failing `verify-at-implement` risk-ruling procedures and
3838
+ // surgically fixes the tree, then re-enters at implement-scope-check to
3839
+ // re-reconcile + re-validate — bounded by the per-destination backward-jump
3840
+ // budget). Deliberately NOT a `fallback`: a missing/unexpected verdict stays
3841
+ // terminal STOP, so un-anticipated data can never route INTO commit OR the
3842
+ // repair arm. Safe by construction: the sole path to commit is an explicit
3843
+ // pass. The `match` branch key (`validate-fix`) doubles as the reachability/
3844
+ // stage declaration, so naming it both routes `fail` and declares the stage
3845
+ // reachable. Sourced from validate's published verdict channel
3846
+ // (`from: "validation"` — the bucket its contract's `artifactKind` derives) —
3847
+ // a prompt stage owns its message and can't inherit its contract's output
3848
+ // schema, so route on the channel, not the raw (un-validated) stage output.
3849
+ validate: match("verdict", { commit: "pass", "validate-fix": "fail" }, { from: "validation" }),
3850
+ // Deterministic re-entry after the repair arm: remediate's code-mutation is
3851
+ // followed by a fresh scope check → reconcile → validate pass, so a fix is
3852
+ // re-verified end-to-end before the gate re-folds. A non-counted edge (a
3853
+ // deterministic hop into the loop body), so it never trips a backward-jump
3854
+ // budget on its own — the budget-consuming decision edge is the validate
3855
+ // gate's `validate-fix` branch above.
3856
+ "validate-fix": "implement-scope-check",
3857
+ commit: "stop",
3858
+ },
3859
+ });
3860
+
3861
+ /**
3862
+ * Reason strings for ship's two bespoke stop picks — persisted on the
3863
+ * `RoutingDecision` row via `setRouteNote` so `summarizeRun` can surface
3864
+ * "stopped at <gate>: <why>" in the end-of-run recap and toast. `match`/`gate`
3865
+ * edges attach their own no-match diagnostics; only these two `defineRoute`
3866
+ * gates would otherwise stop silently. Best-effort DIAGNOSTICS, not gates:
3867
+ * `allDimensionsPass`/`shipGatePasses` stay the sole routing authorities, and
3868
+ * these mirror their severity floor only to NAME the blockers.
3869
+ */
3870
+ const shipCiteStopNote = (state: RunView): string => {
3871
+ const data = state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown } | undefined;
3872
+ const n = Array.isArray(data?.findings) ? data.findings.length : 0;
3873
+ return n > 0 ? `plan citation check failed (${n} finding${n === 1 ? "" : "s"})` : "plan citation check failed";
3874
+ };
3875
+ const shipGradeStopNote = (state: RunView): string => {
3876
+ const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
3877
+ if (fresh.length === 0) return "no fresh verdicts for the current plan";
3878
+ const risks = planAuthoredRisks(state, "plans");
3879
+ const latest = latestVerdictPerDimension(fresh);
3880
+ const blockers: string[] = [];
3881
+ for (const d of SHIP_DIMENSIONS) {
3882
+ const o = latest.get(d);
3883
+ if (!o) continue;
3884
+ const v = o.data as { pass?: boolean; severity?: string; findings?: unknown };
3885
+ const floored = v.pass === true || v.severity === "low" || v.severity === "none" || anchorNitsOnly(v);
3886
+ if (!floored) blockers.push(`${d} failed (${v.severity ?? "unrated"})`);
3887
+ else if (verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id))))
3888
+ blockers.push(`${d} risk flag failed`);
3889
+ }
3890
+ return blockers.length > 0 ? blockers.join(", ") : "gate failed";
3891
+ };
3892
+
3893
+ // Named (not inline) so the stop branch can self-reference for setRouteNote —
3894
+ // the same closure-over-own-binding pattern gate()/match() use internally.
3895
+ // Citation-floor gate. Pass ⇒ grade; fail ⇒ STOP (no fix arm — the lightweight
3896
+ // preset terminates on any red gate). The route folds `allDimensionsPass` over
3897
+ // the stage's OWN published channel, NOT `match("verdict", …)`:
3898
+ // `writeStructureVerdict` (the floor's envelope) carries no `verdict` field, so
3899
+ // a verdict match would misread — this mirrors build's `planGatePasses` first
3900
+ // clause. `readsData: false` — the route consults the deterministic verdict
3901
+ // channel only.
3902
+ const shipCiteGate: EdgeFn = defineRoute(
3903
+ ["grade", "stop"],
3904
+ ({ state }) => {
3905
+ if (allDimensionsPass(state.named["plan-cite-check"])) return "grade";
3906
+ setRouteNote(shipCiteGate, shipCiteStopNote(state));
3907
+ return "stop";
3908
+ },
3909
+ { readsData: false },
3910
+ );
3911
+ // Quality gate PRE-implement. `shipGatePasses` (the bespoke fold over
3912
+ // SHIP_DIMENSIONS + risk flags on the `ship-verdicts` channel) does NOT re-fold
3913
+ // the citation floor; this edge is the sole gate. Pass ⇒ implement; fail ⇒
3914
+ // STOP — no confirm/snapshot/fix loop.
3915
+ const shipGradeGate: EdgeFn = defineRoute(
3916
+ ["implement", "stop"],
3917
+ ({ state }) => {
3918
+ if (shipGatePasses(state)) return "implement";
3919
+ setRouteNote(shipGradeGate, shipGradeStopNote(state));
3920
+ return "stop";
3921
+ },
3922
+ { readsData: false },
3923
+ );
3924
+
3925
+ /**
3926
+ * ship — the lightweight `/wf` preset: the no-ceremony path for small-to-
3927
+ * midsize tasks whose approach is obvious. goal → research → plan →
3928
+ * plan-cite-check → grade → implement → implement-scope-check → reconcile →
3929
+ * validate → commit, stop-on-fail at every gate with NO backward edges: a red
3930
+ * gate terminates the run (the agent hand-repairs and re-invokes) instead of
3931
+ * looping a fix cycle. Research stays front-loaded — a ≤2-subagent grounding
3932
+ * pass (SHIP_RESEARCH_PROMPT, not a full `/skill:research` run) — because the
3933
+ * single PRE-implement grade's architecture-fit dimension needs its artifact as
3934
+ * `--context`. That grade is tier-independent: the bespoke SHIP_DIMENSION_FANOUT
3935
+ * always grades the full correctness/completeness/architecture-fit roster (no
3936
+ * gateTier/gateRoster light-tier drop), and SHIP's gate folds risk flags without
3937
+ * re-folding the citation floor (that floor folds at its own edge).
3938
+ */
3939
+ const shipWorkflow = defineWorkflow({
3940
+ name: "ship",
3941
+ description:
3942
+ "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with at most two targeted codebase-analyzer dispatches (no /skill:research) → one lightweight quick-plan pass → deterministic citation floor → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate terminates the run on fail; no fix loops.",
3943
+ start: "goal",
3944
+ stages: {
3945
+ // build's verbatim goal capture — the brief on its own channel, plus the
3946
+ // run-start pre-existing-dirty snapshot the scope-check subtracts.
3947
+ goal: produces.script({ run: captureGoal }),
3948
+ // The lean grounding pass — SHIP_RESEARCH_PROMPT (a custom prompt, NOT
3949
+ // /skill:research): ≤2 sequential codebase-analyzer subagents, then one
3950
+ // grounding doc under .rpiv/artifacts/research/. A prompt stage, so the
3951
+ // stage name `research` drives outcome derivation (research contract →
3952
+ // `research` bucket) exactly as build's RESEARCH_BRIEF_PROMPT stage does.
3953
+ research: produces({ prompt: SHIP_RESEARCH_PROMPT }),
3954
+ // The lightweight planner — quick-plan: ONE targeted
3955
+ // codebase-pattern-finder dispatch, one `status: ready` plan, no risks
3956
+ // frontmatter, no multi-slice decomposition. Derives its `plans` outcome
3957
+ // from the quick-plan contract (artifactKind: plan). Reads BOTH channels
3958
+ // explicitly (`--research <path> --goal <path>`) — without `goal` the
3959
+ // stage falls to the rolling primary and the planner sees only the
3960
+ // research doc, whose grounding routinely narrows the brief; the grade
3961
+ // panel's completeness dimension anchors on the VERBATIM goal, so the
3962
+ // planner must anchor on the same artifact to defer narrowed-out asks
3963
+ // explicitly instead of silently inheriting the drop.
3964
+ plan: produces({ skill: "quick-plan", reads: ["research", "goal"] }),
3965
+ // Deterministic citation floor BEFORE the LLM gate — build's verifier
3966
+ // verbatim. A fabricated `file:line` fails structurally and STOPs the run.
3967
+ "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
3968
+ // Single PRE-implement grade over the fixed three-dimension roster
3969
+ // (SHIP_DIMENSION_FANOUT — tier-independent, no confirm/snapshot arms);
3970
+ // verdicts on the `ship-verdicts` channel. `research` is read so the
3971
+ // architecture-fit unit threads it as --context; `goal` so
3972
+ // completeness/correctness anchor on the verbatim brief.
3973
+ grade: produces({
3974
+ skill: "grade",
3975
+ loop: SHIP_DIMENSION_FANOUT,
3976
+ outcome: shipVerdictOutcome,
3977
+ reads: ["plans", "research", "goal"],
3978
+ }),
3979
+ // Dep-gated DAG implement — build's lane verbatim.
3980
+ implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
3981
+ // Lane-level scope floor — build's latest-only variant (vet uses the
3982
+ // union variant for its fix loop; ship has no loop, so the latest plan's
3983
+ // declared write-set is the whole contract). Pass ⇒ reconcile; fail ⇒ STOP.
3984
+ "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
3985
+ // Deterministic post-implement reconciliation — build's run-function
3986
+ // verbatim. Pass ⇒ validate; fail/missing ⇒ STOP (no fallback).
3987
+ reconcile: produces.script({ reads: ["plans"], run: reconcile }),
3988
+ validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
3989
+ commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
3990
+ },
3991
+ edges: {
3992
+ goal: "research",
3993
+ research: "plan",
3994
+ plan: "plan-cite-check",
3995
+ // Both gates are the named EdgeFns above — they attach a stop-reason
3996
+ // ROUTE_NOTE the recap surfaces; routing semantics are unchanged.
3997
+ "plan-cite-check": shipCiteGate,
3998
+ grade: shipGradeGate,
3999
+ implement: "implement-scope-check",
4000
+ // Scope floor gate — build's route verbatim: the sole path onward is an
4001
+ // explicit `verdict: "pass"`; a fail (undeclared write) or a missing
4002
+ // verdict is terminal STOP. Sourced from the stage's own channel via the
4003
+ // `from` form (suppresses the READS_DATA outputSchema lint).
4004
+ "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
4005
+ // Reconciliation gate — build's route verbatim: pass ⇒ validate;
4006
+ // fail/missing ⇒ STOP (plan-vs-tree drift the agent reconciles manually).
4007
+ reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
4008
+ // Validate gate — build's validate edge (match verdict pass⇒commit,
4009
+ // from "validation") minus the `validate-fix` arm: `pass` ⇒ commit; `fail`
4010
+ // or missing ⇒ STOP — deliberately NO validate-fix/remediate repair arm
4011
+ // (the lightweight preset does not loop). NOT vet's tail: vet's validate
4012
+ // routes to code-review, which gates back to blueprint (a bounded backward
4013
+ // loop, not stop-on-fail). Sourced from validate's published verdict
4014
+ // channel (`from: "validation"`).
3952
4015
  validate: match("verdict", { commit: "pass" }, { from: "validation" }),
3953
4016
  commit: "stop",
3954
4017
  },
@@ -3961,4 +4024,4 @@ const buildWorkflow = defineWorkflow({
3961
4024
  // Position 0 is load-bearing: `build` is the default `/wf` workflow when no
3962
4025
  // project/user config sets one (resolve-default.ts resolves
3963
4026
  // `Map.keys().next().value`), so it MUST stay first in this array.
3964
- export const builtInWorkflows: readonly Workflow[] = [buildWorkflow, vetWorkflow, polishWorkflow];
4027
+ export const builtInWorkflows: readonly Workflow[] = [buildWorkflow, vetWorkflow, polishWorkflow, shipWorkflow];