@juicesharp/rpiv-pi 2.8.0 → 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.
@@ -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 };
@@ -1,153 +1,92 @@
1
1
  /**
2
2
  * The post-implement reconciliation backstop: `#### Reconciliation` directive
3
- * parsing and write-restricted application.
3
+ * application, write-restricted to the plan's declared write-set.
4
+ *
5
+ * The directive grammar and parser live in the sibling
6
+ * reconcile-directives.mjs — the SAME module the skills/_shared/
7
+ * reconcile-lint.mjs pre-flight CLI (run by the implement skill before it
8
+ * finishes a phase) imports, so a directive that lints clean locally parses
9
+ * identically here.
4
10
  */
5
11
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
12
  import { basename, isAbsolute, join } from "node:path";
7
13
  import { handleToString, type Output, type ScriptContext } from "@juicesharp/rpiv-workflow/registration";
14
+ import { phaseFiles, planPhaseRecords, withTestTwins } from "./plan-phases.js";
15
+ import { classifyApplication, type ReconciliationDirective, reconciliationRecords } from "./reconcile-directives.mjs";
8
16
  import {
9
17
  containedPath,
10
18
  haltPreflight,
11
19
  latestFsArtifact,
12
20
  readArtifactFile,
13
- TEST_PATH_RE,
14
21
  VERDICT_DIR,
15
22
  VERDICT_FAIL_SCORE,
16
23
  VERDICT_PASS_SCORE,
17
24
  } from "./shared.js";
18
25
 
