@juicesharp/rpiv-pi 2.7.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +2 -2
  2. package/docs/architecture.md +3 -3
  3. package/docs/skills.md +8 -6
  4. package/docs/workflows.md +3 -3
  5. package/extensions/rpiv-core/agent-enablement.ts +164 -0
  6. package/extensions/rpiv-core/agents.ts +98 -12
  7. package/extensions/rpiv-core/built-in-workflows.ts +373 -142
  8. package/extensions/rpiv-core/built-ins/gates.ts +38 -15
  9. package/extensions/rpiv-core/built-ins/goal-baseline.ts +43 -1
  10. package/extensions/rpiv-core/built-ins/grade-panel.ts +98 -29
  11. package/extensions/rpiv-core/built-ins/index.ts +1 -0
  12. package/extensions/rpiv-core/built-ins/priors.ts +208 -38
  13. package/extensions/rpiv-core/built-ins/reconcile-directives.d.mts +29 -0
  14. package/extensions/rpiv-core/built-ins/reconcile-directives.mjs +338 -0
  15. package/extensions/rpiv-core/built-ins/reconcile.ts +88 -130
  16. package/extensions/rpiv-core/built-ins/slices.ts +5 -1
  17. package/extensions/rpiv-core/frontmatter.ts +22 -0
  18. package/extensions/rpiv-core/lane-relay-ui.ts +25 -1
  19. package/extensions/rpiv-core/models-config.ts +86 -6
  20. package/extensions/rpiv-core/outcome-derivation.ts +1 -0
  21. package/extensions/rpiv-core/package-checks.ts +13 -0
  22. package/extensions/rpiv-core/pipeline-pointer.ts +1 -1
  23. package/extensions/rpiv-core/workflow-execution-host.ts +3 -2
  24. package/package.json +3 -3
  25. package/skills/_shared/reconcile-lint.mjs +125 -0
  26. package/skills/acceptance/SKILL.md +123 -0
  27. package/skills/elaborate/SKILL.md +3 -3
  28. package/skills/grade/SKILL.md +8 -7
  29. package/skills/implement/SKILL.md +17 -2
  30. package/skills/quick-plan/SKILL.md +19 -2
  31. package/skills/research/SKILL.md +28 -1
  32. package/skills/slice/SKILL.md +4 -4
  33. package/skills/synthesize/SKILL.md +1 -1
  34. package/skills/validate/SKILL.md +11 -5
