diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 6b401015b4..5e8b0cb51c 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -354,7 +354,7 @@ preserved. OpenChamber scheduled tasks remain on the configured `opencode-route` / `workhorse` route. The separate #3026 claimant / executor remains on its own protocol. -### 2b. Laptop systemd user timers (47 listed: 43 enabled, 1 installed-but-disabled; 4 Nix-configured pending deployment) +### 2b. Laptop systemd user timers (48 listed: 43 enabled, 1 installed-but-disabled; 5 Nix-configured pending deployment) The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitActiveUSec` spec, read live from `systemctl --user show`. Specs are recorded **complete** — the full effective calendar expression, date **and** time components (e.g. `*-*-* *:*:00`); never truncate a spec to a date-only prefix, because a bare `*-*-*` normalizes to daily at midnight and misstates the cadence (issue #5313). Prompt/brief pointer is the unit file in `~/.config/systemd/user/` (or its Nix store target for linked units). Installed-but-disabled timer units ARE listed in this table and marked `(disabled)` after the unit name: the registry inventories what is installed on the laptop, not only what is currently scheduled, so a disabled unit stays visible until it is uninstalled (reconciled 2026-11-04, issue #5661). @@ -408,6 +408,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `pm-projector-reconcile.timer` | `OnCalendar=*-*-* *:00/15:00` | `pm-projector-reconcile.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `pm-tunnel-watchdog.timer` (Nix-configured; not yet loaded) | `OnUnitActiveSec=2min,OnBootSec=2min` (not live-verified) | `pm-tunnel-watchdog.service` | laptop (user systemd) | not recorded | not recorded | 2026-11-11 | 2026-11-11 | | `quota-gatherer.timer` | `OnCalendar=*-*-* *:00/15:00` | `quota-gatherer.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-22 | +| `quota-weekly-review.timer` | `OnCalendar=Mon *-*-* 07:20:00` | `quota-weekly-review.service` | laptop (user systemd; code#12701; NixOS module `services.pm-stack`, package `pkgs/pm-aggregator` — Stage-3 S7 weekly forecast-accuracy review: posts the report to epic #12694, S6 proposal PRs only, never edits config; Nix-configured pending deployment) | not recorded | not recorded | 2026-11-23 | 2026-11-23 | | `repo-archive-backup.timer` | `OnCalendar=*-*-* 05:15:00` | `repo-archive-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `repo-universe-issue-check.timer` | `OnCalendar=*-*-* 00:00:00` | `repo-universe-issue-check.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `queue-coverage-reconcile.timer` (repo-shipped, not yet installed) | `OnCalendar=*-*-* *:41:00` | `queue-coverage-reconcile.service` | laptop (user systemd; code#7016) | not recorded | not recorded | 2026-11-08 | 2026-11-08 | diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 2a3610c612..f704e3e367 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -464,6 +464,34 @@ in }; }; + quota-weekly-review = { + Unit = { + Description = "Quota weekly review — Stage-3 S7 forecast-accuracy report to epic #12694 (NixOS; packaged pm-aggregator, #12701)"; + After = [ "network-online.target" ]; + }; + Service = { + Type = "oneshot"; + TimeoutStartSec = 900; + WorkingDirectory = aggState; + # The job reads the snapshot store + S1/S3 products from + # the aggregator state dir, and — like the fleet-feed + # collector — the route config and git operations from + # the checkout: S6 proposal PRs are opened from the + # checkout and NEAR_PCT is read from its derive.ts. + ExecStart = builtins.concatStringsSep " " [ + "${pmAggregator}/bin/pm-aggregator-quota-weekly-review" + "--store-dir ${aggState}/snapshots" + "--route-config ${home}/git/code/.opencode/opencode.jsonc" + "--forecast ${aggState}/quota-forecast.json" + "--shadow ${aggState}/quota-shadow-placement.json" + "--out-dir ${aggState}/weekly-review" + "--repo-root ${home}/git/code" + "--open-prs" + "--post" + ]; + }; + }; + # fleet-feed-collector is the one unit still running from # the checkout, deliberately (code#8171 follow-up): its script # derives repo-root paths from its own file location — it @@ -652,6 +680,17 @@ in Install.WantedBy = [ "timers.target" ]; }; + quota-weekly-review = { + Unit.Description = "Run the Stage-3 weekly forecast-accuracy review on Mondays at 07:20 local (pm-stack, #12701)"; + Timer = { + OnCalendar = "Mon *-*-* 07:20:00"; + RandomizedDelaySec = 60; + Persistent = true; + Unit = "quota-weekly-review.service"; + }; + Install.WantedBy = [ "timers.target" ]; + }; + fleet-feed-collector = { Unit.Description = "Collect the fleet feed for the laptop aggregator every ~5 minutes"; Timer = { diff --git a/pkgs/pm-aggregator/package.nix b/pkgs/pm-aggregator/package.nix index 082cd816ee..d4c764fbcd 100644 --- a/pkgs/pm-aggregator/package.nix +++ b/pkgs/pm-aggregator/package.nix @@ -113,6 +113,8 @@ stdenvNoCC.mkDerivation { --add-flags "run $out/libexec/pm-aggregator/scripts/generate-digest.ts" makeWrapper ${lib.getExe bun} $out/bin/pm-aggregator-export-turso-stores \ --add-flags "run $out/libexec/pm-aggregator/scripts/export-turso-stores.ts" + makeWrapper ${lib.getExe bun} $out/bin/pm-aggregator-quota-weekly-review \ + --add-flags "run $out/libexec/pm-aggregator/scripts/quota-weekly-review.ts" runHook postInstall ''; diff --git a/pm-stack/aggregator/package.json b/pm-stack/aggregator/package.json index a3b951b1d3..1f2f19036e 100644 --- a/pm-stack/aggregator/package.json +++ b/pm-stack/aggregator/package.json @@ -15,7 +15,8 @@ "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", - "proposals:quota-reweight": "bun run scripts/quota-reweight-proposals.ts" + "proposals:quota-reweight": "bun run scripts/quota-reweight-proposals.ts", + "review:quota-weekly": "bun run scripts/quota-weekly-review.ts" }, "devDependencies": { "@playwright/test": "1.64.0", diff --git a/pm-stack/aggregator/scripts/quota-weekly-review.ts b/pm-stack/aggregator/scripts/quota-weekly-review.ts new file mode 100644 index 0000000000..3ca4096b3c --- /dev/null +++ b/pm-stack/aggregator/scripts/quota-weekly-review.ts @@ -0,0 +1,409 @@ +#!/usr/bin/env bun +// The Stage-3 weekly forecast-accuracy review job (issue #12701, +// slice S7 of epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §7, D7). +// +// bun run scripts/quota-weekly-review.ts --store-dir \ +// [--route-config ] [--forecast ] \ +// [--shadow ] [--as-of ] [--week-start ] \ +// [--out-dir ] [--report-out ] [--repo-root ] \ +// [--gh ] [--base ] [--open-prs] [--post] +// +// (Committed as the package.json script `review:quota-weekly`.) +// +// One run of the job: (1) builds S2's accuracy ledger + scored facts +// from the snapshot store and scores the week (the 7 days ending at +// --as-of, or the store's last reading) with src/quota-weekly-review.ts; +// (2) replays the §6 anomaly detectors over the store and keeps the +// week's findings; (3) when --route-config is supplied, runs S6's +// re-weighting generator over the ledger — the §5 fold — writing +// draft packs under --out-dir and, with --open-prs, opening the +// proposal PRs through quota-reweight-pr.ts's PR-only path; (4) with +// --post, posts the rendered report as a comment on epic #12694. +// Without --post the report goes to --report-out or stdout. The job +// never edits quota config in place: its only writes are its own +// outputs, proposal PRs (S6's mechanism), and the epic comment. +// +// The store is read through SnapshotStore.readAll — read-only; this +// script never writes to the store dir. --as-of defaults to the +// store's last reading, never the wall clock, so a run over a fixed +// store copy is reproducible. +// +// Argument contract (#3352): the whole command line is declared +// here — the value options and the two flags 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 { SnapshotStore } from "../src/snapshots.ts"; +import { buildForecastAccuracyLedger } from "../src/quota-forecast-accuracy.ts"; +import { runAnomalyReplay } from "../src/quota-anomaly.ts"; +import { buildReweightProposals, renderEvidencePack, type RouteWeightTable } from "../src/quota-reweight.ts"; +import { nodeRunner, openProposalPr } from "../src/quota-reweight-pr.ts"; +import { buildWeeklyReview, renderWeeklyReview } from "../src/quota-weekly-review.ts"; +import type { QuotaForecastFile } from "../src/quota-forecast.ts"; +import type { ShadowPlacementRecord } from "../src/quota-shadow-placement.ts"; + +const EPIC_REPO = "developing-today/code"; +const EPIC_ISSUE = "12694"; +const WEEK_MS = 7 * 24 * 3_600_000; + +const VALUE_OPTIONS = [ + "--store-dir", + "--route-config", + "--forecast", + "--shadow", + "--as-of", + "--week-start", + "--out-dir", + "--report-out", + "--repo-root", + "--gh", + "--base", +] as const; +type ValueOption = (typeof VALUE_OPTIONS)[number]; +const FLAG_OPTIONS = ["--open-prs", "--post"] as const; + +function usageError(message: string): never { + console.error(`quota-weekly-review: ${message}`); + console.error( + "usage: quota-weekly-review --store-dir [--route-config ] [--forecast ] " + + "[--shadow ] [--as-of ] [--week-start ] [--out-dir ] [--report-out ] " + + "[--repo-root ] [--gh ] [--base ] [--open-prs] [--post]", + ); + process.exit(2); +} + +function parseArgs(argv: string[]): { values: Record; openPrs: boolean; post: boolean } { + const values: Record = { + "--store-dir": undefined, + "--route-config": undefined, + "--forecast": undefined, + "--shadow": undefined, + "--as-of": undefined, + "--week-start": undefined, + "--out-dir": undefined, + "--report-out": undefined, + "--repo-root": undefined, + "--gh": undefined, + "--base": undefined, + }; + let openPrs = false; + let post = 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`); + if (name === "--open-prs") openPrs = true; + else post = 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, post }; +} + +// --- Route-config reading, mirrored from +// scripts/quota-reweight-proposals.ts (the S6 generator's script). +// The pair should be extracted to src/ when a third consumer +// appears; until then the mirror is deliberate and noted here so +// the two cannot drift unnoticed. + +/** Strip line and block 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). */ +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. */ +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; +} + +// --- end of the mirrored route-config reading. + +async function readJson(path: string, what: string): Promise { + try { + return JSON.parse(await readFile(path, "utf8")) as T; + } catch (err) { + console.error(`quota-weekly-review: 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, post } = parseArgs(process.argv.slice(2)); + const storeDir = values["--store-dir"]; + if (!storeDir) usageError("--store-dir is required; refusing to run, no files read or written"); + if (openPrs && !values["--route-config"]) { + usageError("--open-prs requires --route-config (there are no proposals to open without the S6 fold)"); + } + if (post && !values["--out-dir"] && !values["--report-out"]) { + usageError("--post requires --out-dir or --report-out (the posted text must exist as a file first)"); + } + + 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 records = await new SnapshotStore(storeDir).readAll(); + if (!records.length) { + console.error(`quota-weekly-review: no snapshot records in ${storeDir} — nothing to review`); + process.exit(1); + } + const stamps = records.map((r) => Date.parse(r.ts)).filter(Number.isFinite); + const storeLastMs = Math.max(...stamps); + + let weekEndMs = storeLastMs; + if (values["--as-of"] !== undefined) { + weekEndMs = Date.parse(values["--as-of"]); + if (!Number.isFinite(weekEndMs)) usageError(`--as-of '${values["--as-of"]}' is not a parseable instant`); + } + let weekStartMs = weekEndMs - WEEK_MS; + if (values["--week-start"] !== undefined) { + weekStartMs = Date.parse(values["--week-start"]); + if (!Number.isFinite(weekStartMs)) usageError(`--week-start '${values["--week-start"]}' is not a parseable instant`); + if (weekStartMs >= weekEndMs) usageError("--week-start must be before the week's end (--as-of or the store's last reading)"); + } + + const { ledger, facts } = buildForecastAccuracyLedger(records, { asOfMs: weekEndMs }); + const { findings } = runAnomalyReplay(records, { asOfMs: weekEndMs }); + + // The §5 fold (S6): only when the route config is supplied. Its + // absence is a recorded state of the report, never a silent skip. + let reweight: ReturnType | null = null; + const opened: { key: string; branch: string; url: string }[] = []; + if (values["--route-config"]) { + const configText = await readFile(values["--route-config"], "utf8"); + const routes = extractRoutes(configText); + const forecast = values["--forecast"] + ? await readJson(values["--forecast"], "forecast file") + : null; + const shadow = values["--shadow"] + ? await readJson(values["--shadow"], "shadow record") + : null; + 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-weekly-review: 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]); + reweight = buildReweightProposals({ ledger, routes, forecast, shadow, nearPctCurrent }); + + if (values["--out-dir"]) { + const outDir = values["--out-dir"]; + await mkdir(outDir, { recursive: true }); + for (const p of reweight.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)); + } + } + if (openPrs) { + const outDir = values["--out-dir"] ?? join(repoRoot, ".quota-weekly-review-out"); + await mkdir(outDir, { recursive: true }); + for (const p of reweight.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}`); + } + } + } + + const generatedAt = new Date().toISOString(); + const review = buildWeeklyReview({ + ledger, + facts, + findings, + weekStartMs, + weekEndMs, + generatedAt, + reweight, + openedPrs: opened, + }); + const report = renderWeeklyReview(review); + + const reportPath = values["--report-out"] ?? (values["--out-dir"] ? join(values["--out-dir"], "weekly-review.md") : null); + if (reportPath) { + await mkdir(dirname(reportPath), { recursive: true }); + await writeFile(reportPath, report, "utf8"); + } else { + console.log(report); + } + if (values["--out-dir"]) { + await writeFile(join(values["--out-dir"], "weekly-review.json"), `${JSON.stringify(review, null, 2)}\n`, "utf8"); + } + + if (post) { + // The one gh call this job makes, built literally here: a + // comment carrying the report file on the Stage-3 epic. + const res = await nodeRunner( + ghPath, + ["issue", "comment", EPIC_ISSUE, "--repo", EPIC_REPO, "--body-file", reportPath as string], + { cwd: repoRoot }, + ); + if (res.code !== 0) { + console.error(`quota-weekly-review: posting the report to #${EPIC_ISSUE} failed (gh exit ${res.code}): ${res.stderr.trim()}`); + process.exit(1); + } + console.log(`posted the weekly review to ${EPIC_REPO}#${EPIC_ISSUE}: ${res.stdout.trim()}`); + } + + console.error( + `quota-weekly-review: week ${review.weekStartIso} → ${review.weekEndIso}; ` + + `${review.pools.reduce((s, p) => s + p.week.forecastsScored, 0)} forecasts scored, ` + + `${review.findings.total} finding(s), ${review.proposals.length} proposal(s)` + + `${review.noChangeFinding ? ", no-change finding recorded" : ""}${post ? ", report posted" : ""}`, + ); +} + +await main(); diff --git a/pm-stack/aggregator/src/quota-weekly-review.test.ts b/pm-stack/aggregator/src/quota-weekly-review.test.ts new file mode 100644 index 0000000000..d426855c4a --- /dev/null +++ b/pm-stack/aggregator/src/quota-weekly-review.test.ts @@ -0,0 +1,293 @@ +// Tests for the Stage-3 S7 weekly review (#12701, design §7/D7). +// Every test names its oracle: the textbook definitions of +// precision/recall with S2's rounding and null rules +// (quota-forecast-accuracy.ts), S2's own errorDistribution for the +// wall-error quantiles, and the design's §7 report contract (per-pool +// projected-vs-realized, the §6 findings summary, a recorded rule +// consequence in every report). +import { describe, expect, test } from "bun:test"; +import { + buildWeeklyReview, + renderWeeklyReview, + scoreWeekFacts, + summarizeWeekFindings, +} from "./quota-weekly-review.ts"; +import type { ForecastAccuracyLedger, ScoredForecast } from "./quota-forecast-accuracy.ts"; +import type { AnomalyFinding } from "./quota-anomaly.ts"; +import type { ReweightProposal, ReweightRun } from "./quota-reweight.ts"; + +const WEEK_START = Date.parse("2026-11-16T00:00:00Z"); +const WEEK_END = Date.parse("2026-11-23T00:00:00Z"); +const iso = (ms: number) => new Date(ms).toISOString(); + +function fact(partial: Partial & { outcome: ScoredForecast["outcome"] }): ScoredForecast { + return { + pool: "alpha", + providerId: "alpha-provider", + window: "5h", + issuedAt: iso(WEEK_START + 3_600_000), + resetsAt: iso(WEEK_START + 5 * 3_600_000), + state: "projected", + projectedWallAt: null, + wallsBeforeReset: partial.outcome === "tp" || partial.outcome === "fp", + realizedWallAt: null, + errorMin: null, + ...partial, + }; +} + +const FACTS: ScoredForecast[] = [ + fact({ outcome: "tp", errorMin: 30 }), + fact({ outcome: "tp", errorMin: -10 }), + fact({ outcome: "fp" }), + fact({ outcome: "fn" }), + fact({ outcome: "tn" }), + // Period reset before the week: excluded even though scored. + fact({ outcome: "tp", errorMin: 999, resetsAt: iso(WEEK_START - 3_600_000) }), + // Period reset exactly at the week's end: excluded (half-open week). + fact({ outcome: "tp", errorMin: 999, resetsAt: iso(WEEK_END) }), + // Period reset exactly at the week's start: included. + fact({ outcome: "tn", resetsAt: iso(WEEK_START) }), + // Another pool, outside the week only. + fact({ pool: "beta", providerId: null, outcome: "tp", errorMin: 5, resetsAt: iso(WEEK_START - 7_200_000) }), +]; + +function finding(partial: Partial & { detector: AnomalyFinding["detector"] }): AnomalyFinding { + return { + key: "k", + at: iso(WEEK_START + 86_400_000), + serviceId: "alpha", + providerId: null, + window: null, + severity: "warning", + title: "a finding", + baseline: "baseline", + observed: "observed", + detail: {}, + ...partial, + }; +} + +const FINDINGS: AnomalyFinding[] = [ + finding({ detector: "burn-spike", key: "b1", title: "burn spike one" }), + finding({ detector: "burn-spike", key: "b2", title: "burn spike two", at: iso(WEEK_START + 2 * 86_400_000) }), + finding({ detector: "schema-drift", key: "s1", title: "schema drift one", at: iso(WEEK_START + 3 * 86_400_000) }), + finding({ detector: "plan-change", key: "p0", title: "before the week", at: iso(WEEK_START - 86_400_000) }), +]; + +function ledger(): ForecastAccuracyLedger { + const windowBaseline = { + window: "5h", + scoreable: true, + unscoreableReasons: [], + periodsTotal: 1, + periodsScored: 1, + periodsWalled: 1, + periodsOpen: 0, + periodsNoReset: 0, + forecastsIssued: 8, + forecastsScored: 8, + forecastsInsufficient: 0, + detectionsWhileWalled: 0, + tp: 3, + fp: 1, + fn: 1, + tn: 3, + precision: 0.75, + recall: 0.75, + wallErrorMin: null, + firstCallLeadMin: null, + }; + const { window: _window, ...rollup } = windowBaseline; + return { + version: 1, + kind: "quota-forecast-accuracy", + generatedAt: iso(WEEK_END), + model: "test model", + store: { records: 100, pctRecords: 90, fromIso: iso(WEEK_START - 30 * 86_400_000), toIso: iso(WEEK_END) }, + pools: [ + { + pool: "alpha", + providerId: "alpha-provider", + serviceIdsJoined: ["alpha"], + windows: [windowBaseline], + rollup, + }, + { + pool: "beta", + providerId: null, + serviceIdsJoined: ["beta"], + windows: [], + rollup: { + scoreable: false, + unscoreableReasons: ["no completed periods"], + periodsTotal: 0, + periodsScored: 0, + periodsWalled: 0, + periodsOpen: 0, + periodsNoReset: 0, + forecastsIssued: 0, + forecastsScored: 0, + forecastsInsufficient: 0, + detectionsWhileWalled: 0, + tp: 0, + fp: 0, + fn: 0, + tn: 0, + precision: null, + recall: null, + wallErrorMin: null, + firstCallLeadMin: null, + }, + }, + ], + }; +} + +function proposal(): ReweightProposal { + return { + key: "caution-margin/NEAR_PCT/80-to-85", + proposalClass: "caution-margin", + title: "widen the caution margin NEAR_PCT 80 → 85", + target: { + description: "caution margin", + file: "pm-stack/aggregator/src/derive.ts", + find: "export const NEAR_PCT = 80;", + replace: "export const NEAR_PCT = 85;", + currentValue: "80", + proposedValue: "85", + }, + rationale: "walls arrive early", + evidence: { + ledgerGeneratedAt: iso(WEEK_END), + ledgerStore: ledger().store, + ledgerModel: "test model", + rows: [], + forecastSummary: "n/a", + shadowSummary: "n/a", + }, + expectedEffect: { statement: "walls arrive later", metric: "lead coverage", scoredBy: "the S7 weekly review" }, + }; +} + +describe("scoreWeekFacts (oracle: textbook precision/recall, S2 rounding + null rules)", () => { + test("the week is the half-open reset interval [start, end)", () => { + const rows = scoreWeekFacts(FACTS, WEEK_START, WEEK_END); + const alpha = rows.find((r) => r.pool === "alpha"); + if (!alpha) throw new Error("alpha row missing"); + expect(alpha.forecastsScored).toBe(6); + expect(alpha.tp).toBe(2); + expect(alpha.fp).toBe(1); + expect(alpha.fn).toBe(1); + expect(alpha.tn).toBe(2); + expect(alpha.precision).toBe(0.667); + expect(alpha.recall).toBe(0.667); + // Wall error over the week's TP errors [30, -10] only — the two + // out-of-week 999s must not leak in (S2 errorDistribution). + expect(alpha.wallErrorMin?.count).toBe(2); + expect(alpha.wallErrorMin?.meanSignedMin).toBe(10); + expect(alpha.wallErrorMin?.medianAbsMin).toBe(20); + expect(alpha.wallErrorMin?.p90AbsMin).toBe(28); + }); + + test("a pool with no in-week facts gets no row from scoring alone", () => { + // scoreWeekFacts scores facts, nothing else: beta's only fact is + // out-of-week, so beta is absent here. The zero row with + // undefined precision/recall is buildWeeklyReview's job (it owns + // the ledger's pool list) and is asserted there. + const rows = scoreWeekFacts(FACTS, WEEK_START, WEEK_END); + expect(rows.map((r) => r.pool)).toEqual(["alpha"]); + }); +}); + +describe("summarizeWeekFindings (oracle: design §7 step 2 — the §6 findings of the week)", () => { + test("only findings inside the week count, grouped by detector", () => { + const summary = summarizeWeekFindings(FINDINGS, WEEK_START, WEEK_END); + expect(summary.total).toBe(3); + expect(summary.counts).toEqual([ + { detector: "burn-spike", count: 2 }, + { detector: "schema-drift", count: 1 }, + { detector: "plan-change", count: 0 }, + ]); + expect(summary.findings.map((f) => f.key)).toEqual(["b1", "b2", "s1"]); + }); +}); + +describe("buildWeeklyReview + renderWeeklyReview (oracle: design §7 report contract)", () => { + test("a proposal from the S6 fold is the recorded rule consequence, with its PR when opened", () => { + const run: ReweightRun = { proposals: [proposal()], gaps: [], examined: ["caution-margin class"] }; + const review = buildWeeklyReview({ + ledger: ledger(), + facts: FACTS, + findings: FINDINGS, + weekStartMs: WEEK_START, + weekEndMs: WEEK_END, + generatedAt: iso(WEEK_END), + reweight: run, + openedPrs: [{ key: proposal().key, url: "https://example.invalid/pr/1" }], + }); + expect(review.noChangeFinding).toBeNull(); + const md = renderWeeklyReview(review); + expect(md).toContain("# Quota forecast weekly review"); + expect(md).toContain("caution-margin/NEAR_PCT/80-to-85"); + expect(md).toContain("https://example.invalid/pr/1"); + expect(md).toContain("burn spike one"); + // S4 is not live: the pace_hold section names the absence. + expect(md).toContain("#12698"); + }); + + test("no proposal yields an explicit no-change finding carrying the week's numbers", () => { + const run: ReweightRun = { + proposals: [], + gaps: [{ scope: "pool-weight class", reason: "insufficient-history", detail: "too few scored forecasts" }], + examined: ["pool-weight class", "caution-margin class"], + }; + const review = buildWeeklyReview({ + ledger: ledger(), + facts: FACTS, + findings: FINDINGS, + weekStartMs: WEEK_START, + weekEndMs: WEEK_END, + generatedAt: iso(WEEK_END), + reweight: run, + }); + if (!review.noChangeFinding) throw new Error("no-change finding missing"); + expect(review.noChangeFinding).toContain("no rule change"); + expect(review.noChangeFinding).toContain("6 forecasts scored"); + const md = renderWeeklyReview(review); + expect(md).toContain("No-change finding"); + expect(md).toContain("insufficient-history"); + }); + + test("without a reweight run the fold is reported as not evaluated, never as a no-change", () => { + const review = buildWeeklyReview({ + ledger: ledger(), + facts: FACTS, + findings: FINDINGS, + weekStartMs: WEEK_START, + weekEndMs: WEEK_END, + generatedAt: iso(WEEK_END), + reweight: null, + }); + expect(review.noChangeFinding).toBeNull(); + const md = renderWeeklyReview(review); + expect(md).toContain("not evaluated"); + }); + + test("every ledger pool appears in the review, even with no in-week facts", () => { + const review = buildWeeklyReview({ + ledger: ledger(), + facts: FACTS, + findings: FINDINGS, + weekStartMs: WEEK_START, + weekEndMs: WEEK_END, + generatedAt: iso(WEEK_END), + reweight: null, + }); + expect(review.pools.map((p) => p.pool)).toEqual(["alpha", "beta"]); + expect(review.pools[1]?.week.forecastsScored).toBe(0); + expect(review.pools[1]?.week.precision).toBeNull(); + expect(review.pools[1]?.week.recall).toBeNull(); + expect(review.pools[1]?.week.wallErrorMin).toBeNull(); + }); +}); diff --git a/pm-stack/aggregator/src/quota-weekly-review.ts b/pm-stack/aggregator/src/quota-weekly-review.ts new file mode 100644 index 0000000000..c222023a64 --- /dev/null +++ b/pm-stack/aggregator/src/quota-weekly-review.ts @@ -0,0 +1,381 @@ +// Stage-3 S7 — the weekly forecast-accuracy review (issue #12701, +// slice S7 of epic #12694; design +// doc/2026-11-22T22-35-00Z_design_quota-plane-stage-3 §7, D7). +// +// The review is a report and proposals, never edits: this module is +// the pure core the scheduled job (scripts/quota-weekly-review.ts) +// runs. It scores the week's forecasts against realized outcomes +// from S2's accuracy ledger — the scored facts S2's backtest +// produces, cut to the week — appends the §6 detector findings of +// the week, and folds the S6 re-weighting run into the report as the +// week's rule consequence: the proposals it produced (with their PRs +// when the job opened them), or an explicit no-change finding with +// the accuracy numbers. The design's anti-decay rule (§7): the +// first two reports must each record at least one rule consequence, +// so a report with neither a proposal nor a no-change finding is not +// a shape this module can render — when the S6 fold was not +// evaluated at all, the report says so in those words instead. +// +// Week membership, stated once: a scored forecast belongs to the +// week its reset period completed in — the fact's resetsAt in the +// half-open interval [weekStart, weekEnd) — because that is when its +// outcome was realized. A detector finding belongs to the week of +// the instant it is about (its `at`). Precision/recall use the +// textbook definitions with S2's rounding and null rules (undefined +// stays null, never 0); wall error reuses S2's errorDistribution so +// the week's quantiles are the ledger's quantiles. +import { + errorDistribution, + type ErrorDistribution, + type ForecastAccuracyLedger, + type PoolBaseline, + type ScoredForecast, +} from "./quota-forecast-accuracy.ts"; +import type { AnomalyDetectorId, AnomalyFinding } from "./quota-anomaly.ts"; +import type { EvidenceGap, ReweightRun } from "./quota-reweight.ts"; + +export interface WeekPoolScore { + pool: string; + providerId: string | null; + forecastsScored: number; + tp: number; + fp: number; + fn: number; + tn: number; + /** Null when no positive prediction was scored (S2's rule). */ + precision: number | null; + /** Null when no realized wall was scored (S2's rule). */ + recall: number | null; + wallErrorMin: ErrorDistribution | null; +} + +/** Score the facts whose period completed in [weekStartMs, weekEndMs), + * grouped per pool, in first-seen pool order. */ +export function scoreWeekFacts( + facts: readonly ScoredForecast[], + weekStartMs: number, + weekEndMs: number, +): WeekPoolScore[] { + const byPool = new Map(); + for (const f of facts) { + const resetMs = Date.parse(f.resetsAt); + if (!Number.isFinite(resetMs) || resetMs < weekStartMs || resetMs >= weekEndMs) continue; + let entry = byPool.get(f.pool); + if (!entry) { + entry = { providerId: f.providerId, facts: [] }; + byPool.set(f.pool, entry); + } + entry.facts.push(f); + } + const out: WeekPoolScore[] = []; + for (const [pool, entry] of byPool) { + let tp = 0; + let fp = 0; + let fn = 0; + let tn = 0; + const errors: number[] = []; + for (const f of entry.facts) { + if (f.outcome === "tp") tp++; + else if (f.outcome === "fp") fp++; + else if (f.outcome === "fn") fn++; + else tn++; + if (f.errorMin !== null) errors.push(f.errorMin); + } + out.push({ + pool, + providerId: entry.providerId, + forecastsScored: entry.facts.length, + tp, + fp, + fn, + tn, + precision: tp + fp > 0 ? Math.round((tp / (tp + fp)) * 1000) / 1000 : null, + recall: tp + fn > 0 ? Math.round((tp / (tp + fn)) * 1000) / 1000 : null, + wallErrorMin: errorDistribution(errors), + }); + } + return out; +} + +export interface WeekFindingsSummary { + total: number; + /** Every detector, in the §6 register's order, zeros included. */ + counts: { detector: AnomalyDetectorId; count: number }[]; + /** The week's findings, chronological. */ + findings: AnomalyFinding[]; +} + +const DETECTOR_ORDER: readonly AnomalyDetectorId[] = ["burn-spike", "schema-drift", "plan-change"]; + +export function summarizeWeekFindings( + findings: readonly AnomalyFinding[], + weekStartMs: number, + weekEndMs: number, +): WeekFindingsSummary { + const inWeek = findings + .filter((f) => { + const atMs = Date.parse(f.at); + return Number.isFinite(atMs) && atMs >= weekStartMs && atMs < weekEndMs; + }) + .sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); + return { + total: inWeek.length, + counts: DETECTOR_ORDER.map((detector) => ({ + detector, + count: inWeek.filter((f) => f.detector === detector).length, + })), + findings: inWeek, + }; +} + +export interface WeeklyReviewPool { + pool: string; + providerId: string | null; + week: WeekPoolScore; + /** The pool's all-history S2 rollup — the calibration the week's + * numbers are read against. */ + rollup: PoolBaseline["rollup"]; +} + +export interface WeeklyReview { + version: 1; + kind: "quota-weekly-review"; + generatedAt: string; + weekStartIso: string; + weekEndIso: string; + model: string; + store: ForecastAccuracyLedger["store"]; + pools: WeeklyReviewPool[]; + findings: WeekFindingsSummary; + paceHoldNote: string; + /** The S6 fold's proposals for this week (empty when the fold + * produced none or was not evaluated). */ + proposals: { key: string; title: string; prUrl: string | null }[]; + gaps: EvidenceGap[]; + examined: string[]; + /** True when the S6 fold ran (a route config was supplied). */ + reweightEvaluated: boolean; + /** The explicit no-change finding, composed when the fold ran and + * produced no proposal; null otherwise (design §7 anti-decay). */ + noChangeFinding: string | null; +} + +/** The standing pace_hold note while S4 (#12698) is unlanded: there + * are no live forecast-driven admission verdicts to score, and the + * report names that instead of printing an empty section. The job + * overrides this the week S4 produces records. */ +export const PACE_HOLD_NOT_LIVE_NOTE = + "No live pace_hold outcomes to score: S4 (#12698, live forecast-driven admission) has not landed, " + + "so admission issued no forecast-driven pace_hold verdicts this week."; + +function emptyWeekScore(pool: string, providerId: string | null): WeekPoolScore { + return { + pool, + providerId, + forecastsScored: 0, + tp: 0, + fp: 0, + fn: 0, + tn: 0, + precision: null, + recall: null, + wallErrorMin: null, + }; +} + +function emptyRollup(): PoolBaseline["rollup"] { + return { + scoreable: false, + unscoreableReasons: ["pool absent from the accuracy ledger"], + periodsTotal: 0, + periodsScored: 0, + periodsWalled: 0, + periodsOpen: 0, + periodsNoReset: 0, + forecastsIssued: 0, + forecastsScored: 0, + forecastsInsufficient: 0, + detectionsWhileWalled: 0, + tp: 0, + fp: 0, + fn: 0, + tn: 0, + precision: null, + recall: null, + wallErrorMin: null, + firstCallLeadMin: null, + }; +} + +export function buildWeeklyReview(args: { + ledger: ForecastAccuracyLedger; + facts: readonly ScoredForecast[]; + findings: readonly AnomalyFinding[]; + weekStartMs: number; + weekEndMs: number; + generatedAt: string; + paceHoldNote?: string; + reweight?: ReweightRun | null; + openedPrs?: readonly { key: string; url: string }[]; +}): WeeklyReview { + const weekScores = scoreWeekFacts(args.facts, args.weekStartMs, args.weekEndMs); + const scoreByPool = new Map(weekScores.map((s) => [s.pool, s])); + const pools: WeeklyReviewPool[] = args.ledger.pools.map((p) => ({ + pool: p.pool, + providerId: p.providerId, + week: scoreByPool.get(p.pool) ?? emptyWeekScore(p.pool, p.providerId), + rollup: p.rollup, + })); + // A pool present in facts but missing from the ledger cannot + // happen (facts are built from the ledger's pools) — but if the + // inputs ever disagree, the week's facts win a row rather than + // being dropped silently. + for (const s of weekScores) { + if (!pools.some((p) => p.pool === s.pool)) { + pools.push({ + pool: s.pool, + providerId: s.providerId, + week: s, + rollup: emptyRollup(), + }); + } + } + + const reweight = args.reweight ?? null; + const prByKey = new Map((args.openedPrs ?? []).map((p) => [p.key, p.url])); + const proposals = (reweight?.proposals ?? []).map((p) => ({ + key: p.key, + title: p.title, + prUrl: prByKey.get(p.key) ?? null, + })); + + let noChangeFinding: string | null = null; + if (reweight && proposals.length === 0) { + const totalScored = pools.reduce((sum, p) => sum + p.week.forecastsScored, 0); + const poolsScored = pools.filter((p) => p.week.forecastsScored > 0).length; + noChangeFinding = + `no rule change is proposed this week: the S6 generator examined ${reweight.examined.length} ` + + `class(es) (${reweight.examined.join("; ") || "none recorded"}) and produced no proposal. ` + + `The week's accuracy record behind that finding: ${totalScored} forecasts scored across ` + + `${poolsScored} pool(s); ${reweight.gaps.length} evidence gap(s) recorded below.`; + } + + return { + version: 1, + kind: "quota-weekly-review", + generatedAt: args.generatedAt, + weekStartIso: new Date(args.weekStartMs).toISOString(), + weekEndIso: new Date(args.weekEndMs).toISOString(), + model: args.ledger.model, + store: args.ledger.store, + pools, + findings: summarizeWeekFindings(args.findings, args.weekStartMs, args.weekEndMs), + paceHoldNote: args.paceHoldNote ?? PACE_HOLD_NOT_LIVE_NOTE, + proposals, + gaps: reweight?.gaps ?? [], + examined: reweight?.examined ?? [], + reweightEvaluated: reweight !== null, + noChangeFinding, + }; +} + +function fmtMetric(n: number | null): string { + return n === null ? "undefined" : `${n}`; +} + +function fmtErr(e: ErrorDistribution | null): string { + if (!e) return "—"; + return `${e.count} TP — median signed ${e.medianSignedMin}m, median abs ${e.medianAbsMin}m, p90 abs ${e.p90AbsMin}m`; +} + +/** The report the job posts on epic #12694 (design §7 step 3). */ +export function renderWeeklyReview(review: WeeklyReview): string { + const lines: string[] = []; + lines.push(`# Quota forecast weekly review — ${review.weekStartIso.slice(0, 10)} → ${review.weekEndIso.slice(0, 10)}`); + lines.push(""); + lines.push("Stage-3 S7 weekly review (#12701; design §7, D7), posted by the quota-weekly-review job."); + lines.push(""); + lines.push(`- Week: ${review.weekStartIso} → ${review.weekEndIso} (a scored forecast belongs to the week its reset period completed in)`); + lines.push(`- Model under score: ${review.model}`); + lines.push( + `- Store: ${review.store.records} records (${review.store.pctRecords} percent readings), ${review.store.fromIso ?? "?"} → ${review.store.toIso ?? "?"}`, + ); + lines.push(""); + lines.push("## Per-pool accuracy — this week (projected vs realized)"); + lines.push(""); + lines.push("| pool | forecasts scored | TP / FP / FN / TN | precision | recall | wall error (projected − realized) |"); + lines.push("|---|---|---|---|---|---|"); + for (const p of review.pools) { + const w = p.week; + lines.push( + `| ${p.pool} | ${w.forecastsScored} | ${w.tp} / ${w.fp} / ${w.fn} / ${w.tn} | ${fmtMetric(w.precision)} | ${fmtMetric(w.recall)} | ${fmtErr(w.wallErrorMin)} |`, + ); + } + lines.push(""); + lines.push("## Per-pool calibration — all history (S2 ledger rollup)"); + lines.push(""); + lines.push("| pool | scoreable | periods (scored/walled) | forecasts scored | precision | recall |"); + lines.push("|---|---|---|---|---|---|"); + for (const p of review.pools) { + const r = p.rollup; + lines.push( + `| ${p.pool} | ${r.scoreable ? "yes" : "NO"} | ${r.periodsScored}/${r.periodsWalled} | ${r.forecastsScored} | ${fmtMetric(r.precision)} | ${fmtMetric(r.recall)} |`, + ); + } + lines.push(""); + lines.push("## Detector findings (§6) — this week"); + lines.push(""); + if (review.findings.total === 0) { + lines.push("No detector findings this week."); + } else { + lines.push( + `${review.findings.total} finding(s): ${review.findings.counts + .filter((c) => c.count > 0) + .map((c) => `${c.detector} ${c.count}`) + .join(", ")}.`, + ); + lines.push(""); + for (const f of review.findings.findings) { + lines.push(`- \`${f.at}\` **${f.detector}** (${f.serviceId}${f.window ? `, ${f.window}` : ""}) — ${f.title}`); + lines.push(` - baseline: ${f.baseline}`); + lines.push(` - observed: ${f.observed}`); + } + } + lines.push(""); + lines.push("## pace_hold outcomes"); + lines.push(""); + lines.push(review.paceHoldNote); + lines.push(""); + lines.push("## Rule consequences (§5 fold)"); + lines.push(""); + if (!review.reweightEvaluated) { + lines.push( + "The S6 fold was not evaluated this week: no route config was supplied to the review job, so no proposal " + + "could be generated and no no-change finding is claimed. Supplying the route config is the job's " + + "standing configuration (see the schedule-registry entry), and its absence is recorded here rather " + + "than papered over.", + ); + } else if (review.proposals.length > 0) { + lines.push("Proposed through the S6 PR mechanism (never edited in place):"); + lines.push(""); + for (const p of review.proposals) { + lines.push(`- \`${p.key}\` — ${p.title}${p.prUrl ? ` — ${p.prUrl}` : " (PR not opened by this run)"}`); + } + } else { + lines.push("### No-change finding"); + lines.push(""); + lines.push(review.noChangeFinding ?? ""); + } + if (review.gaps.length) { + lines.push(""); + lines.push("Evidence gaps recorded by the generator:"); + lines.push(""); + for (const g of review.gaps) lines.push(`- \`${g.scope}\` — ${g.reason}: ${g.detail}`); + } + lines.push(""); + lines.push( + "_The weekly review produces this report and proposals only; it never edits quota config in place (design §7, D7)._", + ); + lines.push(""); + return lines.join("\n"); +}