@juicesharp/rpiv-pi 2.6.3 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/docs/workflows.md +1 -1
  2. package/extensions/rpiv-core/agents.ts +10 -13
  3. package/extensions/rpiv-core/artifact-collector.ts +111 -6
  4. package/extensions/rpiv-core/bash-timeout.ts +12 -2
  5. package/extensions/rpiv-core/built-in-workflows.ts +233 -3514
  6. package/extensions/rpiv-core/built-ins/citations.ts +357 -0
  7. package/extensions/rpiv-core/built-ins/gates.ts +613 -0
  8. package/extensions/rpiv-core/built-ins/goal-baseline.ts +269 -0
  9. package/extensions/rpiv-core/built-ins/grade-panel.ts +199 -0
  10. package/extensions/rpiv-core/built-ins/index.ts +46 -0
  11. package/extensions/rpiv-core/built-ins/plan-cite.ts +219 -0
  12. package/extensions/rpiv-core/built-ins/plan-phases.ts +424 -0
  13. package/extensions/rpiv-core/built-ins/priors.ts +352 -0
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +283 -0
  15. package/extensions/rpiv-core/built-ins/scope-checks.ts +378 -0
  16. package/extensions/rpiv-core/built-ins/shared.ts +17 -1
  17. package/extensions/rpiv-core/built-ins/slice-checks.ts +420 -0
  18. package/extensions/rpiv-core/built-ins/slices.ts +288 -0
  19. package/extensions/rpiv-core/constants.ts +5 -1
  20. package/extensions/rpiv-core/lane-console.ts +9 -2
  21. package/extensions/rpiv-core/lane-list.ts +10 -1
  22. package/extensions/rpiv-core/question-lifecycle.ts +2 -2
  23. package/extensions/rpiv-core/register-built-in-workflows.ts +2 -2
  24. package/extensions/rpiv-core/run-lane-registry.ts +83 -83
  25. package/package.json +2 -2
  26. package/skills/elaborate/SKILL.md +1 -1
  27. package/skills/grade/SKILL.md +1 -1
  28. package/skills/implement/SKILL.md +1 -0
  29. package/skills/plan/SKILL.md +3 -1
  30. package/skills/remediate/SKILL.md +1 -0
  31. package/skills/synthesize/SKILL.md +1 -0
  32. package/skills/validate/SKILL.md +25 -19
  33. package/skills/validate/templates/validation.md +1 -1
