@juicesharp/rpiv-pi 2.7.1 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/docs/architecture.md +3 -3
- package/docs/skills.md +8 -6
- package/docs/workflows.md +3 -3
- package/extensions/rpiv-core/agent-enablement.ts +164 -0
- package/extensions/rpiv-core/agents.ts +98 -12
- package/extensions/rpiv-core/built-in-workflows.ts +373 -142
- package/extensions/rpiv-core/built-ins/gates.ts +38 -15
- package/extensions/rpiv-core/built-ins/goal-baseline.ts +43 -1
- package/extensions/rpiv-core/built-ins/grade-panel.ts +98 -29
- package/extensions/rpiv-core/built-ins/index.ts +1 -0
- package/extensions/rpiv-core/built-ins/priors.ts +208 -38
- package/extensions/rpiv-core/built-ins/reconcile-directives.d.mts +29 -0
- package/extensions/rpiv-core/built-ins/reconcile-directives.mjs +338 -0
- package/extensions/rpiv-core/built-ins/reconcile.ts +88 -130
- package/extensions/rpiv-core/built-ins/slices.ts +5 -1
- package/extensions/rpiv-core/frontmatter.ts +22 -0
- package/extensions/rpiv-core/lane-relay-ui.ts +25 -1
- package/extensions/rpiv-core/models-config.ts +86 -6
- package/extensions/rpiv-core/outcome-derivation.ts +1 -0
- package/extensions/rpiv-core/package-checks.ts +13 -0
- package/extensions/rpiv-core/pipeline-pointer.ts +1 -1
- package/extensions/rpiv-core/workflow-execution-host.ts +3 -2
- package/package.json +3 -3
- package/skills/_shared/reconcile-lint.mjs +125 -0
- package/skills/acceptance/SKILL.md +123 -0
- package/skills/elaborate/SKILL.md +3 -3
- package/skills/grade/SKILL.md +8 -7
- package/skills/implement/SKILL.md +17 -2
- package/skills/quick-plan/SKILL.md +19 -2
- package/skills/research/SKILL.md +28 -1
- package/skills/slice/SKILL.md +4 -4
- package/skills/synthesize/SKILL.md +1 -1
- package/skills/validate/SKILL.md +11 -5
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
latestVerdictPerDimension,
|
|
19
19
|
planAuthoredRisks,
|
|
20
20
|
procedureSatisfiesDuty,
|
|
21
|
+
type RiskRecord,
|
|
21
22
|
rulingEffectivePass,
|
|
22
23
|
verdictRiskRulings,
|
|
23
24
|
} from "./gates.js";
|
|
@@ -186,16 +187,31 @@ const sectionIndexOf = (lines: readonly string[]): string[] => {
|
|
|
186
187
|
const idx = new Array<string>(lines.length);
|
|
187
188
|
let current = "";
|
|
188
189
|
let inFrontmatter = lines[0]?.trim() === "---";
|
|
190
|
+
let inFence = false;
|
|
189
191
|
for (let i = 0; i < lines.length; i++) {
|
|
190
192
|
if (inFrontmatter) {
|
|
191
193
|
idx[i] = "frontmatter";
|
|
192
194
|
if (i > 0 && lines[i].trim() === "---") inFrontmatter = false;
|
|
193
195
|
continue;
|
|
194
196
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
197
|
+
// Fence-aware: a `## ` line INSIDE a fenced code block is content, not a
|
|
198
|
+
// heading — build plans routinely embed markdown edits (a CHANGELOG
|
|
199
|
+
// snippet's `## [Unreleased]`), and keying those as sections
|
|
200
|
+
// manufactured phantom touched keys no finding could ever cite
|
|
201
|
+
// (observed live: run b307's code-fix went broad on the phantom
|
|
202
|
+
// `[unreleased]` from an embedded changelog block). Fenced lines
|
|
203
|
+
// attribute to the enclosing section.
|
|
204
|
+
if (/^\s*```/.test(lines[i])) {
|
|
205
|
+
inFence = !inFence;
|
|
206
|
+
idx[i] = current;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (!inFence) {
|
|
210
|
+
const m = /^##\s+(.*)$/.exec(lines[i]);
|
|
211
|
+
if (m) {
|
|
212
|
+
const ph = /^Phase\s+(\d+)/i.exec(m[1].trim());
|
|
213
|
+
current = ph ? `phase ${ph[1]}` : m[1].trim().toLowerCase();
|
|
214
|
+
}
|
|
199
215
|
}
|
|
200
216
|
idx[i] = current;
|
|
201
217
|
}
|
|
@@ -254,27 +270,78 @@ const sectionDiff = (prior: string, current: string): { touchedSections: Set<str
|
|
|
254
270
|
};
|
|
255
271
|
|
|
256
272
|
/**
|
|
257
|
-
* Plan sections cited by the FAILING dimensions'
|
|
258
|
-
*
|
|
259
|
-
* `
|
|
260
|
-
*
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
273
|
+
* Plan sections cited by the FAILING dimensions' verdicts, from THREE sources:
|
|
274
|
+
*
|
|
275
|
+
* 1. `Phase N` mentions anywhere in a finding's `where` or `detail`
|
|
276
|
+
* (`phase N`, the original extraction).
|
|
277
|
+
* 2. The `where`'s LEADING SEGMENT as a section heading: the grade skill's
|
|
278
|
+
* `where` convention is "`path:line` or a section heading", and panel
|
|
279
|
+
* wheres read "## Phase 1 > Success Criteria > …" — the text before the
|
|
280
|
+
* first `>` names the plan section, normalized exactly as
|
|
281
|
+
* `sectionIndexOf` keys it (leading `#`s stripped, `Phase N …` →
|
|
282
|
+
* `phase N`, else lowercased). A repo path (a `/` or a `.ext:NN` tail)
|
|
283
|
+
* is a code cite, never a plan section. Before this, `citedSections`
|
|
284
|
+
* could ONLY emit `phase N` keys while `touchedSections` emits every
|
|
285
|
+
* heading key — so a finding citing "Out of Scope" or "Risk Flags"
|
|
286
|
+
* contributed nothing and any amend touching those sections was
|
|
287
|
+
* structurally guaranteed non-surgical (the observed always-broad).
|
|
288
|
+
* 3. Failing risk RULINGS (the reason correctness re-grades when findings
|
|
289
|
+
* are empty): a ruling's repair edits the plan's `## Risk Flags` entry
|
|
290
|
+
* and, for a `verify-at-implement` deferral, the owner phase — cite
|
|
291
|
+
* both, so a risk-driven fix loop is not broad by construction.
|
|
292
|
+
*
|
|
293
|
+
* Still fail-closed: an empty cite set against any non-housekeeping touched
|
|
294
|
+
* section stays out-of-scope (non-surgical).
|
|
264
295
|
*/
|
|
265
|
-
const citedSections = (
|
|
296
|
+
const citedSections = (
|
|
297
|
+
latest: ReadonlyMap<string, Output>,
|
|
298
|
+
pending: readonly string[],
|
|
299
|
+
risks: ReadonlyMap<string, RiskRecord>,
|
|
300
|
+
): Set<string> => {
|
|
266
301
|
const cited = new Set<string>();
|
|
302
|
+
const addHeading = (raw: string): void => {
|
|
303
|
+
const cleaned = raw.replace(/^#+\s*/, "").trim();
|
|
304
|
+
if (cleaned.length === 0) return;
|
|
305
|
+
const ph = /^Phase\s+(\d+)/i.exec(cleaned);
|
|
306
|
+
if (ph) {
|
|
307
|
+
cited.add(`phase ${ph[1]}`);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
// A code cite, not a section: a tight path segment (`a/b`) or an
|
|
311
|
+
// `ext:NN` tail. A SPACED slash is prose punctuation ("Synthesis Notes
|
|
312
|
+
// / 'Adopted rider' bullet" — run d5a9), not a path.
|
|
313
|
+
if (/\S\/\S/.test(cleaned) || /\.\w+:\d+/.test(cleaned)) return;
|
|
314
|
+
cited.add(headingCore(cleaned).toLowerCase());
|
|
315
|
+
};
|
|
267
316
|
for (const d of pending) {
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
317
|
+
const o = latest.get(d);
|
|
318
|
+
const findings = (o?.data as { findings?: unknown } | undefined)?.findings;
|
|
319
|
+
if (Array.isArray(findings)) {
|
|
320
|
+
for (const f of findings) {
|
|
321
|
+
if (f == null || typeof f !== "object") continue;
|
|
322
|
+
const where = typeof (f as { where?: unknown }).where === "string" ? (f as { where: string }).where : "";
|
|
323
|
+
const detail =
|
|
324
|
+
typeof (f as { detail?: unknown }).detail === "string" ? (f as { detail: string }).detail : "";
|
|
325
|
+
for (const text of [where, detail]) {
|
|
326
|
+
for (const m of text.matchAll(/Phase\s+(\d+)/gi)) cited.add(`phase ${m[1]}`);
|
|
327
|
+
// A `## Heading` mention ANYWHERE in the finding cites that
|
|
328
|
+
// section — the observed shape (opendots run d5a9) is a
|
|
329
|
+
// completeness finding whose remedy is CREATING a section,
|
|
330
|
+
// named only in a parenthetical ("... (missing ## Whole-Plan
|
|
331
|
+
// Verification section)"): the amend's creation of that very
|
|
332
|
+
// section must count as cited.
|
|
333
|
+
for (const m of text.matchAll(/##\s+([A-Za-z][^#>\n]*)/g)) addHeading(m[1]);
|
|
334
|
+
}
|
|
335
|
+
addHeading(where.split(">")[0] ?? "");
|
|
276
336
|
}
|
|
277
337
|
}
|
|
338
|
+
if (!o) continue;
|
|
339
|
+
for (const r of verdictRiskRulings(o)) {
|
|
340
|
+
if (rulingEffectivePass(r, risks.get(r.id))) continue;
|
|
341
|
+
cited.add("risk flags");
|
|
342
|
+
const owner = risks.get(r.id)?.owner;
|
|
343
|
+
if (typeof owner === "number") cited.add(`phase ${owner}`);
|
|
344
|
+
}
|
|
278
345
|
}
|
|
279
346
|
return cited;
|
|
280
347
|
};
|
|
@@ -308,45 +375,148 @@ const latestPriorContent = (state: RunView, priorChannel: string, cwd: string):
|
|
|
308
375
|
};
|
|
309
376
|
|
|
310
377
|
/**
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
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.
|
|
378
|
+
* The heading CORE of a section reference — the text before the first
|
|
379
|
+
* descriptor separator (an em/en-dash clause, a spaced slash, a
|
|
380
|
+
* parenthetical). Real headings and finding wheres both carry descriptor
|
|
381
|
+
* suffixes ("Whole-Plan Verification (owned by validate — not any phase)",
|
|
382
|
+
* "Synthesis Notes — 'Adopted rider' bullet"); the core is the comparable
|
|
383
|
+
* identity.
|
|
321
384
|
*/
|
|
322
|
-
const
|
|
385
|
+
const headingCore = (s: string): string => s.split(/ \(|\s+—\s+|\s+–\s+|\s+\/\s+/)[0]?.trim() ?? s;
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* True when a touched section is covered by the cite set. `phase N` keys
|
|
389
|
+
* match EXACTLY (prefix matching would let "phase 1" cover "phase 10").
|
|
390
|
+
* Non-phase keys match on a word-boundary PREFIX in EITHER direction —
|
|
391
|
+
* observed both ways in run d5a9: a cited where carries a descriptor suffix
|
|
392
|
+
* ("synthesis notes — 'adopted rider' bullet") that must cover the bare
|
|
393
|
+
* touched heading key ("synthesis notes"), and a real heading carries its own
|
|
394
|
+
* suffix ("whole-plan verification (owned by validate — not any phase)") that
|
|
395
|
+
* a bare cite ("whole-plan verification") must cover. The boundary check
|
|
396
|
+
* (the next character must not be alphanumeric) keeps "notes" from covering
|
|
397
|
+
* "notes-extra".
|
|
398
|
+
*/
|
|
399
|
+
const sectionCovered = (section: string, cited: ReadonlySet<string>): boolean => {
|
|
400
|
+
if (cited.has(section)) return true;
|
|
401
|
+
if (/^phase \d+$/.test(section)) return false; // phase keys are exact-only
|
|
402
|
+
const core = headingCore(section);
|
|
403
|
+
const boundary = (long: string, short: string): boolean =>
|
|
404
|
+
short.length > 0 &&
|
|
405
|
+
long.startsWith(short) &&
|
|
406
|
+
(long.length === short.length || !/[a-z0-9]/i.test(long[short.length] ?? ""));
|
|
407
|
+
for (const c of cited) {
|
|
408
|
+
if (/^phase \d+$/.test(c)) continue;
|
|
409
|
+
if (boundary(c, section) || boundary(section, c) || boundary(c, core) || boundary(core, c)) return true;
|
|
410
|
+
}
|
|
411
|
+
return false;
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
/** The surgical-fix guard's decision, with the condition that decided it. */
|
|
415
|
+
interface SurgicalDecision {
|
|
416
|
+
surgical: boolean;
|
|
417
|
+
/** Prose naming the deciding condition — the instrumentation channel. */
|
|
418
|
+
reason: string;
|
|
419
|
+
changedLines?: number;
|
|
420
|
+
touchedSections?: string[];
|
|
421
|
+
citedSections?: string[];
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Persist the guard's decision beside the prior sidecar as
|
|
426
|
+
* `<plan-basename>.decision.json` — the instrumentation the always-broad
|
|
427
|
+
* diagnosis lacked: real runs showed every observed fix loop re-grading the
|
|
428
|
+
* full roster, and the surviving artifacts could not say WHICH fail-closed
|
|
429
|
+
* condition tripped (the plan file is later mutated by splice/reconcile, so
|
|
430
|
+
* the decision is unreplayable post-hoc). Best-effort and idempotent: the
|
|
431
|
+
* guard is called from a fanout `units()` fn, which the resume fold re-runs
|
|
432
|
+
* under THE REPLAY CONTRACT — same replayed inputs ⇒ same bytes ⇒ the rewrite
|
|
433
|
+
* is a no-op; a write failure never affects the decision.
|
|
434
|
+
*/
|
|
435
|
+
const recordDecision = (cwd: string, target: string, decision: SurgicalDecision): void => {
|
|
436
|
+
try {
|
|
437
|
+
mkdirSync(join(cwd, PRIOR_DIR), { recursive: true });
|
|
438
|
+
writeFileSync(join(cwd, PRIOR_DIR, `${basename(target)}.decision.json`), JSON.stringify(decision, null, 2));
|
|
439
|
+
} catch {
|
|
440
|
+
// instrumentation only — never let a write failure change the routing
|
|
441
|
+
}
|
|
442
|
+
};
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* The guard body — every missing signal collapses to non-surgical with a
|
|
446
|
+
* `reason` naming the condition (see `isSurgicalFix` for the contract).
|
|
447
|
+
*/
|
|
448
|
+
const decideSurgicalFix = (
|
|
323
449
|
state: RunView,
|
|
324
450
|
priorChannel: string,
|
|
325
451
|
cwd: string,
|
|
326
452
|
target: string,
|
|
327
453
|
latest: ReadonlyMap<string, Output>,
|
|
328
454
|
pending: readonly string[],
|
|
329
|
-
|
|
455
|
+
risks: ReadonlyMap<string, RiskRecord>,
|
|
456
|
+
): SurgicalDecision => {
|
|
330
457
|
const prior = latestPriorContent(state, priorChannel, cwd);
|
|
331
|
-
if (prior === undefined) return false;
|
|
458
|
+
if (prior === undefined) return { surgical: false, reason: "no readable prior sidecar" };
|
|
332
459
|
let current: string;
|
|
333
460
|
try {
|
|
334
461
|
current = readArtifactFile(target, cwd);
|
|
335
462
|
} catch {
|
|
336
|
-
return false;
|
|
463
|
+
return { surgical: false, reason: "current plan unreadable" };
|
|
337
464
|
}
|
|
338
465
|
let diff: { touchedSections: Set<string>; changedLines: number };
|
|
339
466
|
try {
|
|
340
467
|
diff = sectionDiff(prior, current);
|
|
341
468
|
} catch {
|
|
342
|
-
return false;
|
|
469
|
+
return { surgical: false, reason: "section diff threw" };
|
|
343
470
|
}
|
|
344
|
-
const cited = citedSections(latest, pending);
|
|
471
|
+
const cited = citedSections(latest, pending, risks);
|
|
472
|
+
const base = {
|
|
473
|
+
changedLines: diff.changedLines,
|
|
474
|
+
touchedSections: [...diff.touchedSections].sort(),
|
|
475
|
+
citedSections: [...cited].sort(),
|
|
476
|
+
};
|
|
345
477
|
for (const section of diff.touchedSections) {
|
|
346
478
|
if (HOUSEKEEPING_SECTIONS.has(section)) continue;
|
|
347
|
-
if (!
|
|
479
|
+
if (!sectionCovered(section, cited)) {
|
|
480
|
+
return { surgical: false, reason: `touched section no failing verdict cited: ${section}`, ...base };
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (diff.changedLines > NON_SURGICAL_DIFF_LINE_THRESHOLD) {
|
|
484
|
+
return {
|
|
485
|
+
surgical: false,
|
|
486
|
+
reason: `changed lines ${diff.changedLines} over threshold ${NON_SURGICAL_DIFF_LINE_THRESHOLD}`,
|
|
487
|
+
...base,
|
|
488
|
+
};
|
|
348
489
|
}
|
|
349
|
-
return
|
|
490
|
+
return { surgical: true, reason: "touched sections all cited, within threshold", ...base };
|
|
491
|
+
};
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* True ONLY when a readable prior exists AND the current plan's diff from it
|
|
495
|
+
* touches ONLY sections a failing verdict cited (minus housekeeping) AND the
|
|
496
|
+
* changed-line count is within the coarse threshold. Every missing signal — no
|
|
497
|
+
* prior, unreadable sidecar, unreadable current plan, a diff/parse throw, a
|
|
498
|
+
* touched section no failing verdict cited, or an over-threshold diff —
|
|
499
|
+
* collapses to `false` (fail-closed ⇒ the caller re-grades the full roster
|
|
500
|
+
* when a prior is present, or carries forward when none is). `pending` is
|
|
501
|
+
* consumed as-is: whatever `dimensionsToRegrade` ruled still-blocking (after
|
|
502
|
+
* phase 3's `rulingEffectivePass` clause-3 rewrite) is the set this guard
|
|
503
|
+
* narrows on. `risks` is the plan-authored flag map — ruling-derived cites
|
|
504
|
+
* (see `citedSections`) need the owner phases. Every call persists its
|
|
505
|
+
* decision + tripped condition beside the prior (`recordDecision`), so a
|
|
506
|
+
* future always-broad report names the condition instead of guessing.
|
|
507
|
+
*/
|
|
508
|
+
const isSurgicalFix = (
|
|
509
|
+
state: RunView,
|
|
510
|
+
priorChannel: string,
|
|
511
|
+
cwd: string,
|
|
512
|
+
target: string,
|
|
513
|
+
latest: ReadonlyMap<string, Output>,
|
|
514
|
+
pending: readonly string[],
|
|
515
|
+
risks: ReadonlyMap<string, RiskRecord>,
|
|
516
|
+
): boolean => {
|
|
517
|
+
const decision = decideSurgicalFix(state, priorChannel, cwd, target, latest, pending, risks);
|
|
518
|
+
recordDecision(cwd, target, decision);
|
|
519
|
+
return decision.surgical;
|
|
350
520
|
};
|
|
351
521
|
|
|
352
522
|
export { codeDemote, codeSnapshot, isSurgicalFix, planDemote, planSnapshot, priorArtifact };
|
|
@@ -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 };
|