@juicesharp/rpiv-pi 2.8.0 → 2.10.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 (47) hide show
  1. package/extensions/rpiv-core/agent-enablement.ts +164 -0
  2. package/extensions/rpiv-core/agents.ts +98 -12
  3. package/extensions/rpiv-core/artifact-collector.ts +30 -7
  4. package/extensions/rpiv-core/built-in-workflows.ts +370 -96
  5. package/extensions/rpiv-core/built-ins/citations.ts +9 -0
  6. package/extensions/rpiv-core/built-ins/design.ts +64 -0
  7. package/extensions/rpiv-core/built-ins/elaboration.ts +53 -0
  8. package/extensions/rpiv-core/built-ins/gates.ts +282 -12
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +54 -26
  10. package/extensions/rpiv-core/built-ins/index.ts +20 -1
  11. package/extensions/rpiv-core/built-ins/markdown-fence.ts +26 -1
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +8 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +9 -2
  14. package/extensions/rpiv-core/built-ins/reconcile-directives.d.mts +29 -0
  15. package/extensions/rpiv-core/built-ins/reconcile-directives.mjs +338 -0
  16. package/extensions/rpiv-core/built-ins/reconcile.ts +88 -130
  17. package/extensions/rpiv-core/built-ins/remediation.ts +60 -7
  18. package/extensions/rpiv-core/built-ins/scope-checks.ts +74 -11
  19. package/extensions/rpiv-core/built-ins/shared.ts +5 -3
  20. package/extensions/rpiv-core/built-ins/slice-checks.ts +164 -28
  21. package/extensions/rpiv-core/built-ins/slices.ts +44 -13
  22. package/extensions/rpiv-core/built-ins/verdict-collector.ts +207 -0
  23. package/extensions/rpiv-core/built-ins/verdict-outcome.ts +36 -0
  24. package/extensions/rpiv-core/frontmatter.ts +22 -0
  25. package/extensions/rpiv-core/lane-list.ts +10 -1
  26. package/extensions/rpiv-core/lane-progress.ts +1 -1
  27. package/extensions/rpiv-core/lane-usage.ts +1 -1
  28. package/extensions/rpiv-core/models-config.ts +86 -6
  29. package/extensions/rpiv-core/models-picker.ts +4 -3
  30. package/extensions/rpiv-core/package-checks.ts +13 -0
  31. package/extensions/rpiv-core/run-lane-registry.ts +1 -2
  32. package/extensions/rpiv-core/sdk-workflow-host.ts +20 -4
  33. package/extensions/rpiv-core/session-hooks.ts +1 -1
  34. package/extensions/rpiv-core/workflow-execution-host.ts +3 -2
  35. package/package.json +4 -3
  36. package/skills/_shared/reconcile-lint.mjs +125 -0
  37. package/skills/_shared/stitch-elaborations.mjs +282 -21
  38. package/skills/acceptance/SKILL.md +3 -2
  39. package/skills/amend/SKILL.md +5 -5
  40. package/skills/design-slice/SKILL.md +5 -0
  41. package/skills/elaborate/SKILL.md +13 -6
  42. package/skills/grade/SKILL.md +15 -12
  43. package/skills/implement/SKILL.md +17 -2
  44. package/skills/research/SKILL.md +1 -1
  45. package/skills/slice/SKILL.md +2 -2
  46. package/skills/synthesize/SKILL.md +1 -1
  47. package/skills/validate/SKILL.md +14 -0
@@ -2,13 +2,7 @@
2
2
  * The grade panels: the shared tiered panel factory, its build-lane instances,
3
3
  * and ship's bespoke tier-independent panel and verdict channel.
4
4
  */
