@juicesharp/rpiv-pi 2.6.4 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/skills.md +1 -1
- package/extensions/rpiv-core/agents.ts +10 -13
- package/extensions/rpiv-core/artifact-collector.ts +111 -6
- package/extensions/rpiv-core/bash-timeout.ts +12 -2
- package/extensions/rpiv-core/built-in-workflows.ts +329 -3528
- package/extensions/rpiv-core/built-ins/citations.ts +357 -0
- package/extensions/rpiv-core/built-ins/gates.ts +613 -0
- package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
- package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
- package/extensions/rpiv-core/built-ins/index.ts +47 -0
- package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
- package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
- package/extensions/rpiv-core/built-ins/priors.ts +352 -0
- package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
- package/extensions/rpiv-core/built-ins/remediation.ts +96 -0
- package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
- package/extensions/rpiv-core/built-ins/shared.ts +17 -1
- package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
- package/extensions/rpiv-core/built-ins/slices.ts +288 -0
- package/extensions/rpiv-core/constants.ts +5 -1
- package/extensions/rpiv-core/lane-console.ts +9 -2
- package/extensions/rpiv-core/lane-list.ts +10 -1
- package/extensions/rpiv-core/question-lifecycle.ts +2 -2
- package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
- package/extensions/rpiv-core/run-lane-registry.ts +83 -83
- package/package.json +2 -2
- package/skills/elaborate/SKILL.md +1 -1
- package/skills/implement/SKILL.md +1 -0
- package/skills/plan/SKILL.md +3 -1
- package/skills/remediate/SKILL.md +18 -15
- package/skills/synthesize/SKILL.md +1 -0
- package/skills/validate/SKILL.md +26 -19
- package/skills/validate/templates/validation.md +1 -1
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plan-prior pipeline: pre-fix plan snapshots, section diffs, the
|
|
3
|
+
* surgical-fix guard, and the risk-duty demotion stamp.
|
|
4
|
+
*/
|
|
5
|
+
import { copyFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { basename, isAbsolute, join } from "node:path";
|
|
7
|
+
import {
|
|
8
|
+
type Artifact,
|
|
9
|
+
handleToString,
|
|
10
|
+
type Output,
|
|
11
|
+
type RunView,
|
|
12
|
+
type ScriptContext,
|
|
13
|
+
} from "@juicesharp/rpiv-workflow/registration";
|
|
14
|
+
import {
|
|
15
|
+
evidenceCitesFileLine,
|
|
16
|
+
freshVerdicts,
|
|
17
|
+
latestArtifactPath,
|
|
18
|
+
latestVerdictPerDimension,
|
|
19
|
+
planAuthoredRisks,
|
|
20
|
+
procedureSatisfiesDuty,
|
|
21
|
+
rulingEffectivePass,
|
|
22
|
+
verdictRiskRulings,
|
|
23
|
+
} from "./gates.js";
|
|
24
|
+
import { haltPreflight, latestFsArtifact, readArtifactFile } from "./shared.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Copy the latest graded plan off `plans` into `.rpiv/artifacts/priors/`
|
|
28
|
+
* basename-keyed, publishing the bytes on the snapshot stage's OWN channel with
|
|
29
|
+
* role `prior` — one deterministic hop BEFORE the matching fix stage inside the
|
|
30
|
+
* existing fix loop (plan-grade/plan-confirm → plan-snapshot → plan-fix; code
|
|
31
|
+
* twin). Overwritten each fix round, so the prior always reflects the
|
|
32
|
+
* pre-CURRENT-fix content; the re-grade reads it via `latestPriorContent` to
|
|
33
|
+
* decide whether the amend was surgical. `who` attributes the halt when no plan
|
|
34
|
+
* is published. `kind: "artifact-md"` is the honest kind — the prior IS a copy
|
|
35
|
+
* of an artifact-md plan body (the kind plans carry under `rpivBucketOutcome`).
|
|
36
|
+
*/
|
|
37
|
+
const snapshotLatestPlan =
|
|
38
|
+
(who: string) =>
|
|
39
|
+
({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
|
|
40
|
+
const latest = latestFsArtifact(state, "plans");
|
|
41
|
+
if (latest?.handle.kind !== "fs") {
|
|
42
|
+
throw haltPreflight(
|
|
43
|
+
who,
|
|
44
|
+
`${who}: no plan to snapshot`,
|
|
45
|
+
`${who}: no fs artifact on the 'plans' channel — the plan must be graded before the snapshot stage`,
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
const src = isAbsolute(latest.handle.path) ? latest.handle.path : join(cwd, latest.handle.path);
|
|
49
|
+
const priorRel = join(PRIOR_DIR, basename(latest.handle.path));
|
|
50
|
+
mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
|
|
51
|
+
copyFileSync(src, join(cwd, priorRel));
|
|
52
|
+
return {
|
|
53
|
+
kind: "artifact-md",
|
|
54
|
+
artifacts: [{ handle: { kind: "fs", path: priorRel }, role: "prior" }],
|
|
55
|
+
data: { snapshot_of: handleToString(latest.handle) },
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Snapshot the graded plan before `plan-fix` amends it (plan gate). */
|
|
60
|
+
const planSnapshot = snapshotLatestPlan("plan-snapshot");
|
|
61
|
+
/** Snapshot the graded plan before `code-fix` amends it (code gate). */
|
|
62
|
+
const codeSnapshot = snapshotLatestPlan("code-snapshot");
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A duty demotion stamped onto a verdict's on-disk JSON — the legible record
|
|
66
|
+
* that a risk ruling the panel marked `pass: true` was demoted to effective-
|
|
67
|
+
* fail by the evidence or verify-at-implement duty. One entry per FAILING
|
|
68
|
+
* duty (a ruling authored as BOTH mechanics AND verify-at-implement can carry
|
|
69
|
+
* two). `reason` is decision-code-free prose (no run/phase ids, no absolute
|
|
70
|
+
* line numbers) naming the duty that failed, so disk readers (amend, confirm
|
|
71
|
+
* `--prior`) can tell a grader-side demotion from a genuine `pass: false`.
|
|
72
|
+
*/
|
|
73
|
+
interface RiskDutyDemotion {
|
|
74
|
+
id: string;
|
|
75
|
+
duty: "evidence-format" | "procedure-owner";
|
|
76
|
+
reason: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Materialize the duty demotion as legible on-disk data. After a grade round,
|
|
81
|
+
* each latest-per-dimension verdict whose `pass: true` rulings were demoted by
|
|
82
|
+
* the evidence or verify-at-implement duty gets a `risk_duty_demotions` array
|
|
83
|
+
* written onto its on-disk JSON IN PLACE — the one medium amend and confirm's
|
|
84
|
+
* `--prior` read. The verdict's own `pass` is NEVER flipped (every gate fold —
|
|
85
|
+
* `allRiskFlagsPass`/`dimensionsToRegrade`/`confirmDue` — consults
|
|
86
|
+
* `rulingEffectivePass` off in-memory `state.named`, which never re-reads the
|
|
87
|
+
* rewritten file, so gate outcomes are unchanged); the field is an additive,
|
|
88
|
+
* read-only signal for the disk readers.
|
|
89
|
+
*
|
|
90
|
+
* Modeled on `snapshotLatestPlan(who)` (a `ScriptFn` that side-effects AND
|
|
91
|
+
* returns an `Output`): it reads the PLAN-sourced duty triggers
|
|
92
|
+
* (`planAuthoredRisks`), iterates the EXACT verdict set amend keeps + confirm
|
|
93
|
+
* reads (`latestVerdictPerDimension(freshVerdicts(...))`), and rewrites each
|
|
94
|
+
* demoted verdict's fs handle in place. Writes ONLY when ≥1 demotion (a clean
|
|
95
|
+
* grade is a no-op — no needless reformat/mtime churn); each per-file
|
|
96
|
+
* read/parse/write is wrapped so a single unparseable/stale file is skipped
|
|
97
|
+
* (never halts the gate). Returns `{ demotions }` echoing `{dimension, id,
|
|
98
|
+
* duty, verdict}` for journal greppability. `channel` is the plan channel the
|
|
99
|
+
* risks + current artifact live on; `verdictChannel` is the grade's own
|
|
100
|
+
* verdict channel (plan-verdicts / code-verdicts).
|
|
101
|
+
*/
|
|
102
|
+
const demoteDuties =
|
|
103
|
+
(who: string, channel: string, verdictChannel: string) =>
|
|
104
|
+
({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
|
|
105
|
+
const risks = planAuthoredRisks(state, channel);
|
|
106
|
+
const current = latestArtifactPath(state, channel);
|
|
107
|
+
const demotions: { dimension: string; id: string; duty: RiskDutyDemotion["duty"]; verdict: string }[] = [];
|
|
108
|
+
for (const o of latestVerdictPerDimension(freshVerdicts(state.named[verdictChannel] ?? [], current)).values()) {
|
|
109
|
+
const handle = o.artifacts.find((a) => a.handle.kind === "fs")?.handle;
|
|
110
|
+
if (handle?.kind !== "fs") continue;
|
|
111
|
+
const dimRaw = (o.data as { dimension?: unknown } | undefined)?.dimension;
|
|
112
|
+
const dimension = typeof dimRaw === "string" ? dimRaw : "";
|
|
113
|
+
const perFile: RiskDutyDemotion[] = [];
|
|
114
|
+
for (const r of verdictRiskRulings(o)) {
|
|
115
|
+
const authored = risks.get(r.id);
|
|
116
|
+
// Only a `pass: true` ruling that rulingEffectivePass demotes — never a
|
|
117
|
+
// genuine `pass: false` (that is already a fail, not a demoted pass).
|
|
118
|
+
if (r.pass !== true || rulingEffectivePass(r, authored)) continue;
|
|
119
|
+
if (!evidenceCitesFileLine(r, authored)) {
|
|
120
|
+
perFile.push({
|
|
121
|
+
id: r.id,
|
|
122
|
+
duty: "evidence-format",
|
|
123
|
+
reason: "mechanics pass without an adjacent file:line citation in evidence",
|
|
124
|
+
});
|
|
125
|
+
demotions.push({ dimension, id: r.id, duty: "evidence-format", verdict: handleToString(handle) });
|
|
126
|
+
}
|
|
127
|
+
if (!procedureSatisfiesDuty(r, authored)) {
|
|
128
|
+
perFile.push({
|
|
129
|
+
id: r.id,
|
|
130
|
+
duty: "procedure-owner",
|
|
131
|
+
reason: "verify-at-implement pass without a concrete procedure and owner phase",
|
|
132
|
+
});
|
|
133
|
+
demotions.push({ dimension, id: r.id, duty: "procedure-owner", verdict: handleToString(handle) });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (perFile.length === 0) continue;
|
|
137
|
+
try {
|
|
138
|
+
const abs = isAbsolute(handle.path) ? handle.path : join(cwd, handle.path);
|
|
139
|
+
const json = JSON.parse(readFileSync(abs, "utf-8")) as Record<string, unknown>;
|
|
140
|
+
json.risk_duty_demotions = perFile;
|
|
141
|
+
writeFileSync(abs, JSON.stringify(json, null, 2));
|
|
142
|
+
} catch {
|
|
143
|
+
// skip-on-throw: an unparseable/stale verdict file never halts the gate.
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return { kind: "json", artifacts: [], data: { demotions, stage: who } };
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Stamp duty demotions onto the graded plan's verdicts after `plan-grade`, one
|
|
151
|
+
* deterministic hop before the gate routes (plan-grade → plan-demote → route).
|
|
152
|
+
* The code lane re-grades `plans` on `code-verdicts` (mirroring `codeSnapshot`).
|
|
153
|
+
*/
|
|
154
|
+
const planDemote = demoteDuties("plan-demote", "plans", "plan-verdicts");
|
|
155
|
+
const codeDemote = demoteDuties("code-demote", "plans", "code-verdicts");
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Coarse line-count backstop for the surgical-fix guard. The subset test
|
|
159
|
+
* (`touchedSections − HOUSEKEEPING ⊆ cited`) is the binding constraint — do
|
|
160
|
+
* NOT tighten this to compensate for a weak subset test.
|
|
161
|
+
*/
|
|
162
|
+
const NON_SURGICAL_DIFF_LINE_THRESHOLD = 60;
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Plan sections amend ALWAYS bumps without the fix touching their meaning —
|
|
166
|
+
* the pseudo-section `frontmatter` (via the `last_updated` field). Exempt from
|
|
167
|
+
* the "touched outside cited" test. Starts at `{frontmatter}` only; do not
|
|
168
|
+
* pre-widen (a genuinely-meaningful bookkeeping section would let a broad amend
|
|
169
|
+
* pass the subset test by touching it).
|
|
170
|
+
*/
|
|
171
|
+
const HOUSEKEEPING_SECTIONS: ReadonlySet<string> = new Set(["frontmatter"]);
|
|
172
|
+
|
|
173
|
+
/** Directory the snapshot stages copy the pre-fix plan into (basename-keyed). */
|
|
174
|
+
const PRIOR_DIR = ".rpiv/artifacts/priors";
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Map each line index to its plan-section name: the nearest preceding `## `
|
|
178
|
+
* heading — `## Phase N: …` normalizes to `phase N` (case-insensitive); any
|
|
179
|
+
* other heading is lowercased by tail — so touched-section keys and cited-section
|
|
180
|
+
* keys share one space. The frontmatter block (opening `---` through its closing
|
|
181
|
+
* `---`) is the pseudo-section `frontmatter`. Lines before the first heading and
|
|
182
|
+
* outside frontmatter map to `""` (which is neither housekeeping nor a `phase N`
|
|
183
|
+
* cite, so any change there is treated as out-of-scope).
|
|
184
|
+
*/
|
|
185
|
+
const sectionIndexOf = (lines: readonly string[]): string[] => {
|
|
186
|
+
const idx = new Array<string>(lines.length);
|
|
187
|
+
let current = "";
|
|
188
|
+
let inFrontmatter = lines[0]?.trim() === "---";
|
|
189
|
+
for (let i = 0; i < lines.length; i++) {
|
|
190
|
+
if (inFrontmatter) {
|
|
191
|
+
idx[i] = "frontmatter";
|
|
192
|
+
if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const m = /^##\s+(.*)$/.exec(lines[i]);
|
|
196
|
+
if (m) {
|
|
197
|
+
const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
|
|
198
|
+
current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
|
|
199
|
+
}
|
|
200
|
+
idx[i] = current;
|
|
201
|
+
}
|
|
202
|
+
return idx;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Line-level diff of `prior` vs `current` plan bodies, mapped to plan sections.
|
|
207
|
+
* Each changed line (a deletion from `prior` OR an insertion in `current` under
|
|
208
|
+
* an LCS match) is attributed to its nearest preceding `## ` heading in its own
|
|
209
|
+
* document. Returns the union of touched section keys and a coarse changed-line
|
|
210
|
+
* count (deletions + insertions). Insertion-tolerant: a 1-line insert does not
|
|
211
|
+
* mark every trailing line changed (the LCS keeps shared context matched).
|
|
212
|
+
*/
|
|
213
|
+
const sectionDiff = (prior: string, current: string): { touchedSections: Set<string>; changedLines: number } => {
|
|
214
|
+
const a = prior.split("\n");
|
|
215
|
+
const b = current.split("\n");
|
|
216
|
+
const sa = sectionIndexOf(a);
|
|
217
|
+
const sb = sectionIndexOf(b);
|
|
218
|
+
// LCS length table (bottom-up). Plans are a few hundred lines ⇒ O(n·m) trivial.
|
|
219
|
+
const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
|
|
220
|
+
for (let i = a.length - 1; i >= 0; i--) {
|
|
221
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
222
|
+
dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const touched = new Set<string>();
|
|
226
|
+
let changed = 0;
|
|
227
|
+
let i = 0;
|
|
228
|
+
let j = 0;
|
|
229
|
+
while (i < a.length && j < b.length) {
|
|
230
|
+
if (a[i] === b[j]) {
|
|
231
|
+
i++;
|
|
232
|
+
j++;
|
|
233
|
+
} else if (dp[i + 1][j] >= dp[i][j + 1]) {
|
|
234
|
+
touched.add(sa[i]); // a[i] deleted (present in prior, absent in current)
|
|
235
|
+
changed++;
|
|
236
|
+
i++;
|
|
237
|
+
} else {
|
|
238
|
+
touched.add(sb[j]); // b[j] inserted (present in current, absent in prior)
|
|
239
|
+
changed++;
|
|
240
|
+
j++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
while (i < a.length) {
|
|
244
|
+
touched.add(sa[i]);
|
|
245
|
+
changed++;
|
|
246
|
+
i++;
|
|
247
|
+
}
|
|
248
|
+
while (j < b.length) {
|
|
249
|
+
touched.add(sb[j]);
|
|
250
|
+
changed++;
|
|
251
|
+
j++;
|
|
252
|
+
}
|
|
253
|
+
return { touchedSections: touched, changedLines: changed };
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Plan sections cited by the FAILING dimensions' findings — extracted from each
|
|
258
|
+
* finding's `where` and `detail` (`Phase N` → `phase N`, lowercased). Preferred
|
|
259
|
+
* `where: "Phase 1 > lane-dock-editor.ts Edit 1"` → `phase 1`; a repo
|
|
260
|
+
* `path:line`-only `where` (and a detail with no `Phase N`) contributes NO plan
|
|
261
|
+
* section. Empty when no failing finding carries an extractable plan-section
|
|
262
|
+
* reference — fail-closed: the caller treats an empty cite set against any
|
|
263
|
+
* non-housekeeping touched section as out-of-scope (non-surgical).
|
|
264
|
+
*/
|
|
265
|
+
const citedSections = (latest: ReadonlyMap<string, Output>, pending: readonly string[]): Set<string> => {
|
|
266
|
+
const cited = new Set<string>();
|
|
267
|
+
for (const d of pending) {
|
|
268
|
+
const findings = (latest.get(d)?.data as { findings?: unknown } | undefined)?.findings;
|
|
269
|
+
if (!Array.isArray(findings)) continue;
|
|
270
|
+
for (const f of findings) {
|
|
271
|
+
if (f == null || typeof f !== "object") continue;
|
|
272
|
+
const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
|
|
273
|
+
const detail = typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
|
|
274
|
+
for (const text of [where, detail]) {
|
|
275
|
+
for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return cited;
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The prior-role `fs` artifact the snapshot stage published on `priorChannel`
|
|
284
|
+
* (undefined when the channel carries no prior — round 1 / first re-grade).
|
|
285
|
+
* Existence of the ENTRY is distinct from readability of the sidecar: an entry
|
|
286
|
+
* that exists but cannot be read still counts as "prior present" so the caller
|
|
287
|
+
* fails closed to a FULL roster rather than silently carrying forward.
|
|
288
|
+
*/
|
|
289
|
+
const priorArtifact = (state: RunView, priorChannel: string): Artifact | undefined => {
|
|
290
|
+
const entry = state.named[priorChannel]?.at(-1);
|
|
291
|
+
const prior = entry?.artifacts.find((a) => a.handle.kind === "fs" && a.role === "prior");
|
|
292
|
+
return prior?.handle.kind === "fs" ? prior : undefined;
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Read the prior sidecar's bytes off `priorChannel`. Returns `undefined` when
|
|
297
|
+
* the channel is empty, the prior artifact is not fs, OR the sidecar is
|
|
298
|
+
* unreadable — the caller treats `undefined` as fail-closed (non-surgical).
|
|
299
|
+
*/
|
|
300
|
+
const latestPriorContent = (state: RunView, priorChannel: string, cwd: string): string | undefined => {
|
|
301
|
+
const prior = priorArtifact(state, priorChannel);
|
|
302
|
+
if (prior?.handle.kind !== "fs") return undefined;
|
|
303
|
+
try {
|
|
304
|
+
return readArtifactFile(prior.handle.path, cwd);
|
|
305
|
+
} catch {
|
|
306
|
+
return undefined;
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* True ONLY when a readable prior exists AND the current plan's diff from it
|
|
312
|
+
* touches ONLY sections a failing finding cited (minus housekeeping) AND the
|
|
313
|
+
* changed-line count is within the coarse threshold. Every missing signal — no
|
|
314
|
+
* prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
|
|
315
|
+
* touched section no failing finding cited, or an over-threshold diff —
|
|
316
|
+
* collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
|
|
317
|
+
* when a prior is present, or carries forward when none is). `pending` is
|
|
318
|
+
* consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
|
|
319
|
+
* phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
|
|
320
|
+
* narrows on.
|
|
321
|
+
*/
|
|
322
|
+
const isSurgicalFix = (
|
|
323
|
+
state: RunView,
|
|
324
|
+
priorChannel: string,
|
|
325
|
+
cwd: string,
|
|
326
|
+
target: string,
|
|
327
|
+
latest: ReadonlyMap<string, Output>,
|
|
328
|
+
pending: readonly string[],
|
|
329
|
+
): boolean => {
|
|
330
|
+
const prior = latestPriorContent(state, priorChannel, cwd);
|
|
331
|
+
if (prior === undefined) return false;
|
|
332
|
+
let current: string;
|
|
333
|
+
try {
|
|
334
|
+
current = readArtifactFile(target, cwd);
|
|
335
|
+
} catch {
|
|
336
|
+
return false;
|
|
337
|
+
}
|
|
338
|
+
let diff: { touchedSections: Set<string>; changedLines: number };
|
|
339
|
+
try {
|
|
340
|
+
diff = sectionDiff(prior, current);
|
|
341
|
+
} catch {
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
const cited = citedSections(latest, pending);
|
|
345
|
+
for (const section of diff.touchedSections) {
|
|
346
|
+
if (HOUSEKEEPING_SECTIONS.has(section)) continue;
|
|
347
|
+
if (!cited.has(section)) return false;
|
|
348
|
+
}
|
|
349
|
+
return diff.changedLines <= NON_SURGICAL_DIFF_LINE_THRESHOLD;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
export { codeDemote, codeSnapshot, isSurgicalFix, planDemote, planSnapshot, priorArtifact };
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The post-implement reconciliation backstop: `#### Reconciliation` directive
|
|
3
|
+
* parsing and write-restricted application.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { basename, isAbsolute, join } from "node:path";
|
|
7
|
+
import { handleToString, type Output, type ScriptContext } from "@juicesharp/rpiv-workflow/registration";
|
|
8
|
+
import {
|
|
9
|
+
containedPath,
|
|
10
|
+
haltPreflight,
|
|
11
|
+
latestFsArtifact,
|
|
12
|
+
readArtifactFile,
|
|
13
|
+
TEST_PATH_RE,
|
|
14
|
+
VERDICT_DIR,
|
|
15
|
+
VERDICT_FAIL_SCORE,
|
|
16
|
+
VERDICT_PASS_SCORE,
|
|
17
|
+
} from "./shared.js";
|
|
18
|
+
|
|
19
|
+
/**
|
|
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).
|
|
108
|
+
*/
|
|
109
|
+
const applyReconciliationDirectives = (
|
|
110
|
+
directives: readonly ReconciliationDirective[],
|
|
111
|
+
cwd: string,
|
|
112
|
+
): { detail: string; where: string }[] => {
|
|
113
|
+
const findings: { detail: string; where: string }[] = [];
|
|
114
|
+
// Apply directives, write-restricted to test-expectation files.
|
|
115
|
+
for (const d of directives) {
|
|
116
|
+
if (!isTestPath(d.target)) {
|
|
117
|
+
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`,
|
|
119
|
+
where: d.target,
|
|
120
|
+
});
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const abs = containedPath(cwd, d.target);
|
|
124
|
+
if (abs === undefined) {
|
|
125
|
+
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`,
|
|
127
|
+
where: d.target,
|
|
128
|
+
});
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
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
|
+
});
|
|
151
|
+
}
|
|
152
|
+
} catch (err) {
|
|
153
|
+
findings.push({
|
|
154
|
+
detail: `reconcile: could not apply directive to ${d.target} — ${err instanceof Error ? err.message : String(err)}`,
|
|
155
|
+
where: d.target,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return findings;
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Deterministic post-implement reconciliation — the coherence backstop the
|
|
164
|
+
* parallel implement lane needs. Sibling phases run concurrently in one tree;
|
|
165
|
+
* 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`:
|
|
170
|
+
*
|
|
171
|
+
* 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`
|
|
177
|
+
* whose replacement is ALSO absent is a finding (reconcile does not guess);
|
|
178
|
+
* 4. appends a timestamped `### Reconciliation Log (<iso>)` under the plan's
|
|
179
|
+
* `## Synthesis Notes` (best-effort bookkeeping write — non-fatal);
|
|
180
|
+
* 5. emits one `{ dimension: "reconcile" }` verdict, basename-keyed off the plan
|
|
181
|
+
* ⇒ idempotent across fix rounds (the verdict file is overwritten each round).
|
|
182
|
+
*
|
|
183
|
+
* Reconcile deliberately does NOT re-execute the plan's `#### Automated
|
|
184
|
+
* Verification:` commands. That re-run (bare `execFileSync`, no shell, exit-0
|
|
185
|
+
* contract) was measured across the full run history at zero genuine catches and
|
|
186
|
+
* a 100% false-positive finding rate — stale cross-phase presence probes, agent-
|
|
187
|
+
* shell-only binaries (`rg`), prose greps — each halting a finished run at a
|
|
188
|
+
* fail route with no fix arm. The downstream `validate` stage runs the same AV
|
|
189
|
+
* commands as an agent, with a real shell and the judgment to tell a legitimate
|
|
190
|
+
* post-rename mismatch from actual plan-vs-tree drift.
|
|
191
|
+
*
|
|
192
|
+
* The route is the `match("verdict", …, { from: "reconcile" })` gate idiom — pass ⇒
|
|
193
|
+
* validate, fail/missing ⇒ STOP (no fallback), mirroring `implementScopeCheck`.
|
|
194
|
+
* Mirrors `implementScopeCheck`'s `ScriptContext` shape, basename-keyed verdict
|
|
195
|
+
* path, and `dimension`/`pass`/`verdict`/`score`/`severity` data shape. `reads:
|
|
196
|
+
* ["plans"]` only — reconcile consumes no run-start `goal` baseline (the scope
|
|
197
|
+
* floor already proved the write-set; reconcile's own writes are directive targets
|
|
198
|
+
* + the plan bookkeeping). The `from` form suppresses the READS_DATA outputSchema
|
|
199
|
+
* lint, so no schema is declared (matching `slice-check`/`plan-cite-check`/
|
|
200
|
+
* `implement-scope-check`).
|
|
201
|
+
*/
|
|
202
|
+
const reconcile = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
|
|
203
|
+
const latest = latestFsArtifact(state, "plans");
|
|
204
|
+
if (latest?.handle.kind !== "fs") {
|
|
205
|
+
throw haltPreflight(
|
|
206
|
+
"reconcile",
|
|
207
|
+
"reconcile: no plan to reconcile",
|
|
208
|
+
"reconcile: no fs artifact on the 'plans' channel — implement / scope-check must run before reconcile",
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
const planPath = latest.handle.path;
|
|
212
|
+
const planAbs = isAbsolute(planPath) ? planPath : join(cwd, planPath);
|
|
213
|
+
const findings: { detail: string; where: string }[] = [];
|
|
214
|
+
|
|
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.
|
|
218
|
+
let body = "";
|
|
219
|
+
let directives: ReconciliationDirective[] = [];
|
|
220
|
+
let malformed: string[] = [];
|
|
221
|
+
try {
|
|
222
|
+
body = readArtifactFile(planPath, cwd);
|
|
223
|
+
const parsed = reconciliationRecords(body);
|
|
224
|
+
directives = parsed.directives;
|
|
225
|
+
malformed = parsed.malformed;
|
|
226
|
+
} catch (err) {
|
|
227
|
+
findings.push({
|
|
228
|
+
detail: `reconcile: could not read or parse the plan ${planPath} — ${err instanceof Error ? err.message : String(err)}`,
|
|
229
|
+
where: planPath,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
for (const m of malformed) {
|
|
233
|
+
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}`,
|
|
235
|
+
where: "reconciliation-directive",
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
findings.push(...applyReconciliationDirectives(directives, cwd));
|
|
240
|
+
|
|
241
|
+
// Best-effort bookkeeping: append a timestamped log under ## Synthesis Notes.
|
|
242
|
+
// Non-fatal — a write failure here is silent (the verdict below is the signal).
|
|
243
|
+
if (body) {
|
|
244
|
+
try {
|
|
245
|
+
const stamp = new Date().toISOString();
|
|
246
|
+
const verdict = findings.length === 0 ? "pass" : "fail";
|
|
247
|
+
const logBlock = `\n### Reconciliation Log (${stamp})\nApplied ${directives.length} directive(s); ${findings.length} finding(s); verdict: ${verdict}.\n`;
|
|
248
|
+
const heading = "## Synthesis Notes";
|
|
249
|
+
const idx = body.indexOf(heading);
|
|
250
|
+
let updated: string;
|
|
251
|
+
if (idx >= 0) {
|
|
252
|
+
const lineEnd = body.indexOf("\n", idx);
|
|
253
|
+
const at = lineEnd >= 0 ? lineEnd + 1 : body.length;
|
|
254
|
+
updated = body.slice(0, at) + logBlock + body.slice(at);
|
|
255
|
+
} else {
|
|
256
|
+
updated = `${body.replace(/\s+$/, "")}\n${logBlock}`;
|
|
257
|
+
}
|
|
258
|
+
writeFileSync(planAbs, updated, "utf-8");
|
|
259
|
+
} catch {
|
|
260
|
+
// bookkeeping — ignore
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const pass = findings.length === 0;
|
|
265
|
+
const data = {
|
|
266
|
+
dimension: "reconcile",
|
|
267
|
+
pass,
|
|
268
|
+
verdict: pass ? "pass" : "fail",
|
|
269
|
+
score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
|
|
270
|
+
severity: pass ? "none" : "high",
|
|
271
|
+
artifact: handleToString(latest.handle),
|
|
272
|
+
findings,
|
|
273
|
+
feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
|
|
274
|
+
};
|
|
275
|
+
// Basename-keyed off the latest plan ⇒ idempotent across fix rounds (mirrors
|
|
276
|
+
// implementScopeCheck / planCitationCheck, NOT round-stamped like grade).
|
|
277
|
+
const rel = join(VERDICT_DIR, `reconcile__${basename(planPath, ".md")}.json`);
|
|
278
|
+
mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
|
|
279
|
+
writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
|
|
280
|
+
return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
export { reconcile };
|