diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index aa2ff4a29a..6feb7006db 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -248,6 +248,8 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `openclaw-backup.timer` | `OnCalendar=*-*-*` | `openclaw-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | | `opencode-usage-export.timer` | `OnCalendar=*-*-*` | `opencode-usage-export.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | | `pm-dashboard-backup.timer` | `OnCalendar=*-*-*` | `pm-dashboard-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | +| `pm-digest-daily.timer` | `OnCalendar=*-*-* 07:00` | `pm-digest-daily.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | +| `pm-digest-weekly.timer` | `OnCalendar=Mon 07:05` | `pm-digest-weekly.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | | `pm-git-sync.timer` | `OnUnitActiveUSec=30s,OnBootUSec=30s` | `pm-git-sync.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | | `pm-kaneo.timer` | `OnUnitActiveUSec=30min,OnBootUSec=1min` | `pm-kaneo.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | | `pm-projector-reconcile.timer` | `OnCalendar=*-*-*` | `pm-projector-reconcile.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-03 | diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index e614526d7f..7bd42e162b 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -162,6 +162,9 @@ in # checkout (Codex P1 on PR #5141, same failure class as # code#4906 above). "PM_AGG_ACTIVITY_FILE=${aggState}/activity-ingestion.json" + # The digest archive (#1278) is runtime state too: one + # JSON per day, rendered verbatim by /digest?date=. + "PM_AGG_DIGESTS_DIR=${aggState}/digests" ]; Restart = "on-failure"; RestartSec = 5; @@ -239,6 +242,42 @@ in }; }; + pm-digest-daily = { + Unit = { + Description = "PM daily digest — generate + archive + deliver the day's digest (NixOS; runs from ~/git/code checkout, #1278)"; + After = [ "network-online.target" "pm-aggregator.service" ]; + }; + Service = { + Type = "oneshot"; + TimeoutStartSec = 300; + WorkingDirectory = "${repo}/pm-stack/aggregator"; + EnvironmentFile = "${aggState}/.env"; + Environment = [ + "PM_AGG_SOURCE=live" + "PM_AGG_DIGESTS_DIR=${aggState}/digests" + ]; + ExecStart = "${bun} run ${repo}/pm-stack/aggregator/scripts/generate-digest.ts --kind daily"; + }; + }; + + pm-digest-weekly = { + Unit = { + Description = "PM weekly digest — generate + archive + deliver the week's roll-up (NixOS; runs from ~/git/code checkout, #1278)"; + After = [ "network-online.target" "pm-aggregator.service" ]; + }; + Service = { + Type = "oneshot"; + TimeoutStartSec = 300; + WorkingDirectory = "${repo}/pm-stack/aggregator"; + EnvironmentFile = "${aggState}/.env"; + Environment = [ + "PM_AGG_SOURCE=live" + "PM_AGG_DIGESTS_DIR=${aggState}/digests" + ]; + ExecStart = "${bun} run ${repo}/pm-stack/aggregator/scripts/generate-digest.ts --kind weekly"; + }; + }; + fleet-feed-collector = { Unit = { Description = "Fleet feed collector for the PM aggregator — collect the fleet feed every ~5 minutes (NixOS; runs from ~/git/code checkout, #3363)"; @@ -366,6 +405,28 @@ in Install.WantedBy = [ "timers.target" ]; }; + pm-digest-daily = { + Unit.Description = "Run the PM daily digest every morning at 07:00 local (pm-stack, #1278)"; + Timer = { + OnCalendar = "*-*-* 07:00:00"; + RandomizedDelaySec = 60; + Persistent = true; + Unit = "pm-digest-daily.service"; + }; + Install.WantedBy = [ "timers.target" ]; + }; + + pm-digest-weekly = { + Unit.Description = "Run the PM weekly digest on Mondays at 07:05 local (pm-stack, #1278)"; + Timer = { + OnCalendar = "Mon *-*-* 07:05:00"; + RandomizedDelaySec = 60; + Persistent = true; + Unit = "pm-digest-weekly.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/pm-stack/aggregator/scripts/generate-digest.ts b/pm-stack/aggregator/scripts/generate-digest.ts new file mode 100644 index 0000000000..31d2088a9b --- /dev/null +++ b/pm-stack/aggregator/scripts/generate-digest.ts @@ -0,0 +1,107 @@ +#!/usr/bin/env bun +// Generate the scheduled PM digest (#1278): build it from the canonical +// projection (the same Source the dashboard serves), archive it as +// JSON in the digests dir — the /digest/ page renders that file +// verbatim — and deliver it to chat via Web Push to the stored push +// subscriptions (the stack's delivery surface; class "digest"). +// +// Usage: +// bun run scripts/generate-digest.ts [--kind daily|weekly] [--no-deliver] +// +// The weekly timer passes --kind weekly on the configured day +// (systemd OnCalendar=Mon, see systemd/digest-weekly.timer and +// nixos/services/pm-stack). Delivery failure never fails the archive: +// the digest is written first and the exit code reports delivery only +// when --strict-deliver is passed. +import { loadConfig } from "../src/config.ts"; +import { buildDigest, digestText, writeDigestArchive, type DigestKind } from "../src/digest.ts"; +import { fixtureSource } from "../src/sources/fixtures.ts"; +import { liveSource } from "../src/sources/live.ts"; +import { classEnabled, getAlertsStore, inQuietHours } from "../src/alerts.ts"; +import { sendPush, type PushTarget } from "../src/push.ts"; + +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + +async function main(): Promise { + const kind = (arg("kind") ?? "daily") as DigestKind; + if (kind !== "daily" && kind !== "weekly") { + console.error(`generate-digest: --kind must be daily|weekly, got ${kind}`); + process.exit(2); + } + const cfg = loadConfig(); + const source = cfg.source === "live" ? liveSource(cfg) : fixtureSource(); + // Prime the items facet first (#1267 pattern): items() records the + // pool's feed freshness into provenance; projects() alone does not. + await source.items([]).catch(() => null); + const [pool, needsDrew, quota, poolAvailable] = await Promise.all([ + source.projects(), + source.needsDrew ? source.needsDrew().catch(() => null) : Promise.resolve(null), + source.quota().catch(() => null), + source.projectsAvailable ? source.projectsAvailable().catch(() => undefined) : Promise.resolve(undefined), + ]); + const digest = buildDigest({ + pool, + needsDrew, + quota, + provenanceDetail: source.provenanceDetail?.() ?? null, + poolAvailable, + sourceKind: cfg.source, + now: new Date(), + kind, + }); + const file = await writeDigestArchive(cfg.digestsDir, digest); + console.log(`generate-digest: archived ${kind} digest for ${digest.date} → ${file}`); + console.log(digestText(digest)); + + if (process.argv.includes("--no-deliver")) return; + // Delivery: Web Push to every stored subscription, mirroring the + // alert throat's send bookkeeping (gone subscriptions are noted, + // sends are logged under class "digest"). No store (Supabase + // unavailable) = no delivery surface; the archive still stands. + const store = await getAlertsStore(); + if (!store) { + console.error("generate-digest: no alerts store — delivery skipped, archive stands"); + return; + } + const subs = await store.listSubscriptions(); + const payload = { + class: "digest", + objectRef: digest.archiveRoute, + url: digest.archiveRoute, + title: `PM ${kind} digest — ${digest.date}`, + body: digest.sections + .map((s) => `${s.title}: ${s.items.length}${s.stale ? " (stale)" : ""}`) + .join(" · "), + }; + let sent = 0; + const now = new Date(); + for (const sub of subs) { + // Subscription preferences are promises (#3676): a class the + // subscriber turned off gets nothing, and a non-breakthrough class + // like digest honors quiet hours (suppression is ledgered). + if (!classEnabled(sub, "digest")) continue; + if (inQuietHours(sub.quiet, now)) { + await store.logSend({ class: "digest", objectRef: digest.archiveRoute, outcome: "suppressed-quiet" }); + continue; + } + const target: PushTarget = { endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }; + const outcome = await sendPush(target, payload); + if (outcome.ok) { + sent += 1; + await store.logSend({ class: "digest", objectRef: digest.archiveRoute, outcome: "sent" }); + await store.noteSubscriptionAlive(sub.endpoint); + } else if (outcome.gone) { + await store.logSend({ class: "digest", objectRef: digest.archiveRoute, outcome: "gone" }); + await store.noteSubscriptionGone(sub.endpoint); + } else { + await store.logSend({ class: "digest", objectRef: digest.archiveRoute, outcome: "error" }); + } + } + console.log(`generate-digest: delivered to ${sent}/${subs.length} subscriptions`); + if (process.argv.includes("--strict-deliver") && sent === 0 && subs.length > 0) process.exit(1); +} + +await main(); diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 45b36e2f2c..8bffcc2ec0 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -48,6 +48,8 @@ export interface Config { registryFile: string; /** Usage snapshot store (hub §4): a directory of monthly JSONL files. */ snapshotsDir: string; + /** Scheduled-digest archive (#1278): one JSON file per digest. */ + digestsDir: string; /** The stewardship quota view; the hub's live fallback source when the * fleet feed carries no saas/payg sections yet (hub §2.3). */ quotaViewFile: string; @@ -117,6 +119,7 @@ export function loadConfig(env: Record = process.env activityFile: s(env.PM_AGG_ACTIVITY_FILE, join(process.cwd(), "activity-ingestion.json")), registryFile: s(env.PM_AGG_REGISTRY_FILE, join(process.cwd(), "registry.json")), snapshotsDir: s(env.PM_AGG_SNAPSHOTS_DIR, join(process.cwd(), "snapshots")), + digestsDir: s(env.PM_AGG_DIGESTS_DIR, join(process.cwd(), "digests")), quotaViewFile: s( env.PM_AGG_QUOTA_VIEW, join( diff --git a/pm-stack/aggregator/src/digest.ts b/pm-stack/aggregator/src/digest.ts new file mode 100644 index 0000000000..f79b011c28 --- /dev/null +++ b/pm-stack/aggregator/src/digest.ts @@ -0,0 +1,449 @@ +// Scheduled digest (#1278, part of epic #1184): a daily digest — and a +// weekly roll-up on the configured day — generated from the SAME +// canonical projection the dashboard pages render (the Project pool, +// the Needs-Drew census, and the quota view). No separate reporting +// pipeline: buildDigest is a pure function of those inputs, so the +// chat delivery (digestText) and the archived dashboard page +// (renderDigest in render.ts, fed by the JSON archive this module +// writes) can never drift from each other or from the pages. +// +// Honesty rules, mirroring the rest of the stack: +// - The header states the freshness of every facet the digest was +// derived from (state + age), never an unqualified "live". +// - A section whose source is missing, stale, or incomplete renders +// anyway, marked stale with its age — a missed source degrades the +// digest visibly instead of silently omitting the section. +// - Every item in every section carries the link it came from. + +import { mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { NeedsDrewCensus } from "./needs-drew.ts"; +import type { ProjectPoolItem, ProvenanceDetail, QuotaPool, QuotaView } from "./model.ts"; +import { poolState, windowPercent } from "./derive.ts"; + +export type DigestKind = "daily" | "weekly"; + +export interface DigestItem { + ref: string; + title: string; + url: string; + /** One-line context: status, blocker, reason, or quota math. */ + note: string; +} + +export interface DigestSection { + id: "moved" | "blocked" | "needsDrew" | "done" | "quota"; + title: string; + /** True when the section's source was missing/stale/incomplete. */ + stale: boolean; + /** Why the section is degraded, when it is; null when healthy. */ + staleNote: string | null; + /** Age of the section's source data at build time, when known. */ + sourceAgeMs: number | null; + items: DigestItem[]; + /** True when items were capped at DIGEST_SECTION_LIMIT. */ + truncated: boolean; +} + +export interface DigestFacetFreshness { + facet: string; + state: string; + ageMs: number | null; +} + +export interface Digest { + kind: DigestKind; + /** YYYY-MM-DD (UTC) the digest covers — its archive identity. */ + date: string; + generatedAt: string; + /** Start of the activity window the moved/done sections cover. */ + windowStart: string; + windowHours: number; + /** The canonical page this digest is archived as. */ + archiveRoute: string; + freshness: DigestFacetFreshness[]; + sections: DigestSection[]; +} + +export interface DigestInputs { + pool: ProjectPoolItem[]; + /** Null = the census source could not be read at all. */ + needsDrew: NeedsDrewCensus | null; + /** Null = the quota view could not be built. */ + quota: QuotaView | null; + /** Structured per-facet freshness, when the source provides it. */ + provenanceDetail?: ProvenanceDetail | null; + /** Whether the fleet feed actually carried a projects section + * (Source.projectsAvailable); false = the pool is unavailable, not + * empty. Absent = the source cannot say. */ + poolAvailable?: boolean; + /** The caller's source mode: a "fixtures" facet state is the honest + * expected state in fixtures mode, but in live mode it means the + * facet was never primed — stale, not healthy. */ + sourceKind?: "live" | "fixtures"; + now: Date; + kind: DigestKind; +} + +export const DIGEST_SECTION_LIMIT = 20; +/** A facet older than this marks its sections stale in a daily digest. */ +export const DIGEST_STALE_AGE_MS = 2 * 60 * 60 * 1000; + +const WINDOW_HOURS: Record = { daily: 24, weekly: 24 * 7 }; + +function isoDay(d: Date): string { + return d.toISOString().slice(0, 10); +} + +function ageText(ageMs: number | null): string { + if (ageMs === null || !Number.isFinite(ageMs)) return "age unknown"; + const mins = Math.max(0, Math.round(ageMs / 60000)); + if (mins < 60) return `${mins}m old`; + const hours = Math.floor(mins / 60); + if (hours < 48) return `${hours}h ${mins % 60}m old`; + return `${Math.floor(hours / 24)}d ${hours % 24}h old`; +} + +function facetStale( + detail: ProvenanceDetail | null | undefined, + facet: "items" | "quota", + staleAgeMs: number, + sourceKind: "live" | "fixtures" | undefined, +): { stale: boolean; note: string | null; ageMs: number | null } { + const f = detail?.[facet]; + if (!f) return { stale: false, note: null, ageMs: null }; + const ageMs = typeof f.ageMs === "number" ? f.ageMs : null; + if (f.state === "fixtures" && sourceKind === "live") { + return { + stale: true, + note: `source facet “${facet}” is still at its fixture default in live mode — the facet was never primed, so its freshness is unmeasured`, + ageMs, + }; + } + if (f.state !== "live" && f.state !== "fixtures") { + return { stale: true, note: `source facet “${facet}” is ${f.state} (${f.text})`, ageMs }; + } + if (ageMs !== null && ageMs > staleAgeMs) { + return { stale: true, note: `source facet “${facet}” is ${ageText(ageMs)}`, ageMs }; + } + return { stale: false, note: null, ageMs }; +} + +function cap(items: DigestItem[]): { items: DigestItem[]; truncated: boolean } { + return { items: items.slice(0, DIGEST_SECTION_LIMIT), truncated: items.length > DIGEST_SECTION_LIMIT }; +} + +export function buildDigest(inputs: DigestInputs): Digest { + const { now, kind } = inputs; + const windowHours = WINDOW_HOURS[kind]; + const windowStartMs = now.getTime() - windowHours * 60 * 60 * 1000; + const inWindow = (iso: string | undefined): boolean => { + if (!iso) return false; + const t = Date.parse(iso); + return Number.isFinite(t) && t >= windowStartMs && t <= now.getTime(); + }; + const staleAgeMs = kind === "weekly" ? DIGEST_STALE_AGE_MS * 7 : DIGEST_STALE_AGE_MS; + + const poolFreshBase = facetStale(inputs.provenanceDetail, "items", staleAgeMs, inputs.sourceKind); + const poolFresh = + inputs.poolAvailable === false + ? { stale: true, note: "fleet feed carried no projects section — the pool is unavailable, not empty; pool sections are unverified", ageMs: poolFreshBase.ageMs } + : poolFreshBase; + const byRef = new Map(inputs.pool.map((i) => [i.ref, i] as const)); + const byUpdatedDesc = (a: ProjectPoolItem, b: ProjectPoolItem) => + (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""); + + // --- Moved: open items touched inside the window ---------------------- + const movedAll = inputs.pool + .filter((i) => i.state === "open" && inWindow(i.updatedAt)) + .sort(byUpdatedDesc) + .map( + (i): DigestItem => ({ + ref: i.ref, + title: i.title, + url: i.issueUrl, + note: `${i.status ?? "no project status"} · updated ${i.updatedAt ?? "unknown"}`, + }), + ); + const moved = cap(movedAll); + + // --- Done: closed/merged inside the window ---------------------------- + // Selection is by completion time (mergedAt/closedAt), not the last + // update: a comment on an old closed issue must not resurrect it as + // "done today" (#5279 Codex). Items whose projection carried no + // completion stamp fall back to updatedAt. + const completedAt = (i: ProjectPoolItem) => i.mergedAt ?? i.closedAt ?? i.updatedAt; + const doneAll = inputs.pool + .filter((i) => (i.state === "closed" || i.state === "merged") && inWindow(completedAt(i))) + .sort((a, b) => (completedAt(b) ?? "").localeCompare(completedAt(a) ?? "")) + .map( + (i): DigestItem => ({ + ref: i.ref, + title: i.title, + url: i.issueUrl, + note: `${i.state} · completed ${completedAt(i) ?? "unknown"}`, + }), + ); + const done = cap(doneAll); + + // --- Blocked: open items with a live (open or unknown) blocker -------- + const blockedAll: DigestItem[] = []; + for (const i of inputs.pool) { + if (i.state !== "open" || !i.blockedBy?.length) continue; + const live = i.blockedBy.filter((ref) => { + const target = byRef.get(ref); + return !target || target.state === "open"; + }); + if (!live.length) continue; + blockedAll.push({ + ref: i.ref, + title: i.title, + url: i.issueUrl, + note: `blocked by ${live + .map((ref) => (byRef.has(ref) ? ref : `${ref} (state unknown — not in the current pool)`)) + .join(", ")}`, + }); + } + blockedAll.sort((a, b) => a.ref.localeCompare(b.ref)); + const blocked = cap(blockedAll); + + // --- Needs Drew: the label census, reasons stated or honestly absent -- + let needsSection: DigestSection; + if (!inputs.needsDrew) { + needsSection = { + id: "needsDrew", + title: "Needs Drew", + stale: true, + staleNote: "Needs-Drew census unavailable — the census source could not be read", + sourceAgeMs: null, + items: [], + truncated: false, + }; + } else { + const censusAgeMs = now.getTime() - Date.parse(inputs.needsDrew.fetchedAt); + const censusStale = + !inputs.needsDrew.complete || !Number.isFinite(censusAgeMs) || censusAgeMs > staleAgeMs; + const items = cap( + inputs.needsDrew.items.map( + (i): DigestItem => ({ + ref: i.ref, + title: i.title, + url: i.url, + note: i.reason ?? `labelled ${i.needsLabels.join(", ")} — no reason recorded on the item`, + }), + ), + ); + needsSection = { + id: "needsDrew", + title: "Needs Drew", + stale: censusStale, + staleNote: !inputs.needsDrew.complete + ? "Needs-Drew census is incomplete (a repo/label query failed or truncated)" + : censusStale + ? `Needs-Drew census is ${ageText(Number.isFinite(censusAgeMs) ? censusAgeMs : null)}` + : null, + sourceAgeMs: Number.isFinite(censusAgeMs) ? censusAgeMs : null, + items: items.items, + truncated: items.truncated, + }; + } + + // --- Quota outlook: walled / near-wall pools, walls predicted --------- + const quotaFresh = facetStale(inputs.provenanceDetail, "quota", staleAgeMs, inputs.sourceKind); + let quotaSection: DigestSection; + if (!inputs.quota) { + quotaSection = { + id: "quota", + title: "Quota outlook", + stale: true, + staleNote: "quota view unavailable — the quota source could not be read", + sourceAgeMs: null, + items: [], + truncated: false, + }; + } else { + const items: DigestItem[] = []; + for (const pool of inputs.quota.pools) { + const note = quotaPoolNote(pool, now); + if (note) { + items.push({ ref: pool.id, title: `${pool.provider} — ${pool.plan}`, url: "/quota", note }); + } + } + const cappedQ = cap(items); + const degradedProviders = inputs.quota.pools + .filter((p) => (p.freshness?.state ?? p.state) === "error" || (p.freshness?.state ?? p.state) === "stale") + .map((p) => p.provider); + quotaSection = { + id: "quota", + title: "Quota outlook", + stale: quotaFresh.stale || degradedProviders.length > 0, + staleNote: + quotaFresh.note ?? + (degradedProviders.length + ? `provider reads degraded for ${[...new Set(degradedProviders)].join(", ")} — affected pools are marked in their notes` + : null), + sourceAgeMs: quotaFresh.ageMs, + items: cappedQ.items, + truncated: cappedQ.truncated, + }; + } + + const poolSection = ( + id: DigestSection["id"], + title: string, + built: { items: DigestItem[]; truncated: boolean }, + ): DigestSection => ({ + id, + title, + stale: poolFresh.stale, + staleNote: poolFresh.note, + sourceAgeMs: poolFresh.ageMs, + items: built.items, + truncated: built.truncated, + }); + + const freshness: DigestFacetFreshness[] = []; + if (inputs.provenanceDetail) { + for (const [facet, f] of Object.entries(inputs.provenanceDetail)) { + freshness.push({ facet, state: f.state, ageMs: typeof f.ageMs === "number" ? f.ageMs : null }); + } + } + + const date = isoDay(now); + return { + kind, + date, + generatedAt: now.toISOString(), + windowStart: new Date(windowStartMs).toISOString(), + windowHours, + archiveRoute: kind === "weekly" ? `/digest?date=${date}&kind=weekly` : `/digest?date=${date}`, + freshness, + sections: [ + poolSection("moved", kind === "weekly" ? "Moved this week" : "Moved today", moved), + poolSection("blocked", "Blocked", blocked), + needsSection, + poolSection("done", kind === "weekly" ? "Done this week" : "Done today", done), + quotaSection, + ], + }; +} + +/** Why a pool belongs in the outlook, or null when it has headroom. */ +function quotaPoolNote(pool: QuotaPool, now: Date): string | null { + const state = poolState(pool); + const worst = pool.windows.reduce((m, w) => Math.max(m, windowPercent(w)), 0); + const parts: string[] = []; + // Provider freshness (#5279 Codex): quota-current marks a pool + // error/stale while retaining its historical windows, but poolState() + // derives only utilization — without this, a failed pool with low + // windows would vanish from the outlook and a stale high reading + // would read as a current forecast. + const degraded = pool.freshness?.state ?? (pool.state === "error" || pool.state === "stale" ? pool.state : null); + if (degraded === "error") { + parts.push( + `provider read error${pool.freshness?.error ? `: ${pool.freshness.error}` : ""} — current readings unavailable; any figures below are the last successful read`, + ); + } else if (degraded === "stale") { + parts.push( + `provider read stale${pool.freshness?.measuredAt ? ` (measured ${pool.freshness.measuredAt})` : ""} — figures are the last read, not current`, + ); + } + if (state === "walled") parts.push(pool.wallLiftsAt ? `walled until ${pool.wallLiftsAt}` : "walled"); + else if (state === "near") parts.push(`near wall — fullest window ${Math.round(worst)}% used`); + // Wall prediction: at the measured burn, a token window fills before + // it resets — the digest says so before it happens, not after. + if (pool.burnTokensPerMin && pool.burnTokensPerMin > 0) { + for (const w of pool.windows) { + if (w.unit !== "tokens" || !w.limit || !w.resetsAt) continue; + const remaining = w.limit - w.used; + if (remaining <= 0) continue; + const wallAt = now.getTime() + (remaining / pool.burnTokensPerMin) * 60000; + if (wallAt < Date.parse(w.resetsAt)) { + parts.push( + `at ${Math.round(pool.burnTokensPerMin)} tok/min the ${w.name} window fills in ~${Math.round((wallAt - now.getTime()) / 3600000)}h from now (reset: ${w.resetsAt})`, + ); + break; + } + } + } + if (!parts.length && worst >= 80) parts.push(`fullest window ${Math.round(worst)}% used`); + return parts.length ? parts.join("; ") : null; +} + +// --- Chat rendering -------------------------------------------------------- + +/** The chat delivery: the same content as the archived page, as text. */ +export function digestText(digest: Digest): string { + const lines: string[] = []; + lines.push( + `PM ${digest.kind} digest — ${digest.date} (generated ${digest.generatedAt}, window ${digest.windowHours}h from ${digest.windowStart})`, + ); + if (digest.freshness.length) { + lines.push( + `Data freshness: ${digest.freshness.map((f) => `${f.facet}=${f.state}${f.ageMs !== null ? ` (${ageText(f.ageMs)})` : ""}`).join(" · ")}`, + ); + } else { + lines.push("Data freshness: not measured by this source — treat every section as unverified."); + } + lines.push(`Archived as: ${digest.archiveRoute}`); + for (const s of digest.sections) { + lines.push(""); + lines.push(`## ${s.title}${s.stale ? ` — STALE: ${s.staleNote ?? "source degraded"}` : ""}`); + if (!s.items.length) lines.push(s.stale ? "(unavailable — see the stale note above)" : "(nothing)"); + for (const i of s.items) lines.push(`- ${i.title} — ${i.url} — ${i.note}`); + if (s.truncated) lines.push(`- … capped at ${DIGEST_SECTION_LIMIT} items`); + } + return lines.join("\n"); +} + +// --- Archive --------------------------------------------------------------- +// One JSON file per digest in the digests dir, named by kind + date: +// the archive IS the dashboard page's data — /digest?date= renders the +// stored digest verbatim, so a re-read shows exactly what was delivered. + +export function digestArchiveName(kind: DigestKind, date: string): string { + return `${kind}-${date}.json`; +} + +export async function writeDigestArchive(dir: string, digest: Digest): Promise { + await mkdir(dir, { recursive: true }); + const file = join(dir, digestArchiveName(digest.kind, digest.date)); + await writeFile(file, `${JSON.stringify(digest, null, 2)}\n`, "utf8"); + return file; +} + +export async function readDigestArchive( + dir: string, + date: string, + kind: DigestKind = "daily", +): Promise { + try { + const raw = await readFile(join(dir, digestArchiveName(kind, date)), "utf8"); + const parsed = JSON.parse(raw) as Digest; + return parsed && parsed.date === date && Array.isArray(parsed.sections) ? parsed : null; + } catch { + return null; + } +} + +export async function listDigestArchives( + dir: string, +): Promise<{ kind: DigestKind; date: string; route: string }[]> { + let names: string[]; + try { + names = await readdir(dir); + } catch { + return []; + } + const out: { kind: DigestKind; date: string; route: string }[] = []; + for (const name of names) { + const m = /^(daily|weekly)-(\d{4}-\d{2}-\d{2})\.json$/.exec(name); + if (m) + out.push({ + kind: m[1] as DigestKind, + date: m[2], + route: m[1] === "weekly" ? `/digest?date=${m[2]}&kind=weekly` : `/digest?date=${m[2]}`, + }); + } + return out.sort((a, b) => b.date.localeCompare(a.date) || a.kind.localeCompare(b.kind)); +} diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index e13ef49ca1..d8744522ec 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -84,6 +84,12 @@ export interface ProjectPoolItem { labels?: string[]; author?: string; updatedAt?: string; + /** Completion timestamps from the linked issue/PR, when the + * projection carried them: an issue's closedAt, a PR's mergedAt + * (or its closedAt when closed unmerged). The digest's Done + * section selects by these, never by updatedAt (#5279 Codex). */ + closedAt?: string; + mergedAt?: string; /** Project single-select fields; null when unset on the item. */ status: string | null; area: string | null; diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index af5bd6acb1..82f544876d 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -73,6 +73,15 @@ export const PAGES: PageDef[] = [ group: "overview", nav: "primary", }, + { + id: "digest", + title: "Digest", + route: "/digest", + api: "/api/digest.json", + blurb: "The scheduled PM digest (#1278): moved / blocked / needs Drew / done / quota outlook from the canonical projection, archived per day at /digest?date=.", + group: "overview", + nav: "dropdown", + }, { id: "attention", title: "Needs you", diff --git a/pm-stack/aggregator/src/projects.ts b/pm-stack/aggregator/src/projects.ts index e2987fa93b..2402434cfa 100644 --- a/pm-stack/aggregator/src/projects.ts +++ b/pm-stack/aggregator/src/projects.ts @@ -35,8 +35,8 @@ export const PROJECT_QUERY = `query($id: ID!, $cursor: String) { databaseId type content { - ... on Issue { number title state url repository { nameWithOwner } updatedAt author { login } labels(first: 20) { nodes { name } } parent { number url repository { nameWithOwner } } blockedBy(first: 50) { nodes { number url repository { nameWithOwner } } } blocking(first: 50) { nodes { number url repository { nameWithOwner } } } } - ... on PullRequest { number title state url repository { nameWithOwner } updatedAt author { login } isDraft } + ... on Issue { number title state url repository { nameWithOwner } updatedAt closedAt author { login } labels(first: 20) { nodes { name } } parent { number url repository { nameWithOwner } } blockedBy(first: 50) { nodes { number url repository { nameWithOwner } } } blocking(first: 50) { nodes { number url repository { nameWithOwner } } } } + ... on PullRequest { number title state url repository { nameWithOwner } updatedAt mergedAt closedAt author { login } isDraft } ... on DraftIssue { title } } fieldValues(first: 30) { @@ -68,6 +68,8 @@ interface GqlContent { url?: string; repository?: { nameWithOwner?: string } | null; updatedAt?: string; + closedAt?: string; + mergedAt?: string; author?: { login?: string } | null; isDraft?: boolean; labels?: { nodes?: { name?: string }[] } | null; @@ -161,6 +163,8 @@ export function parseProjectItems(json: unknown, projectUrl = PROJECT_URL): Proj labels: (c.labels?.nodes ?? []).map((l) => l?.name).filter((x): x is string => typeof x === "string"), author: c.author?.login ?? "", updatedAt: c.updatedAt ?? "", + ...(c.closedAt ? { closedAt: c.closedAt } : {}), + ...(c.mergedAt ? { mergedAt: c.mergedAt } : {}), status: singleSelect(item, "Status"), area: singleSelect(item, "Area"), horizon: singleSelect(item, "Horizon"), @@ -270,6 +274,8 @@ export function isProjectPoolItem(v: unknown): v is ProjectPoolItem { (p.labels === undefined || (Array.isArray(p.labels) && p.labels.every((x) => typeof x === "string"))) && (p.author === undefined || typeof p.author === "string") && (p.updatedAt === undefined || typeof p.updatedAt === "string") && + (p.closedAt === undefined || typeof p.closedAt === "string") && + (p.mergedAt === undefined || typeof p.mergedAt === "string") && (p.state === "open" || p.state === "closed" || p.state === "merged") && (p.parentRef === undefined || typeof p.parentRef === "string") && (p.epicRef === undefined || typeof p.epicRef === "string") && diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index a8ef1393a0..b1f67ed03b 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -23,6 +23,7 @@ import { import type { RoadmapReconciliation } from "./roadmap-reconcile.ts"; import type { RoadmapAnnotation } from "./roadmap-annotations.ts"; import { diffCoverage, type CoverageSnapshotFile } from "./coverage.ts"; +import { DIGEST_SECTION_LIMIT, type Digest, type DigestKind } from "./digest.ts"; import { registryQueryString, type RegistryView } from "./registry-view.ts"; import { latestInFamily, newClientToken, type DashAction } from "./actions.ts"; import { applyBoardDonePolicy, DONE_STRIP_RENDER_LIMIT } from "./board-policy.ts"; @@ -7124,3 +7125,59 @@ ${ ${proposalHtml}`; return layout("Notifications", body, provenance, "/notifications"); } + +/** The digest page (#1278): renders a Digest verbatim — the archived + * JSON is the page's data, so a re-read shows exactly what was + * delivered to chat. /digest?date= renders that day's archive; + * /digest renders today's live build with the archive index. */ +export function renderDigest( + digest: Digest, + archives: { kind: DigestKind; date: string; route: string }[], + provenance: Provenance, + detail?: ProvenanceDetail, +): string { + const freshness = digest.freshness.length + ? `