19
26
  /**
20
- * One `#### Reconciliation` directive parsed from a plan body: a machine-applicable
21
- * `find → replace` against a single test-expectation file. The implement lane records
22
- * these in a phase's OWN section when a correct change invalidates a test that lives
23
- * in a sibling phase's landed section (which the implementer may NOT edit); `reconcile`
24
- * applies them write-restricted to `*.test.*` targets.
25
- */
26
- interface ReconciliationDirective {
27
- /** Repo-root-relative test target (`*.test.*`). */
28
- target: string;
29
- /** Substring to find (replaced exactly once via `String.replace`). */
30
- find: string;
31
- /** Replacement string. */
32
- replace: string;
33
- }
34
-
35
- /** Directive grammar: `` - `<target>`: replace `<find>` → `<replace>` — <rationale> ``.
36
- * The `→` (U+2192) separates find/replace; the em-dash `—` (U+2014) + rationale is
37
- * optional. Find/replace carry no inner backticks. The two spans are intentionally
38
- * asymmetric and MUST NOT be symmetrized: `find` is one-or-more `[^`]+` (an empty
39
- * find has no anchored target and `String.replace("")` prepends the replacement on
40
- * every run, so the parser rejects it at parse time), while `replace` is
41
- * zero-or-more `[^`]*` (an empty replace is a legitimate deletion directive). */
42
- const RECONCILE_DIRECTIVE_RE = /^-\s+`([^`]+)`\s*:\s*replace\s+`([^`]+)`\s*→\s*`([^`]*)`\s*(?:—\s+.*)?$/;
43
- /** A directive ATTEMPT — `- `<target>`:` — that does not match the full grammar. Used
44
- * to surface a malformed directive as a finding rather than silently dropping it. */
45
- const RECONCILE_DIRECTIVE_ATTEMPT_RE = /^-\s+`[^`]+`\s*:/;
46
-
47
- /**
48
- * Parse every `#### Reconciliation` directive from a plan body. Returns the
49
- * well-formed directives AND the malformed attempts (lines that carry the
50
- * `- `<target>`:` shape but not the full `replace … → …` grammar); `reconcile`
51
- * turns each malformed attempt into a finding so a broken directive is visible,
52
- * never silently dropped. Prose list items are ignored. Pure: no I/O, no throw.
53
- * A section opens at a `#### Reconciliation` heading and closes at the next
54
- * `#{1,4}` heading (so `### Success Criteria` / `## Phase N:` / a sibling
55
- * `#### Automated Verification:` all end it).
56
- */
57
- const reconciliationRecords = (
58
- body: string,
59
- ): {
60
- directives: ReconciliationDirective[];
61
- malformed: string[];
62
- } => {
63
- const directives: ReconciliationDirective[] = [];
64
- const malformed: string[] = [];
65
- let inSection = false;
66
- for (const raw of body.split("\n")) {
67
- const line = raw.trimEnd();
68
- if (/^####\s+Reconciliation\b/.test(line)) {
69
- inSection = true;
70
- continue;
71
- }
72
- // Any other heading ends the section (the open-heading branch above `continue`s,
73
- // so this only fires for non-`#### Reconciliation` headings).
74
- if (/^#{1,4}\s/.test(line)) {
75
- inSection = false;
76
- continue;
77
- }
78
- if (!inSection) continue;
79
- const m = RECONCILE_DIRECTIVE_RE.exec(line);
80
- if (m) {
81
- directives.push({ target: m[1]!.trim(), find: m[2]!, replace: m[3]! });
82
- } else if (RECONCILE_DIRECTIVE_ATTEMPT_RE.test(line)) {
83
- malformed.push(line.trim());
84
- }
85
- }
86
- return { directives, malformed };
87
- };
88
-
89
- const isTestPath = (target: string): boolean => TEST_PATH_RE.test(target);
90
-
91
- /**
92
- * Apply each `#### Reconciliation` directive, write-restricted to test-expectation
93
- * files (`isTestPath` — reconcile writes ONLY test files; a non-test target is a
94
- * finding, left untouched, fail-closed). A present `find` is replaced exactly
95
- * once (`String.replace`, first match); an absent `find` whose `replace` is empty
96
- * is the idempotent-re-run no-op for a deletion (find-absent is the deletion's
97
- * success condition — the directive was already applied, no finding, no write); an
98
- * absent `find` whose non-empty `replace` is ALSO absent is a finding (reconcile
99
- * does not guess); an absent `find` whose non-empty `replace` is already present is
100
- * the idempotent-re-run no-op for a substitution (a prior successful apply, no
101
- * finding, no write). Paths resolve through `cwd` and must stay INSIDE it
102
- * (`containedPath` — an absolute or `..`-escaping target is a finding, never a
103
- * read/write; the suffix allowlist alone cannot confine the sink, so containment
104
- * is checked on the SAME resolved path `readFileSync`/`writeFileSync` use).
105
- * Fail-soft: a read/apply throw degrades to a finding naming
106
- * the target, never a terminal throw. Returns findings in DIRECTIVE order and
107
- * performs the side-effecting writes itself (`reconcile` spreads the return).
27
+ * Apply each `#### Reconciliation` directive, write-restricted to the plan's
28
+ * declared write-set — the union of every phase's `files:`, twin-expanded
29
+ * (`withTestTwins`), the SAME authority the scope floor enforces, so reconcile
30
+ * can never write a path the floor would flag. Eligibility derives from the
31
+ * plan's own declarations, never from a filename convention, so the gate works
32
+ * identically in a project of any language; an undeclared target is a finding,
33
+ * left untouched, fail-closed (a `files:`-less plan declares nothing and
34
+ * rejects every directive).
35
+ *
36
+ * The apply decision per directive is `classifyApplication` (shared with the
37
+ * lint): `already-applied` / `deletion-satisfied` are the idempotent-re-run
38
+ * no-ops (reconcile-fix and validate-fix loop re-entries are normal — see the
39
+ * containment-shaped-directive rationale on `classifyApplication`); `apply`
40
+ * substitutes the FIRST match exactly once (`String.replace`); `missing` is a
41
+ * finding (reconcile does not guess). Paths resolve through `cwd` and must
42
+ * stay INSIDE it (`containedPath` — an absolute or `..`-escaping target is a
43
+ * finding, never a read/write; the declared-set membership check alone cannot
44
+ * confine the sink, so containment is checked on the SAME resolved path
45
+ * `readFileSync`/`writeFileSync` use). Fail-soft: a read/apply throw degrades
46
+ * to a finding naming the target, never a terminal throw. Returns findings in
47
+ * DIRECTIVE order and performs the side-effecting writes itself (`reconcile`
48
+ * spreads the return).
108
49
  */
109
50
  const applyReconciliationDirectives = (
110
51
  directives: readonly ReconciliationDirective[],
52
+ declared: ReadonlySet<string>,
111
53
  cwd: string,
112
54
  ): { detail: string; where: string }[] => {
113
55
  const findings: { detail: string; where: string }[] = [];
114
- // Apply directives, write-restricted to test-expectation files.
115
56
  for (const d of directives) {
116
- if (!isTestPath(d.target)) {
57
+ const abs = containedPath(cwd, d.target);
58
+ if (abs === undefined) {
117
59
  findings.push({
118
- detail: `reconcile: directive target ${d.target} is not a test-expectation file (*.test.{ts,tsx,js,jsx}) — reconcile writes only test files; record the directive against a test target or apply the edit in the owning phase`,
60
+ detail: `reconcile: directive target ${d.target} resolves outside the working tree — reconcile reads and writes only inside cwd; record the directive against a repo-root-relative target`,
119
61
  where: d.target,
120
62
  });
121
63
  continue;
122
64
  }
123
- const abs = containedPath(cwd, d.target);
124
- if (abs === undefined) {
65
+ if (!declared.has(d.target)) {
125
66
  findings.push({
126
- detail: `reconcile: directive target ${d.target} resolves outside the working tree — reconcile reads and writes only inside cwd; record the directive against a repo-root-relative test target`,
67
+ detail: `reconcile: directive target ${d.target} is not in the plan's declared write-set (the union of every phase's 'files:', twin-expanded) — reconcile writes only what the plan declares, the same authority the scope floor enforces; declare the file in the owning phase's 'files:', or route the edit through validate's remediation arm`,
127
68
  where: d.target,
128
69
  });
129
70
  continue;
130
71
  }
131
72
  try {
132
73
  const content = readFileSync(abs, "utf-8");
133
- if (content.includes(d.find)) {
134
- // `String.replace` with a string pattern replaces the FIRST match exactly once.
135
- writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
136
- } else if (d.replace !== "" && content.includes(d.replace)) {
137
- // Idempotent re-run: the find is gone but the replacement is present ⇒ the
138
- // directive was already applied (e.g. a vet review-fix loop re-running
139
- // reconcile). Treated as satisfied — reconcile must not fail on its own
140
- // prior successful apply.
141
- } else if (d.replace === "") {
142
- // Idempotent re-run of a deletion: the find is gone and the replacement is
143
- // empty ⇒ find-absent is the deletion's success condition (a prior successful
144
- // apply removed it). Treated as satisfied — reconcile must not fail on its
145
- // own prior successful apply (e.g. a validate-fix loop re-running reconcile).
146
- } else {
147
- findings.push({
148
- 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`,
149
- where: d.target,
150
- });
74
+ switch (classifyApplication(d, content)) {
75
+ case "already-applied":
76
+ case "deletion-satisfied":
77
+ // Idempotent re-run: treated as satisfied — reconcile must not fail
78
+ // (or re-write) on its own prior successful apply.
79
+ break;
80
+ case "apply":
81
+ // `String.replace` with a string pattern replaces the FIRST match exactly once.
82
+ writeFileSync(abs, content.replace(d.find, d.replace), "utf-8");
83
+ break;
84
+ case "missing":
85
+ findings.push({
86
+ 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 target no longer matches. Repair IN THE PLAN: update the directive's find text to match the target file's current content byte-for-byte (Read the file to ground it; if the text carries backticks, rewrite the directive in the fenced find:/replace: form, which preserves bytes exactly), or delete the directive if it no longer applies`,
87
+ where: d.target,
88
+ });
89
+ break;
151
90
  }
152
91
  } catch (err) {
153
92
  findings.push({
@@ -163,17 +102,19 @@ const applyReconciliationDirectives = (
163
102
  * Deterministic post-implement reconciliation — the coherence backstop the
164
103
  * parallel implement lane needs. Sibling phases run concurrently in one tree;
165
104
  * each phase's own `#### Automated Verification:` passed in isolation, but a
166
- * phase's correct change can invalidate a test that lives in a SIBLING phase's
167
- * landed section (which the implementer may not edit), and the combined tree can
168
- * break in ways no single phase's checks surface. `reconcile` runs after the
169
- * scope floor (which proved the write-set) and before `validate`:
105
+ * phase's correct change can invalidate an expectation that lives in a SIBLING
106
+ * phase's landed section (which the implementer may not edit), and the combined
107
+ * tree can break in ways no single phase's checks surface. `reconcile` runs
108
+ * after the scope floor (which proved the write-set) and before `validate`:
170
109
  *
171
110
  * 1. reads the latest plan (`latestFsArtifact(state, "plans")` — latest-wins);
172
- * 2. parses every `#### Reconciliation` directive — fail-soft (a malformed
173
- * directive / unreadable plan degrades to a finding, never a terminal
174
- * `FAIL_SCRIPT_THREW` halt — a `produces.script` that throws becomes one);
175
- * 3. applies each directive write-restricted to test paths (`isTestPath`); a
176
- * present `find` is replaced exactly once (`String.replace`); an absent `find`
111
+ * 2. parses every `#### Reconciliation` directive (shared parser) and derives
112
+ * the plan's declared write-set (`planPhaseRecords` + `phaseFiles`, twin-
113
+ * expanded) — fail-soft (a malformed directive / unreadable or unparseable
114
+ * plan degrades to a finding, never a terminal `FAIL_SCRIPT_THREW` halt —
115
+ * a `produces.script` that throws becomes one);
116
+ * 3. applies each directive write-restricted to the declared set; a present
117
+ * `find` is replaced exactly once (`String.replace`); an absent `find`
177
118
  * whose replacement is ALSO absent is a finding (reconcile does not guess);
178
119
  * 4. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
179
120
  * `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
@@ -189,8 +130,12 @@ const applyReconciliationDirectives = (
189
130
  * commands as an agent, with a real shell and the judgment to tell a legitimate
190
131
  * post-rename mismatch from actual plan-vs-tree drift.
191
132
  *
192
- * The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
193
- * validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
133
+ * The route is `reconcileGate` (built-in-workflows.ts) — pass ⇒ validate; fail ⇒
134
+ * the `reconcile-fix` arm (`/skill:amend` over the plan's directives from this
135
+ * verdict — every reconcile failure class is a plan-TEXT defect, so the plan
136
+ * reviser has authority over all of them; amend never edits directive targets,
137
+ * this stage stays the sole applier), looping back here; a missing/corrupt
138
+ * verdict ⇒ STOP (integrity clause).
194
139
  * Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
195
140
  * path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
196
141
  * ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
@@ -212,15 +157,22 @@ const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
212
157
  const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
213
158
  const findings: { detail: string; where: string }[] = [];
214
159
 
215
- // Fail-soft read + parse: an unreadable plan or malformed directive degrades
216
- // to a finding, never a terminal throw. If the read fails there is nothing to
217
- // apply.
160
+ // Fail-soft read + parse: an unreadable plan, unparseable phase frontmatter,
161
+ // or malformed directive degrades to a finding, never a terminal throw. If
162
+ // the read fails there is nothing to apply. Assignment order is load-bearing:
163
+ // `directives` lands only after the declared set derived, so a
164
+ // phase-frontmatter defect yields ONE parse finding, never a cascade of
165
+ // per-directive not-declared findings against an empty set.
218
166
  let body = "";
219
167
  let directives: ReconciliationDirective[] = [];
220
168
  let malformed: string[] = [];
169
+ let declared: ReadonlySet<string> = new Set<string>();
221
170
  try {
222
171
  body = readArtifactFile(planPath, cwd);
223
172
  const parsed = reconciliationRecords(body);
173
+ declared = new Set(
174
+ withTestTwins(planPhaseRecords(body, "reconcile", planPath).flatMap((r) => phaseFiles(r.entry))),
175
+ );
224
176
  directives = parsed.directives;
225
177
  malformed = parsed.malformed;
226
178
  } catch (err) {
@@ -231,12 +183,18 @@ const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
231
183
  }
232
184
  for (const m of malformed) {
233
185
  findings.push({
234
- detail: `reconcile: malformed Reconciliation directive — expected a line of the form: - \`<target>\`: replace \`<find>\` → \`<replace>\` (target/find/replace each backtick-wrapped) — ${m}`,
186
+ detail:
187
+ "reconcile: malformed Reconciliation directive — rewrite the directive IN THE PLAN as either " +
188
+ "(a) one list item: - `<target>`: replace `<find>` → `<replace>` — <rationale> " +
189
+ "(find/replace may span lines but must carry no inner backticks), or " +
190
+ "(b) the fenced form for content with backticks: - `<target>`: replace — <rationale>, then a " +
191
+ "`find:` line followed by a fenced code block, then a `replace:` line followed by a fenced code " +
192
+ `block — offending item: ${m}`,
235
193
  where: "reconciliation-directive",
236
194
  });
237
195
  }
238
196
 
239
- findings.push(...applyReconciliationDirectives(directives, cwd));
197
+ findings.push(...applyReconciliationDirectives(directives, declared, cwd));
240
198
 
241
199
  // Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
242
200
  // Non-fatal — a write failure here is silent (the verdict below is the signal).
@@ -30,3 +30,25 @@ export function parseFrontmatterBounds(lines: string[]): { start: number; end: n
30
30
 
31
31
  return null; // unclosed frontmatter
32
32
  }
33
+
34
+ /**
35
+ * Read the raw scalar value of `key` within the frontmatter bounds.
36
+ *
37
+ * Returns the trimmed text after `${key}:` on the key's own line, or
38
+ * `undefined` when the key is absent from the block. Single-line scalars
39
+ * only — a key whose value lives on following lines (block sequence) reads
40
+ * as "", and callers treat that as an unmergeable form. The read
41
+ * counterpart to applyKeyUpdates in agents.ts.
42
+ */
43
+ export function readFrontmatterKey(
44
+ lines: string[],
45
+ bounds: { start: number; end: number },
46
+ key: string,
47
+ ): string | undefined {
48
+ for (let i = bounds.start + 1; i < bounds.end; i++) {
49
+ const line = lines[i];
50
+ if (!line.startsWith(`${key}:`)) continue;
51
+ return line.slice(key.length + 1).trim();
52
+ }
53
+ return undefined;
54
+ }