From 1e7c481f1551fe493802a6494fb9922259200976 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 03:16:12 -0600 Subject: [PATCH] feat(pm-stack): compose C7 period rollups --- pm-stack/aggregator/package.json | 1 + pm-stack/aggregator/report-records-c7.md | 35 +++- .../aggregator/scripts/generate-report.ts | 80 ++++++++ pm-stack/aggregator/src/report-composer.ts | 191 ++++++++++++++++++ pm-stack/aggregator/src/report-periods.ts | 90 +++++++-- pm-stack/aggregator/src/report-records.ts | 33 ++- .../test/report-composer-c7.test.ts | 138 +++++++++++++ .../aggregator/test/report-periods-c7.test.ts | 37 +++- 8 files changed, 582 insertions(+), 23 deletions(-) create mode 100644 pm-stack/aggregator/scripts/generate-report.ts create mode 100644 pm-stack/aggregator/src/report-composer.ts create mode 100644 pm-stack/aggregator/test/report-composer-c7.test.ts diff --git a/pm-stack/aggregator/package.json b/pm-stack/aggregator/package.json index 809531ce54..18aa6820aa 100644 --- a/pm-stack/aggregator/package.json +++ b/pm-stack/aggregator/package.json @@ -8,6 +8,7 @@ "dev": "PM_AGG_DEV=1 bun run src/server.ts", "start": "bun run src/server.ts", "test": "bun test", + "report:generate": "bun run scripts/generate-report.ts", "contract:check": "bun run scripts/check-contract-corpus.ts", "provenance:check": "bun run scripts/check-provenance-matrix.ts", "typecheck": "bunx tsc --noEmit", diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index d83ebf1b61..782eb07fd2 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -31,8 +31,10 @@ adding a database or writing into the disposable projector. as equal and reports substantive changes for callers to skip and surface. Events retain `asOf`, source cursor, source IDs/URIs/observation timestamps, -related timestamps, block IDs and links. `dailyReportPeriod` supplies the -period identity and DST-aware boundaries. +related timestamps, block IDs and links. `reportPeriod` supplies the canonical +period identity and DST-aware boundaries for daily, Monday-based weekly, +monthly, quarterly, and annual periods. `dailyReportPeriod` remains as the +daily convenience function. ## Storage contract and current scope @@ -57,5 +59,30 @@ event keys. At the composition root, callers choose the file or Turso store according to `PM_AGG_STORE_BACKEND` and pass that single backend into the report-record API. There is no dual write and no silent local fallback when the durable store is -selected. This slice supports daily periods; other calendar grains and report -rendering/source integration remain subsequent C7 work. +selected. + +## Period composition and generation + +`src/report-composer.ts` composes an explicit target period from current +canonical lower-grain records. Daily reports use source records; weekly reports +use daily records and separately label the prior Friday as reach-back context; +monthly, quarterly, and annual reports prefer composed records at the next +smaller grain, falling back to source records for a child period when no +composed version exists. Stable source-time and record-ID ordering makes the +result independent of record arrival order. Blocks bubble upward according to +their `importance` grains (or the default path from their source grain), and +classified activity carries linked members into the summary. The template +sections and composer identity are versioned as `c7-rollup-v1`. + +Generate a record with `bun run report:generate --kind +--period --as-of [--store ]`. +Period identities are explicit: `YYYY-MM-DD` (daily), Monday `YYYY-MM-DD` +(weekly), `YYYY-MM` (monthly), `YYYY-QN` (quarterly), and `YYYY` (annual). +The command validates its complete argument list and period identity before +store I/O, reads the selected retained records, and appends the result +idempotently. It follows `PM_AGG_STORE_BACKEND`: file mode uses the local +report-record JSONL file (`PM_AGG_REPORT_RECORDS_FILE` or the default path), +and `--store` selects another JSONL path in file mode. Turso mode uses the +existing durable document adapter and never silently falls back to a file; +`--store` is rejected in that mode. The composition API also accepts the +canonical report-record storage capability directly. diff --git a/pm-stack/aggregator/scripts/generate-report.ts b/pm-stack/aggregator/scripts/generate-report.ts new file mode 100644 index 0000000000..9361770392 --- /dev/null +++ b/pm-stack/aggregator/scripts/generate-report.ts @@ -0,0 +1,80 @@ +#!/usr/bin/env bun +// CLI contract: generate-report.ts --kind --period --as-of [--store ] +// Parse the complete argv before choosing a store or performing any I/O. +import { defaultReportRecordsFile, type ReportRecordLocation } from "../src/report-records.ts"; +import { reportPeriod, type ReportPeriodKind } from "../src/report-periods.ts"; +import { generateReportFromStoredRecords } from "../src/report-composer.ts"; +import { parseStoreBackend } from "../src/store-backend.ts"; +import { createTursoDocumentRemote } from "../src/remote-stores.ts"; + +const USAGE = "usage: generate-report.ts --kind --period --as-of [--store ]"; + +interface Command { + kind: ReportPeriodKind; + identity: string; + asOf: string; + store?: string; +} + +const kinds = new Set(["daily", "weekly", "monthly", "quarterly", "annual"]); +const valueFlags = new Set(["--kind", "--period", "--as-of", "--store"]); + +export function parseArgs(args: string[]): Command { + const values = new Map(); + for (let index = 0; index < args.length; index++) { + const flag = args[index]!; + if (!valueFlags.has(flag)) throw new Error(`unknown argument: ${flag}`); + if (values.has(flag)) throw new Error(`duplicate argument: ${flag}`); + const value = args[index + 1]; + if (!value || value.startsWith("--")) throw new Error(`missing value for ${flag}`); + values.set(flag, value); + index++; + } + for (const required of ["--kind", "--period", "--as-of"]) { + if (!values.has(required)) throw new Error(`missing required argument: ${required}`); + } + const kind = values.get("--kind") as ReportPeriodKind; + if (!kinds.has(kind)) throw new Error(`invalid --kind: ${kind}`); + const identity = values.get("--period")!; + const asOf = values.get("--as-of")!; + if (!Number.isFinite(Date.parse(asOf)) || new Date(asOf).toISOString() !== asOf) { + throw new Error("--as-of must be a canonical ISO-8601 timestamp"); + } + // Resolve now so bad/implicit period identities fail before any store I/O. + reportPeriod(kind, identity); + const store = values.get("--store")?.trim(); + if (values.has("--store") && !store) throw new Error("--store must not be empty"); + return { kind, identity, asOf, ...(store ? { store } : {}) }; +} + +async function main(args: string[]): Promise { + let command: Command; + try { + command = parseArgs(args); + } catch (error) { + console.error(`generate-report: ${error instanceof Error ? error.message : String(error)}`); + console.error(USAGE); + process.exitCode = 2; + return; + } + const period = reportPeriod(command.kind, command.identity); + const backend = parseStoreBackend(); + if (backend === "turso" && command.store) { + console.error("generate-report: --store is only valid with PM_AGG_STORE_BACKEND=file"); + console.error(USAGE); + process.exitCode = 2; + return; + } + const location: ReportRecordLocation = backend === "turso" + ? createTursoDocumentRemote() + : command.store ?? defaultReportRecordsFile(); + const result = await generateReportFromStoredRecords(location, period, { asOf: command.asOf }); + console.log(JSON.stringify({ inserted: result.inserted, id: result.record.id, period: result.record.period.id, sourceCursor: result.record.sourceCursor }, null, 2)); +} + +if (import.meta.main) { + main(Bun.argv.slice(2)).catch((error: unknown) => { + console.error(`generate-report: ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + }); +} diff --git a/pm-stack/aggregator/src/report-composer.ts b/pm-stack/aggregator/src/report-composer.ts new file mode 100644 index 0000000000..4168bf5df8 --- /dev/null +++ b/pm-stack/aggregator/src/report-composer.ts @@ -0,0 +1,191 @@ +// Deterministic C7 period rollups over canonical, persisted lower-grain records. +import { dailyReportPeriod, type ReportPeriod, type ReportPeriodKind } from "./report-periods.ts"; +import type { ReportRecord, ReportRecordBlock, ReportRecordSource, ReportRecordLocation } from "./report-records.ts"; +import { appendReportRecord, makeReportRecord, readCurrentReportRecords } from "./report-records.ts"; + +export const REPORT_TEMPLATE_VERSION = "c7-rollup-v1"; + +export const REPORT_TEMPLATES: Readonly> = { + daily: ["What changed", "Pivots and why", "Permanent remediations", "Activity"], + weekly: ["Handled last week", "Biggest changes", "Planned next week", "Forward-day sketches", "Classified activity"], + monthly: ["Roadmap and features", "Struggles and process improvements", "Cost and capability changes", "Surprises and learnings", "Ideas and designs"], + quarterly: ["Major items", "Roadmap and features", "Cost and traffic patterns", "Surprises and learnings"], + annual: ["Plans and SaaS", "Dollar and PR efficiency", "Major changes and mistakes", "Surprises", "Next-year ideas"], +}; + +export interface ClassifiedActivity { + implemented: string[]; + cancelled: string[]; + duplicate: string[]; + inProgress: string[]; + blocked: string[]; + queued: string[]; +} + +export interface ComposeReportOptions { + asOf: string; + generatedAt?: string; + /** Cursor is derived from selected immutable input IDs when omitted. */ + sourceCursor?: string; +} + +export interface ComposedReport { + period: ReportPeriod; + asOf: string; + templateVersion: string; + sourceCursor: string; + sources: ReportRecordSource[]; + blocks: ReportRecordBlock[]; + classifiedActivity: ClassifiedActivity; +} + +const classificationKeys = { + implemented: "implemented", + cancelled: "cancelled", + duplicate: "duplicate", + "in-progress": "inProgress", + blocked: "blocked", + queued: "queued", +} as const; + +function inPeriod(record: ReportRecord, period: ReportPeriod): boolean { + const start = Date.parse(record.period.periodStart); + const end = Date.parse(record.period.periodEnd); + return start < Date.parse(period.periodEnd) && end > Date.parse(period.periodStart); +} + +function preferComposedChildren(records: ReportRecord[], kind: ReportPeriodKind): ReportRecord[] { + const matching = records.filter((record) => record.period.kind === kind); + const byPeriod = new Map(); + for (const record of matching) byPeriod.set(record.period.id, [...(byPeriod.get(record.period.id) ?? []), record]); + return [...byPeriod.values()].flatMap((periodRecords) => { + const composed = periodRecords.filter((record) => record.templateVersion === REPORT_TEMPLATE_VERSION); + return composed.length ? composed : periodRecords; + }); +} + +function lowerGrainRecords(period: ReportPeriod, records: ReportRecord[]): { record: ReportRecord; reachBack: boolean }[] { + const daily = preferComposedChildren(records, "daily"); + if (period.kind === "daily") return daily + .filter((record) => record.templateVersion !== REPORT_TEMPLATE_VERSION && inPeriod(record, period)) + .map((record) => ({ record, reachBack: false })); + + const current = daily.filter((record) => inPeriod(record, period)).map((record) => ({ record, reachBack: false })); + // Weekly reports carry the prior week's Friday as explicit context. It is + // kept distinct from the current-week source set and never changes identity. + if (period.kind === "weekly") { + const monday = /^weekly:(\d{4}-\d{2}-\d{2}):America\/Chicago$/.exec(period.id)?.[1]; + if (!monday) throw new Error("weekly period has no canonical Monday identity"); + const mondayDate = new Date(`${monday}T00:00:00.000Z`); + mondayDate.setUTCDate(mondayDate.getUTCDate() - 3); + const friday = mondayDate.toISOString().slice(0, 10); + const fridayStart = Date.parse(dailyReportPeriod(friday).periodStart); + const mondayStart = Date.parse(period.periodStart); + const reachBack = daily + .filter((record) => Date.parse(record.period.periodStart) >= fridayStart && Date.parse(record.period.periodStart) < mondayStart) + .map((record) => ({ record, reachBack: true })); + return [...current, ...reachBack]; + } + + const grainOrder: ReportPeriodKind[] = ["daily", "weekly", "monthly", "quarterly", "annual"]; + const parentIndex = grainOrder.indexOf(period.kind); + const childKind = grainOrder[parentIndex - 1]; + return preferComposedChildren(records, childKind!) + .filter((record) => inPeriod(record, period)) + .map((record) => ({ record, reachBack: false })); +} + +function stableSourceRows(period: ReportPeriod, records: ReportRecord[]) { + return lowerGrainRecords(period, records).sort((left, right) => + left.record.period.periodStart.localeCompare(right.record.period.periodStart) || left.record.id.localeCompare(right.record.id), + ); +} + +/** + * Compose one explicit period from durable lower-grain records. Source-time + * ordering and IDs, rather than arrival order, are the determinism oracle. + */ +export function composeReport(period: ReportPeriod, records: ReportRecord[], options: ComposeReportOptions): ComposedReport { + if (!Number.isFinite(Date.parse(options.asOf)) || new Date(options.asOf).toISOString() !== options.asOf) { + throw new Error("asOf must be a canonical ISO-8601 timestamp"); + } + if (Date.parse(options.asOf) < Date.parse(period.periodStart) || Date.parse(options.asOf) >= Date.parse(period.periodEnd)) { + throw new Error("asOf must fall within the report period"); + } + + const rows = stableSourceRows(period, records); + const orderedBlocks = rows.flatMap(({ record, reachBack }) => record.blocks + .filter((block) => !block.importance || block.importance.includes(period.kind)) + .map((block) => ({ + ...structuredClone(block), + id: `${record.id}:${block.id}`, + text: reachBack ? `[Prior-Friday reach-back] ${block.text}` : block.text, + links: [...new Set([...(block.links ?? []), ...record.sources.map((source) => source.uri)])].sort(), + importance: block.importance ?? defaultImportance(record.period.kind), + }))) + .sort((left, right) => left.relatedAt.localeCompare(right.relatedAt) || left.id.localeCompare(right.id)); + + const activity: ClassifiedActivity = { + implemented: [], cancelled: [], duplicate: [], inProgress: [], blocked: [], queued: [], + }; + for (const block of orderedBlocks) { + if (block.classification) activity[classificationKeys[block.classification]].push(...(block.links ?? [])); + } + for (const key of Object.keys(activity) as (keyof ClassifiedActivity)[]) activity[key] = [...new Set(activity[key])].sort(); + + const summaryBlocks: ReportRecordBlock[] = (Object.keys(activity) as (keyof ClassifiedActivity)[]) + .filter((key) => activity[key].length > 0) + .map((key) => ({ + id: `activity:${key}`, + text: `${key}: ${activity[key].length} linked member${activity[key].length === 1 ? "" : "s"}`, + relatedAt: options.asOf, + links: activity[key], + importance: defaultImportance(period.kind), + })); + const sources = [...new Map(rows.flatMap(({ record }) => record.sources).map((source) => [source.id, source])).values()] + .sort((left, right) => left.observedAt.localeCompare(right.observedAt) || left.id.localeCompare(right.id)); + const sourceCursor = options.sourceCursor ?? rows.map(({ record }) => record.id).sort().join(","); + if (!sourceCursor.trim()) throw new Error("cannot compose a report without canonical source records"); + const templateBlocks: ReportRecordBlock[] = REPORT_TEMPLATES[period.kind].map((title, index) => ({ + id: `template:section:${String(index + 1).padStart(2, "0")}`, + text: title, + relatedAt: period.periodStart, + importance: defaultImportance(period.kind), + })); + + return { + period, + asOf: options.asOf, + templateVersion: REPORT_TEMPLATE_VERSION, + sourceCursor, + sources, + blocks: [...templateBlocks, ...summaryBlocks, ...orderedBlocks], + classifiedActivity: activity, + }; +} + +/** Read durable inputs, compose one explicit period, then append idempotently. */ +export async function generateReportFromStoredRecords( + location: ReportRecordLocation, + period: ReportPeriod, + options: ComposeReportOptions, +): Promise<{ record: ReportRecord; inserted: boolean }> { + const stored = await readCurrentReportRecords(location); + const composed = composeReport(period, stored, options); + const record = makeReportRecord(composed, options.generatedAt); + const result = await appendReportRecord(location, record); + return { record: result.record, inserted: result.inserted }; +} + +/** Worked fixture from the C7 amendment; progress is append-only prose. */ +export const MODAL_LIVING_ITEM_FIXTURE = [ + "Began a 2-day re-embed project using Modal; embedding with 2 models; space +~80% per initial benchmarks; will spend $40 on Modal; must purchase $10 of Modal before 18 hours pass.", + "Purchased $10; $28 used, 15% to go; projected $6 of purchased quota used.", +] as const; + +/** Mark a daily block for the normal upward bubbling path. */ +export function defaultImportance(grain: ReportPeriodKind): ReportPeriodKind[] { + const order: ReportPeriodKind[] = ["daily", "weekly", "monthly", "quarterly", "annual"]; + const index = order.indexOf(grain); + return order.slice(index); +} diff --git a/pm-stack/aggregator/src/report-periods.ts b/pm-stack/aggregator/src/report-periods.ts index 464772686d..67ee05513f 100644 --- a/pm-stack/aggregator/src/report-periods.ts +++ b/pm-stack/aggregator/src/report-periods.ts @@ -1,12 +1,16 @@ -export interface DailyReportPeriod { +export type ReportPeriodKind = "daily" | "weekly" | "monthly" | "quarterly" | "annual"; + +export interface ReportPeriod { id: string; - kind: "daily"; + kind: ReportPeriodKind; timezone: "America/Chicago"; periodStart: string; periodEnd: string; softCloseAt: string; } +export type DailyReportPeriod = ReportPeriod & { kind: "daily" }; + const TIME_ZONE = "America/Chicago" as const; const localFormatter = new Intl.DateTimeFormat("en-US", { timeZone: TIME_ZONE, @@ -48,20 +52,82 @@ function nextCalendarDate(date: string): string { return new Date(Date.UTC(year, month - 1, day + 1)).toISOString().slice(0, 10); } -/** Resolve a daily period from an explicit America/Chicago calendar date. */ -export function dailyReportPeriod(date: string): DailyReportPeriod { +function calendarDate(date: string): Date { if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error("date must be a valid YYYY-MM-DD calendar date"); const [year, month, day] = date.split("-").map(Number) as [number, number, number]; - const check = new Date(Date.UTC(year, month - 1, day)); - if (check.toISOString().slice(0, 10) !== date) throw new Error("date must be a valid YYYY-MM-DD calendar date"); + const parsed = new Date(Date.UTC(year, month - 1, day)); + if (parsed.toISOString().slice(0, 10) !== date) throw new Error("date must be a valid YYYY-MM-DD calendar date"); + return parsed; +} - const nextDate = nextCalendarDate(date); +function period(kind: ReportPeriodKind, identity: string, start: string, end: string, softCloseDate: string, softCloseHour: number): ReportPeriod { return { - id: `daily:${date}:${TIME_ZONE}`, - kind: "daily", + id: `${kind}:${identity}:${TIME_ZONE}`, + kind, timezone: TIME_ZONE, - periodStart: localWallTimeToUtc(date, 0), - periodEnd: localWallTimeToUtc(nextDate, 0), - softCloseAt: localWallTimeToUtc(nextDate, 8), + periodStart: localWallTimeToUtc(start, 0), + periodEnd: localWallTimeToUtc(end, 0), + softCloseAt: localWallTimeToUtc(softCloseDate, softCloseHour), }; } + +/** Resolve a daily period from an explicit America/Chicago calendar date. */ +export function dailyReportPeriod(date: string): DailyReportPeriod { + calendarDate(date); + const nextDate = nextCalendarDate(date); + return period("daily", date, date, nextDate, nextDate, 8) as DailyReportPeriod; +} + +/** Resolve a weekly period from its explicit Monday calendar date. */ +export function weeklyReportPeriod(monday: string): ReportPeriod & { kind: "weekly" } { + if (!/^\d{4}-\d{2}-\d{2}$/.test(monday)) throw new Error("weekly period identity must be a Monday YYYY-MM-DD date"); + const start = calendarDate(monday); + if (start.getUTCDay() !== 1) throw new Error("weekly period date must be a Monday"); + const end = new Date(start.getTime() + 7 * 86_400_000).toISOString().slice(0, 10); + const close = new Date(start.getTime() + 9 * 86_400_000).toISOString().slice(0, 10); + return period("weekly", monday, monday, end, close, 0) as ReportPeriod & { kind: "weekly" }; +} + +/** Resolve a monthly period from its explicit YYYY-MM identity. */ +export function monthlyReportPeriod(month: string): ReportPeriod & { kind: "monthly" } { + if (!/^\d{4}-\d{2}$/.test(month)) throw new Error("month must be a valid YYYY-MM calendar month"); + const [year, monthNumber] = month.split("-").map(Number) as [number, number]; + if (monthNumber < 1 || monthNumber > 12) throw new Error("month must be a valid YYYY-MM calendar month"); + const start = `${month}-01`; + const end = new Date(Date.UTC(year, monthNumber, 1)).toISOString().slice(0, 10); + const close = new Date(Date.UTC(year, monthNumber, 8)).toISOString().slice(0, 10); + return period("monthly", month, start, end, close, 0) as ReportPeriod & { kind: "monthly" }; +} + +/** Resolve a quarterly period from an explicit YYYY-QN identity. */ +export function quarterlyReportPeriod(quarter: string): ReportPeriod & { kind: "quarterly" } { + const match = /^(\d{4})-Q([1-4])$/.exec(quarter); + if (!match) throw new Error("quarter must be a valid YYYY-QN calendar quarter"); + const year = Number(match[1]); + const firstMonth = (Number(match[2]) - 1) * 3; + const start = new Date(Date.UTC(year, firstMonth, 1)).toISOString().slice(0, 10); + const end = new Date(Date.UTC(year, firstMonth + 3, 1)).toISOString().slice(0, 10); + const close = new Date(Date.UTC(year, firstMonth + 3, 8)).toISOString().slice(0, 10); + return period("quarterly", quarter, start, end, close, 0) as ReportPeriod & { kind: "quarterly" }; +} + +/** Resolve an annual period from its explicit YYYY identity. */ +export function annualReportPeriod(year: string): ReportPeriod & { kind: "annual" } { + if (!/^\d{4}$/.test(year)) throw new Error("year must be a valid YYYY calendar year"); + const start = `${year}-01-01`; + const nextYear = Number(year) + 1; + const end = `${nextYear}-01-01`; + const close = `${nextYear}-01-08`; + return period("annual", year, start, end, close, 0) as ReportPeriod & { kind: "annual" }; +} + +/** Resolve a canonical C7 period identity; reject implicit or malformed identities. */ +export function reportPeriod(kind: ReportPeriodKind, identity: string): ReportPeriod { + switch (kind) { + case "daily": return dailyReportPeriod(identity); + case "weekly": return weeklyReportPeriod(identity); + case "monthly": return monthlyReportPeriod(identity); + case "quarterly": return quarterlyReportPeriod(identity); + case "annual": return annualReportPeriod(identity); + } +} diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index 1b86bc9b76..9f27bccdd4 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -6,7 +6,7 @@ import { appendFile, mkdir, readFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import type { AppendOnlyDocumentRemote } from "./aa-last-good.ts"; -import { dailyReportPeriod, type DailyReportPeriod } from "./report-periods.ts"; +import { reportPeriod, type ReportPeriod, type ReportPeriodKind } from "./report-periods.ts"; export interface ReportRecordSource { id: string; @@ -19,10 +19,12 @@ export interface ReportRecordBlock { text: string; relatedAt: string; links?: string[]; + importance?: ReportPeriodKind[]; + classification?: "implemented" | "cancelled" | "duplicate" | "in-progress" | "blocked" | "queued"; } export interface ReportRecordInput { - period: DailyReportPeriod; + period: ReportPeriod; asOf: string; templateVersion: string; sourceCursor: string; @@ -43,11 +45,13 @@ export function defaultReportRecordsFile(env: Record const REPORT_UPDATE_OPERATIONS = ["edit", "replace", "quote", "append", "banner", "event-log", "feedback"] as const; export type ReportUpdateOperation = (typeof REPORT_UPDATE_OPERATIONS)[number]; +const REPORT_PERIOD_KINDS = ["daily", "weekly", "monthly", "quarterly", "annual"] as const; +const REPORT_CLASSIFICATIONS = ["implemented", "cancelled", "duplicate", "in-progress", "blocked", "queued"] as const; const ALLOWED_AFTER_SOFT_CLOSE: ReadonlySet = new Set(["quote", "append", "banner", "event-log", "feedback"]); /** Enforce the report's soft-close allowlist; the close instant is exclusive. */ -export function assertReportUpdateAllowed(period: DailyReportPeriod, operation: ReportUpdateOperation, at: string): void { +export function assertReportUpdateAllowed(period: ReportPeriod, operation: ReportUpdateOperation, at: string): void { requireIsoDate(at, "update time"); if (!(REPORT_UPDATE_OPERATIONS as readonly string[]).includes(operation)) throw new Error(`unknown report operation: ${operation}`); if (Date.parse(at) < Date.parse(period.softCloseAt)) return; @@ -92,10 +96,15 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat if (!input.templateVersion.trim()) throw new Error("templateVersion is required"); if (!input.sourceCursor.trim()) throw new Error("sourceCursor is required"); if (input.period.timezone !== "America/Chicago") throw new Error("report period must use America/Chicago"); - const date = /^daily:(\d{4}-\d{2}-\d{2}):America\/Chicago$/.exec(input.period.id)?.[1]; - const canonicalPeriod = date ? dailyReportPeriod(date) : null; + const match = /^(daily|weekly|monthly|quarterly|annual):(.+):America\/Chicago$/.exec(input.period.id); + const kind = match?.[1] as ReportPeriodKind | undefined; + const identity = match?.[2]; + let canonicalPeriod: ReportPeriod | null = null; + if (kind && identity) { + try { canonicalPeriod = reportPeriod(kind, identity); } catch { /* common validation error below */ } + } if (!canonicalPeriod || input.period.kind !== canonicalPeriod.kind || input.period.periodStart !== canonicalPeriod.periodStart || input.period.periodEnd !== canonicalPeriod.periodEnd || input.period.softCloseAt !== canonicalPeriod.softCloseAt) { - throw new Error("period must be a canonical dailyReportPeriod value"); + throw new Error("period must be a canonical C7 reportPeriod value"); } if (Date.parse(input.asOf) < Date.parse(input.period.periodStart) || Date.parse(input.asOf) >= Date.parse(input.period.periodEnd)) { throw new Error("asOf must fall within the report period"); @@ -111,6 +120,18 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat if (blockIds.has(block.id)) throw new Error(`duplicate report block id: ${block.id}`); blockIds.add(block.id); requireIsoDate(block.relatedAt, "block relatedAt"); + if (block.importance && (!Array.isArray(block.importance) || block.importance.some((kind) => !(REPORT_PERIOD_KINDS as readonly string[]).includes(kind)) || new Set(block.importance).size !== block.importance.length)) { + throw new Error(`report block ${block.id} has invalid importance levels`); + } + if (block.classification && !(REPORT_CLASSIFICATIONS as readonly string[]).includes(block.classification)) { + throw new Error(`report block ${block.id} has an invalid activity classification`); + } + if (block.classification && (!block.links || block.links.length === 0)) { + throw new Error(`classified activity block ${block.id} must link its members`); + } + if (block.links && (!Array.isArray(block.links) || block.links.some((link) => typeof link !== "string" || !link.trim()))) { + throw new Error(`report block ${block.id} has invalid links`); + } } return { ...structuredClone(input), id: reportRecordId(input), generatedAt }; } diff --git a/pm-stack/aggregator/test/report-composer-c7.test.ts b/pm-stack/aggregator/test/report-composer-c7.test.ts new file mode 100644 index 0000000000..310f40bed1 --- /dev/null +++ b/pm-stack/aggregator/test/report-composer-c7.test.ts @@ -0,0 +1,138 @@ +import { access, mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, test } from "bun:test"; +import { weeklyReportPeriod, dailyReportPeriod } from "../src/report-periods.ts"; +import { composeReport, generateReportFromStoredRecords, MODAL_LIVING_ITEM_FIXTURE } from "../src/report-composer.ts"; +import { appendReportRecord, makeReportRecord, readCurrentReportRecords, type ReportRecord } from "../src/report-records.ts"; +import { parseArgs } from "../scripts/generate-report.ts"; + +const tempDirs: string[] = []; +async function storePath(): Promise { + const dir = await mkdtemp(join(tmpdir(), "report-composer-c7-")); + tempDirs.push(dir); + return join(dir, "reports.jsonl"); +} + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); +}); + +function dailyRecord( + date: string, + text: string, + classification?: "implemented" | "cancelled" | "duplicate" | "in-progress", + extra?: { text: string; classification: "cancelled" | "duplicate" | "implemented" }, +) { + const period = dailyReportPeriod(date); + const at = new Date(Date.parse(period.periodStart) + 12 * 60 * 60 * 1000).toISOString(); + return makeReportRecord({ + period, + asOf: at, + templateVersion: "daily-source-v1", + sourceCursor: `source:${date}:${text}`, + sources: [{ id: `event:${date}`, uri: `gh:developing-today/code/issues/${date}`, observedAt: at }], + blocks: [ + { + id: `activity:${date}`, + text, + relatedAt: at, + links: [`gh:developing-today/code/issues/${date}`], + classification, + }, + ...(extra ? [{ + id: `activity:${date}:late`, + text: extra.text, + relatedAt: new Date(Date.parse(at) + 60_000).toISOString(), + links: [`gh:developing-today/code/issues/${date}:late`], + classification: extra.classification, + }] : []), + ], + }, at); +} + +describe("C7 report composition", () => { + test("report generation CLI requires an explicit, canonical period before doing I/O", () => { + expect(parseArgs(["--kind", "weekly", "--period", "2026-11-16", "--as-of", "2026-11-22T12:00:00.000Z"])).toEqual({ + kind: "weekly", + identity: "2026-11-16", + asOf: "2026-11-22T12:00:00.000Z", + }); + expect(() => parseArgs(["--kind", "weekly", "--as-of", "2026-11-22T12:00:00.000Z"])).toThrow(/--period/); + expect(() => parseArgs(["--kind", "weekly", "--period", "next-week", "--as-of", "2026-11-22T12:00:00.000Z"])).toThrow(/Monday/); + expect(() => parseArgs(["--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-22T05:00:00Z", "--surprise", "x"])).toThrow(/unknown argument/); + expect(() => parseArgs(["--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-22T05:00:00.000Z", "--kind", "weekly"])).toThrow(/duplicate argument/); + }); + + test("report CLI does not silently use a file when the configured backend is Turso", async () => { + const file = await storePath(); + const script = new URL("../scripts/generate-report.ts", import.meta.url).pathname; + const child = Bun.spawn([ + process.execPath, script, + "--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-21T18:00:00.000Z", "--store", file, + ], { env: { ...Bun.env, PM_AGG_STORE_BACKEND: "turso" }, stdout: "pipe", stderr: "pipe" }); + const [exitCode, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect(exitCode).toBe(2); + expect(stderr).toContain("--store is only valid with PM_AGG_STORE_BACKEND=file"); + await expect(access(file)).rejects.toThrow(); + }); + + test("generates weekly rollups from stored daily records with deterministic ordering and classified links", async () => { + const file = await storePath(); + const inputs = [ + dailyRecord("2026-11-13", "Modal re-embed began.", "in-progress", { text: "Late result disproved the earlier hypothesis.", classification: "cancelled" }), + dailyRecord("2026-11-21", "Late result: implementation confirmed.", "implemented"), + dailyRecord("2026-11-20", "An issue was cancelled as duplicate.", "duplicate"), + dailyRecord("2026-11-16", "Weekly work started.", "implemented"), + ]; + for (const record of inputs) await appendReportRecord(file, record); + + const daily = await generateReportFromStoredRecords(file, dailyReportPeriod("2026-11-21"), { + asOf: "2026-11-21T18:00:00.000Z", + generatedAt: "2026-11-21T18:01:00.000Z", + }); + + const period = weeklyReportPeriod("2026-11-16"); + const generated = await generateReportFromStoredRecords(file, period, { + asOf: "2026-11-22T12:00:00.000Z", + generatedAt: "2026-11-22T12:01:00.000Z", + }); + const persisted = await readCurrentReportRecords(file); + const weekly = persisted.find((record) => record.id === generated.record.id); + + expect(generated.inserted).toBe(true); + expect(daily.record.period.kind).toBe("daily"); + expect(weekly?.period.id).toBe("weekly:2026-11-16:America/Chicago"); + const eventBlocks = weekly?.blocks.filter((block) => block.id.startsWith("report:")) ?? []; + expect(eventBlocks.map((block) => block.relatedAt)).toEqual([...eventBlocks.map((block) => block.relatedAt)].sort()); + expect(weekly?.blocks.some((block) => block.text.startsWith("[Prior-Friday reach-back] Modal"))).toBe(true); + expect(weekly?.blocks.some((block) => block.text.startsWith("[Prior-Friday reach-back] Late result disproved"))).toBe(true); + expect(weekly?.blocks.some((block) => block.text.includes("Late result"))).toBe(true); + expect(generated.record.blocks.some((block) => block.id === "activity:implemented" && block.links?.length === 2)).toBe(true); + expect(generated.record.blocks.some((block) => block.id === "activity:duplicate" && block.links?.length === 1)).toBe(true); + + const dailyReadBack = (await readCurrentReportRecords(file)).filter((record) => record.period.id === "daily:2026-11-21:America/Chicago"); + expect(dailyReadBack.some((record) => record.id === daily.record.id)).toBe(true); + + const rerun = await generateReportFromStoredRecords(file, period, { + asOf: "2026-11-22T12:00:00.000Z", + generatedAt: "2026-11-22T12:05:00.000Z", + }); + expect(rerun.inserted).toBe(false); + expect(rerun.record.id).toBe(generated.record.id); + }); + + test("keeps generation dependent on explicit period identity and uses the amendment's Modal example", () => { + const daily = dailyRecord("2026-11-21", MODAL_LIVING_ITEM_FIXTURE[0]); + const monthlyPeriod = dailyReportPeriod("2026-11-21"); + const result = composeReport(monthlyPeriod, [daily as ReportRecord], { asOf: "2026-11-22T05:00:00.000Z" }); + expect(result.blocks.some((block) => block.text.includes("2-day re-embed project using Modal"))).toBe(true); + expect(MODAL_LIVING_ITEM_FIXTURE[1]).toContain("Purchased $10"); + }); + + test("includes prior Friday through calendar boundaries across a DST transition", () => { + const friday = dailyRecord("2026-03-06", "Friday before the spring DST transition."); + const result = composeReport(weeklyReportPeriod("2026-03-09"), [friday], { asOf: "2026-03-10T12:00:00.000Z" }); + expect(result.blocks.some((block) => block.text.startsWith("[Prior-Friday reach-back] Friday before"))).toBe(true); + }); +}); diff --git a/pm-stack/aggregator/test/report-periods-c7.test.ts b/pm-stack/aggregator/test/report-periods-c7.test.ts index 812fbf517c..48a0fcace6 100644 --- a/pm-stack/aggregator/test/report-periods-c7.test.ts +++ b/pm-stack/aggregator/test/report-periods-c7.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { dailyReportPeriod } from "../src/report-periods.ts"; +import { annualReportPeriod, dailyReportPeriod, monthlyReportPeriod, quarterlyReportPeriod, weeklyReportPeriod } from "../src/report-periods.ts"; describe("C7 daily report periods", () => { test("uses explicit Chicago calendar dates and a stable period identity", () => { @@ -65,3 +65,38 @@ describe("C7 daily report periods", () => { expect(dailyReportPeriod("2024-02-29").periodEnd).toBe("2024-03-01T06:00:00.000Z"); }); }); + +describe("C7 higher-grain report periods", () => { + test("uses explicit calendar identities and CT boundaries", () => { + expect(weeklyReportPeriod("2026-11-16")).toEqual({ + id: "weekly:2026-11-16:America/Chicago", + kind: "weekly", + timezone: "America/Chicago", + periodStart: "2026-11-16T06:00:00.000Z", + periodEnd: "2026-11-23T06:00:00.000Z", + softCloseAt: "2026-11-25T06:00:00.000Z", + }); + expect(monthlyReportPeriod("2026-11").id).toBe("monthly:2026-11:America/Chicago"); + expect(monthlyReportPeriod("2026-11").periodEnd).toBe("2026-12-01T06:00:00.000Z"); + expect(monthlyReportPeriod("2026-11").softCloseAt).toBe("2026-12-08T06:00:00.000Z"); + expect(quarterlyReportPeriod("2026-Q4")).toMatchObject({ + id: "quarterly:2026-Q4:America/Chicago", + periodStart: "2026-10-01T05:00:00.000Z", + periodEnd: "2027-01-01T06:00:00.000Z", + softCloseAt: "2027-01-08T06:00:00.000Z", + }); + expect(annualReportPeriod("2026")).toMatchObject({ + id: "annual:2026:America/Chicago", + periodStart: "2026-01-01T06:00:00.000Z", + periodEnd: "2027-01-01T06:00:00.000Z", + softCloseAt: "2027-01-08T06:00:00.000Z", + }); + }); + + test("rejects ambiguous or malformed period identities", () => { + expect(() => weeklyReportPeriod("2026-11-17")).toThrow(/Monday/); + expect(() => monthlyReportPeriod("2026-13")).toThrow(/YYYY-MM/); + expect(() => quarterlyReportPeriod("2026-05")).toThrow(/YYYY-QN/); + expect(() => annualReportPeriod("this-year")).toThrow(/YYYY/); + }); +});