diff --git a/pm-stack/aggregator/scripts/collect-fleet-feed.ts b/pm-stack/aggregator/scripts/collect-fleet-feed.ts index 702461fd43..f8fc7adf0a 100644 --- a/pm-stack/aggregator/scripts/collect-fleet-feed.ts +++ b/pm-stack/aggregator/scripts/collect-fleet-feed.ts @@ -73,6 +73,7 @@ import { fileURLToPath } from "node:url"; import { dnsSectionFromRegister } from "../src/dns.ts"; import { disabledProvidersFromConfig, aaAbsent, aaSectionFromSupabase, type AaRawPayload } from "../src/aa.ts"; import { normalizeOrchestrationSection, orchestrationSectionProblem, type FleetFeed } from "../src/feed.ts"; +import { computeCheckoutDrift } from "../src/checkout-drift.ts"; import type { AaFeedSection, DnsSection, @@ -617,9 +618,16 @@ async function main(): Promise { } } + // #1116 item 3: this collector runs from the pm-feed checkout of + // this repo; measure its drift vs origin/main so a stale checkout + // (collector running old code) is visible in the health view + // instead of lying quietly. Fail-soft: any git problem becomes + // state "unknown" with the reason, never a failed collection. + const checkout = await computeCheckoutDrift(join(PKG, "..", "..")); const feed: FleetFeed = { version: 1, generatedAt: now.toISOString(), + checkout, quota: { pools, burn: [], choices: computeChoices(pools, now.getTime()) }, attention, julesSummary: jules, diff --git a/pm-stack/aggregator/src/checkout-drift.ts b/pm-stack/aggregator/src/checkout-drift.ts new file mode 100644 index 0000000000..d127cc6335 --- /dev/null +++ b/pm-stack/aggregator/src/checkout-drift.ts @@ -0,0 +1,100 @@ +// Checkout drift for the fleet-feed collector (#1116 item 3): the +// collector runs from a git checkout of this repo (the sandbox +// pm-feed clone), so a checkout that has fallen behind origin/main +// means the collector itself is running old code — and the feed it +// produces can lie quietly. The collector measures the drift at +// collection time and embeds it in the feed; the aggregator surfaces +// it verbatim in the health view. +// +// Honesty rules (the health.ts style): the state is one of +// "in-sync", "behind" (with the exact count), or "unknown" WITH a +// reason. Nothing here invents a state: a git failure, a missing +// ref, or a checkout with local commits is "unknown" naming why. +import { execFile } from "node:child_process"; + +export type CheckoutDriftState = "in-sync" | "behind" | "unknown"; + +export interface CheckoutDrift { + state: CheckoutDriftState; + /** HEAD of the collector's checkout, when git could read it. */ + head?: string; + /** origin/main as the checkout's refs know it, when readable. */ + originMain?: string; + /** Commits HEAD is behind origin/main; set for in-sync (0) and behind (>0). */ + behindBy?: number; + /** Why the state is unknown; set iff state === "unknown". */ + reason?: string; +} + +/** The minimal git runner shape — injectable for tests. */ +export type GitRun = (cwd: string, args: string[]) => Promise; + +export const defaultGitRun: GitRun = (cwd, args) => + new Promise((resolve, reject) => { + execFile("git", args, { cwd, timeout: 10_000, maxBuffer: 1 << 20 }, (err, stdout) => { + if (err) reject(err); + else resolve(stdout.trim()); + }); + }); + +async function revParse(run: GitRun, cwd: string, ref: string): Promise { + const sha = await run(cwd, ["rev-parse", "--verify", `${ref}^{commit}`]); + if (!/^[0-9a-f]{40}$/.test(sha)) throw new Error(`git rev-parse ${ref} returned ${JSON.stringify(sha)}`); + return sha; +} + +async function countRange(run: GitRun, cwd: string, range: string): Promise { + const out = await run(cwd, ["rev-list", "--count", range]); + const n = Number(out); + if (!Number.isInteger(n) || n < 0) throw new Error(`git rev-list --count ${range} returned ${JSON.stringify(out)}`); + return n; +} + +/** + * Measure the drift of the checkout at `cwd` vs its origin/main ref. + * The ref is whatever the checkout's last fetch left — this function + * never fetches (collection must not mutate the checkout it runs + * from), so a stale ref understates drift rather than inventing it; + * the health view shows both SHAs so a human can check. + */ +export async function computeCheckoutDrift(cwd: string, run: GitRun = defaultGitRun): Promise { + let head: string; + let originMain: string; + try { + head = await revParse(run, cwd, "HEAD"); + originMain = await revParse(run, cwd, "origin/main"); + } catch (err) { + return { state: "unknown", reason: `checkout refs unreadable: ${err instanceof Error ? err.message : String(err)}` }; + } + let behindBy: number; + let aheadBy: number; + try { + behindBy = await countRange(run, cwd, "HEAD..origin/main"); + aheadBy = await countRange(run, cwd, "origin/main..HEAD"); + } catch (err) { + return { + state: "unknown", + head, + originMain, + reason: `drift count failed: ${err instanceof Error ? err.message : String(err)}`, + }; + } + if (aheadBy > 0) { + return { + state: "unknown", + head, + originMain, + behindBy, + reason: `checkout has ${aheadBy} local commit(s) not on origin/main — not a clean pull of main`, + }; + } + return behindBy > 0 + ? { state: "behind", head, originMain, behindBy } + : { state: "in-sync", head, originMain, behindBy: 0 }; +} + +/** The drift a health view reports when the feed carries none + * (a feed written before this check existed). */ +export function unreportedCheckoutDrift(): CheckoutDrift { + return { state: "unknown", reason: "collector did not report checkout drift (feed predates the #1116 drift check)" }; +} diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index ba5526265b..5727e44ace 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -5,6 +5,7 @@ // a stale feed keeps rendering with its age stated in provenance. import { readFile } from "node:fs/promises"; import type { UnmatchedCharge } from "./charges-match.ts"; +import type { CheckoutDrift } from "./checkout-drift.ts"; import { isProjectPoolItem } from "./projects.ts"; import type { AaFeedSection, @@ -27,6 +28,10 @@ export interface FleetFeed { version: 1; /** ISO timestamp of collection on the sandbox. */ generatedAt: string; + /** Collector checkout drift vs origin/main (#1116 item 3), measured + * by the collector in its own checkout at collection time. Absent + * in feeds written before the drift check existed. */ + checkout?: CheckoutDrift; quota: QuotaView; /** Sandbox-server + Jules sessions, pre-classification (render classifies). */ attention: SessionFeedEntry[]; diff --git a/pm-stack/aggregator/src/health.ts b/pm-stack/aggregator/src/health.ts index 6b0a646fb6..b2d45fa1d6 100644 --- a/pm-stack/aggregator/src/health.ts +++ b/pm-stack/aggregator/src/health.ts @@ -18,6 +18,7 @@ // reports "fixtures", which is also the degraded-state test fixture. import type { PendingCommentCounts } from "./comments.ts"; import type { Config } from "./config.ts"; +import { unreportedCheckoutDrift, type CheckoutDrift } from "./checkout-drift.ts"; import { ageMsText, GENERATED_AT_FUTURE_SKEW_MS, type FleetFeed, type SectionDiagnosis } from "./feed.ts"; import type { GhItem, ProvenanceDetail, RefKey } from "./model.ts"; import { PAGES } from "./pages.ts"; @@ -160,6 +161,10 @@ export interface HealthView { generatedAt: string | null; fileMtime: string | null; ageMs: number | null; + /** #1116 item 3: the collector checkout's drift vs origin/main, + * as reported in the feed; "unknown" with a reason when the feed + * carries no report — never a silently invented state. */ + checkout: CheckoutDrift; sections: FeedSectionHealth[]; }; jobs: { @@ -355,9 +360,12 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): }); } + const checkout = feed?.checkout ?? unreportedCheckoutDrift(); const degraded = inputs.mode === "live" && - (services.some((s) => s.ok === false) || (feedAgeMs !== null && feedAgeMs > FEED_STALE_MS)); + (services.some((s) => s.ok === false) || + (feedAgeMs !== null && feedAgeMs > FEED_STALE_MS) || + checkout.state === "behind"); return { status: "ok", @@ -371,6 +379,7 @@ export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): generatedAt: feed?.generatedAt ?? null, fileMtime: inputs.feedFileMtimeMs !== null ? new Date(inputs.feedFileMtimeMs).toISOString() : null, ageMs: feedAgeMs, + checkout, sections: feedSections(feed, now), }, jobs: { diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index d65b24c806..0c54122710 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -4729,8 +4729,15 @@ export function renderHealth(view: HealthView, provenance: Provenance): string { ? `last run ${esc(orch.runId ?? "unknown")} · ${esc(ageMsText(orch.ageMs ?? 0))} · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""} · next expected ~${esc(orch.nextExpectedAt ?? "")} (hourly cadence — an expectation, not a promise)` : `no run on record · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""}`; const coll = view.jobs.collector; + const drift = view.feed.checkout; + const driftLine = + drift.state === "behind" + ? ` · collector checkout behind origin/main by ${drift.behindBy ?? "?"} commit(s) — the collector is running old code` + : drift.state === "in-sync" + ? ` · collector checkout in sync with origin/main` + : ` · collector checkout drift unknown: ${esc(drift.reason ?? "no reason given")}`; const collLine = coll.generatedAt - ? `feed generated ${esc(ageMsText(coll.ageMs ?? 0))} · file written ${coll.fileMtime ? esc(coll.fileMtime) : "unknown"}` + ? `feed generated ${esc(ageMsText(coll.ageMs ?? 0))} · file written ${coll.fileMtime ? esc(coll.fileMtime) : "unknown"}${driftLine}` : "no readable fleet feed"; const pageRows = view.pages .map((p) => { diff --git a/pm-stack/aggregator/test/checkout-drift.test.ts b/pm-stack/aggregator/test/checkout-drift.test.ts new file mode 100644 index 0000000000..acf22b85d9 --- /dev/null +++ b/pm-stack/aggregator/test/checkout-drift.test.ts @@ -0,0 +1,117 @@ +// #1116 item 3: checkout-drift classification + health surfacing. +// The git runner is faked — these tests pin the honesty contract: +// in-sync / behind-by-N / unknown-with-reason, never an invented state. +import { describe, expect, test } from "bun:test"; +import { computeCheckoutDrift, type GitRun } from "../src/checkout-drift.ts"; +import type { FleetFeed } from "../src/feed.ts"; +import { buildHealth, createProbeCache, type HealthInputs, type ProbeFetch } from "../src/health.ts"; +import { loadConfig } from "../src/config.ts"; + +const HEAD = "a".repeat(40); +const MAIN = "b".repeat(40); + +function fakeGit(table: Record): GitRun { + return async (_cwd, args) => { + const key = args.join(" "); + if (key in table) return table[key]; + throw new Error(`unexpected git call: ${key}`); + }; +} + +const refs = { + "rev-parse --verify HEAD^{commit}": HEAD, + "rev-parse --verify origin/main^{commit}": MAIN, +}; + +describe("computeCheckoutDrift", () => { + test("in-sync: HEAD == origin/main, zero counts", async () => { + const run = fakeGit({ + ...refs, + "rev-parse --verify origin/main^{commit}": HEAD, + "rev-list --count HEAD..origin/main": "0", + "rev-list --count origin/main..HEAD": "0", + }); + const drift = await computeCheckoutDrift("/x", run); + expect(drift.state).toBe("in-sync"); + expect(drift.behindBy).toBe(0); + expect(drift.head).toBe(HEAD); + }); + + test("behind: exact count is reported", async () => { + const run = fakeGit({ + ...refs, + "rev-list --count HEAD..origin/main": "7", + "rev-list --count origin/main..HEAD": "0", + }); + const drift = await computeCheckoutDrift("/x", run); + expect(drift).toEqual({ state: "behind", head: HEAD, originMain: MAIN, behindBy: 7 }); + }); + + test("unreadable checkout is unknown with a reason, not a state", async () => { + const run: GitRun = async () => { + throw new Error("fatal: not a git repository"); + }; + const drift = await computeCheckoutDrift("/x", run); + expect(drift.state).toBe("unknown"); + expect(drift.reason).toContain("not a git repository"); + expect(drift.behindBy).toBeUndefined(); + }); + + test("local commits are unknown with a reason (not a clean pull of main)", async () => { + const run = fakeGit({ + ...refs, + "rev-list --count HEAD..origin/main": "2", + "rev-list --count origin/main..HEAD": "1", + }); + const drift = await computeCheckoutDrift("/x", run); + expect(drift.state).toBe("unknown"); + expect(drift.reason).toContain("1 local commit"); + expect(drift.behindBy).toBe(2); + }); +}); + +describe("buildHealth checkout surfacing", () => { + const NOW = Date.parse("2026-10-31T00:00:00Z"); + const fetcher: ProbeFetch = async () => ({ status: 200 }); + + function inputs(feed: FleetFeed | null): HealthInputs { + return { + mode: "live", + cfg: loadConfig({}), + feed, + feedFileMtimeMs: null, + }; + } + + function feedWith(checkout?: FleetFeed["checkout"]): FleetFeed { + return { + version: 1, + generatedAt: new Date(NOW).toISOString(), + ...(checkout ? { checkout } : {}), + } as unknown as FleetFeed; + } + + test("a feed without a checkout report surfaces unknown-with-reason", async () => { + const view = await buildHealth(inputs(feedWith()), { fetcher, cache: createProbeCache(), now: NOW }); + expect(view.feed.checkout.state).toBe("unknown"); + expect(view.feed.checkout.reason).toContain("did not report"); + }); + + test("behind drift is surfaced verbatim and marks the view degraded", async () => { + const view = await buildHealth( + inputs(feedWith({ state: "behind", head: HEAD, originMain: MAIN, behindBy: 3 })), + { fetcher, cache: createProbeCache(), now: NOW }, + ); + expect(view.feed.checkout).toEqual({ state: "behind", head: HEAD, originMain: MAIN, behindBy: 3 }); + expect(view.degraded).toBe(true); + }); + + test("in-sync drift does not degrade on its own", async () => { + const view = await buildHealth( + inputs(feedWith({ state: "in-sync", head: HEAD, originMain: HEAD, behindBy: 0 })), + { fetcher, cache: createProbeCache(), now: NOW }, + ); + expect(view.feed.checkout.state).toBe("in-sync"); + expect(view.degraded).toBe(false); + }); +});