Data freshness: ${digest.freshness + .map((f) => `${esc(f.facet)}=${esc(f.state)}${f.ageMs !== null ? ` (${esc(ageTextDigest(f.ageMs))})` : ""}`) + .join(" · ")}

` + : `

Data freshness: not measured by this source — treat every section as unverified.

`; + const sections = digest.sections + .map((s) => { + const items = s.items.length + ? `
    ${s.items + .map( + (i) => + `
  • ${esc(i.title)} ${esc(i.ref)} — ${esc(i.note)}
  • `, + ) + .join("")}
${s.truncated ? `

… capped at ${DIGEST_SECTION_LIMIT} items

` : ""}` + : `

${s.stale ? "(unavailable — see the stale note)" : "(nothing)"}

`; + return `

${esc(s.title)}${s.stale ? ` — STALE: ${esc(s.staleNote ?? "source degraded")}` : ""}

${items}`; + }) + .join("\n"); + const archiveLinks = archives.length + ? `

Archive

    ${archives + .map((a) => `
  • ${esc(a.date)} ${esc(a.kind)}
  • `) + .join("")}
` + : `

Archive

No digests archived yet — the generator (scripts/generate-digest.ts) writes one per day.

`; + const body = `

PM ${esc(digest.kind)} digest — ${esc(digest.date)}