@@ -0,0 +1,378 @@
1
+ /**
2
+ * The lane scope floors: build's latest-plan variant and vet's full-history
3
+ * union variant, sharing one scope-verdict envelope — plus the deterministic
4
+ * `scope-quarantine` remedy arm the untracked-only verdict routes to.
5
+ */
6
+ import { mkdirSync, renameSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname, join } from "node:path";
8
+ import { handleToString, type Output, type ScriptContext } from "@juicesharp/rpiv-workflow/registration";
9
+ import { gitDirtyEntries, goalBaselinePath, readGoalBaseline, scopeExcess } from "./goal-baseline.js";
10
+ import { phaseFiles, planPhaseRecords, withTestTwins } from "./plan-phases.js";
11
+ import {
12
+ containedPath,
13
+ type FsArtifact,
14
+ haltPreflight,
15
+ latestFsArtifact,
16
+ readArtifactFile,
17
+ VERDICT_DIR,
18
+ VERDICT_FAIL_SCORE,
19
+ VERDICT_PASS_SCORE,
20
+ } from "./shared.js";
21
+
22
+ /**
23
+ * Union the per-phase `files:` write-set declared across the FULL `plans`
24
+ * channel history. vet's review-fix loop appends a DISTINCT non-superseding fix
25
+ * plan per iteration (a `produces` stage APPENDS to its named slot, and backward
26
+ * jumps don't reset channels), so a path a prior plan legitimately wrote is not
27
+ * excess against the latest plan — hence the union, not latest-only.
28
+ *
29
+ * Reads every fs artifact in every plan via `planPhaseRecords` + `phaseFiles`,
30
+ * skipping unreadable/unparseable plans (the union stays the sum of the
31
+ * parseable ones; a plan too malformed to parse is a `plan-cite-check`/
32
+ * `plan-fix` concern, not scope). `latest` is the FIRST fs artifact of the LAST
33
+ * plan carrying one (mirrors `latestFsArtifact`'s last-channel-entry / first-fs-
34
+ * artifact resolution) — it keys the basename-keyed verdict path + `artifact`
35
+ * field.
36
+ */
37
+ const unionDeclaredWriteSet = (
38
+ plans: readonly Output[],
39
+ cwd: string,
40
+ ): { declared: Set<string>; latest: FsArtifact | undefined } => {
41
+ const declared = new Set<string>();
42
+ let latest: FsArtifact | undefined;
43
+ for (const out of plans) {
44
+ // Per plan, capture its FIRST fs artifact as the `latest` candidate so the
45
+ // LAST plan with an fs artifact wins (mirrors `latestFsArtifact`'s
46
+ // `.at(-1)?.artifacts.find(kind==="fs")` — last channel entry, first fs
47
+ // artifact in it — which keys the verdict path + `artifact` field).
48
+ let firstFsInPlan: FsArtifact | undefined;
49
+ for (const a of out.artifacts) {
50
+ if (a.handle.kind !== "fs") continue; // fs-artifact filter
51
+ if (!firstFsInPlan) firstFsInPlan = a as FsArtifact;
52
+ const path = a.handle.path;
53
+ try {
54
+ const content = readArtifactFile(path, cwd);
55
+ for (const r of planPhaseRecords(content, "implement-scope-check", path)) {
56
+ for (const f of phaseFiles(r.entry)) declared.add(f);
57
+ }
58
+ } catch {
59
+ // Unreadable/unparseable plan: don't widen the declared set on error —
60
+ // the union stays the sum of the parseable plans. (A plan so malformed
61
+ // it can't be parsed is a `plan-cite-check`/`plan-fix` concern, not scope.)
62
+ }
63
+ }
64
+ if (firstFsInPlan) latest = firstFsInPlan;
65
+ }
66
+ return { declared, latest };
67
+ };
68
+
69
+ /**
70
+ * The scope floor's routing verdict, tiered by what a deterministic check can
71
+ * actually know about each excess path (mirroring the citation floor's
72
+ * advisory tiering — demote where a remedy or adjudicator exists, halt only on
73
+ * data integrity):
74
+ * - "pass" — no excess. Onward to reconcile.
75
+ * - "untracked-only" — EVERY excess path is a run-created untracked file
76
+ * (`??`): provably not in the run-start baseline, owned by no phase, and
77
+ * movable without losing a byte. Routed to the deterministic
78
+ * `scope-quarantine` arm, then re-checked.
79
+ * - "excess" — at least one TRACKED file was modified outside the
80
+ * declared write-set. The floor cannot distinguish benign churn (a
81
+ * lockfile touched by an install, a regenerated snapshot) from a real
82
+ * cross-phase stomp, so it no longer halts: the run continues to
83
+ * reconcile/validate and VALIDATE adjudicates the recorded findings (the
84
+ * `--scope` thread on `VALIDATE_GOAL_PROMPT` — the `--cite-check`
85
+ * pattern), forcing `verdict: fail` on any write it cannot explain.
86
+ * A missing/unexpected verdict still terminates at the route (STOP) — the
87
+ * same integrity clause every de-halting change has preserved.
88
+ */
89
+ type ScopeVerdict = "pass" | "untracked-only" | "excess";
90
+
91
+ /**
92
+ * Shared scope-verdict envelope for the two lane scope floors: the
93
+ * `{ dimension: "scope" }` data shape (carrying BOTH `pass` and the tiered
94
+ * `verdict` enum the route + validate adjudication read), the basename-keyed
95
+ * `VERDICT_DIR` write, and the published-output return shape. Basename-keyed,
96
+ * NOT round-stamped (unlike grade's timestamped slug): each fix-loop round
97
+ * overwrites the file — the route reads the accumulating channel, and on disk
98
+ * only the latest round's scope verdict matters; round-stamp here if a consumer
99
+ * ever needs the history. Severity mirrors the tier ("medium" untracked-only,
100
+ * "high" tracked excess) for TRAIL LEGIBILITY ONLY — no consumer folds it:
101
+ * routing reads `verdict`, and validate's adjudication reads `findings`.
102
+ */
103
+ const writeScopeVerdict = (
104
+ artifact: FsArtifact,
105
+ findings: { detail: string; where: string }[],
106
+ verdict: ScopeVerdict,
107
+ cwd: string,
108
+ ): Omit<Output, "meta"> => {
109
+ const pass = verdict === "pass";
110
+ const data = {
111
+ dimension: "scope",
112
+ pass,
113
+ verdict,
114
+ score: pass ? VERDICT_PASS_SCORE : VERDICT_FAIL_SCORE,
115
+ severity: pass ? "none" : verdict === "untracked-only" ? "medium" : "high",
116
+ artifact: handleToString(artifact.handle),
117
+ findings,
118
+ feedback: pass ? "" : findings.map((f) => f.detail).join(" "),
119
+ };
120
+ const rel = join(VERDICT_DIR, `implement-scope-check__${basename(artifact.handle.path, ".md")}.json`);
121
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
122
+ writeFileSync(join(cwd, rel), JSON.stringify(data, null, 2), "utf-8");
123
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data };
124
+ };
125
+
126
+ /**
127
+ * Partition the excess set by git's own tracking state and fold it to the
128
+ * tiered verdict: `??` is the only status code whose content cannot have
129
+ * overwritten anything a phase owns, so an all-untracked excess is the
130
+ * deterministically-remediable class and ANY tracked path escalates the whole
131
+ * verdict to "excess" (one stomp taints the tree; quarantining the untracked
132
+ * remainder wouldn't make it judgeable-clean).
133
+ *
134
+ * Input assumption, pinned: ONLY `??` counts as untracked. A STAGED new file
135
+ * ("A ") deliberately classifies as tracked excess — the conservative
136
+ * direction (staged work is adjudicated in place, never quarantined). Nothing
137
+ * in the lane stages files between the baseline snapshot and this floor today
138
+ * (the only `git add` is commit's, post-floor); revisit if that changes.
139
+ */
140
+ const foldScopeVerdict = (excess: readonly string[], untracked: ReadonlySet<string>): ScopeVerdict =>
141
+ excess.length === 0 ? "pass" : excess.every((p) => untracked.has(p)) ? "untracked-only" : "excess";
142
+
143
+ /** Per-path finding for the tiered verdict. The floor is workflow-agnostic, so
144
+ * each detail describes the TIER (what the path is and why it was flagged),
145
+ * never the route — what happens next (quarantine arm, validate adjudication,
146
+ * or a loop-less workflow's terminal stop) is the wiring workflow's edge, and
147
+ * baking a route into text persisted on disk would lie under any other wiring. */
148
+ const scopeFinding = (path: string, untracked: boolean): { detail: string; where: string } => ({
149
+ detail: untracked
150
+ ? `Run-created untracked file ${path} outside the plan's declared write-set (the union of every phase's 'files:'). Untracked excess is the deterministically-remediable tier: a workflow wiring the scope-quarantine arm MOVES it (never deletes) under .rpiv/tmp/scope-quarantine/ with a manifest naming the destination — a load-bearing file landing there means its phase forgot to declare it in 'files:'. In a loop-less workflow this verdict is terminal.`
151
+ : `Undeclared write ${path} — a TRACKED file is dirty outside the plan's declared write-set (the union of every phase's 'files:'). The implement lane runs sibling phases concurrently in one tree, so a phase that wrote outside its 'files:' may have stepped on a sibling's in-flight edit — or this is benign churn (a lockfile, a regenerated artifact) a declared phase's own commands produced. A deterministic floor cannot tell these apart, so the finding is recorded for the wiring workflow's adjudicator (build threads it to validate via --scope; vet's review loop sees the whole diff); an out-of-scope write the adjudicator cannot explain blocks. In a loop-less workflow this verdict is terminal.`,
152
+ where: path,
153
+ });
154
+
155
+ /**
156
+ * Deterministic lane-level scope floor — the structural backstop beneath the
157
+ * LLM quality gates. After build's `implement` lane runs (now dep-gated and, as
158
+ * of this phase's unpin, concurrent up to the host cap), this checks the working
159
+ * tree's dirty set against the plan's declared write-set (the union of every
160
+ * phase's `files:`, twin-expanded via `withTestTwins`): any dirty path the run
161
+ * wrote that is NOT in `declared`, NOT
162
+ * pre-existing at the run-start baseline, and NOT under a bookkeeping tree is a
163
+ * scope violation — a phase escaped the upstream write-scope discipline. The
164
+ * floor no longer halts on its own findings (see `ScopeVerdict`): untracked
165
+ * excess routes to the deterministic `scope-quarantine` arm; tracked excess is
166
+ * recorded and adjudicated downstream by validate. Only a missing/unexpected
167
+ * verdict remains terminal at the route.
168
+ *
169
+ * Reads the plan with the SAME inline shape `planCitationCheck(who)` uses —
170
+ * `latestFsArtifact(state,"plans")` + `readArtifactFile` + `planPhaseRecords` +
171
+ * Phase 1's `phaseFiles` — NOT Phase 2's `readPlanPhaseRecords(state,cwd,who)`,
172
+ * because this stage needs the plan HANDLE for the `artifact` field and the
173
+ * basename-keyed verdict path, which the `who`-attributed helper collapses. The
174
+ * baseline is the run-start snapshot on the `goal` channel (`goalBaselinePath`,
175
+ * the same reader `VALIDATE_GOAL_PROMPT` and `COMMIT_BASELINE_PROMPT` use); the
176
+ * dirty set is `git status --porcelain` (non-repo / git-missing ⇒ empty dirty ⇒
177
+ * pass — the lane degrades to unguarded rather than failing a non-repo run).
178
+ * Emits one `{ dimension: "scope" }` verdict, basename-keyed off the plan ⇒
179
+ * idempotent across the build loop.
180
+ *
181
+ * `data` carries a `pass` boolean (true only on `verdict: "pass"`) AND the
182
+ * tiered `verdict` enum (`ScopeVerdict`) the route branches on. The route is a
183
+ * `defineRoute` over the stage's own channel (a `match` cannot send two enum
184
+ * values — "pass" and "excess" — to the same `reconcile` target): "pass" and
185
+ * "excess" continue to reconcile, "untracked-only" takes the quarantine arm,
186
+ * and anything else (missing/corrupt verdict) returns STOP — the integrity
187
+ * clause every de-halting change has preserved. It is deliberately NOT the
188
+ * `allDimensionsPass` severity-floor fold: the tier is explicit in the enum,
189
+ * never inferred from severity. `readsData: false` (the route consults the
190
+ * channel, not the projected output), so no schema is declared on the script
191
+ * stage (matching `slice-check`/`plan-cite-check`).
192
+ */
193
+ const implementScopeCheck = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
194
+ const latest = latestFsArtifact(state, "plans");
195
+ if (latest?.handle.kind !== "fs") {
196
+ throw haltPreflight(
197
+ "implement-scope-check",
198
+ "implement-scope-check: no plan to scope-check",
199
+ "implement-scope-check: no fs artifact on the 'plans' channel — implement must run before the scope check",
200
+ );
201
+ }
202
+ const body = readArtifactFile(latest.handle.path, cwd);
203
+ const records = planPhaseRecords(body, "implement-scope-check", latest.handle.path);
204
+ // Declared write-set = union of every phase's `files:` (via `phaseFiles`),
205
+ // expanded with co-located test twins (`withTestTwins`) — a signature change
206
+ // in a declared file legitimately drags its twin's assertions along.
207
+ // A `files:`-less plan yields `[]` ⇒ `scopeExcess` returns `[]` ⇒ inert floor.
208
+ const declared = withTestTwins(records.flatMap((r) => phaseFiles(r.entry)));
209
+
210
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
211
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
212
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
213
+ const entries = gitDirtyEntries(cwd);
214
+
215
+ const excess = scopeExcess(
216
+ entries.map((e) => e.path),
217
+ baseline,
218
+ declared,
219
+ );
220
+ const untracked = new Set(entries.filter((e) => e.xy === "??").map((e) => e.path));
221
+ const findings = excess.map((path) => scopeFinding(path, untracked.has(path)));
222
+ return writeScopeVerdict(latest as FsArtifact, findings, foldScopeVerdict(excess, untracked), cwd);
223
+ };
224
+
225
+ /**
226
+ * vet's `implement-scope-check` — the loop-aware scope floor, twin of build's
227
+ * `implementScopeCheck`. vet differs in ONE place: build's extra `plans`
228
+ * entries are superseding amendments (`plan-fix` re-publishes the whole plan)
229
+ * so build reads latest-only; vet's review-fix loop pushes a DISTINCT
230
+ * non-superseding fix plan per iteration (completing a `produces` stage APPENDS
231
+ * to its named slot, and backward jumps don't reset channels), so `declared` is
232
+ * the UNION of `phaseFiles` over the FULL `state.named.plans` history — a path
233
+ * a prior iteration's plan legitimately wrote is not excess against the latest
234
+ * plan. The latest plan's handle keys the basename-keyed verdict path
235
+ * (idempotent across fix rounds) and the `artifact` field. Everything else —
236
+ * baseline subtraction, dirty-set read, the tiered `ScopeVerdict` fold, and
237
+ * the shared `dimension: "scope"` verdict envelope via `writeScopeVerdict` —
238
+ * is build's floor verbatim: pass/excess ⇒ reconcile (excess adjudicated by
239
+ * the review loop, which sees the whole diff), untracked-only ⇒ quarantine,
240
+ * missing verdict ⇒ STOP.
241
+ */
242
+ const implementScopeCheckVet = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
243
+ // Declared set = UNION of `phaseFiles` over EVERY non-failed plan on the channel.
244
+ // The fs-artifact filter skips failed/unfilled entries (an Output with no fs
245
+ // handle contributed no plan to read).
246
+ const { declared, latest } = unionDeclaredWriteSet(state.named.plans ?? [], cwd);
247
+ if (!latest) {
248
+ throw haltPreflight(
249
+ "implement-scope-check",
250
+ "implement-scope-check: no plan to check",
251
+ "implement-scope-check: no fs plan artifact on the 'plans' channel — blueprint/implement must run before the scope check",
252
+ );
253
+ }
254
+
255
+ // Run-start baseline (goal channel, role "baseline") + current dirty set —
256
+ // both best-effort (absent / non-repo ⇒ `[]`); see the two helpers' docs.
257
+ const baseline = readGoalBaseline(goalBaselinePath(state), cwd);
258
+ const entries = gitDirtyEntries(cwd);
259
+
260
+ // Shared core: subtract the run's bookkeeping dirs (`.rpiv/`,
261
+ // `thoughts/`) and the run-start baseline; empty-`declared` ⇒ `[]` (degradation
262
+ // ⇒ inert floor — a fully `files:`-less plan never false-fails). Twin-expanded
263
+ // like build's floor: a declared file carries its co-located test twin.
264
+ const excess = scopeExcess(
265
+ entries.map((e) => e.path),
266
+ baseline,
267
+ withTestTwins([...declared]),
268
+ );
269
+ const untracked = new Set(entries.filter((e) => e.xy === "??").map((e) => e.path));
270
+ const findings = excess.map((p) => scopeFinding(p, untracked.has(p)));
271
+ return writeScopeVerdict(latest, findings, foldScopeVerdict(excess, untracked), cwd);
272
+ };
273
+
274
+ /** Bookkeeping home for quarantined excess — under `.rpiv/`, so already exempt
275
+ * from the floor (`SCOPE_BOOKKEEPING_DIRS`) and outside every plan's write-set. */
276
+ const QUARANTINE_DIR = ".rpiv/tmp/scope-quarantine";
277
+
278
+ /** One quarantine move record: the path the floor flagged and where it went. */
279
+ type QuarantineMove = { from: string; to: string };
280
+
281
+ /**
282
+ * Read a prior round's quarantine manifest — best-effort `{ moved: [] }` on a
283
+ * missing/corrupt file. The manifest is the CROSS-ROUND record validate's
284
+ * adjudication reads (its glob finds this basename-keyed file), so each round
285
+ * MERGES into it rather than replacing: a validate-fix re-entry that
286
+ * quarantines again must not erase round 1's move records.
287
+ */
288
+ const readQuarantineManifest = (rel: string, cwd: string): { moved: QuarantineMove[] } => {
289
+ try {
290
+ const parsed = JSON.parse(readArtifactFile(rel, cwd)) as { moved?: unknown };
291
+ const moved = Array.isArray(parsed.moved)
292
+ ? parsed.moved.filter(
293
+ (m): m is QuarantineMove =>
294
+ typeof (m as QuarantineMove)?.from === "string" && typeof (m as QuarantineMove)?.to === "string",
295
+ )
296
+ : [];
297
+ return { moved };
298
+ } catch {
299
+ return { moved: [] };
300
+ }
301
+ };
302
+
303
+ /**
304
+ * Deterministic remedy arm for an "untracked-only" scope verdict: MOVE (never
305
+ * delete) each excess path into `.rpiv/tmp/scope-quarantine/<path>`, preserving
306
+ * relative structure, and record it in the manifest — the ADJUDICATION RECORD
307
+ * validate reads unconditionally (the post-quarantine re-check threads a clean
308
+ * `pass` verdict, so the manifest is the only surviving record of what moved
309
+ * and why). The edge back to `implement-scope-check` is a plain string hop
310
+ * (non-counted, mirroring `validate-fix → implement-scope-check`) with
311
+ * guaranteed progress: quarantined paths leave the dirty set, so the re-check
312
+ * either passes or reveals tracked drift — at most one quarantine hop per gate
313
+ * entry, no new loop budget.
314
+ *
315
+ * Manifest semantics: MERGED across rounds (`moved` accumulates; a re-moved
316
+ * `from` path supersedes its prior entry), written in a `finally` so a
317
+ * mid-loop fs throw still lands every completed move on disk before the stage
318
+ * fails — fail-loud with the files accounted for, never moved-but-unrecorded.
319
+ * `refused` records this round's declined paths (not untracked at move time,
320
+ * or cwd-escaping) so a skipped path is observable without re-running the
321
+ * floor; refusals are per-round observations, not history.
322
+ *
323
+ * Fail-closed: a path that escapes `cwd` is refused via `containedPath` (left
324
+ * in place — the re-check re-judges it), a path no longer untracked at move
325
+ * time is never touched, and a failing rename THROWS (the stage fails, the run
326
+ * stops with the real fs error) rather than ping-ponging the gate on a stuck
327
+ * path.
328
+ */
329
+ const scopeQuarantine = ({ state, cwd }: ScriptContext): Omit<Output, "meta"> => {
330
+ const verdict = state.named["implement-scope-check"]?.at(-1)?.data as
331
+ | { findings?: { where?: unknown }[] }
332
+ | undefined;
333
+ const listed = (verdict?.findings ?? []).map((f) => f.where).filter((w): w is string => typeof w === "string");
334
+ // Fresh status read — move ONLY what is untracked RIGHT NOW. A path that got
335
+ // tracked/settled since the check is never touched (the re-check re-judges it).
336
+ const untracked = new Set(
337
+ gitDirtyEntries(cwd)
338
+ .filter((e) => e.xy === "??")
339
+ .map((e) => e.path),
340
+ );
341
+ // Manifest path + prior rounds resolved BEFORE the move loop, so the finally
342
+ // below can always write the merged record.
343
+ const plan = latestFsArtifact(state, "plans");
344
+ const key = plan?.handle.kind === "fs" ? basename(plan.handle.path, ".md") : "no-plan";
345
+ const rel = join(VERDICT_DIR, `scope-quarantine__${key}.json`);
346
+ const prior = readQuarantineManifest(rel, cwd);
347
+
348
+ const moved: QuarantineMove[] = [];
349
+ const refused: { path: string; reason: string }[] = [];
350
+ try {
351
+ for (const path of listed) {
352
+ if (!untracked.has(path)) {
353
+ refused.push({ path, reason: "not-untracked-at-move-time" });
354
+ continue;
355
+ }
356
+ const abs = containedPath(cwd, path);
357
+ if (!abs) {
358
+ refused.push({ path, reason: "escapes-cwd" });
359
+ continue;
360
+ }
361
+ const destRel = join(QUARANTINE_DIR, path);
362
+ mkdirSync(dirname(join(cwd, destRel)), { recursive: true });
363
+ renameSync(abs, join(cwd, destRel));
364
+ moved.push({ from: path, to: destRel });
365
+ }
366
+ } finally {
367
+ // Partial-progress write: on a mid-loop throw, every completed move is on
368
+ // disk before the failure propagates. Merge: current rounds' moves
369
+ // supersede a prior entry for the same `from`; everything else survives.
370
+ const kept = prior.moved.filter((p) => !moved.some((m) => m.from === p.from));
371
+ mkdirSync(join(cwd, VERDICT_DIR), { recursive: true });
372
+ writeFileSync(join(cwd, rel), JSON.stringify({ moved: [...kept, ...moved], refused }, null, 2), "utf-8");
373
+ }
374
+ return { kind: "json", artifacts: [{ handle: { kind: "fs", path: rel } }], data: { moved, refused } };
375
+ };
376
+
377
+ export type { ScopeVerdict };
378
+ export { implementScopeCheck, implementScopeCheckVet, scopeQuarantine };
@@ -1,5 +1,5 @@
1
1
  import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { basename, isAbsolute, join } from "node:path";
