@juicesharp/rpiv-pi 2.11.0 → 2.12.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.
@@ -99,6 +99,7 @@ import {
99
99
  verdictOutcome,
100
100
  verdictRiskRulings,
101
101
  } from "./built-ins/index.js";
102
+ import { metaWorkflow } from "./meta/presets.js";
102
103
 
103
104
  // The code-review stage's output schema is no longer declared here — every
104
105
  // code-review stage sources it from the skill's contract `produces.data`
@@ -1433,4 +1434,10 @@ export { SHIP_DIMENSION_FANOUT, SHIP_DIMENSIONS, shipGatePasses, shipVerdictOutc
1433
1434
  // Position 0 is load-bearing: `build` is the default `/wf` workflow when no
1434
1435
  // project/user config sets one (resolve-default.ts resolves
1435
1436
  // `Map.keys().next().value`), so it MUST stay first in this array.
1436
- export const builtInWorkflows: readonly Workflow[] = [buildWorkflow, vetWorkflow, polishWorkflow, shipWorkflow];
1437
+ export const builtInWorkflows: readonly Workflow[] = [
1438
+ buildWorkflow,
1439
+ vetWorkflow,
1440
+ polishWorkflow,
1441
+ shipWorkflow,
1442
+ metaWorkflow,
1443
+ ];
@@ -0,0 +1,90 @@
1
+ # meta — a graph of self-correcting units
2
+
3
+ `meta` is an authoring layer over the rpiv-workflow engine. You write a workflow as an ordered list of **units**. Each unit is one loop:
4
+
5
+ ```
6
+ produce ─► checks (code, first) ─► graders (LLM lenses, parallel) ─► gate
7
+ ▲ │
8
+ └──── fix (return record: unit·verdict·reason·evidence·scope) ◄────┘ while rounds < max
9
+ exhausted ─► halt | advance | escalate upstream
10
+ accepted run ─► learn ─► .rpiv/lessons/meta-lessons.json (standing constraints for the next run's producers)
11
+ ```
12
+
13
+ The loop lives inside a unit, and the graph lives between units. `defineUnitGraph` compiles each unit into engine stages and routes: `<u>`, `<u>-fix`, `<u>-check`, `<u>-grade`, `<u>-gate`.
14
+
15
+ ## Unit spec
16
+
17
+ ```ts
18
+ defineUnitGraph({
19
+ name: "my-flow",
20
+ units: [
21
+ ["research", { skill: "research", output: "research", checks: [minCitations(5)] }], // mandatory, first
22
+ ["plan", {
23
+ skill: "quick-plan", // skill XOR prompt (string or (ctx) => string)
24
+ reads: ["research", "goal"], // the only real edges
25
+ output: "plans", // omit ⇒ side-effect unit (the working tree)
26
+ checks: [planCitations], // deterministic graders, run first
27
+ graders: [{ lens: "correctness", rubric: "FAIL if …", context: ["research"] }],
28
+ fix: { prompt: "Revise the plan in place …" }, // default: re-run producer + return record
29
+ maxRounds: 3, // ≤ 4
30
+ onExhausted: "halt", // | "advance" | { escalateTo: "<earlier unit>" }
31
+ }],
32
+ ],
33
+ commit: true,
34
+ });
35
+ ```
36
+
37
+ - `research` is the only mandatory unit, and it must come first.
38
+ - Every other unit is optional.
39
+ - Built-in: `/wf meta "<brief>"` runs research → acceptance → plan → implement → commit. Research is the mandatory first unit; every later unit is optional when you author your own graph.
40
+ - A project pack can import `defineUnitGraph` and `checks.ts` by absolute path.
41
+
42
+ ## How it differs from `build`
43
+
44
+ | | `build` | `meta` |
45
+ |---|---|---|
46
+ | Unit of correction | Whole artifact. `amend` rewrites the plan (170–785 KB) and the whole 5–6 lens panel re-grades. | The failing items only. The return record lists them, with SCOPE = "touch only what the evidence cites". |
47
+ | Check order | Cite floor, then the LLM panel. Floors were mostly demoted to advisory. | Code checks first and short-circuiting. A red check never pays for a grader. |
48
+ | Graders | 5–6 dimensions tiered by size, plus a confirm pass, demote, and priors snapshots. | 1–2 lenses per unit. No confirm, no demote. |
49
+ | Stop condition | Jump budget 3 per destination, lap ceiling 8, a noisy `progress` label. | Per-unit `maxRounds`, plus an identical failure signature twice = stop early. |
50
+ | Exhausted | Halt. A human resumes. | halt, advance, or escalate to an upstream unit. |
51
+ | Decomposition | slice → design ×N → human design-review → subplans → plan → elaborate → splice. | None. One plan; implement fans out by phase. |
52
+ | Human | design-review checkpoint mid-graph. | Only at the end (commit). |
53
+ | Cross-run learning | None. Death scenes and priors are write-only or in-run. | `learn` records corrected failures, and producers read the top ones. |
54
+ | Size | ~35 stages, hand-wired routes. | 4 units → 17 stages, generated. |
55
+
56
+ ### What the corpus says (52 real build runs in opendots)
57
+
58
+ - Every fix round was whole-batch: 90 amend rounds and 193 panel runs.
59
+ - Confirm upheld 40 of 40 failures (~6 min each).
60
+ - Demote demoted 0 of 193.
61
+ - 7 of ~45 multi-round loops regressed mid-loop.
62
+ - Every terminal halt was a corrector that could not reach the cause ("remediation left the working tree unchanged").
63
+
64
+ `meta` is built to test these points:
65
+ - scoped returns
66
+ - no confirm or demote
67
+ - stuck detection by signature
68
+ - upward escalation
69
+ - lessons that cross runs
70
+
71
+ ## What `meta` gives up (and what an A/B will tell you)
72
+
73
+ - **No slicing or parallel design.** Large briefs may produce a weaker single plan. `build`'s decomposition is its strongest feature on big work.
74
+ - **Fewer lenses.** Actionability, pattern-following, architecture-fit and risk rulings are gone. The corpus shows they rarely failed (3–8%), but "rarely" is not "never".
75
+ - **No mid-graph human checkpoint.**
76
+ - **Lessons are raw failure reasons**, not distilled rules. Noisy until counts accumulate.
77
+
78
+ ## A/B
79
+
80
+ ```bash
81
+ node ab.mjs setup ~/opendots air5-x "<brief>" # two worktrees at HEAD, prints launch commands
82
+ # run each arm in its own terminal (pi, then the printed /wf line); they run in parallel
83
+ node ab.mjs compare ~/opendots air5-x --eval "cd packages/arclet-ui && swift test"
84
+ ```
85
+
86
+ `compare` reports, per arm: outcome, wall clock, active time, sessions, tokens, stage visits and re-entries, rounds per unit, and the diff.
87
+
88
+ It also runs a **shared scorecard**: your `--eval` commands plus every arm's frozen acceptance commands, executed on every arm's tree. No arm is graded only by its own standard.
89
+
90
+ Write the `--eval` checks before looking at either result.
@@ -0,0 +1,249 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * A/B harness: run two /wf pipelines on the SAME brief from the SAME commit,
4
+ * in parallel, in isolated git worktrees, then compare them on the same
5
+ * held-out checks.
6
+ *
7
+ * node ab.mjs setup <repo> <label> "<brief>" [--arms build,meta]
8
+ * node ab.mjs compare <repo> <label> [--eval "<cmd>"]... [--no-acceptance] [--adopt-lessons]
9
+ *
10
+ * setup — one worktree + branch per arm (ab/<label>/<arm>) at HEAD. Copies the
11
+ * gitignored .rpiv/guidance into every arm (parity) and .rpiv/lessons
12
+ * into meta arms. Prints the command to launch each arm.
13
+ * compare — reads each arm's run trail + session transcripts and reports:
14
+ * outcome, wall clock, active time, sessions, tokens, stage visits,
15
+ * correction rounds, the diff, and a SHARED scorecard: every --eval
16
+ * command plus EVERY arm's frozen acceptance commands, executed on
17
+ * every arm's tree (so no arm is graded only by its own standard).
18
+ * Writes <repo>/.rpiv/ab/<label>-report.md.
19
+ *
20
+ * Write the --eval commands BEFORE looking at either result — the check first.
21
+ */
22
+
23
+ import { execSync } from "node:child_process";
24
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { basename, dirname, join, resolve } from "node:path";
26
+
27
+ const [, , cmd, repoArg, label, ...rest] = process.argv;
28
+ if (!cmd || !repoArg || !label) {
29
+ console.error('usage:\n ab.mjs setup <repo> <label> "<brief>" [--arms build,meta]\n ab.mjs compare <repo> <label> [--eval "<cmd>"]... [--adopt-lessons]');
30
+ process.exit(2);
31
+ }
32
+ const repo = resolve(repoArg);
33
+ const abDir = join(repo, ".rpiv", "ab");
34
+ const manifestPath = join(abDir, `${label}.json`);
35
+ const sh = (c, cwd = repo, timeout = 30 * 60_000) => execSync(c, { cwd, stdio: ["ignore", "pipe", "pipe"], timeout, shell: "/bin/bash" }).toString();
36
+ const tryRun = (c, cwd) => {
37
+ const t0 = Date.now();
38
+ try {
39
+ sh(c, cwd);
40
+ return { ok: true, ms: Date.now() - t0 };
41
+ } catch (e) {
42
+ const tail = `${e.stdout ?? ""}\n${e.stderr ?? ""}`.trim().split("\n").slice(-3).join(" | ");
43
+ return { ok: false, ms: Date.now() - t0, tail };
44
+ }
45
+ };
46
+ const flag = (name) => {
47
+ const out = [];
48
+ for (let i = 0; i < rest.length; i++) if (rest[i] === name) out.push(rest[++i]);
49
+ return out;
50
+ };
51
+
52
+ // ---------------------------------------------------------------------------
53
+ if (cmd === "setup") {
54
+ const brief = rest.find((a, i) => !a.startsWith("--") && rest[i - 1] !== "--arms");
55
+ if (!brief) throw new Error("setup needs a brief");
56
+ const arms = (flag("--arms")[0] ?? "build,meta").split(",");
57
+ const base = sh("git rev-parse HEAD").trim();
58
+ if (sh("git status --porcelain --untracked-files=no").trim()) {
59
+ console.warn("warning: the repo has uncommitted tracked changes — worktrees start from HEAD and will NOT include them");
60
+ }
61
+ mkdirSync(abDir, { recursive: true });
62
+ const parent = dirname(repo);
63
+ const entries = arms.map((arm) => {
64
+ const path = join(parent, `${basename(repo)}-ab-${label}-${arm}`);
65
+ const branch = `ab/${label}/${arm}`;
66
+ if (existsSync(path)) throw new Error(`${path} already exists — pick another label`);
67
+ sh(`git worktree add -b ${branch} ${JSON.stringify(path)} ${base}`);
68
+ for (const sub of ["guidance", ...(arm.startsWith("meta") ? ["lessons"] : [])]) {
69
+ const src = join(repo, ".rpiv", sub);
70
+ if (existsSync(src)) cpSync(src, join(path, ".rpiv", sub), { recursive: true });
71
+ }
72
+ return { arm, path, branch, runName: `ab-${label}-${arm}` };
73
+ });
74
+ writeFileSync(manifestPath, `${JSON.stringify({ label, brief, base, created: new Date().toISOString(), arms: entries }, null, 2)}\n`);
75
+ console.log(`A/B "${label}" from ${base.slice(0, 8)} — launch each arm in its own terminal (they run in parallel):\n`);
76
+ for (const e of entries) {
77
+ // A meta arm's escalation (implement → plan) adds a re-entry on top of the
78
+ // per-unit correction rounds; lift the per-destination jump budget for it.
79
+ const jumps = e.arm.startsWith("meta") ? " --max-jumps 6" : "";
80
+ console.log(` # ${e.arm}\n cd ${JSON.stringify(e.path)} && pi\n /wf ${e.arm} ${brief} --name ${e.runName}${jumps}\n`);
81
+ }
82
+ console.log(`When both finish: node ${process.argv[1]} compare ${repo} ${label} --eval "<held-out check>" ...`);
83
+ process.exit(0);
84
+ }
85
+
86
+ // ---------------------------------------------------------------------------
87
+ if (cmd !== "compare") throw new Error(`unknown command ${cmd}`);
88
+ const m = JSON.parse(readFileSync(manifestPath, "utf-8"));
89
+ const evals = flag("--eval");
90
+
91
+ const readJsonl = (p) =>
92
+ readFileSync(p, "utf-8")
93
+ .split("\n")
94
+ .filter(Boolean)
95
+ .map((l) => {
96
+ try {
97
+ return JSON.parse(l);
98
+ } catch {
99
+ return null;
100
+ }
101
+ })
102
+ .filter(Boolean);
103
+
104
+ function findRun(arm) {
105
+ const runs = join(arm.path, ".rpiv", "workflows", "runs");
106
+ if (!existsSync(runs)) return undefined;
107
+ const names = existsSync(join(runs, "names.json")) ? JSON.parse(readFileSync(join(runs, "names.json"), "utf-8")) : {};
108
+ const byName = names[arm.runName];
109
+ const id =
110
+ (typeof byName === "string" ? byName : byName?.runId) ??
111
+ readdirSync(runs)
112
+ .filter((f) => f.endsWith(".jsonl"))
113
+ .sort()
114
+ .at(-1)
115
+ ?.replace(/\.jsonl$/, "");
116
+ return id ? { id, file: join(runs, `${id}.jsonl`), sessions: join(runs, id, "sessions") } : undefined;
117
+ }
118
+
119
+ function tokens(dir) {
120
+ if (!existsSync(dir)) return { total: 0, output: 0 };
121
+ let total = 0;
122
+ let output = 0;
123
+ for (const f of readdirSync(dir).filter((x) => x.endsWith(".jsonl"))) {
124
+ const body = readFileSync(join(dir, f), "utf-8");
125
+ for (const mm of body.matchAll(/"usage":\{"input":\d+,"output":(\d+),[^{}]*?"totalTokens":(\d+)/g)) {
126
+ output += Number(mm[1]);
127
+ total += Number(mm[2]);
128
+ }
129
+ }
130
+ return { total, output };
131
+ }
132
+
133
+ function analyze(arm) {
134
+ const run = findRun(arm);
135
+ if (!run || !existsSync(run.file)) return { arm: arm.arm, missing: true };
136
+ const rows = readJsonl(run.file);
137
+ const stages = rows.filter((r) => r.stage && r.ts && !r.type);
138
+ const ts = rows.map((r) => Date.parse(r.ts)).filter(Number.isFinite).sort((a, b) => a - b);
139
+ let active = 0;
140
+ for (let i = 1; i < ts.length; i++) active += Math.min(ts[i] - ts[i - 1], 30 * 60_000);
141
+ const visits = {};
142
+ for (const r of stages.filter((r) => !r.parent)) visits[r.stage] = (visits[r.stage] ?? 0) + 1;
143
+ const revisits = Object.values(visits).reduce((a, n) => a + Math.max(0, n - 1), 0);
144
+ const committed = stages.some((r) => r.stage === "commit" && r.status === "completed");
145
+ const last = stages.at(-1);
146
+ const routeNotes = rows.filter((r) => r.type === "routing" && r.note).map((r) => r.note);
147
+ const failed = stages.find((r) => r.status === "failed");
148
+ const outcome = committed
149
+ ? "committed"
150
+ : failed
151
+ ? `failed at ${failed.stage}: ${(failed.errMsg ?? "").slice(0, 120)}`
152
+ : `stopped after ${last?.stage ?? "?"}${routeNotes.length ? `: ${routeNotes.at(-1).slice(0, 120)}` : ""}`;
153
+ const loopRounds = Object.fromEntries(
154
+ Object.entries(visits)
155
+ .filter(([s]) => s.endsWith("-check"))
156
+ .map(([s, n]) => [s.replace(/-check$/, ""), n]),
157
+ );
158
+ const diff = (() => {
159
+ try {
160
+ return sh(`git diff --shortstat ${m.base} HEAD`, arm.path).trim() || "(no committed diff)";
161
+ } catch {
162
+ return "?";
163
+ }
164
+ })();
165
+ const acceptance = (() => {
166
+ const dir = join(arm.path, ".rpiv", "artifacts", "acceptance");
167
+ if (!existsSync(dir)) return [];
168
+ const f = readdirSync(dir).sort().at(-1);
169
+ if (!f) return [];
170
+ const fm = readFileSync(join(dir, f), "utf-8").split(/^---$/m)[1] ?? "";
171
+ return [...fm.matchAll(/^\s*-?\s*id:\s*(\S+)[\s\S]*?^\s*command:\s*(.+)$/gm)].map((x) => ({
172
+ id: `${arm.arm}:${x[1]}`,
173
+ command: x[2].trim().replace(/^["']|["']$/g, ""),
174
+ }));
175
+ })();
176
+ return {
177
+ arm: arm.arm,
178
+ runId: run.id,
179
+ outcome,
180
+ wallMin: ts.length ? Math.round((ts.at(-1) - ts[0]) / 60_000) : 0,
181
+ activeMin: Math.round(active / 60_000),
182
+ sessions: stages.filter((r) => r.session).length,
183
+ tokens: tokens(run.sessions),
184
+ stageVisits: Object.values(visits).reduce((a, b) => a + b, 0),
185
+ revisits,
186
+ loopRounds,
187
+ diff,
188
+ acceptance,
189
+ routeNotes,
190
+ };
191
+ }
192
+
193
+ const results = m.arms.map((a) => ({ ...analyze(a), path: a.path }));
194
+ const checks = [
195
+ ...evals.map((c, i) => ({ id: `eval${i + 1}`, command: c })),
196
+ ...(rest.includes("--no-acceptance") ? [] : results.flatMap((r) => r.acceptance ?? [])),
197
+ ];
198
+ const score = results.map((r) =>
199
+ r.missing ? checks.map(() => ({ ok: false, tail: "no run" })) : checks.map((c) => tryRun(c.command, r.path)),
200
+ );
201
+
202
+ const fmtK = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : `${Math.round(n / 1e3)}k`);
203
+ const lines = [
204
+ `# A/B ${m.label}`,
205
+ "",
206
+ `Brief: ${m.brief}`,
207
+ `Base: ${m.base.slice(0, 10)} · created ${m.created}`,
208
+ "",
209
+ `| | ${results.map((r) => r.arm).join(" | ")} |`,
210
+ `|---|${results.map(() => "---").join("|")}|`,
211
+ ...[
212
+ ["outcome", (r) => r.outcome ?? "no run"],
213
+ ["wall clock", (r) => `${r.wallMin ?? "-"} min`],
214
+ ["active time (gaps capped 30m)", (r) => `${r.activeMin ?? "-"} min`],
215
+ ["child sessions", (r) => r.sessions ?? "-"],
216
+ ["tokens (total / output)", (r) => (r.tokens ? `${fmtK(r.tokens.total)} / ${fmtK(r.tokens.output)}` : "-")],
217
+ ["stage visits / re-entries", (r) => `${r.stageVisits ?? "-"} / ${r.revisits ?? "-"}`],
218
+ ["correction rounds per unit", (r) => (r.loopRounds && Object.keys(r.loopRounds).length ? Object.entries(r.loopRounds).map(([u, n]) => `${u}:${n}`).join(" ") : "—")],
219
+ ["diff vs base", (r) => r.diff ?? "-"],
220
+ [
221
+ "shared scorecard",
222
+ (r, i) => `${score[i].filter((s) => s.ok).length}/${checks.length} green`,
223
+ ],
224
+ ].map(([k, f]) => `| ${k} | ${results.map((r, i) => String(f(r, i)).replace(/\|/g, "\\|")).join(" | ")} |`),
225
+ "",
226
+ "## Shared scorecard (every check, run on every arm's tree)",
227
+ "",
228
+ `| check | ${results.map((r) => r.arm).join(" | ")} |`,
229
+ `|---|${results.map(() => "---").join("|")}|`,
230
+ ...checks.map((c, j) => `| \`${c.id}\` ${c.command.slice(0, 70).replace(/\|/g, "\\|")} | ${score.map((s) => (s[j].ok ? "✅" : "❌")).join(" | ")} |`),
231
+ "",
232
+ "## Route notes",
233
+ ...results.flatMap((r) => [`### ${r.arm}`, ...(r.routeNotes?.length ? r.routeNotes.map((n) => `- ${n}`) : ["- (none)"])]),
234
+ ];
235
+ mkdirSync(abDir, { recursive: true });
236
+ const reportPath = join(abDir, `${m.label}-report.md`);
237
+ writeFileSync(reportPath, `${lines.join("\n")}\n`);
238
+ console.log(lines.join("\n"));
239
+ console.log(`\nreport: ${reportPath}`);
240
+
241
+ if (rest.includes("--adopt-lessons")) {
242
+ for (const r of results) {
243
+ const src = join(r.path, ".rpiv", "lessons");
244
+ if (r.arm.startsWith("meta") && existsSync(src)) {
245
+ cpSync(src, join(repo, ".rpiv", "lessons"), { recursive: true });
246
+ console.log(`adopted lessons from ${r.arm}`);
247
+ }
248
+ }
249
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Deterministic graders — code nodes with exactly one correct answer. Each is
3
+ * a program a machine can evaluate, never "the output looks good": a file
4
+ * exists, a count clears a floor, a command exits 0.
5
+ */
6
+
7
+ import { execSync } from "node:child_process";
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { isAbsolute, join } from "node:path";
10
+ import { FILE_LINE_CITATION_RE, planCitationCheck } from "../built-ins/index.js";
11
+ import type { Check, CheckContext, Failure } from "./unit-graph.js";
12
+
13
+ const abs = (ctx: CheckContext, p: string) => (isAbsolute(p) ? p : join(ctx.cwd, p));
14
+
15
+ const body = (ctx: CheckContext): string | undefined =>
16
+ ctx.artifactPath && existsSync(abs(ctx, ctx.artifactPath))
17
+ ? readFileSync(abs(ctx, ctx.artifactPath), "utf-8")
18
+ : undefined;
19
+
20
+ /** GREEN when the unit's artifact exists and is non-trivial. */
21
+ export const artifactWritten = (minLines = 10): Check => ({
22
+ name: "artifact-written",
23
+ run: (ctx) => {
24
+ const b = body(ctx);
25
+ if (b === undefined) return [{ source: "artifact-written", reason: "the unit produced no artifact file" }];
26
+ const n = b.split("\n").length;
27
+ return n < minLines
28
+ ? [
29
+ {
30
+ source: "artifact-written",
31
+ reason: `artifact has ${n} lines (< ${minLines})`,
32
+ evidence: ctx.artifactPath,
33
+ },
34
+ ]
35
+ : [];
36
+ },
37
+ });
38
+
39
+ /** GREEN when the artifact carries at least `min` file:line citations ("every claim carries a source line"). */
40
+ export const minCitations = (min: number): Check => ({
41
+ name: "citations",
42
+ run: (ctx) => {
43
+ const b = body(ctx) ?? "";
44
+ const n = [...b.matchAll(new RegExp(FILE_LINE_CITATION_RE))].length;
45
+ return n < min
46
+ ? [
47
+ {
48
+ source: "citations",
49
+ reason: `only ${n} file:line citations (need ≥ ${min}) — ground claims in code`,
50
+ evidence: ctx.artifactPath,
51
+ },
52
+ ]
53
+ : [];
54
+ },
55
+ });
56
+
57
+ /**
58
+ * GREEN when every acceptance item carries runnable evidence (`command`) or an
59
+ * explicit `manual` note. Reads the unit's own published frontmatter.
60
+ */
61
+ export const acceptanceWellFormed: Check = {
62
+ name: "acceptance-shape",
63
+ run: (ctx) => {
64
+ const items = (ctx.state.named.acceptance?.at(-1)?.data as { items?: unknown } | undefined)?.items;
65
+ if (!Array.isArray(items) || items.length === 0)
66
+ return [{ source: "acceptance-shape", reason: "frontmatter `items:` is empty or missing" }];
67
+ return items
68
+ .map((it) => it as { id?: string; command?: string; manual?: string })
69
+ .filter((it) => !it.command && !it.manual)
70
+ .map((it) => ({ source: "acceptance-shape", reason: `item ${it.id ?? "?"} has neither command nor manual` }));
71
+ },
72
+ };
73
+
74
+ /**
75
+ * GREEN when the plan's citations resolve and every edited path is declared —
76
+ * build's own floor (`planCitationCheck`), reused verbatim; only its blocking
77
+ * (non-advisory) findings fail the unit.
78
+ */
79
+ export const planCitations: Check = {
80
+ name: "plan-citations",
81
+ run: (ctx) => {
82
+ const out = planCitationCheck(`${ctx.unit}-cite-check`)(ctx);
83
+ const findings = ((out.data as { findings?: unknown[] } | undefined)?.findings ?? []) as Array<{
84
+ advisory?: boolean;
85
+ detail?: string;
86
+ message?: string;
87
+ where?: string;
88
+ }>;
89
+ return findings
90
+ .filter((f) => f.advisory !== true)
91
+ .map((f) => ({
92
+ source: "plan-citations",
93
+ reason: f.detail ?? f.message ?? JSON.stringify(f),
94
+ evidence: f.where,
95
+ }));
96
+ },
97
+ };
98
+
99
+ /** GREEN when the plan disposes every acceptance id (implemented / deferred / rebound). */
100
+ export const acceptanceDisposed: Check = {
101
+ name: "acceptance-disposed",
102
+ run: (ctx) => {
103
+ const items = (
104
+ (ctx.state.named.acceptance?.at(-1)?.data as { items?: Array<{ id?: string }> } | undefined)?.items ?? []
105
+ )
106
+ .map((i) => i.id)
107
+ .filter((id): id is string => !!id);
108
+ const disposed = new Set(
109
+ (
110
+ (ctx.state.named.plans?.at(-1)?.data as { acceptance?: Array<{ id?: string }> } | undefined)?.acceptance ??
111
+ []
112
+ ).map((d) => d.id),
113
+ );
114
+ return items
115
+ .filter((id) => !disposed.has(id))
116
+ .map((id) => ({
117
+ source: "acceptance-disposed",
118
+ reason: `acceptance item ${id} has no disposition in the plan's frontmatter \`acceptance:\``,
119
+ }));
120
+ },
121
+ };
122
+
123
+ const run = (cmd: string, cwd: string, timeoutMs: number): { ok: boolean; tail: string } => {
124
+ try {
125
+ execSync(cmd, { cwd, stdio: ["ignore", "pipe", "pipe"], timeout: timeoutMs, shell: "/bin/bash" });
126
+ return { ok: true, tail: "" };
127
+ } catch (err) {
128
+ const e = err as { stdout?: Buffer; stderr?: Buffer; message?: string };
129
+ const tail = `${e.stdout?.toString() ?? ""}\n${e.stderr?.toString() ?? ""}`
130
+ .trim()
131
+ .split("\n")
132
+ .slice(-12)
133
+ .join("\n");
134
+ return { ok: false, tail: tail || (e.message ?? "failed") };
135
+ }
136
+ };
137
+
138
+ /** GREEN when a shell command exits 0 (e.g. the build or the test suite). */
139
+ export const commandPasses = (name: string, cmd: string, timeoutMs = 20 * 60_000): Check => ({
140
+ name,
141
+ run: (ctx) => {
142
+ const r = run(cmd, ctx.cwd, timeoutMs);
143
+ return r.ok ? [] : [{ source: name, reason: `\`${cmd}\` exited non-zero`, evidence: r.tail }];
144
+ },
145
+ });
146
+
147
+ /**
148
+ * GREEN when every frozen acceptance evidence command exits 0 on the tree —
149
+ * the executable standard of completion. A plan `rebound` disposition swaps in
150
+ * its replacement command; `deferred` and `manual` items are skipped. One
151
+ * failure per red item, so a correction returns only those items.
152
+ */
153
+ export const acceptanceCommands = (timeoutMs = 20 * 60_000): Check => ({
154
+ name: "acceptance",
155
+ run: (ctx) => {
156
+ const items = ((ctx.state.named.acceptance?.at(-1)?.data as { items?: unknown[] } | undefined)?.items ??
157
+ []) as Array<{
158
+ id?: string;
159
+ statement?: string;
160
+ command?: string;
161
+ expect?: string;
162
+ }>;
163
+ const disp = new Map(
164
+ (
165
+ ((ctx.state.named.plans?.at(-1)?.data as { acceptance?: unknown[] } | undefined)?.acceptance ??
166
+ []) as Array<{
167
+ id?: string;
168
+ disposition?: string;
169
+ command?: string;
170
+ }>
171
+ ).map((d) => [d.id, d]),
172
+ );
173
+ const failures: Failure[] = [];
174
+ for (const it of items) {
175
+ const d = disp.get(it.id);
176
+ const kind = d?.disposition;
177
+ if (kind === "deferred" || !it.command) continue;
178
+ const cmd = kind === "rebound" && d?.command ? d.command : it.command;
179
+ const r = run(cmd, ctx.cwd, timeoutMs);
180
+ if (!r.ok) {
181
+ failures.push({
182
+ source: "acceptance",
183
+ reason: `${it.id}: ${it.statement ?? "acceptance item"} — \`${cmd}\` failed (expected: ${it.expect ?? "exit 0"})`,
184
+ evidence: r.tail,
185
+ });
186
+ }
187
+ }
188
+ return failures;
189
+ },
190
+ });
191
+
192
+ /** GREEN when the working tree has changes (a side-effect unit actually did something). */
193
+ export const treeChanged: Check = {
194
+ name: "tree-changed",
195
+ run: (ctx) => {
196
+ const out = execSync("git status --porcelain", { cwd: ctx.cwd }).toString().trim();
197
+ return out.length === 0 ? [{ source: "tree-changed", reason: "the unit left the working tree unchanged" }] : [];
198
+ },
199
+ };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The learning edge — the long return path. A unit that went red and was then
3
+ * corrected to green in an ACCEPTED run (the run reached `learn`) leaves each
4
+ * corrected failure behind as a standing constraint; every later run's
5
+ * producer for that unit reads the most frequent ones in its brief. It fixes
6
+ * every run after, where the correction edge only fixes the run it is in.
7
+ *
8
+ * Deterministic and cross-run by design: one JSON file under `.rpiv/lessons/`,
9
+ * keyed by unit + source + reason, counted. A failure a unit keeps hitting run
10
+ * after run rises to the top of its brief.
11
+ */
12
+
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import type { ScriptContext } from "@juicesharp/rpiv-workflow/registration";
16
+
17
+ export const LESSONS_FILE = ".rpiv/lessons/meta-lessons.json";
18
+ const MAX_IN_BRIEF = 8;
19
+ const MAX_REASON = 240;
20
+
21
+ interface Lesson {
22
+ unit: string;
23
+ source: string;
24
+ reason: string;
25
+ count: number;
26
+ lastRun: string;
27
+ }
28
+
29
+ type LessonBook = Record<string, Lesson>;
30
+
31
+ const read = (cwd: string): LessonBook => {
32
+ const p = join(cwd, LESSONS_FILE);
33
+ if (!existsSync(p)) return {};
34
+ try {
35
+ return JSON.parse(readFileSync(p, "utf-8")) as LessonBook;
36
+ } catch {
37
+ return {};
38
+ }
39
+ };
40
+
41
+ export function lessonsBlock(cwd: string, unit: string): string {
42
+ const top = Object.values(read(cwd))
43
+ .filter((l) => l.unit === unit)
44
+ .sort((a, b) => b.count - a.count || b.lastRun.localeCompare(a.lastRun))
45
+ .slice(0, MAX_IN_BRIEF);
46
+ if (top.length === 0) return "";
47
+ return [
48
+ "",
49
+ "## Standing constraints (learned from earlier accepted runs)",
50
+ "Earlier runs of this unit went red on the items below and had to be corrected. Get them right the first time:",
51
+ ...top.map((l) => `- [${l.source}, seen ${l.count}×] ${l.reason}`),
52
+ ].join("\n");
53
+ }
54
+
55
+ interface RedRecord {
56
+ unit?: string;
57
+ pass?: boolean;
58
+ failures?: Array<{ source?: string; reason?: string }>;
59
+ }
60
+
61
+ export function recordLessons({ state, cwd }: ScriptContext, units: readonly string[]): void {
62
+ const runId = (state.output?.meta as { runId?: string } | undefined)?.runId ?? new Date().toISOString();
63
+ const book = read(cwd);
64
+ let added = 0;
65
+ for (const unit of units) {
66
+ const reds = [...(state.named[`${unit}-check`] ?? []), ...(state.named[`${unit}-gate`] ?? [])]
67
+ .map((o) => o.data as RedRecord)
68
+ .filter((r) => r && r.pass === false);
69
+ for (const r of reds) {
70
+ for (const f of r.failures ?? []) {
71
+ if (!f.reason) continue;
72
+ const reason = f.reason.slice(0, MAX_REASON);
73
+ const key = `${unit}::${f.source ?? "?"}::${reason}`;
74
+ const prev = book[key];
75
+ book[key] = { unit, source: f.source ?? "?", reason, count: (prev?.count ?? 0) + 1, lastRun: runId };
76
+ added++;
77
+ }
78
+ }
79
+ }
80
+ if (added === 0) return;
81
+ const p = join(cwd, LESSONS_FILE);
82
+ mkdirSync(dirname(p), { recursive: true });
83
+ writeFileSync(p, `${JSON.stringify(book, null, 2)}\n`);
84
+ }