+

Generated ${esc(digest.generatedAt)} from the canonical projection · window ${digest.windowHours}h from ${esc(digest.windowStart)} · machine twin: ${esc(`/api/digest.json?date=${digest.date}&kind=${digest.kind}`)}

+${freshness} +${sections} +${archiveLinks}`; + return layout( + `Digest ${digest.date}`, + body, + provenance, + "/digest", + "", + detail ? freshnessChips(detail, ["items", "quota"]) : "", + ); +} + +function ageTextDigest(ageMs: number): string { + const mins = Math.max(0, Math.round(ageMs / 60000)); + if (mins < 60) return `${mins}m old`; + const hours = Math.floor(mins / 60); + if (hours < 48) return `${hours}h ${mins % 60}m old`; + return `${Math.floor(hours / 24)}d ${hours % 24}h old`; +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 7b2d5250c1..8a8565aba0 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -109,6 +109,7 @@ import { type CommentFormOpts, } from "./render.ts"; import { buildBriefs } from "./brief.ts"; +import { buildDigest, listDigestArchives, readDigestArchive, type Digest, type DigestKind } from "./digest.ts"; import { timingSafeEqual } from "node:crypto"; import { getAlertsStore, @@ -121,7 +122,7 @@ import { import { recordSwProbe, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { resolveBwsSecret } from "./secrets.ts"; import { SW_SOURCE } from "./sw-source.ts"; -import { renderAlerts, renderNotifications, esc } from "./render.ts"; +import { renderAlerts, renderNotifications, renderDigest, esc } from "./render.ts"; import { rollupNotificationSends } from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; @@ -812,6 +813,31 @@ async function applyViewAction(action: DashAction): Promise { } } +/** The digest (#1278): built live from the same Source as every page; + * the archived form is the JSON the generator script wrote. */ +async function digestContext(kind: DigestKind): Promise { + // Prime the items facet first (#1267 pattern): items() is the call + // that records the pool's feed freshness into provenance — without + // it the digest's pool sections would read an unprimed facet. + await source.items([]).catch(() => null); + const [pool, needsDrew, quota, poolAvailable] = await Promise.all([ + source.projects(), + source.needsDrew ? source.needsDrew().catch(() => null) : Promise.resolve(null), + source.quota().catch(() => null), + source.projectsAvailable ? source.projectsAvailable().catch(() => undefined) : Promise.resolve(undefined), + ]); + return buildDigest({ + pool, + needsDrew, + quota, + provenanceDetail: source.provenanceDetail?.() ?? null, + poolAvailable, + sourceKind: cfg.source, + now: new Date(), + kind, + }); +} + const GRAINS = new Set(["quarter", "month", "week", "3d", "today"]); async function handler(req: Request): Promise { @@ -1246,6 +1272,20 @@ async function handler(req: Request): Promise { return sseResponse(ssePatch("#today-main", wrapped)); } + if (path === "/digest") { + const kind = url.searchParams.get("kind") === "weekly" ? "weekly" : "daily"; + const date = url.searchParams.get("date"); + const archives = await listDigestArchives(cfg.digestsDir); + // The dated archive URL (#1278): renders the stored digest verbatim. + if (date && /^\d{4}-\d{2}-\d{2}$/.test(date)) { + const archived = + (await readDigestArchive(cfg.digestsDir, date, kind)) ?? + (kind === "daily" ? null : await readDigestArchive(cfg.digestsDir, date, "daily")); + if (archived) return html(renderDigest(archived, archives, prov(), provDetail())); + return html(renderDigest(await digestContext("daily"), archives, prov(), provDetail()), 404); + } + return html(renderDigest(await digestContext(kind), archives, prov(), provDetail())); + } if (path === "/queue") { if (url.searchParams.get("full") !== "1") return html(renderQueueShell(prov(), provDetail())); return html(renderQueue(await queueContext(), prov(), provDetail())); @@ -1725,6 +1765,24 @@ async function handler(req: Request): Promise { const { today } = await todayContext(); return json(today); } + if (path === "/api/digest.json") { + const kind = url.searchParams.get("kind") === "weekly" ? "weekly" : "daily"; + const date = url.searchParams.get("date"); + // Share the /digest handler's archive resolution (#5279 Codex): a + // dated request returns the stored digest verbatim, so the machine + // twin of a weekly or historical page is the digest it displays. + if (date && /^\d{4}-\d{2}-\d{2}$/.test(date)) { + const archived = + (await readDigestArchive(cfg.digestsDir, date, kind)) ?? + (kind === "daily" ? null : await readDigestArchive(cfg.digestsDir, date, "daily")); + if (archived) return json(archived); + return json({ error: `no ${kind} digest archived for ${date}` }, 404); + } + return json(await digestContext(kind)); + } + if (path === "/api/digests.json") { + return json({ archives: await listDigestArchives(cfg.digestsDir) }); + } if (path === "/api/queue.json") { return json(await queueContext()); } diff --git a/pm-stack/aggregator/systemd/digest-daily.service b/pm-stack/aggregator/systemd/digest-daily.service new file mode 100644 index 0000000000..edae08a97c --- /dev/null +++ b/pm-stack/aggregator/systemd/digest-daily.service @@ -0,0 +1,15 @@ +[Unit] +Description=PM daily digest — generate + archive + deliver the day's digest (pm-stack, #1278) +After=network-online.target pm-aggregator.service + +[Service] +Type=oneshot +TimeoutStartSec=300 +WorkingDirectory=%h/git/code/pm-stack/aggregator +# Runs from the laptop's code checkout; the archive lives in the +# stable state directory, never the checkout (same rule as the +# quota gatherer's outputs). +Environment=PM_AGG_SOURCE=live +EnvironmentFile=%h/.local/state/pm-aggregator/.env +Environment=PM_AGG_DIGESTS_DIR=%h/.local/state/pm-aggregator/digests +ExecStart=/run/current-system/sw/bin/bun run %h/git/code/pm-stack/aggregator/scripts/generate-digest.ts --kind daily diff --git a/pm-stack/aggregator/systemd/digest-daily.timer b/pm-stack/aggregator/systemd/digest-daily.timer new file mode 100644 index 0000000000..4b9b96a706 --- /dev/null +++ b/pm-stack/aggregator/systemd/digest-daily.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the PM daily digest every morning at 07:00 local (pm-stack, #1278) + +[Timer] +OnCalendar=*-*-* 07:00:00 +RandomizedDelaySec=60 +Persistent=true +Unit=digest-daily.service + +[Install] +WantedBy=timers.target diff --git a/pm-stack/aggregator/systemd/digest-weekly.service b/pm-stack/aggregator/systemd/digest-weekly.service new file mode 100644 index 0000000000..bfe7bbd54a --- /dev/null +++ b/pm-stack/aggregator/systemd/digest-weekly.service @@ -0,0 +1,12 @@ +[Unit] +Description=PM weekly digest — generate + archive + deliver the week's roll-up (pm-stack, #1278) +After=network-online.target pm-aggregator.service + +[Service] +Type=oneshot +TimeoutStartSec=300 +WorkingDirectory=%h/git/code/pm-stack/aggregator +Environment=PM_AGG_SOURCE=live +EnvironmentFile=%h/.local/state/pm-aggregator/.env +Environment=PM_AGG_DIGESTS_DIR=%h/.local/state/pm-aggregator/digests +ExecStart=/run/current-system/sw/bin/bun run %h/git/code/pm-stack/aggregator/scripts/generate-digest.ts --kind weekly diff --git a/pm-stack/aggregator/systemd/digest-weekly.timer b/pm-stack/aggregator/systemd/digest-weekly.timer new file mode 100644 index 0000000000..c54137ab53 --- /dev/null +++ b/pm-stack/aggregator/systemd/digest-weekly.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the PM weekly digest on Mondays at 07:05 local (pm-stack, #1278) + +[Timer] +OnCalendar=Mon *-*-* 07:05:00 +RandomizedDelaySec=60 +Persistent=true +Unit=digest-weekly.service + +[Install] +WantedBy=timers.target diff --git a/pm-stack/aggregator/test/curation-1497.test.ts b/pm-stack/aggregator/test/curation-1497.test.ts index e92aa90da1..139b425d96 100644 --- a/pm-stack/aggregator/test/curation-1497.test.ts +++ b/pm-stack/aggregator/test/curation-1497.test.ts @@ -57,6 +57,10 @@ const DECISIONS: Record = { // measurement page enters at dropdown tier — no curation ruling // promotes it, and new pages do not take primary slots without one. notifications: "dropdown", + // Post-#1497 addition (#1278, 2026-11-03): the scheduled-digest + // archive page enters at dropdown tier — no curation ruling promotes + // it, and new pages do not take primary slots without one. + digest: "dropdown", }; describe("the #1497 decision table is applied to the manifest", () => { diff --git a/pm-stack/aggregator/test/digest.test.ts b/pm-stack/aggregator/test/digest.test.ts new file mode 100644 index 0000000000..530b5417c2 --- /dev/null +++ b/pm-stack/aggregator/test/digest.test.ts @@ -0,0 +1,285 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + buildDigest, + digestText, + listDigestArchives, + readDigestArchive, + writeDigestArchive, + type DigestInputs, +} from "../src/digest.ts"; +import type { NeedsDrewCensus } from "../src/needs-drew.ts"; +import type { ProjectPoolItem, ProvenanceDetail, QuotaView } from "../src/model.ts"; + +// Fixture tests for the scheduled digest (#1278): sections are built +// from the canonical projection only, every item is linked, the header +// states freshness, and a missing/stale source degrades its section +// visibly instead of omitting it. + +const NOW = new Date("2026-11-02T13:00:00Z"); + +function item(partial: Partial & { number: number }): ProjectPoolItem { + return { + id: `PVTI_${partial.number}`, + url: `https://github.com/orgs/developing-today/projects/4?pane=issue&itemId=${partial.number}`, + projectUrl: "https://github.com/orgs/developing-today/projects/4", + ref: `developing-today/code#${partial.number}`, + repo: "developing-today/code", + issueUrl: `https://github.com/developing-today/code/issues/${partial.number}`, + title: `item ${partial.number}`, + state: "open", + contentKind: "issue", + status: null, + area: null, + horizon: null, + kind: "Task", + updatedAt: "2026-11-02T10:00:00Z", + ...partial, + }; +} + +const census: NeedsDrewCensus = { + fetchedAt: "2026-11-02T12:30:00Z", + complete: true, + sources: [], + items: [ + { + ref: "developing-today/code#42", + repo: "developing-today/code", + number: 42, + kind: "issue", + title: "decide the thing", + url: "https://github.com/developing-today/code/issues/42", + labels: ["user/escalated"], + needsLabels: ["user/escalated"], + reason: "needs a budget call", + updatedAt: "2026-11-02T09:00:00Z", + }, + ], +}; + +const quota: QuotaView = { + pools: [ + { + id: "pool-ok", + provider: "Fine", + plan: "Plan", + state: "healthy", + windows: [{ name: "weekly", unit: "tokens", limit: 1000, used: 100, resetsAt: "2026-11-09T00:00:00Z", percent: 10 }], + }, + { + id: "pool-hot", + provider: "Hot", + plan: "Plan", + state: "near", + windows: [{ name: "weekly", unit: "tokens", limit: 1000, used: 950, resetsAt: "2026-11-09T00:00:00Z", percent: 95 }], + }, + ], + burn: [], + choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] }, +}; + +function inputs(partial: Partial = {}): DigestInputs { + return { + pool: [ + item({ number: 1, status: "In Progress" }), + item({ number: 2, state: "merged", contentKind: "pr", updatedAt: "2026-11-02T08:00:00Z" }), + item({ number: 3, blockedBy: ["developing-today/code#1"] }), + item({ number: 4, updatedAt: "2026-10-20T08:00:00Z" }), // outside the daily window + item({ number: 5, state: "closed", updatedAt: "2026-10-28T08:00:00Z" }), // done 5d ago: weekly news, not daily + ], + needsDrew: census, + quota, + provenanceDetail: null, + now: NOW, + kind: "daily", + ...partial, + }; +} + +function section(d: ReturnType, id: string) { + const s = d.sections.find((x) => x.id === id); + if (!s) throw new Error(`no section ${id}`); + return s; +} + +describe("buildDigest", () => { + test("sections come from the projection, windowed, with links", () => { + const d = buildDigest(inputs()); + expect(d.date).toBe("2026-11-02"); + expect(d.archiveRoute).toBe("/digest?date=2026-11-02"); + expect(section(d, "moved").items.map((i) => i.ref)).toEqual([ + "developing-today/code#1", + "developing-today/code#3", + ]); + expect(section(d, "done").items.map((i) => i.ref)).toEqual(["developing-today/code#2"]); + const blocked = section(d, "blocked"); + expect(blocked.items).toHaveLength(1); + expect(blocked.items[0].note).toContain("blocked by developing-today/code#1"); + expect(blocked.items[0].url).toBe("https://github.com/developing-today/code/issues/3"); + const needs = section(d, "needsDrew"); + expect(needs.stale).toBe(false); + expect(needs.items[0].note).toBe("needs a budget call"); + const outlook = section(d, "quota"); + expect(outlook.items.map((i) => i.ref)).toEqual(["pool-hot"]); + expect(outlook.items[0].note).toContain("near wall"); + }); + + test("weekly window reaches back seven days", () => { + const d = buildDigest(inputs({ kind: "weekly" })); + expect(d.windowHours).toBe(168); + expect(d.archiveRoute).toBe("/digest?date=2026-11-02&kind=weekly"); + expect(section(d, "done").items.map((i) => i.ref)).toContain("developing-today/code#5"); + }); + + test("an unavailable pool degrades the pool sections visibly", () => { + const d = buildDigest(inputs({ poolAvailable: false })); + expect(section(d, "moved").stale).toBe(true); + expect(section(d, "moved").staleNote).toContain("no projects section"); + }); + + test("an unprimed (fixtures) facet in live mode is stale, not healthy", () => { + const detail = { + items: { text: "fixtures", state: "fixtures", ageMs: 0 }, + } as unknown as ProvenanceDetail; + const live = buildDigest(inputs({ provenanceDetail: detail, sourceKind: "live" })); + expect(section(live, "moved").stale).toBe(true); + const fixtures = buildDigest(inputs({ provenanceDetail: detail, sourceKind: "fixtures" })); + expect(section(fixtures, "moved").stale).toBe(false); + }); + + test("a missing census degrades Needs Drew visibly, never silently", () => { + const d = buildDigest(inputs({ needsDrew: null })); + const needs = section(d, "needsDrew"); + expect(needs.stale).toBe(true); + expect(needs.staleNote).toContain("unavailable"); + expect(needs.items).toHaveLength(0); + expect(digestText(d)).toContain("STALE"); + }); + + test("an incomplete or old census is marked stale with its age", () => { + const d = buildDigest(inputs({ needsDrew: { ...census, complete: false, fetchedAt: "2026-11-01T00:00:00Z" } })); + const needs = section(d, "needsDrew"); + expect(needs.stale).toBe(true); + expect(needs.staleNote).toContain("incomplete"); + }); + + test("a stale pool facet marks the pool sections stale", () => { + const detail = { + items: { text: "feed 5h old", state: "stale", ageMs: 5 * 3600000 }, + } as unknown as ProvenanceDetail; + const d = buildDigest(inputs({ provenanceDetail: detail })); + expect(section(d, "moved").stale).toBe(true); + expect(section(d, "moved").staleNote).toContain("items"); + expect(d.freshness).toContainEqual({ facet: "items", state: "stale", ageMs: 5 * 3600000 }); + }); + + test("quota wall prediction fires when burn fills the window before reset", () => { + const burning: QuotaView = { + ...quota, + pools: [ + { + id: "pool-burn", + provider: "Burny", + plan: "Plan", + state: "healthy", + burnTokensPerMin: 100, + windows: [ + { name: "weekly", unit: "tokens", limit: 100000, used: 90000, resetsAt: "2026-11-09T00:00:00Z", percent: 90 }, + ], + }, + ], + }; + const d = buildDigest(inputs({ quota: burning })); + const outlook = section(d, "quota"); + expect(outlook.items).toHaveLength(1); + expect(outlook.items[0].note).toContain("fills in ~"); + expect(outlook.items[0].note).not.toContain("before its"); + }); + + test("done selects by completion time, not last update (#5279 Codex)", () => { + const d = buildDigest( + inputs({ + pool: [ + // Closed long ago, commented today: not done today. + item({ number: 10, state: "closed", updatedAt: "2026-11-02T12:00:00Z", closedAt: "2026-10-20T08:00:00Z" }), + // Merged this morning, untouched since: done today. + item({ + number: 11, + state: "merged", + contentKind: "pr", + updatedAt: "2026-10-20T08:00:00Z", + mergedAt: "2026-11-02T07:00:00Z", + }), + ], + }), + ); + const done = section(d, "done"); + expect(done.items.map((i) => i.ref)).toEqual(["developing-today/code#11"]); + expect(done.items[0].note).toContain("completed 2026-11-02T07:00:00Z"); + }); + + test("quota outlook preserves provider error/stale states (#5279 Codex)", () => { + const degraded: QuotaView = { + ...quota, + pools: [ + { + id: "pool-down", + provider: "Down", + plan: "Plan", + state: "error", + freshness: { measuredAt: "2026-11-02T06:00:00Z", source: "gatherer", state: "error", error: "boom" }, + windows: [{ name: "weekly", unit: "tokens", limit: 1000, used: 100, resetsAt: "2026-11-09T00:00:00Z", percent: 10 }], + }, + { + id: "pool-stale", + provider: "Stale", + plan: "Plan", + state: "stale", + freshness: { measuredAt: "2026-11-01T06:00:00Z", source: "gatherer", state: "stale" }, + windows: [{ name: "weekly", unit: "tokens", limit: 1000, used: 950, resetsAt: "2026-11-09T00:00:00Z", percent: 95 }], + }, + ], + }; + const d = buildDigest(inputs({ quota: degraded })); + const outlook = section(d, "quota"); + const byRef = new Map(outlook.items.map((i) => [i.ref, i.note])); + expect(byRef.get("pool-down")).toContain("provider read error"); + expect(byRef.get("pool-down")).toContain("boom"); + expect(byRef.get("pool-stale")).toContain("provider read stale"); + expect(outlook.stale).toBe(true); + expect(outlook.staleNote).toContain("Down"); + }); + + test("chat text states freshness and links every section item", () => { + const text = digestText(buildDigest(inputs())); + expect(text).toContain("PM daily digest — 2026-11-02"); + expect(text).toContain("https://github.com/developing-today/code/issues/42"); + expect(text).toContain("Archived as: /digest?date=2026-11-02"); + }); +}); + +describe("digest archive", () => { + test("write → read round-trips; list sees the dated route", async () => { + const dir = await mkdtemp(join(tmpdir(), "digest-archive-")); + try { + const d = buildDigest(inputs()); + await writeDigestArchive(dir, d); + const back = await readDigestArchive(dir, "2026-11-02"); + expect(back?.generatedAt).toBe(d.generatedAt); + expect(back?.sections).toHaveLength(5); + expect(await readDigestArchive(dir, "2026-11-03")).toBeNull(); + expect(await listDigestArchives(dir)).toEqual([ + { kind: "daily", date: "2026-11-02", route: "/digest?date=2026-11-02" }, + ]); + const weekly = buildDigest(inputs({ kind: "weekly" })); + await writeDigestArchive(dir, weekly); + const list = await listDigestArchives(dir); + expect(list).toContainEqual({ kind: "weekly", date: "2026-11-02", route: "/digest?date=2026-11-02&kind=weekly" }); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/pm-stack/systemd/pm-aggregator.service b/pm-stack/systemd/pm-aggregator.service index b7a7aaec4e..84d04f562c 100644 --- a/pm-stack/systemd/pm-aggregator.service +++ b/pm-stack/systemd/pm-aggregator.service @@ -12,6 +12,10 @@ ExecStart=/run/current-system/sw/bin/bun run src/server.ts # ~/secrets/pm-stack.sops.yaml by install.sh (mode 600, never committed). # Runtime files live outside the checkout so deploys cannot overwrite them. EnvironmentFile=%h/.local/state/pm-aggregator/.env +# Digest archives live in the state dir (same rule as above); this must +# match the digest units (aggregator/systemd/digest-*.service) or the +# server defaults to /digests and never sees generated archives. +Environment=PM_AGG_DIGESTS_DIR=%h/.local/state/pm-aggregator/digests Restart=on-failure RestartSec=5