5
- import {
6
- directoryPathCollector,
7
- fanout,
8
- handleToString,
9
- jsonBodyParser,
10
- type RunView,
11
- } from "@juicesharp/rpiv-workflow/registration";
5
+ import { fanout, handleToString, type RunView } from "@juicesharp/rpiv-workflow/registration";
12
6
  import {
13
7
  dimensionsToRegrade,
14
8
  freshVerdicts,
@@ -17,12 +11,14 @@ import {
17
11
  gateTier,
18
12
  latestVerdictPerDimension,
19
13
  PLAN_DIMENSIONS,
14
+ panelProgress,
20
15
  planAuthoredRisks,
21
16
  SHIP_DIMENSIONS,
22
17
  SLICE_DIMENSIONS,
23
18
  } from "./gates.js";
24
19
  import { isSurgicalFix, priorArtifact } from "./priors.js";
25
- import { latestFsArtifact } from "./shared.js";
20
+ import { haltPreflight, latestFsArtifact } from "./shared.js";
21
+ import { verdictOutcome } from "./verdict-outcome.js";
26
22
 
27
23
  /**
28
24
  * The dimension-scoped artifact flags every panel body composes — ONE
@@ -54,13 +50,24 @@ const dimensionArtifactFlags = (state: RunView): { contextFlag: string; goalFlag
54
50
  * duplicates (the single most expensive part of the most expensive dimension)
55
51
  * and spend its spot-check budget on claim-vs-code semantics — the one thing
56
52
  * the floor cannot judge. A findings-bearing verdict additionally carries the
57
- * advisory leads the grader folds into its sample. Empty when the channel has
58
- * no fs verdict (a workflow without the floor simply emits no flag).
53
+ * advisory leads the grader folds into its sample. Required, never degraded:
54
+ * a panel configured over a cite channel whose channel carries no fs verdict
55
+ * throws the halt preflight — the built-in graphs run the floor before every
56
+ * panel dispatch, so an absent verdict is an integrity break. A panel with no
57
+ * `citeChannel` (the slice gate, a user workflow without a floor) composes no
58
+ * flag.
59
59
  */
60
60
  const citeCheckFlag = (state: RunView, citeChannel: string | undefined): string => {
61
61
  if (citeChannel === undefined) return "";
62
62
  const doc = latestFsArtifact(state, citeChannel);
63
- return doc?.handle.kind === "fs" ? ` --cite-check ${handleToString(doc.handle)}` : "";
63
+ if (doc?.handle.kind !== "fs") {
64
+ throw haltPreflight(
65
+ "grade",
66
+ "grade: no citation-floor verdict to thread as --cite-check",
67
+ `grade: the '${citeChannel}' channel carries no fs verdict — the deterministic citation floor must run before the correctness unit dispatches (a panel configured over a cite channel requires it)`,
68
+ );
69
+ }
70
+ return ` --cite-check ${handleToString(doc.handle)}`;
64
71
  };
65
72
 
66
73
  /**
@@ -90,14 +97,11 @@ const citeCheckFlag = (state: RunView, citeChannel: string | undefined): string
90
97
  * (and the slice gate's `design-readiness`, which never grades fit or
91
98
  * goal-completeness) gets the bare flags.
92
99
  *
93
- * A CONFIRM panel (`confirm: true`) additionally threads each still-blocking
94
- * dimension's latest verdict in as `--prior`: the confirming grader must
95
- * adjudicate the prior round's findings — uphold or refute each with cited
96
- * evidence — instead of silently out-voting them (a blind second opinion once
97
- * rationalized past a checkable fact and its pass overwrote a correct fail at
98
- * the latest-per-dimension fold). Only PENDING dimensions get the flag: in the
99
- * degenerate full-roster fallback a carried passing verdict has nothing to
100
- * adjudicate, and a first grade has no prior at all.
100
+ * `--prior` threads a dimension's latest fresh verdict when that dimension is
101
+ * still pending (a confirm or re-grade of a blocking prior — the grader must
102
+ * adjudicate the prior findings, not out-vote them) and always on correctness
103
+ * (its re-grades scope to the prior). A carried passing prior on any other
104
+ * dimension is not re-adjudicated. Round 1 emits no flag.
101
105
  *
102
106
  * Every panel wires `haltWhenAllFailed: true`: a generation in which EVERY
103
107
  * dispatched dimension unit failed is a dead panel — nothing was collected, so
@@ -119,6 +123,7 @@ const gradePanelFanout = (
119
123
  unit: { by: "dimension-list", pattern: "dimensions" },
120
124
  max: dimensions.length,
121
125
  haltWhenAllFailed: true,
126
+ retryHaltedUnits: 1,
122
127
  units: ({ state, cwd }) => {
123
128
  const doc = latestFsArtifact(state, channel);
124
129
  if (doc?.handle.kind !== "fs") return [];
@@ -150,7 +155,7 @@ const gradePanelFanout = (
150
155
  isSurgicalFix(state, priorChannel, cwd, target, latest, pending, risks);
151
156
  const priorPresent = priorChannel !== undefined && priorArtifact(state, priorChannel) !== undefined;
152
157
  const priorFlag = (d: string): string => {
153
- if (!confirm || !pending.includes(d)) return "";
158
+ if (d !== "correctness" && !pending.includes(d)) return "";
154
159
  const handle = latest.get(d)?.artifacts.find((a) => a.handle.kind === "fs")?.handle;
155
160
  return handle ? ` --prior ${handleToString(handle)}` : "";
156
161
  };
@@ -196,6 +201,22 @@ const CODE_CONFIRM_FANOUT = gradePanelFanout("plans", PLAN_DIMENSIONS, "code-ver
196
201
  citeChannel: "code-cite-check",
197
202
  });
198
203
 
204
+ // The three build lanes' whole-lap progress hooks — one instance per lane,
205
+ // declared on every stage the guard can re-enter (grade / fix-or-confirm /
206
+ // snapshot), beside the fanout twins that grade the same channels. The
207
+ // plan/code lanes amend the plan in place, so their rounds are cut at
208
+ // snapshot rows; the slice lane re-slices to a new file, so its rounds group
209
+ // by artifact basename (see panelProgress).
210
+ const SLICE_PANEL_PROGRESS = panelProgress("slice-verdicts", SLICE_DIMENSIONS);
211
+ const PLAN_PANEL_PROGRESS = panelProgress("plan-verdicts", PLAN_DIMENSIONS, {
212
+ snapshotChannel: "plan-snapshot",
213
+ artifactChannel: "plans",
214
+ });
215
+ const CODE_PANEL_PROGRESS = panelProgress("code-verdicts", PLAN_DIMENSIONS, {
216
+ snapshotChannel: "code-snapshot",
217
+ artifactChannel: "plans",
218
+ });
219
+
199
220
  /**
200
221
  * Ship's grade panel — a bespoke `fanout({...})` mirroring `gradePanelFanout`'s
201
222
  * body but binding the roster to `SHIP_DIMENSIONS` DIRECTLY (no
@@ -225,6 +246,7 @@ export const SHIP_DIMENSION_FANOUT = fanout({
225
246
  unit: { by: "dimension-list", pattern: "dimensions" },
226
247
  max: SHIP_DIMENSIONS.length,
227
248
  haltWhenAllFailed: true,
249
+ retryHaltedUnits: 1,
228
250
  units: ({ state }) => {
229
251
  const doc = latestFsArtifact(state, "plans");
230
252
  if (doc?.handle.kind !== "fs") return [];
@@ -232,7 +254,8 @@ export const SHIP_DIMENSION_FANOUT = fanout({
232
254
  // The shared flag-composition site — the twins compose it rather than
233
255
  // mirroring it (dimension keying below stays ship's own).
234
256
  const { contextFlag, goalFlag, acceptanceFlag } = dimensionArtifactFlags(state);
235
- // The floor's verdict threads whenever it exists — clean settles
257
+ // The floor's verdict is REQUIRED here — citeCheckFlag fails closed when
258
+ // the configured channel carries no fs verdict; a clean verdict settles
236
259
  // resolution, findings carry the advisory leads (see citeCheckFlag).
237
260
  const citeFlag = citeCheckFlag(state, "plan-cite-check");
238
261
  // Tier-independent roster: SHIP_DIMENSIONS verbatim — never gateRoster(gateTier(...)).
@@ -249,20 +272,25 @@ export const SHIP_DIMENSION_FANOUT = fanout({
249
272
  },
250
273
  });
251
274
 
275
+ // Ship's whole-lap hook — INERT by topology (the grade gate routes implement
276
+ // or stop, so no edge ever re-enters the grade stage), declared for uniformity
277
+ // so every panel lane names its hook beside its panel.
278
+ const SHIP_PANEL_PROGRESS = panelProgress("ship-verdicts", SHIP_DIMENSIONS);
279
+
252
280
  // Ship's grade panel writes its verdicts to a DISTINCT channel (same
253
281
  // directory, different artifact basenames) so they never mix with build's
254
282
  // plan/code verdicts — named for the workflow, completing the slice-verdicts
255
283
  // / plan-verdicts / code-verdicts / ship-verdicts parallel.
256
- export const shipVerdictOutcome = {
257
- name: "ship-verdicts",
258
- collector: directoryPathCollector({ dir: ".rpiv/artifacts/verdicts", ext: "json" }),
259
- parser: jsonBodyParser,
260
- };
284
+ export const shipVerdictOutcome = verdictOutcome("ship-verdicts", "plans");
261
285
 
262
286
  export {
263
287
  CODE_CONFIRM_FANOUT,
264
288
  CODE_DIMENSION_FANOUT,
289
+ CODE_PANEL_PROGRESS,
265
290
  PLAN_CONFIRM_FANOUT,
266
291
  PLAN_DIMENSION_FANOUT,
292
+ PLAN_PANEL_PROGRESS,
293
+ SHIP_PANEL_PROGRESS,
267
294
  SLICE_DIMENSION_FANOUT,
295
+ SLICE_PANEL_PROGRESS,
268
296
  };
@@ -4,6 +4,8 @@
4
4
  * re-export targets a `.js` specifier (Node16 ESM, source stays `.ts`).
5
5
  */
6
6
 
7
+ export { designOutcome, designParser, designStructure } from "./design.js";
8
+ export { elaborationOutcome, elaborationParser, elaborationStructure } from "./elaboration.js";
7
9
  export {
8
10
  allDimensionsPass,
9
11
  anchorNitsOnly,
@@ -13,13 +15,23 @@ export {
13
15
  latestArtifactPath,
14
16
  latestVerdictPerDimension,
15
17
  PLAN_DIMENSIONS,
18
+ panelProgress,
16
19
  planAuthoredRisks,
17
20
  planGatePasses,
21
+ progressFromRoundCounts,
18
22
  rulingEffectivePass,
23
+ type SeedOnlyVerdict,
19
24
  SHIP_DIMENSIONS,
25
+ SLICE_DIMENSIONS,
26
+ seedLiftStuck,
27
+ seedOnlyCiteFail,
28
+ seedOnlyFindings,
20
29
  shipGatePasses,
21
30
  sliceGatePasses,
22
31
  subplanGatePasses,
32
+ unitFailedDimensions,
33
+ type VerdictRecord,
34
+ verdictBlocks,
23
35
  verdictRiskRulings,
24
36
  } from "./gates.js";
25
37
  export {
@@ -31,10 +43,14 @@ export {
31
43
  export {
32
44
  CODE_CONFIRM_FANOUT,
33
45
  CODE_DIMENSION_FANOUT,
46
+ CODE_PANEL_PROGRESS,
34
47
  PLAN_CONFIRM_FANOUT,
35
48
  PLAN_DIMENSION_FANOUT,
49
+ PLAN_PANEL_PROGRESS,
36
50
  SHIP_DIMENSION_FANOUT,
51
+ SHIP_PANEL_PROGRESS,
37
52
  SLICE_DIMENSION_FANOUT,
53
+ SLICE_PANEL_PROGRESS,
38
54
  shipVerdictOutcome,
39
55
  } from "./grade-panel.js";
40
56
  export {
@@ -43,9 +59,11 @@ export {
43
59
  FENCE_LINE_RE,
44
60
  fencedSpans,
45
61
  forEachLineOutsideFences,
62
+ openFenceLine,
46
63
  } from "./markdown-fence.js";
47
64
  export { planCitationCheck } from "./plan-cite.js";
48
65
  export {
66
+ ELABORATE_PHASE_FANOUT,
49
67
  FRONTMATTER_PHASE_FANOUT,
50
68
  IMPLEMENT_DAG_FANOUT,
51
69
  IMPLEMENT_PLANS_FANOUT,
@@ -71,5 +89,6 @@ export {
71
89
  VERDICT_PASS_SCORE,
72
90
  writeStructureVerdict,
73
91
  } from "./shared.js";
74
- export { sliceStructureCheck, subplanCoverageCheck } from "./slice-checks.js";
92
+ export { sliceSeedLift, sliceStructureCheck, subplanCoverageCheck } from "./slice-checks.js";
75
93
  export { SLICE_DESIGN_FANOUT, SYNTH_CLUSTER_FANOUT } from "./slices.js";
94
+ export { verdictOutcome } from "./verdict-outcome.js";
@@ -105,4 +105,29 @@ const fencedSpans = (content: string): [number, number][] => {
105
105
  return spans;
106
106
  };
107
107
 
108
- export { closesFence, countHeadingsOutsideFences, FENCE_LINE_RE, fencedSpans, forEachLineOutsideFences };
108
+ /**
109
+ * 1-based line of a fence opener that never closes, or `undefined` when every
110
+ * fence is balanced. Same walk as `fencedSpans`, reported as the one number an
111
+ * author needs to fix the leak.
112
+ */
113
+ const openFenceLine = (content: string): number | undefined => {
114
+ let inFence = false;
115
+ let fenceLen = 0;
116
+ let fenceChar = "";
117
+ let opened = 0;
118
+ content.split("\n").forEach((line, index) => {
119
+ const fence = FENCE_LINE_RE.exec(line);
120
+ if (!fence) return;
121
+ if (!inFence) {
122
+ inFence = true;
123
+ fenceLen = fence[1].length;
124
+ fenceChar = fence[1][0];
125
+ opened = index + 1;
126
+ } else if (closesFence(line, fence, fenceChar, fenceLen)) {
127
+ inFence = false;
128
+ }
129
+ });
130
+ return inFence ? opened : undefined;
131
+ };
132
+
133
+ export { closesFence, countHeadingsOutsideFences, FENCE_LINE_RE, fencedSpans, forEachLineOutsideFences, openFenceLine };
@@ -138,6 +138,13 @@ const FRONTMATTER_PHASE_FANOUT = fanout({
138
138
  },
139
139
  });
140
140
 
141
+ /**
142
+ * The elaborate fanout: `FRONTMATTER_PHASE_FANOUT` with one re-dispatch for a
143
+ * unit whose output failed its contract after the in-session retries — a
144
+ * malformed section is re-produced with the failure memo, not stitched.
145
+ */
146
+ const ELABORATE_PHASE_FANOUT = { ...FRONTMATTER_PHASE_FANOUT, retryHaltedUnits: 1 };
147
+
141
148
  /**
142
149
  * Derive the directed `deps` edges for ONE implement phase under the dep-gated
143
150
  * DAG fanout (`IMPLEMENT_DAG_FANOUT`). Edges point strictly downward (toward
@@ -412,6 +419,7 @@ const PLANS_PHASE_FANOUT = fanout({
412
419
  const IMPLEMENT_PLANS_FANOUT = { ...PLANS_PHASE_FANOUT, concurrency: 1 };
413
420
 
414
421
  export {
422
+ ELABORATE_PHASE_FANOUT,
415
423
  FRONTMATTER_PHASE_FANOUT,
416
424
  IMPLEMENT_DAG_FANOUT,
417
425
  IMPLEMENT_PLANS_FANOUT,
@@ -3,7 +3,7 @@
3
3
  * surgical-fix guard, and the risk-duty demotion stamp.
4
4
  */
5
5
  import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { basename, isAbsolute, join } from "node:path";
6
+ import { basename, extname, isAbsolute, join } from "node:path";
7
7
  import {
8
8
  type Artifact,
9
9
  handleToString,
@@ -47,9 +47,16 @@ const snapshotLatestPlan =
47
47
  );
48
48
  }
49
49
  const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
50
- const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
50
+ // One file per round, so a resume replaying an earlier round reads that
51
+ // round's bytes, not the newest copy. The basename-keyed file is still
52
+ // written for readers that key on it.
53
+ const round = (state.named[who]?.length ?? 0) + 1;
54
+ const base = basename(latest.handle.path);
55
+ const ext = extname(base);
56
+ const priorRel = join(PRIOR_DIR, `${base.slice(0, base.length - ext.length)}.r${round}${ext}`);
51
57
  mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
52
58
  copyFileSync(src, join(cwd, priorRel));
59
+ copyFileSync(src, join(cwd, PRIOR_DIR, base));
53
60
  return {
54
61
  kind: "artifact-md",
55
62
  artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Typed surface of reconcile-directives.mjs for the TS consumer
3
+ * (extensions/rpiv-core/built-ins/reconcile.ts). Keep in lockstep with the
4
+ * .mjs exports — the runtime source of truth.
5
+ */
6
+
7
+ /** One `#### Reconciliation` directive parsed from a plan body. */
8
+ export interface ReconciliationDirective {
9
+ /** Repo-root-relative target declared in the plan's write-set. */
10
+ target: string;
11
+ /** Substring to find (replaced exactly once via `String.replace`). */
12
+ find: string;
13
+ /** Replacement string. */
14
+ replace: string;
15
+ }
16
+
17
+ /** What applying a directive to the target's current content would do. */
18
+ export type ApplicationClass = "already-applied" | "apply" | "deletion-satisfied" | "missing";
19
+
20
+ export declare function reconciliationRecords(body: string): {
21
+ directives: ReconciliationDirective[];
22
+ malformed: string[];
23
+ };
24
+
25
+ export declare function classifyApplication(directive: ReconciliationDirective, content: string): ApplicationClass;
26
+
27
+ export declare function declaredWriteSet(body: string): Set<string>;
28
+
29
+ export declare function phaseSection(body: string, n: number | string): string | undefined;
@@ -0,0 +1,338 @@
1
+ /**
2
+ * Single source of truth for the `#### Reconciliation` directive grammar:
3
+ * parsing and application-classification, shared by the deterministic
4
+ * `reconcile` gate (the sibling reconcile.ts) and skills/_shared/
5
+ * reconcile-lint.mjs — the pre-flight CLI the implement skill runs before
6
+ * finishing a phase (the skill-layer script depends on this extension module,
7
+ * never the reverse). Because both sides import the SAME parser, a
8
+ * directive that lints clean locally parses identically at the gate — the
9
+ * lint's whole guarantee. Pure ESM, node-runnable, no dependencies (the Pi
10
+ * peer dependency is NOT resolvable from a bare `node` invocation, so nothing
11
+ * here may import it).
12
+ *
13
+ * Typed surface for TS consumers lives in reconcile-directives.d.mts.
14
+ */
15
+
16
+ /**
17
+ * A fence-opening line: optional leading whitespace then 3+ backticks or 3+
18
+ * tildes. Mirrors extensions/rpiv-core/built-ins/markdown-fence.ts (which
19
+ * .mjs cannot import) — the same deliberate mirror stitch-elaborations.mjs
20
+ * carries; CommonMark fence rules are stable, drift is pinned by the shared
21
+ * parser tests exercising fenced directives end to end.
22
+ */
23
+ const FENCE_LINE_RE = /^\s*(`{3,}|~{3,})/;
24
+
25
+ /** Whether `line` CLOSES the fence whose opener recorded `fenceChar`/`fenceLen`:
26
+ * same char, at least as long, nothing else on the line. */
27
+ const closesFence = (line, fence, fenceChar, fenceLen) => {
28
+ const len = fence[1].length;
29
+ return fence[1][0] === fenceChar && len >= fenceLen && line.trim().length === len;
30
+ };
31
+
32
+ /** Directive grammar (inline form), matched against a whole LIST ITEM (which
33
+ * may span lines — `[^`]` matches `\n`, so a multi-line find/replace snippet
34
+ * parses as long as it carries no inner backticks):
35
+ * `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
36
+ * The arrow is `→` (U+2192) or the ASCII `->`; the em-dash `—` (U+2014) +
37
+ * rationale is optional and may span lines. The two spans are intentionally
38
+ * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an
39
+ * empty find has no anchored target and `String.replace("")` prepends the
40
+ * replacement on every run, so the parser rejects it at parse time), while
41
+ * `replace` is zero-or-more `[^`]*` (an empty replace is a legitimate
42
+ * deletion directive). */
43
+ const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*(?:→|->)\s*`([^`]*)`\s*(?:—[\s\S]*)?$/;
44
+ /** The fenced form's HEADER line — `- `<target>`: replace` with NO inline
45
+ * spans (an optional `— rationale` tail): the find/replace live in labeled
46
+ * fenced blocks on the item's continuation lines. The escape hatch for
47
+ * content a backtick grammar cannot express (inner backticks, template
48
+ * literals, markdown-in-tests). */
49
+ const RECONCILE_BLOCK_HEADER_RE = /^-\s+`([^`]+)`\s*:\s*replace\s*(?:—.*)?$/;
50
+ /** A directive ATTEMPT — `- `<target>`:` — that does not match either grammar.
51
+ * Used to surface a malformed directive as a finding rather than silently
52
+ * dropping it. */
53
+ const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
54
+
55
+ /**
56
+ * Parse the fenced-form continuation lines of one directive item: a `find:`
57
+ * label line, a fenced code block, a `replace:` label line, a second fenced
58
+ * block. Fence chars/lengths follow CommonMark (`closesFence`); content is
59
+ * dedented by the opening fence line's own indentation so a list-nested block
60
+ * captures the target file's exact bytes. Returns `undefined` when the
61
+ * structure does not complete — the caller degrades to a malformed finding.
62
+ */
63
+ const parseFencedSpans = (lines) => {
64
+ const spans = [];
65
+ let i = 0;
66
+ for (const label of ["find:", "replace:"]) {
67
+ while (i < lines.length && lines[i].trim() === "") i++;
68
+ if (lines[i]?.trim() !== label) return undefined;
69
+ i++;
70
+ const open = lines[i] !== undefined ? FENCE_LINE_RE.exec(lines[i]) : null;
71
+ if (!open) return undefined;
72
+ const indent = /^[ \t]*/.exec(lines[i])?.[0] ?? "";
73
+ const fenceChar = open[1][0];
74
+ const fenceLen = open[1].length;
75
+ i++;
76
+ const content = [];
77
+ let closed = false;
78
+ for (; i < lines.length; i++) {
79
+ const close = FENCE_LINE_RE.exec(lines[i]);
80
+ if (close && closesFence(lines[i], close, fenceChar, fenceLen)) {
81
+ closed = true;
82
+ i++;
83
+ break;
84
+ }
85
+ content.push(lines[i].startsWith(indent) ? lines[i].slice(indent.length) : lines[i]);
86
+ }
87
+ if (!closed) return undefined;
88
+ spans.push(content.join("\n"));
89
+ }
90
+ // An empty find is rejected for the same anchorless-`String.replace("")`
91
+ // reason as the inline grammar; an empty replace is a legitimate deletion.
92
+ if (spans[0] === "") return undefined;
93
+ return { find: spans[0], replace: spans[1] };
94
+ };
95
+
96
+ /** Classify one collected list item (header + continuation lines) as a
97
+ * directive, a malformed attempt (the header line, surfaced), or prose (ignored).
98
+ *
99
+ * Order and byte discipline are both load-bearing (review 2026-08-31 I4/Q2):
100
+ * the INLINE grammar runs first, over the RAW joined item — a per-line
101
+ * `trimEnd` stripped interior-line trailing whitespace from the captured
102
+ * spans while the applier matches raw file bytes, so a span whose file text
103
+ * carries line-trailing whitespace could never match (only the whole-item
104
+ * tail is trimmed, for the `$` anchor). Fenced-header second — trying it
105
+ * first mis-routed an inline item whose spans start on a continuation line
106
+ * (header ending at `replace`) into the fenced parser and surfaced a phantom
107
+ * malformed finding; the reverse mis-route cannot happen because a fenced
108
+ * item's `find:` label (or `— rationale` tail) sits where the inline grammar
109
+ * demands a backtick. */
110
+ const classifyItem = (lines, out) => {
111
+ const header = lines[0].trimEnd();
112
+ const m = RECONCILE_DIRECTIVE_RE.exec(lines.join("\n").trimEnd());
113
+ if (m) {
114
+ out.directives.push({ target: m[1].trim(), find: m[2], replace: m[3] });
115
+ return;
116
+ }
117
+ const blockHeader = RECONCILE_BLOCK_HEADER_RE.exec(header);
118
+ if (blockHeader) {
119
+ const spans = parseFencedSpans(lines.slice(1));
120
+ if (spans) {
121
+ out.directives.push({ target: blockHeader[1].trim(), find: spans.find, replace: spans.replace });
122
+ } else {
123
+ out.malformed.push(header.trim());
124
+ }
125
+ return;
126
+ }
127
+ if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(header)) {
128
+ out.malformed.push(header.trim());
129
+ }
130
+ };
131
+
132
+ /**
133
+ * Parse every `#### Reconciliation` directive from a plan body. Returns the
134
+ * well-formed directives AND the malformed attempts (items that carry the
135
+ * `- `<target>`:` shape but neither the inline `replace … → …` grammar nor a
136
+ * complete fenced find:/replace: pair). Prose list items are ignored. Pure:
137
+ * no I/O, no throw.
138
+ *
139
+ * Structure: a section opens at a `#### Reconciliation` heading and closes at
140
+ * the next `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a
141
+ * sibling `#### Automated Verification:` all end it) — headings are only
142
+ * recognized OUTSIDE fenced code blocks, so fenced find/replace content that
143
+ * happens to carry `#`-leading lines cannot truncate the section. Within a
144
+ * section, a `- ` line outside a fence starts a new list item; every following
145
+ * line until the next item / section end is that item's continuation (this is
146
+ * what lets a multi-line inline directive parse as one unit).
147
+ */
148
+ const reconciliationRecords = (body) => {
149
+ const out = { directives: [], malformed: [] };
150
+ let inSection = false;
151
+ let item;
152
+ let fenceChar = "";
153
+ let fenceLen = 0;
154
+ const flush = () => {
155
+ if (item) classifyItem(item, out);
156
+ item = undefined;
157
+ };
158
+ for (const raw of body.split("\n")) {
159
+ const line = raw.trimEnd();
160
+ if (fenceLen > 0) {
161
+ // Inside a fenced block: only a matching closer changes state; every
162
+ // line (closer included) rides the current item verbatim.
163
+ const close = FENCE_LINE_RE.exec(line);
164
+ if (close && closesFence(line, close, fenceChar, fenceLen)) {
165
+ fenceChar = "";
166
+ fenceLen = 0;
167
+ }
168
+ item?.push(raw);
169
+ continue;
170
+ }
171
+ const open = FENCE_LINE_RE.exec(line);
172
+ if (open) {
173
+ fenceChar = open[1][0];
174
+ fenceLen = open[1].length;
175
+ item?.push(raw);
176
+ continue;
177
+ }
178
+ if (/^####\s+Reconciliation\b/.test(line)) {
179
+ flush();
180
+ inSection = true;
181
+ continue;
182
+ }
183
+ // Any other heading ends the section (the open-heading branch above `continue`s,
184
+ // so this only fires for non-`#### Reconciliation` headings).
185
+ if (/^#{1,4}\s/.test(line)) {
186
+ flush();
187
+ inSection = false;
188
+ continue;
189
+ }
190
+ if (!inSection) continue;
191
+ if (/^-\s/.test(line)) {
192
+ flush();
193
+ item = [raw];
194
+ } else {
195
+ item?.push(raw);
196
+ }
197
+ }
198
+ flush();
199
+ return out;
200
+ };
201
+
202
+ /**
203
+ * Classify what applying `directive` to the target's current `content` would
204
+ * do — the gate's apply-branch decision, factored out so the lint predicts the
205
+ * gate byte-for-byte:
206
+ *
207
+ * - `"already-applied"` — the replacement is present AND (the find is gone,
208
+ * or the find only survives because the replacement contains it). The
209
+ * idempotent-re-run no-op for a substitution: a re-apply on a containment-
210
+ * shaped directive would compound drift (review 2026-08-31 I1), so this
211
+ * check runs FIRST.
212
+ * - `"apply"` — the find is present; `String.replace` would substitute the
213
+ * FIRST match exactly once.
214
+ * - `"deletion-satisfied"` — the find is gone and the replacement is empty:
215
+ * find-absent is the deletion's success condition (a prior apply removed it).
216
+ * - `"missing"` — the find is absent and the non-empty replacement is also
217
+ * absent: the directive is stale or authored from memory; the gate emits a
218
+ * finding (reconcile does not guess).
219
+ */
220
+ const classifyApplication = (directive, content) => {
221
+ const applied =
222
+ directive.replace !== "" &&
223
+ content.includes(directive.replace) &&
224
+ (!content.includes(directive.find) || directive.replace.includes(directive.find));
225
+ if (applied) return "already-applied";
226
+ if (content.includes(directive.find)) return "apply";
227
+ if (directive.replace === "") return "deletion-satisfied";
228
+ return "missing";
229
+ };
230
+
231
+ /**
232
+ * Mirror of plan-phases.ts `withTestTwins`: expand a declared write-set with
233
+ * each `.ts/.tsx/.js/.jsx` production file's co-located `.test.*` twin (a file
234
+ * already matching the test suffix maps to itself). Files of any other
235
+ * language pass through untouched — the twin convention is a JS/TS-ecosystem
236
+ * convenience layered on the language-agnostic declared set.
237
+ */
238
+ const withTestTwins = (files) => {
239
+ const out = new Set(files);
240
+ for (const f of files) {
241
+ if (/\.test\.[tj]sx?$/.test(f)) continue;
242
+ const twin = f.replace(/\.([tj]sx?)$/, ".test.$1");
243
+ if (twin !== f) out.add(twin);
244
+ }
245
+ return [...out];
246
+ };
247
+
248
+ /**
249
+ * BEST-EFFORT extraction of the plan's declared write-set — the union of every
250
+ * phase's `files:` entries in the leading `---` frontmatter block, twin-
251
+ * expanded (`withTestTwins`) to match the scope floor. The gate derives the
252
+ * authoritative set via Pi's real YAML parser (`planPhaseRecords` +
253
+ * `phaseFiles`), which a bare `node` script cannot import — this line-scan
254
+ * covers the two shapes plans actually carry: block style (`files:` followed
255
+ * by `- path` items) and flow style (`files: ["a", "b"]` inline). Used by
256
+ * reconcile-lint only, for the pre-flight eligibility warning; the gate never
257
+ * calls this.
258
+ */
259
+ const declaredWriteSet = (body) => {
260
+ const lines = body.split("\n");
261
+ if (lines[0]?.trim() !== "---") return new Set();
262
+ const files = [];
263
+ let inFilesBlock = false;
264
+ for (let i = 1; i < lines.length; i++) {
265
+ const line = lines[i];
266
+ if (line.trim() === "---") break;
267
+ const flow = /(?:^|\s)files:\s*\[([^\]]*)\]/.exec(line);
268
+ if (flow) {
269
+ inFilesBlock = false;
270
+ for (const part of flow[1].split(",")) {
271
+ const f = part.trim().replace(/^["']|["']$/g, "");
272
+ if (f) files.push(f);
273
+ }
274
+ continue;
275
+ }
276
+ if (/(?:^|\s)files:\s*$/.test(line)) {
277
+ inFilesBlock = true;
278
+ continue;
279
+ }
280
+ if (inFilesBlock) {
281
+ const item = /^\s+-\s+(.+)$/.exec(line);
282
+ if (item) {
283
+ files.push(item[1].trim().replace(/^["']|["']$/g, ""));
284
+ continue;
285
+ }
286
+ inFilesBlock = false;
287
+ }
288
+ }
289
+ return new Set(withTestTwins(files));
290
+ };
291
+
292
+ /**
293
+ * Slice one `## Phase <n>:` section out of a plan body (heading line included,
294
+ * ending at the next `## `-level heading), recognizing headings only OUTSIDE
295
+ * fenced code blocks — a plan phase embedding a markdown fixture must not
296
+ * truncate the section (the fence-aware discipline every plan scan shares).
297
+ * Returns `undefined` when the phase heading is absent.
298
+ */
299
+ const phaseSection = (body, n) => {
300
+ const headingRe = new RegExp(`^##\\s+Phase\\s+${n}\\b`);
301
+ const collected = [];
302
+ let inPhase = false;
303
+ let found = false;
304
+ let fenceChar = "";
305
+ let fenceLen = 0;
306
+ for (const raw of body.split("\n")) {
307
+ const line = raw.trimEnd();
308
+ const fence = FENCE_LINE_RE.exec(line);
309
+ if (fenceLen > 0) {
310
+ if (fence && closesFence(line, fence, fenceChar, fenceLen)) {
311
+ fenceChar = "";
312
+ fenceLen = 0;
313
+ }
314
+ if (inPhase) collected.push(raw);
315
+ continue;
316
+ }
317
+ if (fence) {
318
+ fenceChar = fence[1][0];
319
+ fenceLen = fence[1].length;
320
+ if (inPhase) collected.push(raw);
321
+ continue;
322
+ }
323
+ if (headingRe.test(line)) {
324
+ inPhase = true;
325
+ found = true;
326
+ collected.push(raw);
327
+ continue;
328
+ }
329
+ if (inPhase && /^##\s/.test(line) && !/^###/.test(line)) {
330
+ inPhase = false;
331
+ continue;
332
+ }
333
+ if (inPhase) collected.push(raw);
334
+ }
335
+ return found ? collected.join("\n") : undefined;
336
+ };
337
+
338
+ export { classifyApplication, declaredWriteSet, phaseSection, reconciliationRecords };