@@ -44,6 +44,7 @@ import {
44
44
  CODE_DIMENSION_FANOUT,
45
45
  COMMIT_BASELINE_PROMPT,
46
46
  captureGoal,
47
+ captureReviewScope,
47
48
  codeDemote,
48
49
  codeGatePasses,
49
50
  codeSnapshot,
@@ -144,7 +145,8 @@ const polishWorkflow = defineWorkflow({
144
145
  });
145
146
 
146
147
  // ===========================================================================
147
- // build — goal (verbatim-brief capture) → research → slice → slice-check
148
+ // build — goal (verbatim-brief capture) → research → acceptance (the
149
+ // goal-derived executable standard of completion) → slice → slice-check
148
150
  // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
149
151
  // → slice-design (fanout) → design-review (one human checkpoint) →
150
152
  // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
@@ -183,26 +185,41 @@ const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.
183
185
 
184
186
  /**
185
187
  * ship's research front-load — a LEANER grounding than build's `/skill:research`
186
- * pass. Bypasses the research skill and bounds the agent to at most TWO targeted
187
- * `codebase-analyzer` dispatches (sequentially — never parallel, never
188
- * `run_in_background`) to map only what a lightweight single-phase plan needs to
189
- * be correct: entry points, the relevant module's shape, and the conventions the
190
- * implement lane must match. The agent then `Write`s a grounding doc under
191
- * `.rpiv/artifacts/research/`, where the research bucket collector harvests it —
192
- * the grade panel's architecture-fit dimension threads it as `--context` exactly
193
- * as build's research artifact does. A prompt stage (no skill), so the stage
194
- * name `research` drives outcome derivation (research contract → `research`
188
+ * pass, tiered to the brief's pre-chewedness. Bypasses the research skill: a
189
+ * pre-chewed brief (root cause, files to touch, or fix already named) gets
190
+ * VERIFICATION, not re-derivation — at most ONE verify-only `codebase-analyzer`
191
+ * dispatch confirming each named anchor, or none at all when the anchors are
192
+ * plain file paths the stage child reads itself; a symptom-only brief keeps at
193
+ * most TWO targeted `codebase-analyzer` dispatches (sequentially — never
194
+ * parallel, never `run_in_background`) mapping only what a lightweight
195
+ * single-phase plan needs to be correct. The agent then `Write`s a grounding
196
+ * doc under `.rpiv/artifacts/research/` (the prompt names the directory only —
197
+ * a full example path would prime the collector's pre-write path-echo hazard),
198
+ * where the research bucket collector harvests it — the grade panel's
199
+ * architecture-fit dimension threads it as `--context` exactly as build's
200
+ * research artifact does. A prompt stage (no skill), so the stage name
201
+ * `research` drives outcome derivation (research contract → `research`
195
202
  * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
196
- * text, not dispatch, is what differs.
203
+ * text, not dispatch, is what differs. The prompt also pins a progress-marker
204
+ * protocol — a `[Classified]:` first line naming the chosen tier,
205
+ * `[Dispatch N/M]:` / `[Dispatch N/M returned]:` echo lines around each
206
+ * grounding dispatch (plus the `[Dispatch]: none` zero-dispatch escape) — so
207
+ * the lane console's live tail narrates the otherwise-silent batch window;
208
+ * markers are transcript text only and never carry an artifacts path before
209
+ * the write.
197
210
  */
198
211
  const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
199
212
  [
200
213
  "Ground this brief for a lightweight ship plan.",
201
- "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.",
214
+ "Do NOT dispatch /skill:research — size the grounding to what the brief already carries.",
215
+ "Classify the brief first, then follow ONLY the matching tier:",
216
+ "- Tier A (pre-chewed — the brief names the root cause, the files to touch, or the fix): VERIFY, don't re-derive. Dispatch at most ONE codebase-analyzer subagent (sequentially — never parallel, never run_in_background) in verify-only mode, confirming or denying each named anchor against the actual code and reporting drift with the corrected file:line. If the anchors are plain file paths, dispatch nothing — Read/Grep them yourself.",
217
+ "- Tier B (symptom only — the brief names none of the three: no root cause, no files, no fix): 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.",
218
+ "Progress markers — echo your status as you go: the first line of your reply, before anything else, is [Classified]: Tier A — verify-only or [Classified]: Tier B — map ground truth (the tier you classified the brief into). Before each dispatch, emit [Dispatch N/M]: <purpose phrase>; once it lands, emit [Dispatch N/M returned]: <outcome phrase> (M is the tier's dispatch ceiling: 1 for Tier A, 2 for Tier B). For Tier A's zero-dispatch escape, emit [Dispatch]: none — reading the named anchors directly. Markers are transcript text only, never artifact content, and must NEVER contain a .rpiv/artifacts/ path before the file is written.",
202
219
  "",
203
220
  `Brief: ${state.originalInput}`,
204
221
  "",
205
- "Then Write a grounding doc under .rpiv/artifacts/research/ (timestamped filename) carrying the findings, and stop.",
222
+ "Then Write the grounding doc under .rpiv/artifacts/research/ (timestamped filename, under 150 lines) carrying the findings with verifiable file:line citations — Code References, Integration Points, the relevant module's shape, and the conventions the implement lane must match — announce the written file's path in your final message, and stop.",
206
223
  ].join("\n");
207
224
 
208
225
  /**
@@ -284,6 +301,97 @@ const scopeFloorGate = (): EdgeFn => {
284
301
  return route;
285
302
  };
286
303
 
304
+ /**
305
+ * The reconciliation gate — pass ⇒ validate; fail ⇒ the `reconcile-fix` repair
306
+ * arm; missing/corrupt verdict ⇒ STOP (integrity clause, exactly the `match` it
307
+ * replaces). The arm exists because every reconcile failure class — a malformed
308
+ * directive, a stale `find`, a non-test target — is a defect in the PLAN's
309
+ * directive text, which is `amend`'s exact authority ("fix the artifact, never
310
+ * the repo"); the old no-arm route stopped the run on a fail that hand-repairing
311
+ * the TREE could never clear (run 2026-08-31_15-21-14-57d0: a multi-line
312
+ * directive re-failed every resume because the defect lived in the plan
313
+ * artifact, which nothing in the pipeline could edit). Reconcile itself stays
314
+ * the sole test-file writer — the arm only repairs directives; the loop
315
+ * re-enters reconcile to apply them.
316
+ *
317
+ * A factory for the validateGate/scopeFloorGate reason — each workflow's
318
+ * route-note symbol must never alias the other's. `maxFixRounds` caps the
319
+ * amend hops a fail may buy, counted from the `reconcile-fix` channel — the
320
+ * channel ONLY the arm itself writes (its outcome publishes there, not on
321
+ * `plans`), mirroring validateGate's `remediation`-channel cap. It must NOT
322
+ * count reconcile-channel entries: reconcile re-executes on paths that spend
323
+ * no amend hop — ship's validate-fix loop re-enters through
324
+ * implement-scope-check → reconcile, and a resume replays entries — so an
325
+ * entry-count budget let the validate-fix loop spend the arm's only round
326
+ * before the arm ever ran, with a stop-note claiming a fix round that never
327
+ * happened (review 2026-08-31 I1; the fourth instance of the cap-must-read-a-
328
+ * channel-the-arm-writes lesson). Build/vet pass no cap (the runner's
329
+ * per-destination backward-jump budget on `reconcile-fix` is theirs, the
330
+ * plan-fix precedent); ship caps at ONE — the same single bounded hop its
331
+ * stop-on-fail identity concedes at the validate gate.
332
+ */
333
+ const reconcileGate = (opts?: { maxFixRounds?: number }): EdgeFn => {
334
+ const maxFixRounds = opts?.maxFixRounds ?? Number.POSITIVE_INFINITY;
335
+ const route: EdgeFn = defineRoute(
336
+ ["validate", "reconcile-fix", "stop"],
337
+ ({ state }) => {
338
+ const verdict = (state.named.reconcile?.at(-1)?.data as { verdict?: unknown } | undefined)?.verdict;
339
+ if (verdict === "pass") return "validate";
340
+ if (verdict !== "fail") {
341
+ setRouteNote(
342
+ route,
343
+ `reconcile verdict ${JSON.stringify(verdict ?? null)} matched no branch — terminated (no fallback)`,
344
+ );
345
+ return "stop";
346
+ }
347
+ const roundsSpent = state.named["reconcile-fix"]?.length ?? 0;
348
+ if (roundsSpent >= maxFixRounds) {
349
+ setRouteNote(
350
+ route,
351
+ `reconcile still fails after ${roundsSpent} amend round${roundsSpent === 1 ? "" : "s"} — repair the #### Reconciliation directives in the PLAN artifact by hand (the failure lives in the plan text, not the tree), then resume`,
352
+ );
353
+ return "stop";
354
+ }
355
+ return "reconcile-fix";
356
+ },
357
+ { readsData: false },
358
+ );
359
+ return route;
360
+ };
361
+
362
+ /**
363
+ * The `reconcile-fix` arm's dispatch — `/skill:amend` over the latest plan and
364
+ * the reconcile verdict. A PROMPT stage (owning its whole message, the
365
+ * VALIDATE_PLANS_PROMPT precedent) because amend's generic flag parser keys
366
+ * verdict inputs on the `-verdicts` name suffix, and reconcile's script stage
367
+ * publishes on its stage-key channel `reconcile` — a `reads: ["reconcile"]`
368
+ * skill stage would thread `--reconcile <path>`, which amend reads as a SECOND
369
+ * artifact flag and refuses. The explicit `--reconcile-verdicts` spelling
370
+ * parses as exactly one artifact (`--plans`) + one verdicts flag. The gate only
371
+ * dispatches this arm on a fail verdict, so both channel reads are present by
372
+ * construction; a torn state degrades to amend's own front-door refusal
373
+ * (exactly-one-artifact + at-least-one-verdicts), never a silent guess.
374
+ */
375
+ const RECONCILE_FIX_PROMPT: PromptFn = ({ state }) => {
376
+ const parts = ["/skill:amend"];
377
+ const plan = latestFsArtifact(state, "plans");
378
+ if (plan) parts.push("--plans", handleToString(plan.handle));
379
+ const verdict = state.named.reconcile?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
380
+ if (verdict) parts.push("--reconcile-verdicts", handleToString(verdict.handle));
381
+ return parts.join(" ");
382
+ };
383
+
384
+ /**
385
+ * The arm's outcome — the plans-bucket collector publishing on the arm's OWN
386
+ * `reconcile-fix` channel. Amend re-emits the plan IN PLACE (same path, its
387
+ * hard rule), so the `plans` channel's latest entry stays correct without a
388
+ * republish; what the channel choice buys is the round counter ONLY the arm
389
+ * increments, which `reconcileGate`'s cap reads (the validateGate/
390
+ * `remediation` pattern — see the gate doc for why counting reconcile
391
+ * executions instead let the validate-fix loop spend the budget).
392
+ */
393
+ const RECONCILE_FIX_OUTCOME = { ...rpivBucketOutcome("plans"), name: "reconcile-fix" };
394
+
287
395
  const vetWorkflow = defineWorkflow({
288
396
  name: "vet",
289
397
  description:
@@ -291,8 +399,10 @@ const vetWorkflow = defineWorkflow({
291
399
  start: "goal",
292
400
  stages: {
293
401
  // Capture the user's brief verbatim on its own `goal` channel, and snapshot
294
- // the run-start pre-existing-dirty paths (role "baseline"). Reuses build's
295
- // `captureGoal` verbatim — no new function — so the scope-check's
402
+ // the run-start pre-existing-dirty paths (role "baseline"). Uses
403
+ // `captureReviewScope` — build's capture minus the garbage-brief floor,
404
+ // because vet's input is a review-scope token ("staged", a hash) that is
405
+ // legitimately shorter than any brief the floor admits — so the scope-check's
296
406
  // `reads: ["plans", "goal"]` resolves a baseline to subtract and the goal md
297
407
  // rides the channel face. `goal` as start publishes the goal-md as
298
408
  // `artifacts[0]`; `code-review` is a plain `produces()` SKILL stage (skill
@@ -308,7 +418,7 @@ const vetWorkflow = defineWorkflow({
308
418
  // attaches its `outputSchema` and the `blockers_count` gate would read
309
419
  // UNVALIDATED data (NaN-route risk, not just a warning). Keeping it a skill
310
420
  // stage keeps `skill="code-review"` → contract schema attaches → validated.
311
- goal: produces.script({ run: captureGoal }),
421
+ goal: produces.script({ run: captureReviewScope }),
312
422
  "code-review": produces(),
313
423
  blueprint: produces(),
314
424
  // Dep-gated DAG variant: implement phases now
@@ -330,11 +440,16 @@ const vetWorkflow = defineWorkflow({
330
440
  "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
331
441
  // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
332
442
  // run-function as build (no vet twin): applies every `#### Reconciliation`
333
- // directive (write-restricted to test files) + re-runs every per-phase
334
- // `#### Automated Verification:` command, fail-soft. Pass ⇒ validate; fail/
335
- // missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no run-start goal
336
- // baseline. The `from` form suppresses the READS_DATA outputSchema lint.
443
+ // directive (write-restricted to the plan's declared write-set), fail-soft. Pass ⇒ validate;
444
+ // fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒ STOP.
445
+ // `reads: ["plans"]` only — no run-start goal baseline.
337
446
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
447
+ // Repair arm for the reconciliation gate: /skill:amend over the plan's
448
+ // directives from the reconcile verdict (a prompt stage — see
449
+ // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
450
+ // through reconcile to apply. Bounded by the runner's per-destination
451
+ // backward-jump budget (the plan-fix precedent).
452
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
338
453
  validate: produces(),
339
454
  commit: acts({ outcome: gitCommitOutcome }),
340
455
  },
@@ -360,10 +475,14 @@ const vetWorkflow = defineWorkflow({
360
475
  // either passes or reveals tracked drift. At most one quarantine hop per
361
476
  // gate entry; no new loop budget.
362
477
  "scope-quarantine": "implement-scope-check",
363
- // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target /
364
- // absent find / failed AV command) or a missing verdict ⇒ STOP (no fix arm —
365
- // a reconciliation failure is plan-vs-tree drift the agent reconciles manually).
366
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
478
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
479
+ // absent find / non-test target — all plan-TEXT defects) ⇒ the
480
+ // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
481
+ reconcile: reconcileGate(),
482
+ // Deterministic re-entry after the amend arm: reconcile re-parses the
483
+ // repaired directives and applies them (a plain string edge — the
484
+ // counted decision is the gate's reconcile-fix pick).
485
+ "reconcile-fix": "reconcile",
367
486
  // Backward edge: validate → code-review creates the review-fix loop —
368
487
  // UNCHANGED. The scope-check inserts before validate, so a failing scope
369
488
  // verdict halts before re-review, and a passing one flows into validate and
@@ -375,81 +494,111 @@ const vetWorkflow = defineWorkflow({
375
494
  });
376
495
 
377
496
  /**
378
- * Build's validate gate — classifies a failing verdict BEFORE routing to the
379
- * repair arm. `remediate`'s work-list is contractually the report's `pass:
380
- * false` risk rulings plus its structured `blockers:` entries; a `verdict:
381
- * fail` carrying NEITHER (run 2026-08-22_12-14-12-64eb: two whole-plan gate
382
- * failures recorded only in report prose) has no handle the arm may act on,
383
- * so routing it to `validate-fix` buys a provably futile lap — the arm
384
- * drift-escapes without an edit and the unchanged tree re-validates to the
385
- * identical verdict until the backward-jump guard halts the run. Such a fail
386
- * now STOPs at the gate with a route note naming why (the ship-gate
497
+ * The classifying validate gate — classifies a failing verdict BEFORE routing
498
+ * to the repair arm. `remediate`'s work-list is contractually the report's
499
+ * `pass: false` risk rulings plus its structured `blockers:` entries; a
500
+ * `verdict: fail` carrying NEITHER (run 2026-08-22_12-14-12-64eb: two
501
+ * whole-plan gate failures recorded only in report prose) has no handle the
502
+ * arm may act on, so routing it to `validate-fix` buys a provably futile lap
503
+ * — the arm drift-escapes without an edit and the unchanged tree re-validates
504
+ * to the identical verdict until the backward-jump guard halts the run. Such
505
+ * a fail STOPs at the gate with a route note naming why (the ship-gate
387
506
  * `setRouteNote` pattern; a noted decision stop records as a halt). The
388
507
  * repair-arm authority rule the slice gate learned the same way: a gate may
389
508
  * only loop into an arm whose authority covers the failure class.
390
509
  *
510
+ * A factory (not one shared EdgeFn) for the scopeFloorGate reason — each
511
+ * workflow's route-note symbol must never alias the other's. `maxFixRounds`
512
+ * caps the remediation hops a remediable fail may buy: each `validate-fix`
513
+ * pass publishes exactly one digest on the `remediation` channel, so the
514
+ * channel length IS the rounds already spent. Build passes no cap (the
515
+ * runner's backward-jump guard is its budget); ship caps at ONE — the single
516
+ * bounded hop its stop-on-fail identity concedes (run 7299: a docs-gap
517
+ * `fail` at the last stage stranded ~50 min of verified implementation).
518
+ *
391
519
  * Reads the `validation` channel (validate's contract-derived publish bucket
392
520
  * — a prompt stage owns its message and can't inherit its contract's output
393
521
  * schema, so the gate folds the channel, never the raw stage output). A
394
522
  * missing/unexpected verdict stays terminal STOP, exactly as the `match` it
395
523
  * replaces — un-anticipated data can never route INTO commit OR the repair arm.
396
524
  */
397
- const validateGate: EdgeFn = defineRoute(
398
- ["commit", "validate-fix", "stop"],
399
- ({ state }) => {
400
- const latest = state.named.validation?.at(-1);
401
- const data = latest?.data as { verdict?: unknown; blockers?: unknown } | undefined;
402
- if (data?.verdict === "pass") return "commit";
403
- if (data?.verdict !== "fail") {
404
- setRouteNote(
405
- validateGate,
406
- `validate verdict ${JSON.stringify(data?.verdict ?? null)} matched no branch — terminated (no fallback)`,
407
- );
408
- return "stop";
409
- }
410
- // Remediable handles: `pass: false` risk rulings (the arm's original
411
- // work-list) + structured `blockers:` entries (whole-plan gate failures
412
- // the validate skill attributes with a runnable command + in-delta file).
413
- const failedRulings = latest ? verdictRiskRulings(latest).filter((r) => !r.pass).length : 0;
414
- const blockers = Array.isArray(data.blockers) ? data.blockers.length : 0;
415
- if (failedRulings + blockers > 0) return "validate-fix";
416
- setRouteNote(
417
- validateGate,
418
- "validate failed with no remediable handle (no pass:false risk ruling, no blockers entry) — the remediation arm cannot act; fix manually or revise the plan",
419
- );
420
- return "stop";
421
- },
422
- { readsData: false },
423
- );
525
+ const validateGate = (opts?: { maxFixRounds?: number }): EdgeFn => {
526
+ const maxFixRounds = opts?.maxFixRounds ?? Number.POSITIVE_INFINITY;
527
+ const route: EdgeFn = defineRoute(
528
+ ["commit", "validate-fix", "stop"],
529
+ ({ state }) => {
530
+ const latest = state.named.validation?.at(-1);
531
+ const data = latest?.data as { verdict?: unknown; blockers?: unknown } | undefined;
532
+ if (data?.verdict === "pass") return "commit";
533
+ if (data?.verdict !== "fail") {
534
+ setRouteNote(
535
+ route,
536
+ `validate verdict ${JSON.stringify(data?.verdict ?? null)} matched no branch — terminated (no fallback)`,
537
+ );
538
+ return "stop";
539
+ }
540
+ // Remediable handles: `pass: false` risk rulings (the arm's original
541
+ // work-list) + structured `blockers:` entries (whole-plan gate failures
542
+ // the validate skill attributes with a runnable command + in-delta file).
543
+ const failedRulings = latest ? verdictRiskRulings(latest).filter((r) => !r.pass).length : 0;
544
+ const blockers = Array.isArray(data.blockers) ? data.blockers.length : 0;
545
+ if (failedRulings + blockers === 0) {
546
+ setRouteNote(
547
+ route,
548
+ "validate failed with no remediable handle (no pass:false risk ruling, no blockers entry) — the remediation arm cannot act; fix manually or revise the plan",
549
+ );
550
+ return "stop";
551
+ }
552
+ if ((state.named.remediation?.length ?? 0) >= maxFixRounds) {
553
+ setRouteNote(
554
+ route,
555
+ `validate still fails after ${maxFixRounds} remediation round${maxFixRounds === 1 ? "" : "s"} — fix manually, then resume to re-validate`,
556
+ );
557
+ return "stop";
558
+ }
559
+ return "validate-fix";
560
+ },
561
+ { readsData: false },
562
+ );
563
+ return route;
564
+ };
424
565
 
425
566
  /**
426
- * Build's repair-arm progress gate — the deterministic no-op backstop. The
567
+ * The repair-arm progress gate — the deterministic no-op backstop. The
427
568
  * `remediation` channel carries `remediationOutcome`'s `{ changed }` (a
428
569
  * git-only tree digest snapshotted around the `validate-fix` stage): an
429
570
  * unchanged tree makes the re-validate lap provably futile (validate's
430
571
  * verdict is a function of the tree), so it STOPs with a note instead of
431
572
  * burning a backward-jump on an identical verdict. Only an explicit
432
573
  * `changed: false` stops — a missing signal (non-repo, git failure, absent
433
- * channel) proceeds, the worktree-digest degrade doctrine.
574
+ * channel) proceeds, the worktree-digest degrade doctrine. A factory for the
575
+ * same note-symbol-aliasing reason as `validateGate`. NOTE the resume
576
+ * asymmetry this stop relies on: the runner never re-dispatches a halted
577
+ * SIDE-EFFECT gate stage — resume re-enters at this gate's onward target
578
+ * (implement-scope-check), so a hand-fix after this stop re-verifies
579
+ * end-to-end instead of replaying a remediation that would no-op again.
434
580
  */
435
- const validateFixGate: EdgeFn = defineRoute(
436
- ["implement-scope-check", "stop"],
437
- ({ state }) => {
438
- const data = state.named.remediation?.at(-1)?.data as { changed?: unknown } | undefined;
439
- if (data?.changed !== false) return "implement-scope-check";
440
- setRouteNote(
441
- validateFixGate,
442
- "remediation left the working tree unchanged — re-validating cannot change the verdict; fix manually or revise the plan",
443
- );
444
- return "stop";
445
- },
446
- { readsData: false },
447
- );
581
+ const validateFixGate = (): EdgeFn => {
582
+ const route: EdgeFn = defineRoute(
583
+ ["implement-scope-check", "stop"],
584
+ ({ state }) => {
585
+ const data = state.named.remediation?.at(-1)?.data as { changed?: unknown } | undefined;
586
+ if (data?.changed !== false) return "implement-scope-check";
587
+ setRouteNote(
588
+ route,
589
+ "remediation left the working tree unchanged — re-validating cannot change the verdict; fix manually or revise the plan",
590
+ );
591
+ return "stop";
592
+ },
593
+ { readsData: false },
594
+ );
595
+ return route;
596
+ };
448
597
 
449
598
  const buildWorkflow = defineWorkflow({
450
599
  name: "build",
451
600
  description:
452
- "Ship, sliced: capture the verbatim brief as a goal artifact (the north star the quality gates' completeness/correctness dimensions and validate anchor against) → research the brief → decompose it into vertical slices → two-phase slice gate (a deterministic floor — dependency-cycle freedom + brief-coverage conservation so a slice-fix can't pass by dropping scope — then one LLM design-readiness judgment that each slice is chewable by a single design pass) with a slice-fix loop → design each slice in parallel → one consolidated developer checkpoint (accept or adjust the proposed interfaces/data types, adjustments applied surgically and cascaded to dependents) → synthesize hierarchically (per-cluster sub-plans → one merged plan) → tier-scaled quality-panel gate (a one-slice, <=2-phase run grades correctness+completeness only; larger or previously-failing runs grade the full completeness/correctness/actionability/pattern-following/architecture-fit roster) where a dimension's first blocking verdict gets one confirming second judgment before it buys a plan-fix round → elaborate code per phase in parallel → splice it into the plan → re-grade the code-bearing plan (same tier + confirm contract) → implement → implement-scope-check → reconcile → validate → commit. Research-led; three automated gates plus one human design checkpoint, before design, before code, and after the splice.",
601
+ "Ship, sliced: capture the verbatim brief as a goal artifact (the north star the quality gates' completeness/correctness dimensions and validate anchor against) → research the brief → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before any plan so it cannot inherit the plan's scope; the completeness gates anchor on it and validate executes its evidence commands) → decompose it into vertical slices → two-phase slice gate (a deterministic floor — dependency-cycle freedom + brief-coverage conservation so a slice-fix can't pass by dropping scope — then one LLM design-readiness judgment that each slice is chewable by a single design pass) with a slice-fix loop → design each slice in parallel → one consolidated developer checkpoint (accept or adjust the proposed interfaces/data types, adjustments applied surgically and cascaded to dependents) → synthesize hierarchically (per-cluster sub-plans → one merged plan) → tier-scaled quality-panel gate (a one-slice, <=2-phase run grades correctness+completeness only; larger or previously-failing runs grade the full completeness/correctness/actionability/pattern-following/architecture-fit roster) where a dimension's fresh HIGH-severity, risk-ruling, or regressed-pass blocking verdict gets one confirming second judgment before it buys a plan-fix round (a first-time medium finding routes straight to the surgical fix) → elaborate code per phase in parallel → splice it into the plan → re-grade the code-bearing plan (same tier + confirm contract) → implement → implement-scope-check → reconcile → validate → commit. Research-led; three automated gates plus one human design checkpoint, before design, before code, and after the splice.",
453
602
  start: "goal",
454
603
  stages: {
455
604
  // The user's brief, verbatim, on its own channel — the judgment seams
@@ -462,7 +611,20 @@ const buildWorkflow = defineWorkflow({
462
611
  // gate's architecture-fit dimension its --context. Prompt-dispatched so it
463
612
  // still receives the raw brief now that `goal` holds the start slot.
464
613
  research: produces({ prompt: RESEARCH_BRIEF_PROMPT }),
465
- slice: produces(),
614
+ // The goal-derived acceptance inventory (see ship's twin comment): the
615
+ // executable standard of completion, frozen before slicing/planning so
616
+ // it cannot inherit their scope. Threaded to the plan/code gates'
617
+ // completeness units (--acceptance) and to validate, which executes the
618
+ // evidence commands. Deliberately NOT fed to slice/design/synthesize —
619
+ // the bounded-context doctrine that keeps `goal` out of the generative
620
+ // stages applies to its derived standard too.
621
+ acceptance: produces({ reads: ["goal", "research"] }),
622
+ // `reads: ["research"]` (not the rolling primary): `acceptance` now sits
623
+ // between research and slice, so the rolling primary at this stage is
624
+ // the acceptance doc — the explicit read restores the research artifact
625
+ // as slice's grounding input (dispatched as `--research <path>`; the
626
+ // slice skill accepts the flag form of its fresh input).
627
+ slice: produces({ reads: ["research"] }),
466
628
  // Deterministic floor (no LLM): dependency-cycle freedom + brief-coverage conservation.
467
629
  "slice-check": produces.script({ reads: ["slices"], run: sliceStructureCheck }),
468
630
  // One LLM design-readiness judgment; verdicts on their own channel.
@@ -525,7 +687,7 @@ const buildWorkflow = defineWorkflow({
525
687
  outcome: planVerdictOutcome,
526
688
  // `research` is read so the architecture-fit unit can thread it as
527
689
  // --context; `goal` so completeness/correctness anchor on the brief.
528
- reads: ["plans", "research", "goal"],
690
+ reads: ["plans", "research", "goal", "acceptance"],
529
691
  }),
530
692
  // Stamp the duty demotion onto the graded verdicts as legible on-disk data
531
693
  // (a `risk_duty_demotions` array written in place onto each demoted
@@ -544,7 +706,7 @@ const buildWorkflow = defineWorkflow({
544
706
  skill: "grade",
545
707
  loop: PLAN_CONFIRM_FANOUT,
546
708
  outcome: planVerdictOutcome,
547
- reads: ["plans", "research", "goal"],
709
+ reads: ["plans", "research", "goal", "acceptance"],
548
710
  }),
549
711
  "plan-fix": produces({
550
712
  skill: "amend",
@@ -594,7 +756,7 @@ const buildWorkflow = defineWorkflow({
594
756
  outcome: codeVerdictOutcome,
595
757
  // `research` is read so the architecture-fit unit can thread it as
596
758
  // --context; `goal` so completeness/correctness anchor on the brief.
597
- reads: ["plans", "research", "goal"],
759
+ reads: ["plans", "research", "goal", "acceptance"],
598
760
  }),
599
761
  // The code-gate twin of `plan-demote`: stamp the duty demotion onto the
600
762
  // code-graded verdicts (re-grading `plans` on `code-verdicts`) one hop
@@ -615,7 +777,7 @@ const buildWorkflow = defineWorkflow({
615
777
  skill: "grade",
616
778
  loop: CODE_CONFIRM_FANOUT,
617
779
  outcome: codeVerdictOutcome,
618
- reads: ["plans", "research", "goal"],
780
+ reads: ["plans", "research", "goal", "acceptance"],
619
781
  }),
620
782
  "code-fix": produces({
621
783
  skill: "amend",
@@ -647,15 +809,20 @@ const buildWorkflow = defineWorkflow({
647
809
  // and publish a manifest, then re-enter the floor — see scopeQuarantine.
648
810
  "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
649
811
  // Deterministic post-implement reconciliation (no LLM): applies every
650
- // `#### Reconciliation` directive (find→replace, write-restricted to test
651
- // files) and re-runs every per-phase `#### Automated Verification:`
652
- // command, fail-soft — a coherence backstop the parallel implement lane
653
- // needs (a phase's correct change can invalidate a sibling's test, and the
812
+ // `#### Reconciliation` directive (find→replace, write-restricted to the
813
+ // plan's declared write-set), fail-soft — a coherence backstop the parallel
814
+ // implement lane needs (a phase's correct change can invalidate a sibling's test, and the
654
815
  // combined tree can break in ways no single phase's checks surface). Pass ⇒
655
- // validate; fail/missing ⇒ STOP (no fallback). `reads: ["plans"]` only — no
656
- // run-start goal baseline (the scope floor already proved the write-set). The
657
- // `from` form suppresses the READS_DATA outputSchema lint.
816
+ // validate; fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒
817
+ // STOP. `reads: ["plans"]` only — no run-start goal baseline (the scope
818
+ // floor already proved the write-set).
658
819
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
820
+ // Repair arm for the reconciliation gate: /skill:amend over the plan's
821
+ // directives from the reconcile verdict (a prompt stage — see
822
+ // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
823
+ // through reconcile to apply. Bounded by the runner's per-destination
824
+ // backward-jump budget (the plan-fix precedent).
825
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
659
826
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
660
827
  // Repair arm the validate gate dispatches on a remediable `verdict: "fail"`.
661
828
  // `acts()` (not `produces()`) because remediate is `side-effect`/`code-mutation`
@@ -672,9 +839,12 @@ const buildWorkflow = defineWorkflow({
672
839
  },
673
840
  edges: {
674
841
  goal: "research",
675
- // Research's artifact is auto-fed to slice as its argument (the slice skill's
676
- // "Fresh" input is a research path).
677
- research: "slice",
842
+ // The acceptance inventory derives between research (which grounds its
843
+ // evidence commands) and slice (which must never see it — bounded
844
+ // context). Slice's research input rides its explicit `reads` now that
845
+ // the rolling primary here is the acceptance doc.
846
+ research: "acceptance",
847
+ acceptance: "slice",
678
848
  slice: "slice-check",
679
849
  // Skip the design-readiness re-grade when the gate is already satisfied — after
680
850
  // a `slice-fix` that only cleared the deterministic structure floor (the common
@@ -734,8 +904,11 @@ const buildWorkflow = defineWorkflow({
734
904
  // readers. `plan-grade` is now a simple always-hop edge to `plan-demote`;
735
905
  // the route body below is the verbatim logic that used to live here.
736
906
  "plan-grade": "plan-demote",
737
- // Pass ⇒ code. A dimension's FIRST blocking verdict ⇒ plan-confirm (one
738
- // independent second judgment — see `confirmDue`); a confirmed blocker, or
907
+ // Pass ⇒ code. A dimension's fresh confirm-worthy blocking verdict — a
908
+ // HIGH-severity or risk-ruling blocker, or a regressed carried pass — ⇒
909
+ // plan-confirm (one independent second judgment — see `confirmDue`; a
910
+ // first-time medium finding skips the confirm and buys the surgical fix
911
+ // directly); a confirmed blocker, or
739
912
  // a failure with no dimension blocking (the citation floor alone is red) ⇒
740
913
  // plan-fix, looping back THROUGH the citation floor so the amended plan
741
914
  // re-verifies. Route logic unchanged — merely shifted one hop later so the
@@ -777,7 +950,7 @@ const buildWorkflow = defineWorkflow({
777
950
  // duty-demotion write-back lands before this fold. `code-grade` is now a
778
951
  // simple always-hop edge to `code-demote`; the route body below is verbatim.
779
952
  "code-grade": "code-demote",
780
- // Pass ⇒ implement. A first blocking verdict ⇒ code-confirm (the plan
953
+ // Pass ⇒ implement. A fresh confirm-worthy blocking verdict ⇒ code-confirm (the plan
781
954
  // gate's confirm contract, on the code-verdicts channel); a confirmed
782
955
  // blocker or cite-floor-only failure ⇒ code-fix. Routes to `code-fix`, NOT
783
956
  // back to `code`: the gate fails on plan-text defects (edit anchors, line
@@ -818,12 +991,16 @@ const buildWorkflow = defineWorkflow({
818
991
  // reveals tracked drift. At most one quarantine hop per gate entry; no new
819
992
  // loop budget.
820
993
  "scope-quarantine": "implement-scope-check",
821
- // Reconciliation gate. Pass ⇒ validate; a `fail` (non-test directive target
822
- // / absent find / failed AV command) or a missing verdict ⇒ STOP (no fix
823
- // arm — a reconciliation failure is plan-vs-tree drift the agent reconciles
824
- // manually). Safe by construction: the sole path onward is an explicit
825
- // `verdict: "pass"`. Sourced from the reconcile channel via the `from` form.
826
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
994
+ // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
995
+ // absent find / non-test target — all plan-TEXT defects) ⇒ the
996
+ // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
997
+ // Safe by construction: the sole path onward to validate is an explicit
998
+ // `verdict: "pass"`.
999
+ reconcile: reconcileGate(),
1000
+ // Deterministic re-entry after the amend arm: reconcile re-parses the
1001
+ // repaired directives and applies them (a plain string edge — the
1002
+ // counted decision is the gate's reconcile-fix pick).
1003
+ "reconcile-fix": "reconcile",
827
1004
  // Gate commit on validate's own verdict — see `validateGate`. `pass` ⇒
828
1005
  // commit; a `fail` WITH remediable handles (a `pass: false` risk ruling or a
829
1006
  // structured `blockers:` entry) ⇒ validate-fix, which re-enters at
@@ -833,15 +1010,16 @@ const buildWorkflow = defineWorkflow({
833
1010
  // it re-validated an unchanged tree until the guard halted the run).
834
1011
  // A missing/unexpected verdict stays terminal STOP, so un-anticipated data
835
1012
  // can never route INTO commit OR the repair arm. Safe by construction: the
836
- // sole path to commit is an explicit pass.
837
- validate: validateGate,
1013
+ // sole path to commit is an explicit pass. No fix-round cap — the runner's
1014
+ // backward-jump guard is build's remediation budget.
1015
+ validate: validateGate(),
838
1016
  // Re-entry after the repair arm: remediate's code-mutation is followed by a
839
1017
  // fresh scope check → reconcile → validate pass, so a fix is re-verified
840
1018
  // end-to-end before the gate re-folds. Now a decision edge (`validateFixGate`
841
1019
  // folds the `remediation` channel's deterministic digest verdict): a
842
1020
  // remediation that changed nothing STOPs here — progress is verified, not
843
1021
  // assumed — while a real fix proceeds into the loop body.
844
- "validate-fix": validateFixGate,
1022
+ "validate-fix": validateFixGate(),
845
1023
  commit: "stop",
846
1024
  },
847
1025
  });
@@ -919,44 +1097,68 @@ const shipGradeGate: EdgeFn = defineRoute(
919
1097
 
920
1098
  /**
921
1099
  * ship — the lightweight `/wf` preset: the no-ceremony path for small-to-
922
- * midsize tasks whose approach is obvious. goal → research → plan →
923
- * plan-cite-check → grade → implement → implement-scope-check → reconcile →
924
- * validate → commit, stop-on-fail at every gate with NO backward edges: a red
925
- * gate terminates the run (the agent hand-repairs and re-invokes) instead of
926
- * looping a fix cycle. Research stays front-loaded — a ≤2-subagent grounding
927
- * pass (SHIP_RESEARCH_PROMPT, not a full `/skill:research` run) — because the
928
- * single PRE-implement grade's architecture-fit dimension needs its artifact as
929
- * `--context`. That grade is tier-independent: the bespoke SHIP_DIMENSION_FANOUT
930
- * always grades the full correctness/completeness/architecture-fit roster (no
931
- * gateTier/gateRoster light-tier drop), and SHIP's gate folds risk flags without
932
- * re-folding the citation floor (that floor folds at its own edge).
1100
+ * midsize tasks whose approach is obvious. goal → research → acceptance →
1101
+ * plan → plan-cite-check → grade → implement → implement-scope-check →
1102
+ * reconcile → validate → (validate-fix, once) | commit, stop-on-fail at every gate: a red
1103
+ * gate halts the run (the agent hand-repairs and RESUMES — `/wf @<runId>`
1104
+ * re-runs the halted gate against the repaired tree, reusing every upstream
1105
+ * artifact) instead of looping a fix cycle. The ONE concession to that
1106
+ * identity is validate's single bounded remediation hop (run 7299: a
1107
+ * remediable docs-gap `fail` at the last stage stranded ~50 min of verified
1108
+ * implementation behind a terminal stop). Research stays front-loaded — a
1109
+ * brief-sized grounding pass (SHIP_RESEARCH_PROMPT, not a full
1110
+ * `/skill:research` run: at most one verify-only dispatch when the brief names
1111
+ * root cause, files, or fix — none when its anchors are plain file paths; at
1112
+ * most two targeted dispatches otherwise) — because the single PRE-implement
1113
+ * grade's architecture-fit dimension needs its artifact as `--context`. That
1114
+ * grade is tier-independent: the bespoke SHIP_DIMENSION_FANOUT always grades
1115
+ * the full correctness/completeness/architecture-fit roster (no
1116
+ * gateTier/gateRoster light-tier drop), and SHIP's gate folds risk flags
1117
+ * without re-folding the citation floor (that floor folds at its own edge).
933
1118
  */
934
1119
  const shipWorkflow = defineWorkflow({
935
1120
  name: "ship",
936
1121
  description:
937
- "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 (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → 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.",
1122
+ "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with a brief-sized research pass (none or one verify-only codebase-analyzer dispatch when the brief names root cause, files, or fix; at most two targeted dispatches otherwise — no /skill:research) → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before planning; quick-plan records a per-item disposition, the completeness gate anchors on it, validate executes its evidence commands) → one lightweight quick-plan pass → deterministic citation floor (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate halts the run on fail (hand-repair, then resume with /wf @<runId> to re-run the gate) — except a reconcile fail (a plan-text directive defect), which buys ONE bounded amend hop over the plan's directives, and a validate fail carrying structured remediable handles, which buys ONE bounded remediation hop before halting.",
938
1123
  start: "goal",
939
1124
  stages: {
940
1125
  // build's verbatim goal capture — the brief on its own channel, plus the
941
1126
  // run-start pre-existing-dirty snapshot the scope-check subtracts.
942
1127
  goal: produces.script({ run: captureGoal }),
943
1128
  // The lean grounding pass — SHIP_RESEARCH_PROMPT (a custom prompt, NOT
944
- // /skill:research): ≤2 sequential codebase-analyzer subagents, then one
945
- // grounding doc under .rpiv/artifacts/research/. A prompt stage, so the
946
- // stage name `research` drives outcome derivation (research contract →
947
- // `research` bucket) exactly as build's RESEARCH_BRIEF_PROMPT stage does.
1129
+ // /skill:research), sized to the brief's pre-chewedness: at most one
1130
+ // verify-only codebase-analyzer dispatch when the brief names root
1131
+ // cause, files, or fix (none when its anchors are plain file paths);
1132
+ // at most two targeted dispatches when it names only a symptom; then
1133
+ // one grounding doc under .rpiv/artifacts/research/. A prompt stage,
1134
+ // so the stage name `research` drives outcome derivation (research
1135
+ // contract → `research` bucket) exactly as build's
1136
+ // RESEARCH_BRIEF_PROMPT stage does.
948
1137
  research: produces({ prompt: SHIP_RESEARCH_PROMPT }),
1138
+ // The goal-derived acceptance inventory — the executable standard of
1139
+ // completion, authored BEFORE any plan exists so it cannot inherit the
1140
+ // plan's scope. Items enumerate the verbatim brief's asks (research
1141
+ // grounds only the evidence commands, never membership — the skill's
1142
+ // hard rule, since research routinely narrows the brief). Downstream:
1143
+ // quick-plan addresses-or-defers each item, the grade panel's
1144
+ // completeness unit anchors on the inventory (--acceptance), and
1145
+ // validate EXECUTES the evidence commands against the finished tree.
1146
+ // Outcome derives from the acceptance contract (artifactKind:
1147
+ // acceptance → `acceptance` bucket).
1148
+ acceptance: produces({ reads: ["goal", "research"] }),
949
1149
  // The lightweight planner — quick-plan: ONE targeted
950
1150
  // codebase-pattern-finder dispatch, one `status: ready` plan, no risks
951
1151
  // frontmatter, no multi-slice decomposition. Derives its `plans` outcome
952
- // from the quick-plan contract (artifactKind: plan). Reads BOTH channels
953
- // explicitly (`--research <path> --goal <path>`) — without `goal` the
954
- // stage falls to the rolling primary and the planner sees only the
955
- // research doc, whose grounding routinely narrows the brief; the grade
956
- // panel's completeness dimension anchors on the VERBATIM goal, so the
957
- // planner must anchor on the same artifact to defer narrowed-out asks
958
- // explicitly instead of silently inheriting the drop.
959
- plan: produces({ skill: "quick-plan", reads: ["research", "goal"] }),
1152
+ // from the quick-plan contract (artifactKind: plan). Reads all three
1153
+ // channels explicitly (`--research <path> --goal <path>
1154
+ // --acceptance <path>`) — without `goal` the stage falls to the rolling
1155
+ // primary and the planner sees only the research doc, whose grounding
1156
+ // routinely narrows the brief; the grade panel's completeness dimension
1157
+ // anchors on the VERBATIM goal and the acceptance inventory, so the
1158
+ // planner must anchor on the same artifacts and record a per-item
1159
+ // disposition (implemented or deferred) instead of silently inheriting
1160
+ // the drop.
1161
+ plan: produces({ skill: "quick-plan", reads: ["research", "goal", "acceptance"] }),
960
1162
  // Deterministic citation floor BEFORE the LLM gate — build's verifier
961
1163
  // verbatim. Only a `files:` coverage gap fails structurally and STOPs the
962
1164
  // run; every citation-resolution finding (unresolved path, ambiguity,
@@ -967,12 +1169,14 @@ const shipWorkflow = defineWorkflow({
967
1169
  // (SHIP_DIMENSION_FANOUT — tier-independent, no confirm/snapshot arms);
968
1170
  // verdicts on the `ship-verdicts` channel. `research` is read so the
969
1171
  // architecture-fit unit threads it as --context; `goal` so
970
- // completeness/correctness anchor on the verbatim brief.
1172
+ // completeness/correctness anchor on the verbatim brief; `acceptance` so
1173
+ // the completeness unit checks the plan's per-item dispositions against
1174
+ // the frozen inventory (--acceptance).
971
1175
  grade: produces({
972
1176
  skill: "grade",
973
1177
  loop: SHIP_DIMENSION_FANOUT,
974
1178
  outcome: shipVerdictOutcome,
975
- reads: ["plans", "research", "goal"],
1179
+ reads: ["plans", "research", "goal", "acceptance"],
976
1180
  }),
977
1181
  // Dep-gated DAG implement — build's lane verbatim.
978
1182
  implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
@@ -981,14 +1185,28 @@ const shipWorkflow = defineWorkflow({
981
1185
  // declared write-set is the whole contract). Pass ⇒ reconcile; fail ⇒ STOP.
982
1186
  "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
983
1187
  // Deterministic post-implement reconciliation — build's run-function
984
- // verbatim. Pass ⇒ validate; fail/missing ⇒ STOP (no fallback).
1188
+ // verbatim. Pass ⇒ validate; fail ⇒ ONE bounded reconcile-fix hop
1189
+ // (maxFixRounds: 1 — the validate-gate concession's twin); missing ⇒ STOP.
985
1190
  reconcile: produces.script({ reads: ["plans"], run: reconcile }),
1191
+ // Repair arm — build's prompt stage verbatim; ship's reconcile gate
1192
+ // dispatches it at most ONCE. Kept despite the stop-on-fail identity for
1193
+ // the same reason as validate-fix: a reconcile fail is a plan-TEXT defect
1194
+ // a hand-repair of the TREE can never clear, so the terminal stop was
1195
+ // unresumable without hand-editing the plan artifact.
1196
+ "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
986
1197
  validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1198
+ // Repair arm — build's stage verbatim; ship's validate gate dispatches it
1199
+ // at most ONCE (maxFixRounds: 1). Kept because the terminal gate is where
1200
+ // a red verdict strands the most verified work over the least defect: the
1201
+ // arm acts only on the report's structured handles, and its own progress
1202
+ // gate stops a no-op remediation instead of re-validating an unchanged tree.
1203
+ "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"], outcome: remediationOutcome }),
987
1204
  commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
988
1205
  },
989
1206
  edges: {
990
1207
  goal: "research",
991
- research: "plan",
1208
+ research: "acceptance",
1209
+ acceptance: "plan",
992
1210
  plan: "plan-cite-check",
993
1211
  // Both gates are the named EdgeFns above — they attach a stop-reason
994
1212
  // ROUTE_NOTE the recap surfaces; routing semantics are unchanged.
@@ -1004,17 +1222,30 @@ const shipWorkflow = defineWorkflow({
1004
1222
  // the stage's own channel via the `from` form (suppresses the READS_DATA
1005
1223
  // outputSchema lint).
1006
1224
  "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
1007
- // Reconciliation gate — build's route verbatim: pass ⇒ validate;
1008
- // fail/missing ⇒ STOP (plan-vs-tree drift the agent reconciles manually).
1009
- reconcile: match("verdict", { validate: "pass" }, { from: "reconcile" }),
1010
- // Validate gate — build's validate edge (match verdict pass⇒commit,
1011
- // from "validation") minus the `validate-fix` arm: `pass` ⇒ commit; `fail`
1012
- // or missing ⇒ STOP — deliberately NO validate-fix/remediate repair arm
1013
- // (the lightweight preset does not loop). NOT vet's tail: vet's validate
1014
- // routes to code-review, which gates back to blueprint (a bounded backward
1015
- // loop, not stop-on-fail). Sourced from validate's published verdict
1016
- // channel (`from: "validation"`).
1017
- validate: match("verdict", { commit: "pass" }, { from: "validation" }),
1225
+ // Reconciliation gate — build's route, capped at ONE amend round (the
1226
+ // reconcile channel's entry count IS the rounds spent): pass ⇒ validate;
1227
+ // first fail ⇒ reconcile-fix; a fail after the spent round, or a missing
1228
+ // verdict ⇒ STOP with a route note naming the plan artifact as the
1229
+ // repair site.
1230
+ reconcile: reconcileGate({ maxFixRounds: 1 }),
1231
+ // Re-entry after the amend arm — reconcile re-parses and applies the
1232
+ // repaired directives; the spent round now stops any remaining fail.
1233
+ "reconcile-fix": "reconcile",
1234
+ // Validate gate — build's classifying gate, capped at ONE remediation
1235
+ // round: `pass` ⇒ commit; a `fail` WITH structured remediable handles and
1236
+ // no remediation spent ⇒ validate-fix; every other fail (prose-only, or
1237
+ // the one round already used) ⇒ STOP with a route note. The cap is what
1238
+ // keeps ship's stop-on-fail identity: the arm is a single bounded hop,
1239
+ // not a loop — the runner's `remediation`-channel length enforces it
1240
+ // deterministically. NOT vet's tail: vet's validate routes to
1241
+ // code-review, which gates back to blueprint (a bounded backward loop).
1242
+ validate: validateGate({ maxFixRounds: 1 }),
1243
+ // Re-entry after the repair arm — build's edge: a remediation that
1244
+ // changed nothing STOPs (progress is verified, not assumed); a real fix
1245
+ // re-enters at implement-scope-check so it is re-verified end-to-end
1246
+ // (scope floor → reconcile → validate) before the gate re-folds — where
1247
+ // the spent round now stops any remaining fail.
1248
+ "validate-fix": validateFixGate(),
1018
1249
  commit: "stop",
1019
1250
  },
1020
1251
  });