@juicesharp/rpiv-pi 2.10.1 → 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.
@@ -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
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * The built-in `meta` unit graph — the A/B challenger to `build`.
3
+ *
4
+ * meta research → acceptance → plan → implement → commit
5
+ *
6
+ * research is the one mandatory unit; the rest are optional per graph.
7
+ *
8
+ * Same skills as build/ship (research, acceptance, quick-plan, implement), so
9
+ * an A/B run measures the SHAPE — per-unit loops with code-first graders and
10
+ * scoped returns vs build's sliced, panel-gated stage graph — not the prompts.
11
+ */
12
+
13
+ import { IMPLEMENT_DAG_FANOUT } from "../built-ins/index.js";
14
+ import {
15
+ acceptanceCommands,
16
+ acceptanceDisposed,
17
+ acceptanceWellFormed,
18
+ artifactWritten,
19
+ minCitations,
20
+ planCitations,
21
+ treeChanged,
22
+ } from "./checks.js";
23
+ import { defineUnitGraph, type UnitSpec } from "./unit-graph.js";
24
+
25
+ const research: UnitSpec = {
26
+ skill: "research",
27
+ output: "research",
28
+ checks: [artifactWritten(20), minCitations(5)],
29
+ graders: [
30
+ {
31
+ lens: "grounding",
32
+ rubric:
33
+ "FAIL if any claim the brief depends on is asserted without a file:line that actually shows it, or if a cited file:line does not say what the doc claims (open and check at least 5 citations). FAIL if the doc misses a module the brief obviously touches. Otherwise PASS.",
34
+ context: ["goal"],
35
+ },
36
+ ],
37
+ maxRounds: 2,
38
+ };
39
+
40
+ const acceptance: UnitSpec = {
41
+ skill: "acceptance",
42
+ reads: ["goal", "research"],
43
+ output: "acceptance",
44
+ checks: [artifactWritten(5), acceptanceWellFormed],
45
+ maxRounds: 2,
46
+ };
47
+
48
+ const plan: UnitSpec = {
49
+ skill: "quick-plan",
50
+ reads: ["research", "goal", "acceptance"],
51
+ output: "plans",
52
+ fix: {
53
+ prompt: ({ flags }) =>
54
+ `Revise the implementation plan in place so it clears the failures below. Read these inputs first: ${flags}. Keep the plan's frontmatter schema (phases, files, acceptance dispositions) intact; announce the plan's path when done.`,
55
+ },
56
+ checks: [artifactWritten(20), planCitations, acceptanceDisposed],
57
+ graders: [
58
+ {
59
+ lens: "correctness",
60
+ rubric:
61
+ "FAIL (medium+) only for a defect that makes the plan wrong AS WRITTEN: a referenced symbol/API/file that does not exist or has a different signature, an edit anchor that does not match the code, or a phase whose code would not compile against the tree. Open the cited code — batch your reads — before ruling. Style and nits are low.",
62
+ context: ["research"],
63
+ },
64
+ {
65
+ lens: "completeness",
66
+ rubric:
67
+ "FAIL (medium+) if any ask in the goal is neither implemented by a phase nor explicitly deferred under Out of Scope, or if any acceptance item's disposition is dishonest (marked implemented but no phase delivers it). Otherwise PASS.",
68
+ context: ["goal", "acceptance"],
69
+ },
70
+ ],
71
+ maxRounds: 3,
72
+ };
73
+
74
+ const implement: UnitSpec = {
75
+ skill: "implement",
76
+ reads: ["plans"],
77
+ loop: IMPLEMENT_DAG_FANOUT,
78
+ fix: {
79
+ prompt: ({ flags }) =>
80
+ `Repair the implementation of the plan (${flags}) so the failing checks below pass. You are fixing, not re-implementing: the other phases are done and correct.`,
81
+ },
82
+ checks: [treeChanged, acceptanceCommands()],
83
+ graders: [
84
+ {
85
+ lens: "goal",
86
+ rubric:
87
+ "Read the goal, then the working-tree diff (git diff + untracked files). FAIL (medium+) if the diff does not deliver an ask the goal makes, delivers something the goal did not ask for, or leaves an obvious break (dead code path, unwired call site). Cite file:line. Otherwise PASS.",
88
+ context: ["goal", "plans"],
89
+ },
90
+ ],
91
+ maxRounds: 3,
92
+ onExhausted: { escalateTo: "plan" },
93
+ };
94
+
95
+ export const metaWorkflow = defineUnitGraph({
96
+ name: "meta",
97
+ description:
98
+ "Graph of self-correcting units: research → acceptance → plan → implement → commit. Each unit loops produce → deterministic checks → parallel lens graders → scoped correction (max 3 rounds; identical failures twice stop early); an exhausted implement escalates to plan. No confirm/demote passes, no slicing; accepted runs feed their corrected failures forward as standing constraints (.rpiv/lessons). The A/B challenger to build.",
99
+ units: [
100
+ ["research", research],
101
+ ["acceptance", acceptance],
102
+ ["plan", plan],
103
+ ["implement", implement],
104
+ ],
105
+ });