diff --git a/pm-stack/aggregator/package.json b/pm-stack/aggregator/package.json index 0d4086cee0..a3b951b1d3 100644 --- a/pm-stack/aggregator/package.json +++ b/pm-stack/aggregator/package.json @@ -14,7 +14,8 @@ "contract:check": "bun run scripts/check-contract-corpus.ts", "provenance:check": "bun run scripts/check-provenance-matrix.ts", "typecheck": "bunx tsc --noEmit", - "build:css": "tailwindcss -i src/ui.css -o src/assets/app.css" + "build:css": "tailwindcss -i src/ui.css -o src/assets/app.css", + "proposals:quota-reweight": "bun run scripts/quota-reweight-proposals.ts" }, "devDependencies": { "@playwright/test": "1.64.0", diff --git a/pm-stack/aggregator/scripts/quota-reweight-proposals.ts b/pm-stack/aggregator/scripts/quota-reweight-proposals.ts new file mode 100644 index 0000000000..2a095345cb --- /dev/null +++ b/pm-stack/aggregator/scripts/quota-reweight-proposals.ts @@ -0,0 +1,327 @@ +#!/usr/bin/env bun +// Generate Stage-3 re-weighting proposals from the forecast +// accuracy ledger (issue #12700, slice S6 of epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §5, D5). +// +// bun run scripts/quota-reweight-proposals.ts --ledger \ +// --route-config --out-dir \ +// [--forecast ] [--shadow ] [--repo-root ] \ +// [--gh ] [--base ] [--open-prs] +// +// (Committed as the package.json script `proposals:quota-reweight`.) +// +// Draft mode (default) writes, per proposal, a directory holding +// proposal.json, the evidence pack (proposal.md — the exact text +// the PR body carries), and change.patch; plus a run report.md +// listing proposals AND evidence gaps. Nothing touches git or gh +// in draft mode. With --open-prs, each proposal additionally goes +// through quota-reweight-pr.ts's PR-only path: a quota-proposal/… +// branch and a `gh pr create` — never a merge, never a push to +// main (the allowlist there is the enforcement; see that module). +// +// Inputs: --ledger is S2's accuracy ledger JSON (the +// `backtest:quota-forecast --ledger-out` product today; the same +// shape scored from live forecast rows later — the generator's +// contract is the ledger shape, not its provenance). --forecast +// and --shadow are the S1/S3 products from the aggregator state +// dir when they exist; both are optional evidence-pack inputs, +// and their absence is reported in the pack, never papered over. +// +// Argument contract (#3352): the whole command line is declared +// here — the value options and the one flag above, in `--opt +// value` or `--opt=value` form — and parsed strictly before any +// file is read or written. An unknown argument, a stray +// positional, or a present-but-valueless option is a usage error +// (exit 2) naming the offending argument. +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import type { ForecastAccuracyLedger } from "../src/quota-forecast-accuracy.ts"; +import type { QuotaForecastFile } from "../src/quota-forecast.ts"; +import type { ShadowPlacementRecord } from "../src/quota-shadow-placement.ts"; +import { + buildReweightProposals, + renderEvidencePack, + renderRunReport, + type RouteWeightTable, +} from "../src/quota-reweight.ts"; +import { nodeRunner, openProposalPr } from "../src/quota-reweight-pr.ts"; + +const VALUE_OPTIONS = [ + "--ledger", + "--route-config", + "--forecast", + "--shadow", + "--out-dir", + "--repo-root", + "--gh", + "--base", +] as const; +type ValueOption = (typeof VALUE_OPTIONS)[number]; +const FLAG_OPTIONS = ["--open-prs"] as const; + +function usageError(message: string): never { + console.error(`quota-reweight-proposals: ${message}`); + console.error( + "usage: quota-reweight-proposals --ledger --route-config --out-dir " + + "[--forecast ] [--shadow ] [--repo-root ] [--gh ] [--base ] [--open-prs]", + ); + process.exit(2); +} + +function parseArgs(argv: string[]): { values: Record; openPrs: boolean } { + const values: Record = { + "--ledger": undefined, + "--route-config": undefined, + "--forecast": undefined, + "--shadow": undefined, + "--out-dir": undefined, + "--repo-root": undefined, + "--gh": undefined, + "--base": undefined, + }; + let openPrs = false; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] as string; + const eq = arg.indexOf("="); + const name = eq >= 0 ? arg.slice(0, eq) : arg; + if ((FLAG_OPTIONS as readonly string[]).includes(name)) { + if (eq >= 0) usageError(`flag '${name}' takes no value; refusing to run, no files read or written`); + openPrs = true; + continue; + } + if (!(VALUE_OPTIONS as readonly string[]).includes(name)) { + usageError(`unknown argument '${arg}'; refusing to run, no files read or written`); + } + const opt = name as ValueOption; + let value: string | undefined; + if (eq >= 0) { + value = arg.slice(eq + 1); + } else { + value = argv[i + 1]; + if (value !== undefined) i++; + } + if (value === undefined || value.trim() === "" || value.startsWith("--")) { + usageError(`option '${opt}' requires a non-empty value; refusing to run, no files read or written`); + } + values[opt] = value; + } + return { values, openPrs }; +} + +/** Strip // and /* *\/ comments from JSONC without touching string + * literals (the route config's comments are load-bearing prose, + * but its strings carry URLs and model ids a naive strip would + * corrupt). */ +export function stripJsoncComments(text: string): string { + let out = ""; + let inString = false; + let escaped = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i] as string; + const next = text[i + 1] ?? ""; + if (inString) { + out += ch; + if (escaped) escaped = false; + else if (ch === "\\") escaped = true; + else if (ch === '"') inString = false; + continue; + } + if (ch === '"') { + inString = true; + out += ch; + continue; + } + if (ch === "/" && next === "/") { + while (i < text.length && text[i] !== "\n") i++; + out += "\n"; + continue; + } + if (ch === "/" && next === "*") { + i += 2; + while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++; + i++; + continue; + } + out += ch; + } + return dropTrailingCommas(out); +} + +/** Remove trailing commas (a comma whose next non-whitespace + * character closes an object or array) — JSONC permits them, + * JSON.parse does not. String-aware, like the comment pass. */ +function dropTrailingCommas(text: string): string { + let out = ""; + let inString = false; + let escaped = false; + for (let i = 0; i < text.length; i++) { + const ch = text[i] as string; + if (inString) { + out += ch; + if (escaped) escaped = false; + else if (ch === "\\") escaped = true; + else if (ch === '"') inString = false; + continue; + } + if (ch === '"') { + inString = true; + out += ch; + continue; + } + if (ch === ",") { + let j = i + 1; + while (j < text.length && /\s/.test(text[j] as string)) j++; + if (text[j] === "}" || text[j] === "]") continue; + } + out += ch; + } + return out; +} + +/** Extract every route carrying a selection + numeric weights map + * from the parsed route config, and anchor each one's weights + * line in the original (commented) text for exact find/replace. */ +export function extractRoutes(configText: string): RouteWeightTable[] { + const parsed = JSON.parse(stripJsoncComments(configText)) as unknown; + const routes: RouteWeightTable[] = []; + const walk = (node: unknown): void => { + if (Array.isArray(node)) { + for (const item of node) walk(item); + return; + } + if (node === null || typeof node !== "object") return; + for (const [key, value] of Object.entries(node as Record)) { + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + const v = value as Record; + const weights = v.weights; + if ( + typeof v.selection === "string" && + weights !== null && + typeof weights === "object" && + !Array.isArray(weights) && + Object.values(weights as Record).every((n) => typeof n === "number") + ) { + routes.push({ + routeId: key, + selection: v.selection, + weights: weights as Record, + weightsLine: findWeightsLine(configText, key), + }); + } + } + walk(value); + } + }; + walk(parsed); + return routes; +} + +/** The exact source line carrying a route's weights object, or + * null when the object spans lines (the generator then refuses + * to edit it rather than guess). */ +function findWeightsLine(configText: string, routeId: string): string | null { + const anchor = configText.indexOf(`"${routeId}"`); + if (anchor < 0) return null; + const wIdx = configText.indexOf('"weights"', anchor); + if (wIdx < 0) return null; + const lineStart = configText.lastIndexOf("\n", wIdx) + 1; + const lineEnd = configText.indexOf("\n", wIdx); + const line = configText.slice(lineStart, lineEnd < 0 ? undefined : lineEnd); + const afterWeights = line.slice(line.indexOf('"weights"')); + return afterWeights.includes("}") ? line : null; +} + +async function readJson(path: string, what: string): Promise { + try { + return JSON.parse(await readFile(path, "utf8")) as T; + } catch (err) { + console.error(`quota-reweight-proposals: could not read ${what} at ${path}: ${(err as Error).message}`); + process.exit(1); + } +} + +function patchFor(file: string, find: string, replace: string): string { + return [`--- a/${file}`, `+++ b/${file}`, `-${find}`, `+${replace}`, ""].join("\n"); +} + +async function main(): Promise { + const { values, openPrs } = parseArgs(process.argv.slice(2)); + const ledgerPath = values["--ledger"]; + const routeConfigPath = values["--route-config"]; + const outDir = values["--out-dir"]; + if (!ledgerPath) usageError("--ledger is required; refusing to run, no files read or written"); + if (!routeConfigPath) usageError("--route-config is required; refusing to run, no files read or written"); + if (!outDir) usageError("--out-dir is required; refusing to run, no files read or written"); + + const scriptDir = dirname(fileURLToPath(import.meta.url)); + const repoRoot = resolve(values["--repo-root"] ?? join(scriptDir, "..", "..", "..")); + const ghPath = values["--gh"] ?? "/usr/bin/gh"; + const base = values["--base"] ?? "main"; + + const ledger = await readJson(ledgerPath, "accuracy ledger"); + if (ledger?.kind !== "quota-forecast-accuracy" || !Array.isArray(ledger.pools)) { + console.error(`quota-reweight-proposals: ${ledgerPath} is not a quota-forecast-accuracy ledger`); + process.exit(1); + } + const forecast = values["--forecast"] + ? await readJson(values["--forecast"], "forecast file") + : null; + const shadow = values["--shadow"] + ? await readJson(values["--shadow"], "shadow record") + : null; + const configText = await readFile(routeConfigPath, "utf8"); + const routes = extractRoutes(configText); + + const derivePath = join(repoRoot, "pm-stack", "aggregator", "src", "derive.ts"); + const deriveText = await readFile(derivePath, "utf8"); + const nearMatches = [...deriveText.matchAll(/export const NEAR_PCT = (\d+);/g)]; + if (nearMatches.length !== 1) { + console.error( + `quota-reweight-proposals: expected exactly one 'export const NEAR_PCT = ;' in ${derivePath}, found ${nearMatches.length}; refusing to run`, + ); + process.exit(1); + } + const nearPctCurrent = Number((nearMatches[0] as RegExpMatchArray)[1]); + + const run = buildReweightProposals({ ledger, routes, forecast, shadow, nearPctCurrent }); + const generatedAt = new Date().toISOString(); + + await mkdir(outDir, { recursive: true }); + for (const p of run.proposals) { + const dir = join(outDir, p.key.replace(/[^a-zA-Z0-9._-]/g, "-")); + await mkdir(dir, { recursive: true }); + await writeFile(join(dir, "proposal.json"), `${JSON.stringify(p, null, 2)}\n`); + await writeFile(join(dir, "proposal.md"), renderEvidencePack(p)); + await writeFile(join(dir, "change.patch"), patchFor(p.target.file, p.target.find, p.target.replace)); + } + + const opened: { key: string; branch: string; url: string }[] = []; + if (openPrs) { + for (const p of run.proposals) { + const res = await openProposalPr({ + runner: nodeRunner, + ghPath, + repoRoot, + scratchDir: join(outDir, "scratch"), + proposal: p, + base, + }); + opened.push({ key: p.key, ...res }); + console.log(`opened proposal PR for ${p.key}: ${res.url}`); + } + if (opened.length) await writeFile(join(outDir, "prs.json"), `${JSON.stringify(opened, null, 2)}\n`); + } + + let report = renderRunReport(run, generatedAt); + if (opened.length) { + report += `\n## Proposal PRs opened\n\n${opened.map((o) => `- \`${o.key}\`: ${o.url}`).join("\n")}\n`; + } + await writeFile(join(outDir, "report.md"), report); + console.log( + `quota-reweight-proposals: ${run.proposals.length} proposal(s), ${run.gaps.length} evidence gap(s); ` + + `drafts in ${outDir}${openPrs ? `; ${opened.length} PR(s) opened` : ""}`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/quota-reweight-pr.test.ts b/pm-stack/aggregator/src/quota-reweight-pr.test.ts new file mode 100644 index 0000000000..02ead8885c --- /dev/null +++ b/pm-stack/aggregator/src/quota-reweight-pr.test.ts @@ -0,0 +1,164 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ReweightProposal } from "./quota-reweight.ts"; +import { + ProposalPrError, + applyProposalEdit, + assertGhAllowed, + assertGitAllowed, + openProposalPr, + proposalBranch, + type CommandResult, + type CommandRunner, +} from "./quota-reweight-pr.ts"; + +// Oracle: design D5's hard rule (#1177, via #12700's acceptance): +// the generator has no write path to configuration except the PR +// and no merge rights. These tests pin the structural form of +// that rule — the allowlist refuses merge/push-to-main BEFORE any +// command runs, and a full openProposalPr drive over a fake runner +// performs exactly the branch+PR sequence and nothing else. + +const MARGIN_PROPOSAL: ReweightProposal = { + key: "caution-margin:NEAR_PCT:85->90", + proposalClass: "caution-margin", + title: "proposal(quota-plane): widen the caution margin NEAR_PCT 85 → 90", + target: { + description: "the caution margin NEAR_PCT", + file: "pm-stack/aggregator/src/derive.ts", + find: "export const NEAR_PCT = 85;", + replace: "export const NEAR_PCT = 90;", + currentValue: "85", + proposedValue: "90", + }, + rationale: "test rationale", + evidence: { + ledgerGeneratedAt: "2026-11-23T00:00:00.000Z", + ledgerStore: { records: 1, pctRecords: 1, fromIso: null, toIso: null }, + ledgerModel: "test-model", + rows: [], + forecastSummary: "no forecast file supplied to this run", + shadowSummary: "no shadow record supplied to this run", + }, + expectedEffect: { statement: "s", metric: "m", scoredBy: "S7" }, +}; + +describe("gh allowlist", () => { + test("permits only pr create and pr list", () => { + expect(() => assertGhAllowed(["pr", "create", "--title", "x"])).not.toThrow(); + expect(() => assertGhAllowed(["pr", "list", "--state", "open"])).not.toThrow(); + }); + test("refuses merge, close, edit, api, and issue commands", () => { + for (const args of [ + ["pr", "merge", "123"], + ["pr", "close", "123"], + ["pr", "edit", "123"], + ["api", "repos/x/y/pulls/1/merge"], + ["issue", "create", "--title", "x"], + ]) { + expect(() => assertGhAllowed(args)).toThrow(ProposalPrError); + } + }); +}); + +describe("git allowlist", () => { + test("permits fetch, worktree add, add, commit, and push to a proposal branch", () => { + expect(() => assertGitAllowed(["fetch", "origin", "main"])).not.toThrow(); + expect(() => assertGitAllowed(["worktree", "add", "-b", "quota-proposal/x", "/tmp/wt", "origin/main"])).not.toThrow(); + expect(() => assertGitAllowed(["add", "--", "file.ts"])).not.toThrow(); + expect(() => assertGitAllowed(["commit", "-m", "msg"])).not.toThrow(); + expect(() => assertGitAllowed(["push", "origin", "quota-proposal/caution-margin/NEAR_PCT/85-to-90"])).not.toThrow(); + }); + test("refuses push to main or any non-proposal ref, and refuses merge/rebase", () => { + for (const args of [ + ["push", "origin", "main"], + ["push", "origin", "felix/some-branch"], + ["push", "--force", "origin", "quota-proposal/x"], + ["merge", "origin/main"], + ["rebase", "main"], + ["worktree", "remove", "/tmp/wt"], + ]) { + expect(() => assertGitAllowed(args)).toThrow(ProposalPrError); + } + }); +}); + +describe("edit anchoring", () => { + test("applies an exactly-once anchor", () => { + expect(applyProposalEdit("a\nexport const NEAR_PCT = 85;\nb", MARGIN_PROPOSAL)).toContain("NEAR_PCT = 90;"); + }); + test("refuses zero or multiple occurrences", () => { + expect(() => applyProposalEdit("nothing here", MARGIN_PROPOSAL)).toThrow(ProposalPrError); + expect(() => + applyProposalEdit("export const NEAR_PCT = 85;\nexport const NEAR_PCT = 85;", MARGIN_PROPOSAL), + ).toThrow(ProposalPrError); + }); +}); + +describe("openProposalPr over a fake runner", () => { + let scratch: string | null = null; + afterEach(async () => { + if (scratch) await rm(scratch, { recursive: true, force: true }); + scratch = null; + }); + + function fakeRunner(calls: { cmd: string; args: string[] }[], prListStdout = "[]"): CommandRunner { + return async (cmd, args): Promise => { + calls.push({ cmd, args: [...args] }); + if (cmd.endsWith("gh") && args[0] === "pr" && args[1] === "list") return { code: 0, stdout: prListStdout, stderr: "" }; + if (cmd.endsWith("gh") && args[0] === "pr" && args[1] === "create") + return { code: 0, stdout: "https://github.com/developing-today/code/pull/99999\n", stderr: "" }; + return { code: 0, stdout: "", stderr: "" }; + }; + } + + test("performs exactly the branch + edit + push + pr-create sequence, with no merge anywhere", async () => { + scratch = await mkdtemp(join(tmpdir(), "reweight-pr-")); + const repoRoot = join(scratch, "repo"); + const branch = proposalBranch(MARGIN_PROPOSAL.key); + const wtDir = join(scratch, "out", branch.replace(/\//g, "-")); + await mkdir(join(wtDir, "pm-stack", "aggregator", "src"), { recursive: true }); + await writeFile(join(wtDir, "pm-stack", "aggregator", "src", "derive.ts"), "export const NEAR_PCT = 85;\n"); + + const calls: { cmd: string; args: string[] }[] = []; + const res = await openProposalPr({ + runner: fakeRunner(calls), + ghPath: "/usr/bin/gh", + repoRoot, + scratchDir: join(scratch, "out"), + proposal: MARGIN_PROPOSAL, + }); + expect(res.url).toBe("https://github.com/developing-today/code/pull/99999"); + expect(res.branch).toBe("quota-proposal/caution-margin/NEAR_PCT/85-to-90"); + // the edit landed in the scratch worktree + const edited = await readFile(join(wtDir, "pm-stack", "aggregator", "src", "derive.ts"), "utf8"); + expect(edited).toContain("NEAR_PCT = 90;"); + // the whole drive used only allowlisted shapes + for (const c of calls) { + if (c.cmd.endsWith("gh")) expect(() => assertGhAllowed(c.args)).not.toThrow(); + else expect(() => assertGitAllowed(c.args)).not.toThrow(); + expect(c.args).not.toContain("merge"); + } + const pushes = calls.filter((c) => c.args[0] === "push"); + expect(pushes).toHaveLength(1); + expect(pushes[0]?.args).toEqual(["push", "origin", branch]); + const creates = calls.filter((c) => c.cmd.endsWith("gh") && c.args[1] === "create"); + expect(creates).toHaveLength(1); + }); + + test("dedupes: an already-open PR for the branch is returned, nothing else runs", async () => { + scratch = await mkdtemp(join(tmpdir(), "reweight-pr-")); + const calls: { cmd: string; args: string[] }[] = []; + const res = await openProposalPr({ + runner: fakeRunner(calls, JSON.stringify([{ url: "https://github.com/developing-today/code/pull/88888" }])), + ghPath: "/usr/bin/gh", + repoRoot: join(scratch, "repo"), + scratchDir: join(scratch, "out"), + proposal: MARGIN_PROPOSAL, + }); + expect(res.url).toBe("https://github.com/developing-today/code/pull/88888"); + expect(calls).toHaveLength(1); // the pr list only + }); +}); diff --git a/pm-stack/aggregator/src/quota-reweight-pr.ts b/pm-stack/aggregator/src/quota-reweight-pr.ts new file mode 100644 index 0000000000..ef82b80c18 --- /dev/null +++ b/pm-stack/aggregator/src/quota-reweight-pr.ts @@ -0,0 +1,261 @@ +// The PR-only write path for the Stage-3 re-weighting proposal +// generator (issue #12700, slice S6 of epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §5, D5). +// +// Acceptance shape: the generator provably cannot merge or push +// to main directly. The proof here is structural, not procedural: +// +// - Every subprocess the generator runs goes through one choke +// point (runChecked), and every command is validated against an +// allowlist BEFORE it executes. A command not on the list throws +// ProposalPrError and never runs. +// - The gh allowlist is exactly two subcommands: `pr create` and +// `pr list` (the latter for dedupe). There is no `pr merge`, no +// `pr close`, no `api`, no `issue` — the vocabulary to merge or +// to edit anything except by opening a PR does not exist here. +// - The git allowlist permits fetch, worktree add, add, commit, +// and push — and push is validated to target a proposal branch +// (quota-proposal/…) and nothing else. A push to main (or any +// other ref) throws before it runs. +// - The config edit itself is an exact find/replace that must +// match exactly once in the target file, or it throws: the +// generator cannot produce a fuzzy edit. +// +// The generator runs under the owner's ordinary gh/git identity — +// the enforcement is this code path, stated plainly: within the +// generator, merging is not a forbidden call, it is an +// unrepresentable one. Merge authority stays where it is +// (Felix/Drew); a proposal PR is reviewed and merged (or not) by +// a human through the ordinary path. + +import { execFile } from "node:child_process"; +import { mkdir, readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { ReweightProposal } from "./quota-reweight.ts"; +import { renderEvidencePack } from "./quota-reweight.ts"; + +export class ProposalPrError extends Error {} + +/** Every proposal branch carries this prefix; pushes to anything + * else are refused by assertGitAllowed. */ +export const PROPOSAL_BRANCH_PREFIX = "quota-proposal/"; + +export type CommandResult = { code: number; stdout: string; stderr: string }; +export type CommandRunner = ( + cmd: string, + args: string[], + opts: { cwd: string }, +) => Promise; + +/** The real runner: execFile, no shell, so an argument can never + * smuggle a second command. */ +export const nodeRunner: CommandRunner = (cmd, args, opts) => + new Promise((resolve) => { + execFile(cmd, args, { cwd: opts.cwd, maxBuffer: 16 * 1024 * 1024 }, (err, stdout, stderr) => { + resolve({ + code: err ? ((err as { code?: number }).code ?? 1) : 0, + stdout: String(stdout), + stderr: String(stderr), + }); + }); + }); + +const GH_ALLOWED: ReadonlyArray = [ + ["pr", "create"], + ["pr", "list"], +]; + +/** Validate a gh invocation against the PR-only allowlist. Throws + * ProposalPrError naming the refused command; returns void when + * the invocation is one the generator may make. */ +export function assertGhAllowed(args: readonly string[]): void { + const [a, b] = args; + if (!GH_ALLOWED.some(([x, y]) => x === a && y === b)) { + throw new ProposalPrError( + `refused gh invocation 'gh ${args.join(" ")}': the proposal generator's gh surface is ` + + `only 'pr create' and 'pr list' (design D5, PR-only write path)`, + ); + } +} + +const GIT_ALLOWED_SUBCOMMANDS: ReadonlySet = new Set([ + "fetch", + "worktree", + "add", + "commit", + "push", + "rev-parse", + "status", +]); + +/** Validate a git invocation. Push is restricted to proposal + * branches; worktree is restricted to `add`. */ +export function assertGitAllowed(args: readonly string[]): void { + const [sub, ...rest] = args; + if (sub === undefined || !GIT_ALLOWED_SUBCOMMANDS.has(sub)) { + throw new ProposalPrError( + `refused git invocation 'git ${args.join(" ")}': subcommand '${sub ?? ""}' is not in the ` + + `proposal generator's allowlist`, + ); + } + if (sub === "worktree" && rest[0] !== "add") { + throw new ProposalPrError( + `refused git invocation 'git ${args.join(" ")}': only 'worktree add' is allowed`, + ); + } + if (sub === "push") { + const target = rest[rest.length - 1] ?? ""; + if (rest[0] !== "origin" || !target.startsWith(PROPOSAL_BRANCH_PREFIX)) { + throw new ProposalPrError( + `refused git push 'git ${args.join(" ")}': the proposal generator may push only to ` + + `${PROPOSAL_BRANCH_PREFIX}… branches — never to main or any other ref (design D5)`, + ); + } + } +} + +/** Run one command through the choke point: validate, then run, + * then require success. */ +async function runChecked( + runner: CommandRunner, + cmd: string, + args: string[], + cwd: string, +): Promise { + if (cmd.endsWith("gh") || cmd === "gh") assertGhAllowed(args); + else if (cmd.endsWith("git") || cmd === "git") assertGitAllowed(args); + else throw new ProposalPrError(`refused command '${cmd}': the generator runs only gh and git`); + const res = await runner(cmd, args, { cwd }); + if (res.code !== 0) { + throw new ProposalPrError( + `'${cmd} ${args.join(" ")}' failed (exit ${res.code}): ${res.stderr.trim() || res.stdout.trim()}`, + ); + } + return res; +} + +/** The branch a proposal opens under. The key's ':' separators + * become path segments and '->' becomes '-to-', so the branch is + * a valid ref and the key is recoverable from it. */ +export function proposalBranch(key: string): string { + const slug = key.replace(/:/g, "/").replace(/->/g, "-to-").replace(/[^a-zA-Z0-9._/-]/g, "-"); + return `${PROPOSAL_BRANCH_PREFIX}${slug}`; +} + +/** Apply a proposal's edit to file contents: the find text must + * occur exactly once, or the edit is refused — the generator + * never produces a fuzzy or partial edit. */ +export function applyProposalEdit(content: string, proposal: ReweightProposal): string { + const { find, replace } = proposal.target; + const occurrences = content.split(find).length - 1; + if (occurrences !== 1) { + throw new ProposalPrError( + `edit anchor for '${proposal.key}' occurs ${occurrences} times in ${proposal.target.file} ` + + `(expected exactly 1); refusing to edit`, + ); + } + return content.replace(find, replace); +} + +/** The URL of an already-open PR for this proposal's branch, if + * one exists (dedupe: the generator never opens a second PR for + * the same proposal key). */ +export async function findOpenProposalPr(args: { + runner: CommandRunner; + ghPath: string; + repoRoot: string; + branch: string; +}): Promise { + const res = await runChecked( + args.runner, + args.ghPath, + ["pr", "list", "--state", "open", "--head", args.branch, "--json", "url", "--limit", "1"], + args.repoRoot, + ); + try { + const rows = JSON.parse(res.stdout) as { url?: string }[]; + return rows[0]?.url ?? null; + } catch { + throw new ProposalPrError(`could not parse 'gh pr list' output for ${args.branch}: ${res.stdout.slice(0, 200)}`); + } +} + +/** + * Open the proposal PR: branch from origin/main in a scratch + * worktree, apply the exact edit, commit, push the proposal + * branch, and `gh pr create` with the evidence pack as the body. + * Returns the PR URL. This function contains no merge step and + * cannot be made to perform one — see the allowlist above. + */ +export async function openProposalPr(args: { + runner: CommandRunner; + ghPath: string; + gitPath?: string; + repoRoot: string; + scratchDir: string; + proposal: ReweightProposal; + base?: string; +}): Promise<{ branch: string; url: string }> { + const git = args.gitPath ?? "git"; + const base = args.base ?? "main"; + const branch = proposalBranch(args.proposal.key); + const existing = await findOpenProposalPr({ + runner: args.runner, + ghPath: args.ghPath, + repoRoot: args.repoRoot, + branch, + }); + if (existing) return { branch, url: existing }; + + await runChecked(args.runner, git, ["fetch", "origin", base], args.repoRoot); + const wtDir = join(args.scratchDir, branch.replace(/\//g, "-")); + await mkdir(args.scratchDir, { recursive: true }); + await runChecked( + args.runner, + git, + ["worktree", "add", "-b", branch, wtDir, `origin/${base}`], + args.repoRoot, + ); + const targetPath = join(wtDir, args.proposal.target.file); + const content = await readFile(targetPath, "utf8"); + await writeFile(targetPath, applyProposalEdit(content, args.proposal)); + const packPath = join(args.scratchDir, `${branch.replace(/\//g, "-")}.md`); + await writeFile(packPath, renderEvidencePack(args.proposal)); + await runChecked(args.runner, git, ["add", "--", args.proposal.target.file], wtDir); + await runChecked( + args.runner, + git, + [ + "commit", + "-m", + args.proposal.title, + "-m", + `Generated by the Stage-3 re-weighting proposal generator (S6, #12700; design D5). ` + + `Proposal key: ${args.proposal.key}. The full evidence pack is the PR body.`, + ], + wtDir, + ); + await runChecked(args.runner, git, ["push", "origin", branch], wtDir); + const pr = await runChecked( + args.runner, + args.ghPath, + [ + "pr", + "create", + "--base", + base, + "--head", + branch, + "--title", + args.proposal.title, + "--body-file", + packPath, + ], + args.repoRoot, + ); + const url = pr.stdout.trim().split("\n").filter(Boolean).pop() ?? ""; + if (!url.startsWith("http")) { + throw new ProposalPrError(`'gh pr create' did not return a PR URL for ${branch}: ${pr.stdout.slice(0, 200)}`); + } + return { branch, url }; +} diff --git a/pm-stack/aggregator/src/quota-reweight.test.ts b/pm-stack/aggregator/src/quota-reweight.test.ts new file mode 100644 index 0000000000..5957abfbfc --- /dev/null +++ b/pm-stack/aggregator/src/quota-reweight.test.ts @@ -0,0 +1,362 @@ +import { describe, expect, test } from "bun:test"; +import type { + ForecastAccuracyLedger, + PoolBaseline, + WindowBaseline, +} from "./quota-forecast-accuracy.ts"; +import { + buildReweightProposals, + renderEvidencePack, + type RouteWeightTable, +} from "./quota-reweight.ts"; + +// Oracle: the Stage-3 design D5 (doc/2026-11-22T22-35-00Z_design_ +// quota-plane-stage-3, #12700): re-weighting proposals are PRs +// carrying the full evidence pack, grounded in S2's accuracy +// record — and a pool/window the record cannot score never +// grounds a proposal. S2's honesty rules bind here verbatim: +// unscoreable stays unscoreable with its reasons, undefined +// precision/recall stays undefined, and the bare opencode-go +// pool's rows (a cross-workspace mixing artifact) never ground +// anything — the per-workspace rows are the real ones. + +function win(over: Partial = {}): WindowBaseline { + return { + window: "weekly", + scoreable: true, + unscoreableReasons: [], + periodsTotal: 4, + periodsScored: 4, + periodsWalled: 3, + periodsOpen: 0, + periodsNoReset: 0, + forecastsIssued: 300, + forecastsScored: 300, + forecastsInsufficient: 0, + detectionsWhileWalled: 0, + tp: 100, + fp: 0, + fn: 50, + tn: 150, + precision: 1, + recall: 0.667, + wallErrorMin: { count: 100, meanSignedMin: 1000, medianSignedMin: 1000, medianAbsMin: 1000, p90AbsMin: 2000 }, + firstCallLeadMin: null, + ...over, + }; +} + +function pool(serviceId: string, windows: WindowBaseline[]): PoolBaseline { + return { + pool: serviceId, + providerId: null, + serviceIdsJoined: [serviceId], + windows, + rollup: win({ window: "rollup" }), + }; +} + +function ledger(pools: PoolBaseline[]): ForecastAccuracyLedger { + return { + version: 1, + kind: "quota-forecast-accuracy", + generatedAt: "2026-11-23T00:00:00.000Z", + model: "quota-analytics.projectWindow pace v1 (design D2, via S1 #12695)", + store: { records: 20663, pctRecords: 19735, fromIso: "2026-10-20T12:00:00.000Z", toIso: "2026-11-23T00:00:00.000Z" }, + pools, + }; +} + +const GO_ROUTE: RouteWeightTable = { + routeId: "opencode-go-plans", + selection: "weighted", + weights: { + "opencode-go.drewrypope": 2, + "opencode-go.popesdrew": 1, + "opencode-go.developing-today-0": 1, + "opencode-go.0x111dev": 1, + }, + weightsLine: + ' "weights": { "opencode-go.drewrypope": 2, "opencode-go.popesdrew": 1, "opencode-go.developing-today-0": 1, "opencode-go.0x111dev": 1 }', +}; + +describe("pool-weight class", () => { + test("fires on a late-wall member with a headroom sibling, preserving total weight", () => { + const run = buildReweightProposals({ + ledger: ledger([ + pool("opencode-go.drewrypope", [ + win({ forecastsScored: 300, precision: 1, recall: 0.5, wallErrorMin: { count: 40, meanSignedMin: 2000, medianSignedMin: 2000, medianAbsMin: 2000, p90AbsMin: 3000 } }), + ]), + pool("opencode-go.popesdrew", [ + win({ forecastsScored: 250, precision: 1, recall: 0.95, wallErrorMin: { count: 30, meanSignedMin: 100, medianSignedMin: 100, medianAbsMin: 100, p90AbsMin: 200 } }), + ]), + pool("opencode-go.developing-today-0", [win({ scoreable: false, forecastsScored: 0, unscoreableReasons: ["no percent readings for this pool/window in the store"] })]), + pool("opencode-go.0x111dev", [win({ forecastsScored: 10 })]), + ]), + routes: [GO_ROUTE], + nearPctCurrent: 85, + }); + const p = run.proposals.find((x) => x.proposalClass === "pool-weight"); + expect(p).toBeDefined(); + expect(p?.key).toBe("pool-weight:opencode-go-plans:opencode-go.drewrypope:2->1.5"); + expect(p?.target.replace).toContain('"opencode-go.drewrypope": 1.5'); + expect(p?.target.replace).toContain('"opencode-go.popesdrew": 1.5'); + // gaps name the two members that could not ground + const reasons = run.gaps.map((g) => g.reason); + expect(reasons).toContain("unscoreable-window"); + expect(reasons).toContain("insufficient-scored-forecasts"); + }); + + test("refuses when no sibling has headroom evidence", () => { + const run = buildReweightProposals({ + ledger: ledger([ + pool("opencode-go.drewrypope", [win({ forecastsScored: 300, precision: 1, recall: 0.5 })]), + pool("opencode-go.popesdrew", [win({ forecastsScored: 250, precision: 0.4, recall: 0.5 })]), + ]), + routes: [GO_ROUTE], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "pool-weight")).toHaveLength(0); + expect(run.examined.join("\n")).toContain("no weight proposal"); + }); + + test("refuses an unscoreable binding window, carrying S2's reason verbatim", () => { + const s2Reason = "every issued forecast was insufficient-history — the pace was never measurable in a completed period"; + const run = buildReweightProposals({ + ledger: ledger([ + pool("opencode-go.drewrypope", [win({ scoreable: false, forecastsScored: 0, unscoreableReasons: [s2Reason] })]), + pool("opencode-go.popesdrew", [win({ forecastsScored: 250, precision: 1, recall: 0.95 })]), + ]), + routes: [GO_ROUTE], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "pool-weight")).toHaveLength(0); + const gap = run.gaps.find((g) => g.reason === "unscoreable-window"); + expect(gap?.detail).toContain(s2Reason); + }); + + test("refuses undefined precision/recall instead of reading them as numbers", () => { + const run = buildReweightProposals({ + ledger: ledger([ + pool("opencode-go.drewrypope", [ + win({ forecastsScored: 300, precision: 0, recall: null, wallErrorMin: null, unscoreableReasons: ["recall undefined: no realized wall was scored"] }), + ]), + pool("opencode-go.popesdrew", [win({ forecastsScored: 250, precision: 1, recall: 0.95 })]), + ]), + routes: [GO_ROUTE], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "pool-weight")).toHaveLength(0); + const gap = run.gaps.find((g) => g.reason === "undefined-accuracy-metric"); + expect(gap?.detail).toContain("recall undefined"); + }); + + test("a route member with no exact forecast pool is a gap, never a silent join", () => { + const zen: RouteWeightTable = { + routeId: "zen-plans", + selection: "weighted", + weights: { "opencode.drewrypope": 1, "opencode.popesdrew": 1 }, + weightsLine: ' "weights": { "opencode.drewrypope": 1, "opencode.popesdrew": 1 }', + }; + const run = buildReweightProposals({ + ledger: ledger([pool("opencode-go.drewrypope", [win({ forecastsScored: 300 })])]), + routes: [zen], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "pool-weight")).toHaveLength(0); + expect(run.gaps.filter((g) => g.reason === "no-forecast-pool-for-member")).toHaveLength(2); + }); +}); + +describe("caution-margin class", () => { + const anthropic = () => + pool("anthropic:claude-pro", [ + win({ window: "5h", forecastsScored: 305, precision: 0.593, recall: 0.44 }), + win({ forecastsScored: 273, precision: 1, recall: 0.582, wallErrorMin: { count: 159, meanSignedMin: 900, medianSignedMin: 795, medianAbsMin: 2204, p90AbsMin: 4000 } }), + ]); + const meta = () => + pool("meta", [ + win({ forecastsScored: 269, precision: 0.529, recall: 0.647, wallErrorMin: { count: 110, meanSignedMin: 3194, medianSignedMin: 4741, medianAbsMin: 4741, p90AbsMin: 6000 } }), + ]); + + test("fires DOWNWARD when weekly walls arrive early across pools with a precision anchor", () => { + // Oracle: derive.ts poolState — a pool reads "near" at + // windowPercent >= NEAR_PCT. Walls arriving early (positive + // median signed error) must enter caution EARLIER, which is + // a LOWER threshold: 85 → 80. (The pre-fix generator stepped + // 85 → 90 on this same evidence — caution later, the exact + // opposite of its rationale; Felix's review of PR #12761.) + const run = buildReweightProposals({ + ledger: ledger([ + anthropic(), + meta(), + pool("_openai.alt", [win({ forecastsScored: 169, precision: 1, recall: 0.958, wallErrorMin: { count: 60, meanSignedMin: -100, medianSignedMin: -155, medianAbsMin: 370, p90AbsMin: 900 } })]), + ]), + routes: [], + nearPctCurrent: 85, + }); + const p = run.proposals.find((x) => x.proposalClass === "caution-margin"); + expect(p).toBeDefined(); + expect(p?.key).toBe("caution-margin:NEAR_PCT:85->80"); + expect(p?.target.file).toBe("pm-stack/aggregator/src/derive.ts"); + expect(p?.target.find).toBe("export const NEAR_PCT = 85;"); + expect(p?.target.replace).toBe("export const NEAR_PCT = 80;"); + expect(p?.title).toContain("lower the caution threshold"); + expect(p?.title).not.toContain("widen"); + // the pack carries the grounding rows' numbers verbatim, + // and the rationale states the mechanism: caution entered + // at a lower measured percent + const pack = renderEvidencePack(p as NonNullable); + expect(pack).toContain("anthropic:claude-pro"); + expect(pack).toContain("+795"); + expect(pack).toContain("4741"); + expect(pack).toContain("lower measured"); + expect(pack).not.toContain("widen"); + }); + + test("fires UPWARD when weekly walls arrive systematically late across pools", () => { + // Mirror oracle: walls arriving late (negative median + // signed error) mean caution is being spent early; the + // threshold steps UP — caution entered at a higher + // measured percent, later in the window: 85 → 90. + const run = buildReweightProposals({ + ledger: ledger([ + pool("meta", [ + win({ forecastsScored: 269, precision: 0.9, recall: 0.9, wallErrorMin: { count: 110, meanSignedMin: -3000, medianSignedMin: -3000, medianAbsMin: 3000, p90AbsMin: 5000 } }), + ]), + pool("opendesign", [ + win({ forecastsScored: 200, precision: 1, recall: 0.95, wallErrorMin: { count: 50, meanSignedMin: -2000, medianSignedMin: -2000, medianAbsMin: 2000, p90AbsMin: 3000 } }), + ]), + ]), + routes: [], + nearPctCurrent: 85, + }); + const p = run.proposals.find((x) => x.proposalClass === "caution-margin"); + expect(p).toBeDefined(); + expect(p?.key).toBe("caution-margin:NEAR_PCT:85->90"); + expect(p?.target.find).toBe("export const NEAR_PCT = 85;"); + expect(p?.target.replace).toBe("export const NEAR_PCT = 90;"); + expect(p?.title).toContain("raise the caution threshold"); + const pack = renderEvidencePack(p as NonNullable); + expect(pack).toContain("higher measured"); + expect(pack).not.toContain("widen"); + }); + + test("materially mixed signs — both sides fully gated — are a named gap, not a proposal", () => { + const run = buildReweightProposals({ + ledger: ledger([ + anthropic(), + meta(), + pool("opendesign", [ + win({ forecastsScored: 200, precision: 1, recall: 0.9, wallErrorMin: { count: 50, meanSignedMin: -2000, medianSignedMin: -2000, medianAbsMin: 2000, p90AbsMin: 3000 } }), + ]), + pool("_openai.main", [ + win({ forecastsScored: 180, precision: 1, recall: 0.9, wallErrorMin: { count: 60, meanSignedMin: -1500, medianSignedMin: -1500, medianAbsMin: 1500, p90AbsMin: 2500 } }), + ]), + ]), + routes: [], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + const gap = run.gaps.find((g) => g.reason === "counter-evidence-present"); + expect(gap).toBeDefined(); + expect(gap?.detail).toContain("anthropic:claude-pro"); + expect(gap?.detail).toContain("opendesign"); + }); + + test("a downward step stops at the floor with a named gap", () => { + const run = buildReweightProposals({ + ledger: ledger([anthropic(), meta()]), + routes: [], + nearPctCurrent: 50, + }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + expect(run.gaps.some((g) => g.reason === "margin-at-floor")).toBe(true); + }); + + test("an upward step stops at the ceiling with a named gap", () => { + const run = buildReweightProposals({ + ledger: ledger([ + pool("meta", [ + win({ forecastsScored: 269, precision: 0.9, recall: 0.9, wallErrorMin: { count: 110, meanSignedMin: -3000, medianSignedMin: -3000, medianAbsMin: 3000, p90AbsMin: 5000 } }), + ]), + pool("opendesign", [ + win({ forecastsScored: 200, precision: 1, recall: 0.95, wallErrorMin: { count: 50, meanSignedMin: -2000, medianSignedMin: -2000, medianAbsMin: 2000, p90AbsMin: 3000 } }), + ]), + ]), + routes: [], + nearPctCurrent: 95, + }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + expect(run.gaps.some((g) => g.reason === "margin-at-ceiling")).toBe(true); + }); + + test("does not fire on a single qualifying pool", () => { + const run = buildReweightProposals({ ledger: ledger([anthropic()]), routes: [], nearPctCurrent: 85 }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + }); + + test("does not fire when strong counter-evidence exists", () => { + const run = buildReweightProposals({ + ledger: ledger([ + anthropic(), + meta(), + pool("opendesign", [win({ forecastsScored: 200, precision: 1, recall: 0.9, wallErrorMin: { count: 50, meanSignedMin: -2000, medianSignedMin: -2000, medianAbsMin: 2000, p90AbsMin: 3000 } })]), + ]), + routes: [], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + expect(run.gaps.some((g) => g.reason === "counter-evidence-present")).toBe(true); + }); + + test("the bare opencode-go pool never grounds the margin, even with the strongest numbers", () => { + const run = buildReweightProposals({ + ledger: ledger([ + anthropic(), + pool("opencode-go", [ + win({ forecastsScored: 711, precision: 1, recall: 0.454, wallErrorMin: { count: 300, meanSignedMin: 1903, medianSignedMin: 1903, medianAbsMin: 2961, p90AbsMin: 5000 } }), + win({ window: "monthly", forecastsScored: 513, precision: 0.054, recall: 0.929 }), + ]), + ]), + routes: [], + nearPctCurrent: 85, + }); + // anthropic alone cannot fire the rule; the bare pool is excluded, not counted + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + expect(run.gaps.some((g) => g.reason === "aggregate-pool-excluded")).toBe(true); + }); + + test("refuses an unscoreable weekly baseline as grounding (named gap via the volume gate)", () => { + const run = buildReweightProposals({ + ledger: ledger([ + anthropic(), + pool("_antigravity.claude-gpt", [ + win({ scoreable: false, forecastsScored: 0, precision: null, recall: null, wallErrorMin: null, unscoreableReasons: ["every issued forecast was insufficient-history — the pace was never measurable in a completed period"] }), + ]), + ]), + routes: [], + nearPctCurrent: 85, + }); + expect(run.proposals.filter((x) => x.proposalClass === "caution-margin")).toHaveLength(0); + }); +}); + +describe("evidence pack honesty", () => { + test("absent forecast/shadow inputs are named in the pack, never papered over", () => { + const run = buildReweightProposals({ + ledger: ledger([ + pool("anthropic:claude-pro", [win({ forecastsScored: 273, precision: 1, recall: 0.582, wallErrorMin: { count: 159, meanSignedMin: 900, medianSignedMin: 795, medianAbsMin: 2204, p90AbsMin: 4000 } })]), + pool("meta", [win({ forecastsScored: 269, precision: 0.529, recall: 0.647, wallErrorMin: { count: 110, meanSignedMin: 3194, medianSignedMin: 4741, medianAbsMin: 4741, p90AbsMin: 6000 } })]), + ]), + routes: [], + nearPctCurrent: 85, + }); + const p = run.proposals[0]; + expect(p).toBeDefined(); + const pack = renderEvidencePack(p as NonNullable); + expect(pack).toContain("no forecast file supplied"); + expect(pack).toContain("no shadow record supplied"); + expect(pack).toContain("does not\n> merge"); + }); +}); diff --git a/pm-stack/aggregator/src/quota-reweight.ts b/pm-stack/aggregator/src/quota-reweight.ts new file mode 100644 index 0000000000..610a61ee99 --- /dev/null +++ b/pm-stack/aggregator/src/quota-reweight.ts @@ -0,0 +1,811 @@ +// Re-weighting proposal generator for the Stage-3 quota plane +// (issue #12700, slice S6 of epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §5, decision +// D5). +// +// D5: the only configuration Stage 3 ever changes, it changes by +// pull request. This module examines the forecast accuracy record +// (S2's ledger, #12696) and, when the evidence supports a durable +// change — a pool weight, a caution margin — produces a proposal: +// the config edit as an exact find/replace pair, the full evidence +// pack (the accuracy rows behind it verbatim, the S1 forecast and +// S3 shadow summaries when supplied), and the expected effect +// stated as a measurable prediction the weekly review (S7) can +// score. This module has no write path at all: it returns plain +// values. The only component that can turn a proposal into a PR is +// quota-reweight-pr.ts, whose command surface is an allowlist with +// no merge on it; merge authority stays where it is (Felix/Drew). +// +// Evidence discipline (the S1/S2 honesty rules, applied to +// proposals): +// - A pool/window the accuracy ledger cannot score never grounds a +// proposal. The generator emits a named gap instead, carrying +// S2's unscoreable reasons verbatim — a gap is a report, not a +// proposal with weaker numbers. +// - Volume gates: a window grounds a proposal only with at least +// MIN_SCORED_FORECASTS scored forecasts and, where wall timing is +// the signal, at least MIN_WALL_SAMPLES scored wall errors. Thin +// per-workspace rows (single-digit scored forecasts today) are +// named as gaps, not averaged into confidence. +// - The bare `opencode-go` pool is excluded from grounding in +// every window: S2 showed its rows are assembled from all +// workspaces' records (the monthly row is the named mixing +// artifact — precision 0.054 over 290 reset clusters); the +// per-workspace rows are the real ones. The exclusion is itself +// reported as a gap so the register's coverage stays visible. +// - Undefined precision/recall (null in the ledger) is never read +// as 0 or 1: a rule that needs the metric reports the gap with +// S2's reason. +// +// The two v1 proposal classes: +// - pool-weight: inside one weighted-selection route, shift weight +// from a member whose binding window walls systematically +// earlier than the forecast projects (walls are real when called +// — high precision — but systematically missed/late — low +// recall, large positive median signed wall error) toward the +// member with the strongest headroom evidence. Total route +// weight is preserved. Round-robin routes are out of scope: +// their "weights" are tier keys, not traffic shares (the config +// says so itself), so re-weighting them is a different class. +// - caution-margin: when the weekly calibration shows walls +// arriving systematically off the forecast across pools (the +// S2 headline: linear pace under-calls accelerating weekly +// burn), propose moving the caution threshold NEAR_PCT +// (derive.ts) one step in the direction the signed wall +// error indicates — early walls (positive median) step it +// DOWN so pools enter caution at a lower measured percent, +// late walls step it UP. D4 reserves margin changes to this +// mechanism. The margin is global, so the rule demands +// breadth: at least two qualifying pools on one side, at +// least one whose wall calls are trustworthy (precision +// anchor), and no counter-evidence on the other side — +// materially disagreeing signs are a named gap, not a +// proposal in either direction. +// +// Pure functions over plain values — no I/O, no clock reads except +// through arguments. The CLI is scripts/quota-reweight-proposals.ts. + +import type { ForecastAccuracyLedger, PoolBaseline, WindowBaseline } from "./quota-forecast-accuracy.ts"; +import { FORECAST_POOLS } from "./quota-forecast-accuracy.ts"; +import type { QuotaForecastFile } from "./quota-forecast.ts"; +import type { ShadowPlacementRecord } from "./quota-shadow-placement.ts"; + +/** Minimum scored forecasts for a window to ground a proposal. */ +export const MIN_SCORED_FORECASTS = 100; +/** Minimum scored wall errors for a wall-timing signal. */ +export const MIN_WALL_SAMPLES = 20; +/** Median signed wall error (minutes) at/above which walls count + * as arriving systematically early: +12h. Sign convention is S2's: + * projectedWallAt − realizedWallAt, so positive means the wall + * arrived BEFORE the projection — the forecast ran late. The + * same magnitude at/below −720 counts as walls arriving + * systematically late — the forecast ran early. */ +export const LATE_WALL_MEDIAN_MIN = 720; +/** A late-wall signal needs wall calls that are real when made. */ +export const LATE_WALL_PRECISION_MIN = 0.9; +/** …and walls that are systematically missed or late. */ +export const LATE_WALL_RECALL_MAX = 0.7; +/** Headroom evidence: trustworthy calls, no late-wall pattern. */ +export const HEADROOM_PRECISION_MIN = 0.9; +export const HEADROOM_RECALL_MIN = 0.85; +/** One margin step, in percentage points, and the threshold's + * bounds: never proposed past 95 (leaving a 5-point caution band + * below the wall at 100) or below 50 (under half the window, + * "near" stops discriminating near-limit from ordinary use). */ +export const MARGIN_STEP_PTS = 5; +export const MARGIN_MAX_PCT = 95; +export const MARGIN_MIN_PCT = 50; +/** A late-wall member keeps at least this weight after a shift. */ +export const WEIGHT_FLOOR = 0.5; +/** Fraction of a late-wall member's weight proposed to move. */ +export const WEIGHT_SHIFT_FRACTION = 0.25; + +/** Pools whose ledger rows mix several pools' records and so can + * never ground a proposal (S2's mixing-artifact finding). */ +export const AGGREGATE_POOLS_EXCLUDED: ReadonlySet = new Set(["opencode-go"]); + +/** One weighted-selection route, as the CLI extracted it from the + * route config: the weights map plus the exact source line the + * weights object sits on, so a proposal's edit is a verifiable + * find/replace against the file as it stands. */ +export interface RouteWeightTable { + routeId: string; + selection: string; + weights: Record; + /** Exact text of the line carrying the weights object; null when + * the object spans lines (the generator then refuses to edit it + * rather than guess at the file's shape). */ + weightsLine: string | null; +} + +export interface EvidenceGap { + /** What was examined: a route member, a pool/window, a class. */ + scope: string; + /** Stable machine-readable reason. */ + reason: string; + /** The reason in prose, with the numbers (or S2's words). */ + detail: string; +} + +export interface AccuracyEvidenceRow { + pool: string; + window: string; + scoreable: boolean; + forecastsScored: number; + precision: number | null; + recall: number | null; + wallErrorMedianSignedMin: number | null; + wallErrorCount: number | null; + periodsWalled: number; + periodsScored: number; +} + +export interface ReweightProposal { + /** Stable dedupe key: class + target + from → to. */ + key: string; + proposalClass: "pool-weight" | "caution-margin"; + title: string; + target: { + description: string; + /** Repo-relative path the PR edits. */ + file: string; + /** Exact current text (must occur exactly once in the file). */ + find: string; + /** The text it becomes. */ + replace: string; + currentValue: string; + proposedValue: string; + }; + rationale: string; + evidence: { + ledgerGeneratedAt: string; + ledgerStore: ForecastAccuracyLedger["store"]; + ledgerModel: string; + /** The accuracy rows the proposal grounds on, verbatim. */ + rows: AccuracyEvidenceRow[]; + /** One-line summary of the current forecast for the grounding + * pools, or the named reason no forecast input was supplied. */ + forecastSummary: string; + /** The S3 shadow diff summary for the change class, or the + * named reason no shadow record was supplied. */ + shadowSummary: string; + }; + expectedEffect: { + /** The prediction, stated so next week's review can score it. */ + statement: string; + /** The measurable quantity that decides it. */ + metric: string; + /** Where the measurement comes from. */ + scoredBy: string; + }; +} + +export interface ReweightRun { + proposals: ReweightProposal[]; + gaps: EvidenceGap[]; + /** Human-readable list of everything examined, in order. */ + examined: string[]; +} + +/** serviceId (the ledger's pool key) -> providerId (the route + * config's member key), from S2's own pool register. */ +const PROVIDER_BY_POOL: ReadonlyMap = new Map( + FORECAST_POOLS.map((p) => [p.serviceId, p.providerId]), +); +/** providerId -> ledger pool baseline, for exact member matches. */ +function poolByProvider(ledger: ForecastAccuracyLedger): Map { + const out = new Map(); + for (const pool of ledger.pools) { + const providerId = PROVIDER_BY_POOL.get(pool.pool); + if (providerId) out.set(providerId, pool); + } + return out; +} + +function evidenceRow(pool: string, w: WindowBaseline): AccuracyEvidenceRow { + return { + pool, + window: w.window, + scoreable: w.scoreable, + forecastsScored: w.forecastsScored, + precision: w.precision, + recall: w.recall, + wallErrorMedianSignedMin: w.wallErrorMin?.medianSignedMin ?? null, + wallErrorCount: w.wallErrorMin?.count ?? null, + periodsWalled: w.periodsWalled, + periodsScored: w.periodsScored, + }; +} + +/** The window a pool's evidence is strongest on: among scoreable + * windows, the one with the most scored forecasts. Null when no + * window is scoreable. */ +function bindingWindow(pool: PoolBaseline): WindowBaseline | null { + let best: WindowBaseline | null = null; + for (const w of pool.windows) { + if (!w.scoreable) continue; + if (!best || w.forecastsScored > best.forecastsScored) best = w; + } + return best; +} + +interface GateResult { + ok: boolean; + gap?: EvidenceGap; +} + +/** The volume/honesty gates every grounding window must pass. + * Returns the named gap instead of a verdict when it cannot. */ +function gateWindow(scope: string, pool: PoolBaseline, w: WindowBaseline | null): GateResult { + if (AGGREGATE_POOLS_EXCLUDED.has(pool.pool)) { + return { + ok: false, + gap: { + scope, + reason: "aggregate-pool-excluded", + detail: + `${pool.pool} is assembled from every workspace's records (S2's mixing-artifact ` + + `finding); its rows never ground a proposal — the per-workspace rows are the real ones.`, + }, + }; + } + if (!w) { + const reasons = pool.windows.flatMap((x) => x.unscoreableReasons); + return { + ok: false, + gap: { + scope, + reason: "unscoreable-window", + detail: `no scoreable window for ${pool.pool}: ${reasons.join("; ") || "no percent windows in the ledger"}`, + }, + }; + } + if (!w.scoreable) { + return { + ok: false, + gap: { + scope, + reason: "unscoreable-window", + detail: `${pool.pool}/${w.window} is unscoreable: ${w.unscoreableReasons.join("; ")}`, + }, + }; + } + if (w.forecastsScored < MIN_SCORED_FORECASTS) { + return { + ok: false, + gap: { + scope, + reason: "insufficient-scored-forecasts", + detail: + `${pool.pool}/${w.window} has ${w.forecastsScored} scored forecasts, below the ` + + `${MIN_SCORED_FORECASTS} a durable config change must ground on.`, + }, + }; + } + if (w.precision === null || w.recall === null) { + return { + ok: false, + gap: { + scope, + reason: "undefined-accuracy-metric", + detail: `${pool.pool}/${w.window}: ${w.unscoreableReasons.join("; ") || "precision/recall undefined"}`, + }, + }; + } + return { ok: true }; +} + +function isLateWall(w: WindowBaseline): boolean { + return ( + w.precision !== null && + w.precision >= LATE_WALL_PRECISION_MIN && + w.recall !== null && + w.recall <= LATE_WALL_RECALL_MAX && + w.wallErrorMin !== null && + w.wallErrorMin.count >= MIN_WALL_SAMPLES && + w.wallErrorMin.medianSignedMin >= LATE_WALL_MEDIAN_MIN + ); +} + +function isHeadroom(w: WindowBaseline): boolean { + if (w.precision === null || w.precision < HEADROOM_PRECISION_MIN) return false; + if (w.recall !== null && w.recall < HEADROOM_RECALL_MIN) return false; + if (w.wallErrorMin !== null && w.wallErrorMin.medianSignedMin >= LATE_WALL_MEDIAN_MIN) return false; + return true; +} + +function forecastSummaryFor( + forecast: QuotaForecastFile | null, + serviceIds: readonly string[], +): string { + if (!forecast) { + return "no forecast file supplied to this run (the accuracy ledger alone grounds the proposal; the live forecast's current projections join the pack when the generator runs against the aggregator state dir)"; + } + const parts: string[] = []; + for (const rows of Object.values(forecast.pools)) { + for (const pool of rows) { + if (!serviceIds.includes(pool.serviceId)) continue; + for (const w of pool.windows) { + parts.push( + `${pool.serviceId}/${w.name}: state ${w.state}, wallsBeforeReset ${w.wallsBeforeReset ?? "unknown"}` + + (w.pctNow !== null ? `, at ${w.pctNow}%` : ""), + ); + } + } + } + return parts.length + ? `forecast ${forecast.generatedAt}: ${parts.join("; ")}` + : `forecast ${forecast.generatedAt}: no rows for the grounding pools`; +} + +function shadowSummaryFor( + shadow: ShadowPlacementRecord | null, + changeClass: string, + nearPctCurrent: number, +): string { + if (!shadow) { + return ( + `no shadow record supplied to this run (the ${changeClass} class is the one S3 shadows; ` + + `its diff summary joins the pack when the generator runs against the aggregator state dir, ` + + `and the post-change shadow record is what S7 scores the expected effect against)` + ); + } + const demoted = shadow.pools.filter((p) => p.moved === "demoted").map((p) => p.providerId); + return ( + `shadow record ${shadow.generatedAt} (computed at NEAR_PCT=${nearPctCurrent}): ` + + `${shadow.summary.pools} pools, ${shadow.summary.moved} moved, ${shadow.summary.demotedByForecast} demoted by forecast` + + (demoted.length ? ` (${demoted.join(", ")})` : "") + + `; live and shadow orderings ${shadow.summary.identical ? "identical" : "differ"}` + ); +} + +/** Class pool-weight: one proposal per weighted route at most — + * the strongest late-wall member against the strongest headroom + * member. Every member that cannot ground is a named gap. */ +function poolWeightProposals(args: { + ledger: ForecastAccuracyLedger; + routes: readonly RouteWeightTable[]; + forecast: QuotaForecastFile | null; + shadow: ShadowPlacementRecord | null; + nearPctCurrent: number; + gaps: EvidenceGap[]; + examined: string[]; +}): ReweightProposal[] { + const byProvider = poolByProvider(args.ledger); + const proposals: ReweightProposal[] = []; + for (const route of args.routes) { + args.examined.push(`route ${route.routeId} (selection ${route.selection})`); + if (route.selection !== "weighted") continue; + const members = Object.keys(route.weights); + const evaluated: { member: string; pool: PoolBaseline; window: WindowBaseline }[] = []; + for (const member of members) { + const scope = `route ${route.routeId} member ${member}`; + const pool = byProvider.get(member); + if (!pool) { + args.gaps.push({ + scope, + reason: "no-forecast-pool-for-member", + detail: + `${member} matches no forecast pool's provider id exactly, so no accuracy ` + + `evidence exists for it (near-miss spellings are not joined silently).`, + }); + continue; + } + const w = bindingWindow(pool); + const gate = gateWindow(scope, pool, w); + if (!gate.ok || !w) { + if (gate.gap) args.gaps.push(gate.gap); + continue; + } + evaluated.push({ member, pool, window: w }); + } + const late = evaluated + .filter((e) => isLateWall(e.window)) + .sort((a, b) => (b.window.wallErrorMin?.medianSignedMin ?? 0) - (a.window.wallErrorMin?.medianSignedMin ?? 0)); + const head = evaluated + .filter((e) => isHeadroom(e.window) && !late.includes(e)) + .sort((a, b) => b.window.forecastsScored - a.window.forecastsScored); + if (!late.length || !head.length) { + args.examined.push( + `route ${route.routeId}: ${evaluated.length} members evaluated, ` + + `${late.length} late-wall, ${head.length} headroom — no weight proposal`, + ); + continue; + } + const from = late[0] as (typeof evaluated)[number]; + const to = head[0] as (typeof evaluated)[number]; + const fromOld = route.weights[from.member] as number; + const toOld = route.weights[to.member] as number; + const shift = Math.round(fromOld * WEIGHT_SHIFT_FRACTION * 100) / 100; + const fromNew = Math.max(WEIGHT_FLOOR, Math.round((fromOld - shift) * 100) / 100); + const moved = Math.round((fromOld - fromNew) * 100) / 100; + if (moved <= 0) continue; + const toNew = Math.round((toOld + moved) * 100) / 100; + if (route.weightsLine === null) { + args.gaps.push({ + scope: `route ${route.routeId}`, + reason: "weights-not-single-line", + detail: + `the weights object for ${route.routeId} spans lines in the route config; ` + + `the generator refuses to edit a shape it cannot anchor exactly.`, + }); + continue; + } + const line = route.weightsLine; + const fromEntry = `"${from.member}": ${fromOld}`; + const toEntry = `"${to.member}": ${toOld}`; + if (line.split(fromEntry).length !== 2 || line.split(toEntry).length !== 2) { + args.gaps.push({ + scope: `route ${route.routeId}`, + reason: "weights-line-anchor-mismatch", + detail: `the weights line for ${route.routeId} does not contain ${fromEntry} / ${toEntry} exactly once each; refusing to edit.`, + }); + continue; + } + const newLine = line.replace(fromEntry, `"${from.member}": ${fromNew}`).replace(toEntry, `"${to.member}": ${toNew}`); + const rows = [evidenceRow(from.pool.pool, from.window), evidenceRow(to.pool.pool, to.window)]; + proposals.push({ + key: `pool-weight:${route.routeId}:${from.member}:${fromOld}->${fromNew}`, + proposalClass: "pool-weight", + title: `proposal(quota-plane): shift ${route.routeId} weight from ${from.member} (${fromOld} → ${fromNew}) to ${to.member} (${toOld} → ${toNew})`, + target: { + description: `route ${route.routeId} weights in the route config`, + file: ".opencode/opencode.jsonc", + find: line, + replace: newLine, + currentValue: `${from.member}=${fromOld}, ${to.member}=${toOld}`, + proposedValue: `${from.member}=${fromNew}, ${to.member}=${toNew}`, + }, + rationale: + `${from.member}'s binding window (${from.pool.pool}/${from.window.window}) walls systematically earlier than ` + + `the forecast projects: precision ${from.window.precision} (wall calls are real), recall ${from.window.recall} ` + + `(walls are systematically missed), median signed wall error +${from.window.wallErrorMin?.medianSignedMin} min ` + + `over ${from.window.forecastsScored} scored forecasts. ${to.member} shows headroom on the same evidence standard ` + + `(precision ${to.window.precision}, recall ${to.window.recall}, ${to.window.forecastsScored} scored). Shifting ` + + `${moved} of weight moves burn toward the pool the evidence says holds, and preserves the route's total weight.`, + evidence: { + ledgerGeneratedAt: args.ledger.generatedAt, + ledgerStore: args.ledger.store, + ledgerModel: args.ledger.model, + rows, + forecastSummary: forecastSummaryFor(args.forecast, [from.pool.pool, to.pool.pool]), + shadowSummary: shadowSummaryFor(args.shadow, "pool-weight", args.nearPctCurrent), + }, + expectedEffect: { + statement: + `In the four weeks after this lands, ${from.pool.pool}'s share of the route's realized walls falls and its ` + + `weekly wall-before-reset recall (S2 scoring) rises toward ${HEADROOM_RECALL_MIN}, with no scoreable window ` + + `of ${to.pool.pool} losing precision below ${LATE_WALL_PRECISION_MIN}.`, + metric: "per-pool wall-before-reset precision/recall and realized wall counts, S2-scored", + scoredBy: "the S7 weekly review, from the accuracy ledger and the snapshot store", + }, + }); + } + return proposals; +} + +/** Class caution-margin: walls arriving systematically off the + * forecast on weekly windows across pools → move NEAR_PCT one + * step in the direction the signed wall error indicates. The + * sign convention is S2's (projected − realized): a positive + * median means walls arrive EARLY, so the threshold steps DOWN + * — a pool reads "near" at windowPercent >= NEAR_PCT + * (derive.ts), so a lower threshold enters caution at a lower + * measured percent, earlier in the window. A negative median + * (walls arrive late) steps the threshold UP, entering caution + * at a higher measured percent, later in the window. */ +function cautionMarginProposal(args: { + ledger: ForecastAccuracyLedger; + forecast: QuotaForecastFile | null; + shadow: ShadowPlacementRecord | null; + nearPctCurrent: number; + gaps: EvidenceGap[]; + examined: string[]; +}): ReweightProposal | null { + const weekly: { pool: PoolBaseline; window: WindowBaseline }[] = []; + for (const pool of args.ledger.pools) { + const w = pool.windows.find((x) => x.window === "weekly"); + if (w) weekly.push({ pool, window: w }); + } + args.examined.push(`weekly baselines: ${weekly.length} pools carry one`); + const considered = weekly.filter( + ({ window: w }) => w.scoreable && w.forecastsScored >= MIN_SCORED_FORECASTS, + ); + // The step direction comes from the sign of the grounding + // pools' median signed wall error — never from the word + // "margin": NEAR_PCT is the measured percent at which a pool + // enters the caution tier, so which way the number moves + // decides whether caution starts earlier or later in the + // window. Both sides are gated identically; the grounding + // side is the one with breadth and no counter-evidence. + const early = considered.filter( + ({ pool, window: w }) => + !AGGREGATE_POOLS_EXCLUDED.has(pool.pool) && + w.wallErrorMin !== null && + w.wallErrorMin.count >= MIN_WALL_SAMPLES && + w.wallErrorMin.medianSignedMin >= LATE_WALL_MEDIAN_MIN, + ); + const late = considered.filter( + ({ pool, window: w }) => + !AGGREGATE_POOLS_EXCLUDED.has(pool.pool) && + w.wallErrorMin !== null && + w.wallErrorMin.count >= MIN_WALL_SAMPLES && + w.wallErrorMin.medianSignedMin <= -LATE_WALL_MEDIAN_MIN, + ); + // Counter-evidence is counted at any volume on the side + // opposite a direction: even a thin pool whose walls land on + // the other side of the forecast means the calibration + // disagrees with itself, and a global threshold move is not + // grounded while it does. + const counterTo = (side: "early" | "late") => + considered.filter( + ({ pool, window: w }) => + !AGGREGATE_POOLS_EXCLUDED.has(pool.pool) && + w.wallErrorMin !== null && + (side === "early" + ? w.wallErrorMin.medianSignedMin <= -LATE_WALL_MEDIAN_MIN + : w.wallErrorMin.medianSignedMin >= LATE_WALL_MEDIAN_MIN), + ); + const excluded = considered.filter(({ pool }) => AGGREGATE_POOLS_EXCLUDED.has(pool.pool)); + for (const { pool, window: w } of excluded) { + args.gaps.push({ + scope: `caution-margin evidence ${pool.pool}/weekly`, + reason: "aggregate-pool-excluded", + detail: + `${pool.pool}/weekly shows median signed wall error +${w.wallErrorMin?.medianSignedMin} min over ` + + `${w.forecastsScored} scored forecasts, but the bare pool's rows mix every workspace's records ` + + `(S2) and never ground a proposal; it is reported here, not counted.`, + }); + } + const direction: "early" | "late" | null = + early.length >= 2 && counterTo("early").length === 0 + ? "early" + : late.length >= 2 && counterTo("late").length === 0 + ? "late" + : null; + const grounding = direction === "early" ? early : direction === "late" ? late : []; + const anchors = grounding.filter( + ({ window: w }) => w.precision !== null && w.precision >= LATE_WALL_PRECISION_MIN, + ); + args.examined.push( + `caution-margin: ${considered.length} weekly baselines over the volume gate, ` + + `${early.length} qualifying early-wall, ${late.length} qualifying late-wall` + + (direction + ? `, direction ${direction === "early" ? "down (walls arrive early)" : "up (walls arrive late)"} ` + + `on ${grounding.length} grounding pools, ${anchors.length} precision anchors` + : `, no direction grounded`), + ); + if (!direction || anchors.length < 1) { + // Materially disagreeing signs are a named gap, not a + // proposal in either direction. + if (early.length > 0 && counterTo("early").length > 0) { + args.gaps.push({ + scope: "caution-margin", + reason: "counter-evidence-present", + detail: + `weekly walls arrive early in ${early.map((q) => q.pool.pool).join(", ")} but late in ` + + `${counterTo("early").map((c) => c.pool.pool).join(", ")}; a global margin change is not grounded while the ` + + `calibration disagrees with itself.`, + }); + } else if (late.length > 0 && counterTo("late").length > 0) { + args.gaps.push({ + scope: "caution-margin", + reason: "counter-evidence-present", + detail: + `weekly walls arrive late in ${late.map((q) => q.pool.pool).join(", ")} but early in ` + + `${counterTo("late").map((c) => c.pool.pool).join(", ")}; a global margin change is not grounded while the ` + + `calibration disagrees with itself.`, + }); + } + return null; + } + const from = args.nearPctCurrent; + const to = direction === "early" ? from - MARGIN_STEP_PTS : from + MARGIN_STEP_PTS; + if (to > MARGIN_MAX_PCT) { + args.gaps.push({ + scope: "caution-margin", + reason: "margin-at-ceiling", + detail: `NEAR_PCT is already ${from}; the generator does not propose past ${MARGIN_MAX_PCT}.`, + }); + return null; + } + if (to < MARGIN_MIN_PCT) { + args.gaps.push({ + scope: "caution-margin", + reason: "margin-at-floor", + detail: `NEAR_PCT is already ${from}; the generator does not propose below ${MARGIN_MIN_PCT}.`, + }); + return null; + } + const rows = considered + .filter(({ pool }) => !AGGREGATE_POOLS_EXCLUDED.has(pool.pool)) + .map(({ pool, window: w }) => evidenceRow(pool.pool, w)); + const names = grounding.map((q) => q.pool.pool).join(", "); + return { + key: `caution-margin:NEAR_PCT:${from}->${to}`, + proposalClass: "caution-margin", + title: + direction === "early" + ? `proposal(quota-plane): lower the caution threshold NEAR_PCT ${from} → ${to} — pools enter caution at a lower measured percent (weekly walls arrive systematically early)` + : `proposal(quota-plane): raise the caution threshold NEAR_PCT ${from} → ${to} — pools enter caution at a higher measured percent (weekly walls arrive systematically late)`, + target: { + description: "the caution margin NEAR_PCT (derive.ts), the threshold at which a pool enters the caution/near tier", + file: "pm-stack/aggregator/src/derive.ts", + find: `export const NEAR_PCT = ${from};`, + replace: `export const NEAR_PCT = ${to};`, + currentValue: `${from}`, + proposedValue: `${to}`, + }, + rationale: + (direction === "early" + ? `Weekly walls arrive systematically earlier than the linear pace projects: ` + : `Weekly walls arrive systematically later than the linear pace projects: `) + + `${grounding + .map( + ({ pool, window: w }) => + `${pool.pool} (median signed wall error ${fmtSigned(w.wallErrorMin?.medianSignedMin ?? null)} min over ${w.forecastsScored} scored forecasts, precision ${w.precision}, recall ${w.recall})`, + ) + .join("; ")}. ` + + (direction === "early" + ? `A pool enters the caution tier when a window's measured percent reaches NEAR_PCT (derive.ts); ` + + `lowering the threshold by one step (${from} → ${to}) means pools enter caution at a lower measured ` + + `percent — earlier in the window — in exactly the windows whose walls the forecast under-calls. ` + : `A pool enters the caution tier when a window's measured percent reaches NEAR_PCT (derive.ts); ` + + `raising the threshold by one step (${from} → ${to}) means pools enter caution at a higher measured ` + + `percent — later in the window — so caution discipline is not spent early in the windows whose ` + + `walls the forecast over-calls. `) + + `D4 reserves margin changes to this proposal mechanism; the #1342 controlled A/B gate applies before the ` + + `margin class becomes routine.`, + evidence: { + ledgerGeneratedAt: args.ledger.generatedAt, + ledgerStore: args.ledger.store, + ledgerModel: args.ledger.model, + rows, + forecastSummary: forecastSummaryFor( + args.forecast, + grounding.map((q) => q.pool.pool), + ), + shadowSummary: shadowSummaryFor(args.shadow, "caution-margin", args.nearPctCurrent), + }, + expectedEffect: { + statement: + direction === "early" + ? `In the four weeks after this lands, the fraction of realized weekly walls in the grounding pools ` + + `(${names}) that were preceded by at least one gatherer tick with the pool in the caution/near state ` + + `rises versus the pre-change baseline computed the same way, and no scoreable weekly baseline's ` + + `wall-before-reset precision falls below 0.5.` + : `In the four weeks after this lands, the grounding pools (${names}) spend a smaller share of ` + + `gatherer ticks in the caution/near state than the pre-change baseline computed the same way, ` + + `while the fraction of their realized weekly walls preceded by at least one caution/near tick ` + + `does not fall — the walls arrive later than projected, so the later caution entry still precedes them.`, + metric: + direction === "early" + ? "caution-tier lead coverage of realized weekly walls (shadow history × realized wall instants)" + : "caution-tier occupancy and lead coverage of realized weekly walls (shadow history × realized wall instants)", + scoredBy: "the S7 weekly review, from quota-shadow-placement-history.jsonl and the accuracy ledger", + }, + }; +} + +/** Run every v1 proposal class over the evidence. */ +export function buildReweightProposals(args: { + ledger: ForecastAccuracyLedger; + routes: readonly RouteWeightTable[]; + forecast?: QuotaForecastFile | null; + shadow?: ShadowPlacementRecord | null; + nearPctCurrent: number; +}): ReweightRun { + const gaps: EvidenceGap[] = []; + const examined: string[] = []; + const forecast = args.forecast ?? null; + const shadow = args.shadow ?? null; + const proposals = poolWeightProposals({ + ledger: args.ledger, + routes: args.routes, + forecast, + shadow, + nearPctCurrent: args.nearPctCurrent, + gaps, + examined, + }); + const margin = cautionMarginProposal({ + ledger: args.ledger, + forecast, + shadow, + nearPctCurrent: args.nearPctCurrent, + gaps, + examined, + }); + if (margin) proposals.push(margin); + return { proposals, gaps, examined }; +} + +function fmtMetric(n: number | null): string { + return n === null ? "undefined" : `${n}`; +} + +function fmtSigned(n: number | null): string { + if (n === null) return "n/a"; + return n > 0 ? `+${n}` : `${n}`; +} + +/** The evidence pack: the PR body a proposal carries (design D5: + * the forecasts behind the proposal, their accuracy record, the + * shadow diff summary when the class was shadow-tested, and the + * expected effect). Also written verbatim as proposal.md in draft + * mode, so the pack reviewed in a draft is the pack the PR gets. */ +export function renderEvidencePack(p: ReweightProposal): string { + const s = p.evidence.ledgerStore; + const lines: string[] = [ + `# ${p.title}`, + "", + `> Generated by the Stage-3 re-weighting proposal generator (S6, #12700; design D5).`, + `> This PR was opened by the generator, not hand-written. It proposes; it does not`, + `> merge — merge authority is unchanged (Felix/Drew), and the #1342 controlled A/B`, + `> gate applies before this proposal class becomes routine.`, + "", + `**Proposal key:** \`${p.key}\``, + `**Class:** ${p.proposalClass}`, + `**Target:** ${p.target.description} — \`${p.target.file}\`: \`${p.target.currentValue}\` → \`${p.target.proposedValue}\``, + "", + "## Rationale", + "", + p.rationale, + "", + "## Evidence — accuracy record (S2)", + "", + `Accuracy ledger generated ${p.evidence.ledgerGeneratedAt}; model: ${p.evidence.ledgerModel}.`, + `Store span: ${s.records} records (${s.pctRecords} percent readings), ${s.fromIso ?? "?"} → ${s.toIso ?? "?"}.`, + "", + "| pool | window | scored | precision | recall | median signed wall error (min) | wall samples | walled periods |", + "|---|---|---|---|---|---|---|---|", + ...p.evidence.rows.map( + (r) => + `| ${r.pool} | ${r.window} | ${r.forecastsScored} | ${fmtMetric(r.precision)} | ${fmtMetric(r.recall)} | ${fmtSigned(r.wallErrorMedianSignedMin)} | ${r.wallErrorCount ?? "n/a"} | ${r.periodsWalled}/${r.periodsScored} |`, + ), + "", + "## Evidence — forecast (S1)", + "", + p.evidence.forecastSummary, + "", + "## Evidence — shadow diff (S3)", + "", + p.evidence.shadowSummary, + "", + "## Expected effect (scored by the weekly review)", + "", + p.expectedEffect.statement, + "", + `- Metric: ${p.expectedEffect.metric}`, + `- Scored by: ${p.expectedEffect.scoredBy}`, + "", + ]; + return lines.join("\n"); +} + +/** The run report: proposals and gaps together — the gaps are + * half the product (they are the evidence register's coverage, + * stated instead of silently skipped). */ +export function renderRunReport(run: ReweightRun, generatedAt: string): string { + const lines: string[] = [ + `# Re-weighting proposal run — ${generatedAt}`, + "", + "## Examined", + "", + ...run.examined.map((e) => `- ${e}`), + "", + `## Proposals (${run.proposals.length})`, + "", + ...(run.proposals.length + ? run.proposals.map((p) => `- \`${p.key}\` — ${p.title}`) + : ["- none: the evidence grounded no durable change this run"]), + "", + `## Evidence gaps (${run.gaps.length})`, + "", + ...(run.gaps.length + ? run.gaps.map((g) => `- **${g.scope}** [\`${g.reason}\`]: ${g.detail}`) + : ["- none"]), + "", + ]; + return lines.join("\n"); +}