2
+ import { basename, isAbsolute, join, relative, resolve } from "node:path";
3
3
  import { type Artifact, handleToString, type Output, type RunView } from "@juicesharp/rpiv-workflow/registration";
4
4
  import { StagePreflightError } from "@juicesharp/rpiv-workflow/runner";
5
5
 
@@ -146,8 +146,24 @@ const writeStructureVerdict = (
146
146
  */
147
147
  const TEST_PATH_RE = /\.test\.[tj]sx?$/;
148
148
 
149
+ /**
150
+ * Resolve `target` against `cwd` and require the result to stay INSIDE `cwd`.
151
+ * Returns the resolved absolute path, or `undefined` when the target escapes
152
+ * (an absolute path outside `cwd`, or `..` traversal — `resolve` collapses the
153
+ * dot segments, `relative` exposes an escape as a leading `..` or a different
154
+ * root). The guard runs on the SAME resolved string the fs sinks operate on,
155
+ * so a suffix/charset check on the raw directive or citation text can never be
156
+ * bypassed by an absolute target or a mid-path `..`.
157
+ */
158
+ const containedPath = (cwd: string, target: string): string | undefined => {
159
+ const abs = resolve(cwd, target);
160
+ const rel = relative(cwd, abs);
161
+ return rel.startsWith("..") || isAbsolute(rel) ? undefined : abs;
162
+ };
163
+
149
164
  export type { FsArtifact, PhaseRecord, StructureFinding };
150
165
  export {
166
+ containedPath,
151
167
  FILE_LINE_CITATION_RE,
152
168
  haltPreflight,
153
169
  latestFsArtifact,