From 1e7c481f1551fe493802a6494fb9922259200976 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 03:16:12 -0600 Subject: [PATCH 1/4] 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/); + }); +}); From 524bf3feac56cd00fed4a581df104a0586cfef16 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 04:59:41 -0600 Subject: [PATCH 2/4] fix(pm-stack): address C7 rollup review findings --- pm-stack/aggregator/report-records-c7.md | 31 +++++--- .../aggregator/scripts/generate-report.ts | 5 +- pm-stack/aggregator/src/report-composer.ts | 75 +++++++++++++----- pm-stack/aggregator/src/report-records.ts | 12 +++ .../test/report-composer-c7.test.ts | 79 ++++++++++++++++++- 5 files changed, 166 insertions(+), 36 deletions(-) diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index 782eb07fd2..d1ee92df4c 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -63,24 +63,29 @@ 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`. +`src/report-composer.ts` composes an explicit target period from the latest +retained lower-grain records available at `asOf`, and excludes blocks after +that instant or outside the target period. Daily reports use source records; +weekly reports use daily records and separately label only 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). Non-visible `bubblingCandidates` preserve explicitly selected +higher grains across an excluded intermediate grain. Classified activity +carries only explicit member links; source attribution remains in `sources`. +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 +The command validates its complete argument list, period identity, and +half-open `asOf` bounds before store I/O, selects retained records available at +that point in time, and appends the result idempotently. A changed `asOf` is +part of the derived source cursor so distinct point-in-time views cannot +conflict under one immutable record ID. 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; diff --git a/pm-stack/aggregator/scripts/generate-report.ts b/pm-stack/aggregator/scripts/generate-report.ts index 9361770392..002f726862 100644 --- a/pm-stack/aggregator/scripts/generate-report.ts +++ b/pm-stack/aggregator/scripts/generate-report.ts @@ -41,7 +41,10 @@ export function parseArgs(args: string[]): Command { 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 period = reportPeriod(kind, identity); + if (Date.parse(asOf) < Date.parse(period.periodStart) || Date.parse(asOf) >= Date.parse(period.periodEnd)) { + throw new Error("--as-of must fall within the report period"); + } 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 } : {}) }; diff --git a/pm-stack/aggregator/src/report-composer.ts b/pm-stack/aggregator/src/report-composer.ts index 4168bf5df8..90ffe449e3 100644 --- a/pm-stack/aggregator/src/report-composer.ts +++ b/pm-stack/aggregator/src/report-composer.ts @@ -1,7 +1,7 @@ // 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"; +import { appendReportRecord, makeReportRecord, readReportRecords } from "./report-records.ts"; export const REPORT_TEMPLATE_VERSION = "c7-rollup-v1"; @@ -36,6 +36,7 @@ export interface ComposedReport { sourceCursor: string; sources: ReportRecordSource[]; blocks: ReportRecordBlock[]; + bubblingCandidates: ReportRecordBlock[]; classifiedActivity: ClassifiedActivity; } @@ -65,9 +66,11 @@ function preferComposedChildren(records: ReportRecord[], kind: ReportPeriodKind) } function lowerGrainRecords(period: ReportPeriod, records: ReportRecord[]): { record: ReportRecord; reachBack: boolean }[] { - const daily = preferComposedChildren(records, "daily"); + const daily = period.kind === "daily" + ? records.filter((record) => record.period.kind === "daily" && record.templateVersion !== REPORT_TEMPLATE_VERSION) + : preferComposedChildren(records, "daily"); if (period.kind === "daily") return daily - .filter((record) => record.templateVersion !== REPORT_TEMPLATE_VERSION && inPeriod(record, period)) + .filter((record) => inPeriod(record, period)) .map((record) => ({ record, reachBack: false })); const current = daily.filter((record) => inPeriod(record, period)).map((record) => ({ record, reachBack: false })); @@ -79,10 +82,9 @@ function lowerGrainRecords(period: ReportPeriod, records: ReportRecord[]): { rec 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 fridayPeriod = dailyReportPeriod(friday); const reachBack = daily - .filter((record) => Date.parse(record.period.periodStart) >= fridayStart && Date.parse(record.period.periodStart) < mondayStart) + .filter((record) => record.period.id === fridayPeriod.id) .map((record) => ({ record, reachBack: true })); return [...current, ...reachBack]; } @@ -113,17 +115,37 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt 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 rows = stableSourceRows(period, records.filter((record) => Date.parse(record.asOf) <= Date.parse(options.asOf))); + if (!rows.length) throw new Error("cannot compose a report without canonical source records"); + const orderedBlocks: ReportRecordBlock[] = []; + const bubblingCandidates: ReportRecordBlock[] = []; + const grainOrder: ReportPeriodKind[] = ["daily", "weekly", "monthly", "quarterly", "annual"]; + const targetGrain = grainOrder.indexOf(period.kind); + for (const { record, reachBack } of rows) { + const sourceBlocks = [...new Map( + [...record.blocks, ...(record.bubblingCandidates ?? [])].map((block) => [block.id, block]), + ).values()]; + for (const block of sourceBlocks) { + const relatedAt = Date.parse(block.relatedAt); + const inRequestedPeriod = relatedAt >= Date.parse(period.periodStart) && relatedAt < Date.parse(period.periodEnd); + if (relatedAt > Date.parse(options.asOf) || (!inRequestedPeriod && !reachBack)) continue; + const importance = block.importance ?? defaultImportance(record.period.kind); + const normalized = { ...structuredClone(block), importance }; + if (importance.includes(period.kind)) { + orderedBlocks.push({ + ...normalized, + id: `${record.id}:${block.id}`, + text: reachBack ? `[Prior-Friday reach-back] ${block.text}` : block.text, + links: block.links ? [...new Set(block.links)].sort() : undefined, + }); + } + if (importance.some((kind) => grainOrder.indexOf(kind) > targetGrain)) { + bubblingCandidates.push({ ...normalized, id: `${record.id}:${block.id}` }); + } + } + } + const uniqueCandidates = [...new Map(bubblingCandidates.map((block) => [block.id, block])).values()]; + orderedBlocks.sort((left, right) => left.relatedAt.localeCompare(right.relatedAt) || left.id.localeCompare(right.id)); const activity: ClassifiedActivity = { implemented: [], cancelled: [], duplicate: [], inProgress: [], blocked: [], queued: [], @@ -142,9 +164,11 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt links: activity[key], importance: defaultImportance(period.kind), })); - const sources = [...new Map(rows.flatMap(({ record }) => record.sources).map((source) => [source.id, source])).values()] + const sources = [...new Map(rows.flatMap(({ record }) => record.sources) + .filter((source) => Date.parse(source.observedAt) <= Date.parse(options.asOf)) + .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(","); + const sourceCursor = options.sourceCursor ?? `${rows.map(({ record }) => record.id).sort().join(",")};asOf:${options.asOf}`; 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")}`, @@ -160,6 +184,7 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt sourceCursor, sources, blocks: [...templateBlocks, ...summaryBlocks, ...orderedBlocks], + bubblingCandidates: uniqueCandidates, classifiedActivity: activity, }; } @@ -170,7 +195,17 @@ export async function generateReportFromStoredRecords( period: ReportPeriod, options: ComposeReportOptions, ): Promise<{ record: ReportRecord; inserted: boolean }> { - const stored = await readCurrentReportRecords(location); + const allStored = await readReportRecords(location); + const latestAsOf = new Map(); + for (const record of allStored) { + if (Date.parse(record.asOf) > Date.parse(options.asOf)) continue; + const key = `${record.period.id}\n${record.templateVersion}`; + const previous = latestAsOf.get(key); + if (!previous || record.asOf > previous.asOf || (record.asOf === previous.asOf && record.generatedAt > previous.generatedAt)) { + latestAsOf.set(key, record); + } + } + const stored = [...latestAsOf.values()]; const composed = composeReport(period, stored, options); const record = makeReportRecord(composed, options.generatedAt); const result = await appendReportRecord(location, record); diff --git a/pm-stack/aggregator/src/report-records.ts b/pm-stack/aggregator/src/report-records.ts index 9f27bccdd4..732ec876d1 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -30,6 +30,8 @@ export interface ReportRecordInput { sourceCursor: string; sources: ReportRecordSource[]; blocks: ReportRecordBlock[]; + /** Non-visible blocks retained for explicitly requested higher-grain rollups. */ + bubblingCandidates?: ReportRecordBlock[]; } export interface ReportRecord extends ReportRecordInput { @@ -133,6 +135,16 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat throw new Error(`report block ${block.id} has invalid links`); } } + for (const block of input.bubblingCandidates ?? []) { + if (!block.id.trim() || !block.text.trim()) throw new Error("each bubbling candidate requires an id and text"); + requireIsoDate(block.relatedAt, "bubbling candidate 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(`bubbling candidate ${block.id} has invalid importance levels`); + } + if (block.links && (!Array.isArray(block.links) || block.links.some((link) => typeof link !== "string" || !link.trim()))) { + throw new Error(`bubbling candidate ${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 index 310f40bed1..8ee04c9bae 100644 --- a/pm-stack/aggregator/test/report-composer-c7.test.ts +++ b/pm-stack/aggregator/test/report-composer-c7.test.ts @@ -2,7 +2,7 @@ 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 { annualReportPeriod, monthlyReportPeriod, quarterlyReportPeriod, 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"; @@ -62,6 +62,7 @@ describe("C7 report composition", () => { 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/); + expect(() => parseArgs(["--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-22T12:00:00.000Z"])).toThrow(/within the report period/); }); test("report CLI does not silently use a file when the configured backend is Turso", async () => { @@ -120,6 +121,19 @@ describe("C7 report composition", () => { }); expect(rerun.inserted).toBe(false); expect(rerun.record.id).toBe(generated.record.id); + + const dailyRerun = await generateReportFromStoredRecords(file, dailyReportPeriod("2026-11-21"), { + asOf: "2026-11-21T18:00:00.000Z", + generatedAt: "2026-11-21T18:02:00.000Z", + }); + expect(dailyRerun.inserted).toBe(false); + expect(dailyRerun.record.id).toBe(daily.record.id); + const dailyRefresh = await generateReportFromStoredRecords(file, dailyReportPeriod("2026-11-21"), { + asOf: "2026-11-21T19:00:00.000Z", + generatedAt: "2026-11-21T19:01:00.000Z", + }); + expect(dailyRefresh.inserted).toBe(true); + expect(dailyRefresh.record.id).not.toBe(daily.record.id); }); test("keeps generation dependent on explicit period identity and uses the amendment's Modal example", () => { @@ -132,7 +146,68 @@ describe("C7 report composition", () => { 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" }); + const saturday = dailyRecord("2026-03-07", "Saturday must not be reach-back context."); + const sunday = dailyRecord("2026-03-08", "Sunday must not be reach-back context."); + const result = composeReport(weeklyReportPeriod("2026-03-09"), [friday, saturday, sunday], { asOf: "2026-03-10T12:00:00.000Z" }); expect(result.blocks.some((block) => block.text.startsWith("[Prior-Friday reach-back] Friday before"))).toBe(true); + expect(result.blocks.some((block) => block.text.includes("Saturday must not"))).toBe(false); + expect(result.blocks.some((block) => block.text.includes("Sunday must not"))).toBe(false); + }); + + test("keeps source provenance separate from classified member links", () => { + const period = dailyReportPeriod("2026-11-21"); + const at = "2026-11-21T18:00:00.000Z"; + const source = makeReportRecord({ + period, + asOf: at, + templateVersion: "daily-source-v1", + sourceCursor: "member-and-evidence", + sources: [{ id: "evidence", uri: "doc:evidence", observedAt: at }], + blocks: [{ id: "done", text: "Implemented one issue.", relatedAt: at, links: ["issue:one"], classification: "implemented" }], + }, at); + const report = composeReport(period, [source], { asOf: at }); + expect(report.classifiedActivity.implemented).toEqual(["issue:one"]); + expect(report.sources.map((item) => item.uri)).toEqual(["doc:evidence"]); + }); + + test("carries explicit higher-grain candidates without showing them at excluded grains", () => { + const source = makeReportRecord({ + period: dailyReportPeriod("2026-01-05"), + asOf: "2026-01-05T18:00:00.000Z", + templateVersion: "daily-source-v1", + sourceCursor: "annual-only-candidate", + sources: [{ id: "event", uri: "event:annual", observedAt: "2026-01-05T18:00:00.000Z" }], + blocks: [{ id: "candidate", text: "This item is explicitly annual.", relatedAt: "2026-01-05T18:00:00.000Z", importance: ["daily", "weekly", "annual"] }], + }, "2026-01-05T18:01:00.000Z"); + const daily = makeReportRecord(composeReport(dailyReportPeriod("2026-01-05"), [source], { asOf: "2026-01-05T18:00:00.000Z" }), "2026-01-05T18:02:00.000Z"); + const weekly = makeReportRecord(composeReport(weeklyReportPeriod("2026-01-05"), [source, daily], { asOf: "2026-01-11T18:00:00.000Z" }), "2026-01-11T18:01:00.000Z"); + const monthly = makeReportRecord(composeReport(monthlyReportPeriod("2026-01"), [weekly], { asOf: "2026-01-31T18:00:00.000Z" }), "2026-01-31T18:01:00.000Z"); + const quarterly = makeReportRecord(composeReport(quarterlyReportPeriod("2026-Q1"), [monthly], { asOf: "2026-03-31T18:00:00.000Z" }), "2026-03-31T18:01:00.000Z"); + const annual = composeReport(annualReportPeriod("2026"), [quarterly], { asOf: "2026-12-31T18:00:00.000Z" }); + + expect(weekly.blocks.some((block) => block.text === "This item is explicitly annual.")).toBe(true); + expect(monthly.blocks.some((block) => block.text === "This item is explicitly annual.")).toBe(false); + expect(monthly.bubblingCandidates?.some((block) => block.text === "This item is explicitly annual.")).toBe(true); + expect(annual.blocks.some((block) => block.text === "This item is explicitly annual.")).toBe(true); + }); + + test("excludes future records and activity from an earlier as-of view", () => { + const monday = dailyRecord("2026-11-16", "Occurred before the requested point.", "implemented"); + const saturday = dailyRecord("2026-11-21", "Occurred after the requested point.", "implemented"); + const result = composeReport(weeklyReportPeriod("2026-11-16"), [monday, saturday], { asOf: "2026-11-19T12:00:00.000Z" }); + expect(result.blocks.some((block) => block.text.includes("Occurred before"))).toBe(true); + expect(result.blocks.some((block) => block.text.includes("Occurred after"))).toBe(false); + expect(result.classifiedActivity.implemented).toEqual(["gh:developing-today/code/issues/2026-11-16"]); + }); + + test("excludes prior-month activity from a weekly record used in a monthly rollup", () => { + const start = dailyRecord("2026-10-27", "October activity in a cross-month week.", "implemented"); + const november = dailyRecord("2026-11-01", "November activity in a cross-month week.", "implemented"); + const weekPeriod = weeklyReportPeriod("2026-10-26"); + const weekly = makeReportRecord(composeReport(weekPeriod, [start, november], { asOf: "2026-11-01T18:00:00.000Z" }), "2026-11-01T18:01:00.000Z"); + const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekly], { asOf: "2026-11-30T18:00:00.000Z" }); + expect(monthly.blocks.some((block) => block.text.includes("October activity"))).toBe(false); + expect(monthly.blocks.some((block) => block.text.includes("November activity"))).toBe(true); + expect(monthly.classifiedActivity.implemented).toEqual(["gh:developing-today/code/issues/2026-11-01"]); }); }); From 8006366bc510058bcc52b462f9c5d2626b6f1082 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 06:03:05 -0600 Subject: [PATCH 3/4] Fix C7 rollup review findings --- pm-stack/aggregator/src/report-composer.ts | 31 ++++++++-- .../test/report-composer-c7.test.ts | 58 +++++++++++++++++++ 2 files changed, 83 insertions(+), 6 deletions(-) diff --git a/pm-stack/aggregator/src/report-composer.ts b/pm-stack/aggregator/src/report-composer.ts index 90ffe449e3..df7c8b836e 100644 --- a/pm-stack/aggregator/src/report-composer.ts +++ b/pm-stack/aggregator/src/report-composer.ts @@ -119,40 +119,59 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt if (!rows.length) throw new Error("cannot compose a report without canonical source records"); const orderedBlocks: ReportRecordBlock[] = []; const bubblingCandidates: ReportRecordBlock[] = []; + const orderedByIdentity = new Map(); const grainOrder: ReportPeriodKind[] = ["daily", "weekly", "monthly", "quarterly", "annual"]; const targetGrain = grainOrder.indexOf(period.kind); for (const { record, reachBack } of rows) { + const composedInput = record.templateVersion === REPORT_TEMPLATE_VERSION; const sourceBlocks = [...new Map( [...record.blocks, ...(record.bubblingCandidates ?? [])].map((block) => [block.id, block]), ).values()]; for (const block of sourceBlocks) { + // Templates and summaries describe their source report, not source + // activity. Rebuild them at the target grain instead of rolling them up. + if (composedInput && (block.id.startsWith("template:") || block.id.startsWith("activity:"))) continue; const relatedAt = Date.parse(block.relatedAt); const inRequestedPeriod = relatedAt >= Date.parse(period.periodStart) && relatedAt < Date.parse(period.periodEnd); if (relatedAt > Date.parse(options.asOf) || (!inRequestedPeriod && !reachBack)) continue; const importance = block.importance ?? defaultImportance(record.period.kind); const normalized = { ...structuredClone(block), importance }; + const id = composedInput ? block.id : `${record.id}:${block.id}`; if (importance.includes(period.kind)) { - orderedBlocks.push({ + const ordered = { ...normalized, - id: `${record.id}:${block.id}`, + id, text: reachBack ? `[Prior-Friday reach-back] ${block.text}` : block.text, links: block.links ? [...new Set(block.links)].sort() : undefined, - }); + }; + const previous = orderedByIdentity.get(id); + if (!previous || (previous.reachBack && !reachBack)) orderedByIdentity.set(id, { block: ordered, reachBack }); } - if (importance.some((kind) => grainOrder.indexOf(kind) > targetGrain)) { - bubblingCandidates.push({ ...normalized, id: `${record.id}:${block.id}` }); + if (!reachBack && importance.some((kind) => grainOrder.indexOf(kind) > targetGrain)) { + bubblingCandidates.push({ ...normalized, id }); } } } + orderedBlocks.push(...[...orderedByIdentity.values()].map(({ block }) => block)); const uniqueCandidates = [...new Map(bubblingCandidates.map((block) => [block.id, block])).values()]; orderedBlocks.sort((left, right) => left.relatedAt.localeCompare(right.relatedAt) || left.id.localeCompare(right.id)); const activity: ClassifiedActivity = { implemented: [], cancelled: [], duplicate: [], inProgress: [], blocked: [], queued: [], }; + const latestClassification = new Map(); for (const block of orderedBlocks) { - if (block.classification) activity[classificationKeys[block.classification]].push(...(block.links ?? [])); + if (!block.classification) continue; + const key = classificationKeys[block.classification]; + for (const member of block.links ?? []) { + const previous = latestClassification.get(member); + if (!previous || block.relatedAt.localeCompare(previous.relatedAt) > 0 || + (block.relatedAt === previous.relatedAt && block.id.localeCompare(previous.id) > 0)) { + latestClassification.set(member, { relatedAt: block.relatedAt, id: block.id, key }); + } + } } + for (const [member, latest] of latestClassification) activity[latest.key].push(member); 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)[]) diff --git a/pm-stack/aggregator/test/report-composer-c7.test.ts b/pm-stack/aggregator/test/report-composer-c7.test.ts index 8ee04c9bae..4a09e43fe0 100644 --- a/pm-stack/aggregator/test/report-composer-c7.test.ts +++ b/pm-stack/aggregator/test/report-composer-c7.test.ts @@ -210,4 +210,62 @@ describe("C7 report composition", () => { expect(monthly.blocks.some((block) => block.text.includes("November activity"))).toBe(true); expect(monthly.classifiedActivity.implemented).toEqual(["gh:developing-today/code/issues/2026-11-01"]); }); + + test("preserves source identity across Friday reach-back and does not bubble the context copy", () => { + const friday = dailyRecord("2026-11-06", "Friday living-item update.", "implemented"); + const weekOnePeriod = weeklyReportPeriod("2026-11-02"); + const weekOne = makeReportRecord(composeReport(weekOnePeriod, [friday], { asOf: "2026-11-08T18:00:00.000Z" }), "2026-11-08T19:00:00.000Z"); + const weekTwoPeriod = weeklyReportPeriod("2026-11-09"); + const weekTwo = makeReportRecord(composeReport(weekTwoPeriod, [friday], { asOf: "2026-11-10T18:00:00.000Z" }), "2026-11-10T19:00:00.000Z"); + const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekOne, weekTwo], { asOf: "2026-11-30T18:00:00.000Z" }); + + expect(weekTwo.bubblingCandidates?.some((block) => block.text.includes("Friday living-item update."))).toBe(false); + expect(monthly.blocks.filter((block) => block.text.includes("Friday living-item update."))).toHaveLength(1); + }); + + test("regenerates activity summaries at the target grain instead of carrying weekly summaries upward", () => { + const october = dailyRecord("2026-10-27", "October implementation.", "implemented"); + const november = dailyRecord("2026-11-01", "November implementation.", "implemented"); + const weekly = makeReportRecord(composeReport(weeklyReportPeriod("2026-10-26"), [october, november], { + asOf: "2026-11-01T18:00:00.000Z", + }), "2026-11-01T19:00:00.000Z"); + const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekly], { asOf: "2026-11-30T18:00:00.000Z" }); + + const summaries = monthly.blocks.filter((block) => block.id === "activity:implemented"); + const implementedSummary = summaries[0]; + expect(implementedSummary?.text).toBe("implemented: 1 linked member"); + expect(implementedSummary?.links).toEqual(["gh:developing-today/code/issues/2026-11-01"]); + expect(summaries).toHaveLength(1); + }); + + test("counts each linked member only in its latest classification as of the report time", () => { + const mondayAt = "2026-11-16T18:00:00.000Z"; + const tuesdayAt = "2026-11-17T18:00:00.000Z"; + const member = "gh:developing-today/code/issues/12345"; + const monday = makeReportRecord({ + period: dailyReportPeriod("2026-11-16"), + asOf: mondayAt, + templateVersion: "daily-source-v1", + sourceCursor: "monday-progress", + sources: [{ id: "monday-source", uri: "issue:12345", observedAt: mondayAt }], + blocks: [{ id: "started", text: "Started work.", relatedAt: mondayAt, links: [member], classification: "in-progress" }], + }, mondayAt); + const tuesday = makeReportRecord({ + period: dailyReportPeriod("2026-11-17"), + asOf: tuesdayAt, + templateVersion: "daily-source-v1", + sourceCursor: "tuesday-implemented", + sources: [{ id: "tuesday-source", uri: "issue:12345", observedAt: tuesdayAt }], + blocks: [{ id: "finished", text: "Finished work.", relatedAt: tuesdayAt, links: [member], classification: "implemented" }], + }, tuesdayAt); + const period = weeklyReportPeriod("2026-11-16"); + const mondayView = composeReport(period, [monday, tuesday], { asOf: "2026-11-16T23:00:00.000Z" }); + const tuesdayView = composeReport(period, [monday, tuesday], { asOf: "2026-11-17T23:00:00.000Z" }); + + expect(mondayView.classifiedActivity.inProgress).toEqual([member]); + expect(tuesdayView.classifiedActivity.implemented).toEqual([member]); + expect(tuesdayView.classifiedActivity.inProgress).toEqual([]); + expect(tuesdayView.blocks.some((block) => block.text === "Started work.")).toBe(true); + expect(tuesdayView.blocks.some((block) => block.text === "Finished work.")).toBe(true); + }); }); From b3d1e06c10bfc7f488e754a0ad0ff1673fc32496 Mon Sep 17 00:00:00 2001 From: felix Date: Sun, 22 Nov 2026 19:40:57 +0000 Subject: [PATCH 4/4] style(pm-stack): treefmt the C7 rollup files after main refresh Shepherd pass for #12504: merged origin/main into the PR branch. The C7 feature had landed on main via #12486 as a token-identical copy of this branch's feature commit, so the add/add conflicts resolved to this branch's content (feature + review fixes); biome/prettier formatting then restored main's treefmt style, leaving a net diff of exactly the review-fix delta. --- pm-stack/aggregator/report-records-c7.md | 2 +- .../aggregator/scripts/generate-report.ts | 21 +- pm-stack/aggregator/src/report-composer.ts | 95 ++++-- pm-stack/aggregator/src/report-periods.ts | 24 +- pm-stack/aggregator/src/report-records.ts | 173 +++++++++-- .../test/report-composer-c7.test.ts | 294 +++++++++++++----- .../aggregator/test/report-periods-c7.test.ts | 37 ++- 7 files changed, 486 insertions(+), 160 deletions(-) diff --git a/pm-stack/aggregator/report-records-c7.md b/pm-stack/aggregator/report-records-c7.md index d1ee92df4c..3cf28ce86d 100644 --- a/pm-stack/aggregator/report-records-c7.md +++ b/pm-stack/aggregator/report-records-c7.md @@ -21,7 +21,7 @@ adding a database or writing into the disposable projector. `(period, templateVersion)`. - `appendReportSnapshot(file, record, snapshotAt)` freezes the record once per period. A changed snapshot conflicts. `appendReportSnapshotCorrection(file, - snapshotId, record, correctedAt)` creates a separate linked correction event +snapshotId, record, correctedAt)` creates a separate linked correction event without mutating the snapshot; correction records must match the snapshot period. `readReportSnapshots(file)` reads immutable snapshots, and `readReportSnapshotCorrections(file)` reads their correction history. diff --git a/pm-stack/aggregator/scripts/generate-report.ts b/pm-stack/aggregator/scripts/generate-report.ts index 002f726862..518c164814 100644 --- a/pm-stack/aggregator/scripts/generate-report.ts +++ b/pm-stack/aggregator/scripts/generate-report.ts @@ -7,7 +7,8 @@ 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 ]"; +const USAGE = + "usage: generate-report.ts --kind --period --as-of [--store ]"; interface Command { kind: ReportPeriodKind; @@ -68,11 +69,21 @@ async function main(args: string[]): Promise { process.exitCode = 2; return; } - const location: ReportRecordLocation = backend === "turso" - ? createTursoDocumentRemote() - : command.store ?? defaultReportRecordsFile(); + 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)); + 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) { diff --git a/pm-stack/aggregator/src/report-composer.ts b/pm-stack/aggregator/src/report-composer.ts index df7c8b836e..846753df8b 100644 --- a/pm-stack/aggregator/src/report-composer.ts +++ b/pm-stack/aggregator/src/report-composer.ts @@ -8,7 +8,13 @@ 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"], + 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"], }; @@ -65,13 +71,16 @@ function preferComposedChildren(records: ReportRecord[], kind: ReportPeriodKind) }); } -function lowerGrainRecords(period: ReportPeriod, records: ReportRecord[]): { record: ReportRecord; reachBack: boolean }[] { - const daily = period.kind === "daily" - ? records.filter((record) => record.period.kind === "daily" && record.templateVersion !== REPORT_TEMPLATE_VERSION) - : preferComposedChildren(records, "daily"); - if (period.kind === "daily") return daily - .filter((record) => inPeriod(record, period)) - .map((record) => ({ record, reachBack: false })); +function lowerGrainRecords( + period: ReportPeriod, + records: ReportRecord[], +): { record: ReportRecord; reachBack: boolean }[] { + const daily = + period.kind === "daily" + ? records.filter((record) => record.period.kind === "daily" && record.templateVersion !== REPORT_TEMPLATE_VERSION) + : preferComposedChildren(records, "daily"); + if (period.kind === "daily") + return daily.filter((record) => 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 @@ -98,8 +107,10 @@ function lowerGrainRecords(period: ReportPeriod, records: ReportRecord[]): { rec } 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), + return lowerGrainRecords(period, records).sort( + (left, right) => + left.record.period.periodStart.localeCompare(right.record.period.periodStart) || + left.record.id.localeCompare(right.record.id), ); } @@ -107,15 +118,25 @@ function stableSourceRows(period: ReportPeriod, records: ReportRecord[]) { * 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 { +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)) { + 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.filter((record) => Date.parse(record.asOf) <= Date.parse(options.asOf))); + const rows = stableSourceRows( + period, + records.filter((record) => Date.parse(record.asOf) <= Date.parse(options.asOf)), + ); if (!rows.length) throw new Error("cannot compose a report without canonical source records"); const orderedBlocks: ReportRecordBlock[] = []; const bubblingCandidates: ReportRecordBlock[] = []; @@ -124,9 +145,9 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt const targetGrain = grainOrder.indexOf(period.kind); for (const { record, reachBack } of rows) { const composedInput = record.templateVersion === REPORT_TEMPLATE_VERSION; - const sourceBlocks = [...new Map( - [...record.blocks, ...(record.bubblingCandidates ?? [])].map((block) => [block.id, block]), - ).values()]; + const sourceBlocks = [ + ...new Map([...record.blocks, ...(record.bubblingCandidates ?? [])].map((block) => [block.id, block])).values(), + ]; for (const block of sourceBlocks) { // Templates and summaries describe their source report, not source // activity. Rebuild them at the target grain instead of rolling them up. @@ -157,7 +178,12 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt orderedBlocks.sort((left, right) => left.relatedAt.localeCompare(right.relatedAt) || left.id.localeCompare(right.id)); const activity: ClassifiedActivity = { - implemented: [], cancelled: [], duplicate: [], inProgress: [], blocked: [], queued: [], + implemented: [], + cancelled: [], + duplicate: [], + inProgress: [], + blocked: [], + queued: [], }; const latestClassification = new Map(); for (const block of orderedBlocks) { @@ -165,14 +191,18 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt const key = classificationKeys[block.classification]; for (const member of block.links ?? []) { const previous = latestClassification.get(member); - if (!previous || block.relatedAt.localeCompare(previous.relatedAt) > 0 || - (block.relatedAt === previous.relatedAt && block.id.localeCompare(previous.id) > 0)) { + if ( + !previous || + block.relatedAt.localeCompare(previous.relatedAt) > 0 || + (block.relatedAt === previous.relatedAt && block.id.localeCompare(previous.id) > 0) + ) { latestClassification.set(member, { relatedAt: block.relatedAt, id: block.id, key }); } } } for (const [member, latest] of latestClassification) activity[latest.key].push(member); - for (const key of Object.keys(activity) as (keyof ClassifiedActivity)[]) activity[key] = [...new Set(activity[key])].sort(); + 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) @@ -183,11 +213,20 @@ export function composeReport(period: ReportPeriod, records: ReportRecord[], opt links: activity[key], importance: defaultImportance(period.kind), })); - const sources = [...new Map(rows.flatMap(({ record }) => record.sources) - .filter((source) => Date.parse(source.observedAt) <= Date.parse(options.asOf)) - .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(",")};asOf:${options.asOf}`; + const sources = [ + ...new Map( + rows + .flatMap(({ record }) => record.sources) + .filter((source) => Date.parse(source.observedAt) <= Date.parse(options.asOf)) + .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(",")};asOf:${options.asOf}`; 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")}`, @@ -220,7 +259,11 @@ export async function generateReportFromStoredRecords( if (Date.parse(record.asOf) > Date.parse(options.asOf)) continue; const key = `${record.period.id}\n${record.templateVersion}`; const previous = latestAsOf.get(key); - if (!previous || record.asOf > previous.asOf || (record.asOf === previous.asOf && record.generatedAt > previous.generatedAt)) { + if ( + !previous || + record.asOf > previous.asOf || + (record.asOf === previous.asOf && record.generatedAt > previous.generatedAt) + ) { latestAsOf.set(key, record); } } diff --git a/pm-stack/aggregator/src/report-periods.ts b/pm-stack/aggregator/src/report-periods.ts index 67ee05513f..315d35c27e 100644 --- a/pm-stack/aggregator/src/report-periods.ts +++ b/pm-stack/aggregator/src/report-periods.ts @@ -60,7 +60,14 @@ function calendarDate(date: string): Date { return parsed; } -function period(kind: ReportPeriodKind, identity: string, start: string, end: string, softCloseDate: string, softCloseHour: number): ReportPeriod { +function period( + kind: ReportPeriodKind, + identity: string, + start: string, + end: string, + softCloseDate: string, + softCloseHour: number, +): ReportPeriod { return { id: `${kind}:${identity}:${TIME_ZONE}`, kind, @@ -124,10 +131,15 @@ export function annualReportPeriod(year: string): 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); + 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 732ec876d1..2a4115e61e 100644 --- a/pm-stack/aggregator/src/report-records.ts +++ b/pm-stack/aggregator/src/report-records.ts @@ -50,12 +50,19 @@ 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"]); +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: 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 (!(REPORT_UPDATE_OPERATIONS as readonly string[]).includes(operation)) + throw new Error(`unknown report operation: ${operation}`); if (Date.parse(at) < Date.parse(period.softCloseAt)) return; if (!ALLOWED_AFTER_SOFT_CLOSE.has(operation)) { throw new Error(`report operation ${operation} is not allowed after soft close ${period.softCloseAt}`); @@ -103,15 +110,29 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat const identity = match?.[2]; let canonicalPeriod: ReportPeriod | null = null; if (kind && identity) { - try { canonicalPeriod = reportPeriod(kind, identity); } catch { /* common validation error below */ } + 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) { + 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 C7 reportPeriod value"); } - if (Date.parse(input.asOf) < Date.parse(input.period.periodStart) || Date.parse(input.asOf) >= Date.parse(input.period.periodEnd)) { + 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"); } - if (!Array.isArray(input.sources) || !Array.isArray(input.blocks)) throw new Error("sources and blocks must be arrays"); + if (!Array.isArray(input.sources) || !Array.isArray(input.blocks)) + throw new Error("sources and blocks must be arrays"); for (const source of input.sources) { if (!source.id.trim() || !source.uri.trim()) throw new Error("each source requires id and uri"); requireIsoDate(source.observedAt, "source observedAt"); @@ -122,7 +143,12 @@ 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)) { + 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)) { @@ -131,17 +157,28 @@ export function makeReportRecord(input: ReportRecordInput, generatedAt = new Dat 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()))) { + 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`); } } for (const block of input.bubblingCandidates ?? []) { if (!block.id.trim() || !block.text.trim()) throw new Error("each bubbling candidate requires an id and text"); requireIsoDate(block.relatedAt, "bubbling candidate 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)) { + 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(`bubbling candidate ${block.id} has invalid importance levels`); } - if (block.links && (!Array.isArray(block.links) || block.links.some((link) => typeof link !== "string" || !link.trim()))) { + if ( + block.links && + (!Array.isArray(block.links) || block.links.some((link) => typeof link !== "string" || !link.trim())) + ) { throw new Error(`bubbling candidate ${block.id} has invalid links`); } } @@ -160,9 +197,27 @@ function parseEvent(line: string): ReportRecordEvent | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const event = value as Record; if (typeof event.eventId !== "string" || typeof event.ts !== "string") return null; - if (event.type === "report.generated" && event.record && typeof event.record === "object" && !Array.isArray(event.record)) return value as ReportRecordEvent; - if (event.type === "report.snapshot" && event.snapshot && typeof event.snapshot === "object" && !Array.isArray(event.snapshot)) return value as ReportRecordEvent; - if (event.type === "report.snapshot-correction" && event.correction && typeof event.correction === "object" && !Array.isArray(event.correction)) return value as ReportRecordEvent; + if ( + event.type === "report.generated" && + event.record && + typeof event.record === "object" && + !Array.isArray(event.record) + ) + return value as ReportRecordEvent; + if ( + event.type === "report.snapshot" && + event.snapshot && + typeof event.snapshot === "object" && + !Array.isArray(event.snapshot) + ) + return value as ReportRecordEvent; + if ( + event.type === "report.snapshot-correction" && + event.correction && + typeof event.correction === "object" && + !Array.isArray(event.correction) + ) + return value as ReportRecordEvent; return null; } catch { return null; // Ignore a malformed/torn final line, matching decision-events.ts. @@ -210,7 +265,8 @@ async function readLocationEvents(location: ReportRecordLocation): Promise { - if (!store.startsWith(REPORT_DOCUMENT_PREFIX)) throw new Error("permanent report store returned a key outside its namespace"); + if (!store.startsWith(REPORT_DOCUMENT_PREFIX)) + throw new Error("permanent report store returned a key outside its namespace"); return parseDocumentEvent(document); }); // The table's stable key ordering is arbitrary; projections need event-time order. @@ -223,10 +279,23 @@ function sameReportEvent(left: ReportRecordEvent, right: ReportRecordEvent): boo return !!left.record && !!right.record && sameRecordContent(left.record, right.record); } if (left.type === "report.snapshot" && right.type === "report.snapshot") { - return !!left.snapshot && !!right.snapshot && left.snapshot.id === right.snapshot.id && left.snapshot.reportRecordId === right.snapshot.reportRecordId && sameRecordContent(left.snapshot.record, right.snapshot.record); + return ( + !!left.snapshot && + !!right.snapshot && + left.snapshot.id === right.snapshot.id && + left.snapshot.reportRecordId === right.snapshot.reportRecordId && + sameRecordContent(left.snapshot.record, right.snapshot.record) + ); } if (left.type === "report.snapshot-correction" && right.type === "report.snapshot-correction") { - return !!left.correction && !!right.correction && left.correction.id === right.correction.id && left.correction.snapshotId === right.correction.snapshotId && left.correction.originalRecordId === right.correction.originalRecordId && sameRecordContent(left.correction.record, right.correction.record); + return ( + !!left.correction && + !!right.correction && + left.correction.id === right.correction.id && + left.correction.snapshotId === right.correction.snapshotId && + left.correction.originalRecordId === right.correction.originalRecordId && + sameRecordContent(left.correction.record, right.correction.record) + ); } return false; } @@ -238,10 +307,14 @@ async function claimRemoteRecord(location: AppendOnlyDocumentRemote, record: Rep if (!stored || !isObject(stored.document) || typeof stored.document.id !== "string") { throw new Error(`permanent report identity claim disappeared or is malformed: ${record.id}`); } - if (!sameRecordContent(stored.document as unknown as ReportRecord, record)) throw new ReportRecordConflictError(record.id); + if (!sameRecordContent(stored.document as unknown as ReportRecord, record)) + throw new ReportRecordConflictError(record.id); } -async function appendDocumentEvent(location: AppendOnlyDocumentRemote, event: ReportRecordEvent): Promise<{ inserted: boolean; event: ReportRecordEvent }> { +async function appendDocumentEvent( + location: AppendOnlyDocumentRemote, + event: ReportRecordEvent, +): Promise<{ inserted: boolean; event: ReportRecordEvent }> { const key = reportDocumentKey(event); if (await location.insertIfAbsent(key, 1, event)) return { inserted: true, event }; const stored = await location.load(key); @@ -285,7 +358,10 @@ export interface AppendReportRecordResult { * Append once by stable record ID. A content-equivalent rerun is a no-op; the * same id with changed content is a conflict and is never silently replaced. */ -export async function appendReportRecord(location: ReportRecordLocation, record: ReportRecord): Promise { +export async function appendReportRecord( + location: ReportRecordLocation, + record: ReportRecord, +): Promise { assertCanonicalRecord(record); const event: ReportRecordEvent = { eventId: record.id, @@ -297,7 +373,8 @@ export async function appendReportRecord(location: ReportRecordLocation, record: assertRecordIdContent(await readLocationEvents(location), record); await claimRemoteRecord(location, record); const result = await appendDocumentEvent(location, event); - if (result.event.type !== "report.generated" || !result.event.record) throw new Error("permanent report record has an invalid event type"); + if (result.event.type !== "report.generated" || !result.event.record) + throw new Error("permanent report record has an invalid event type"); return { inserted: result.inserted, record: result.event.record }; } return serializeAppend(location, async () => { @@ -355,7 +432,11 @@ export interface AppendReportSnapshotCorrectionResult { /** Freeze a dated view in the same append-only PM-stack log. Existing snapshot * IDs are immutable: a repeated identical write is idempotent, changed content * is a conflict that must become a separately linked correction record. */ -export async function appendReportSnapshot(location: ReportRecordLocation, record: ReportRecord, snapshotAt: string): Promise { +export async function appendReportSnapshot( + location: ReportRecordLocation, + record: ReportRecord, + snapshotAt: string, +): Promise { assertCanonicalRecord(record); requireIsoDate(snapshotAt, "snapshotAt"); const snapshot: ReportSnapshot = { @@ -375,13 +456,16 @@ export async function appendReportSnapshot(location: ReportRecordLocation, recor assertRecordIdContent(events, record); await claimRemoteRecord(location, record); const result = await appendDocumentEvent(location, event); - if (result.event.type !== "report.snapshot" || !result.event.snapshot) throw new Error("permanent snapshot has an invalid event type"); + if (result.event.type !== "report.snapshot" || !result.event.snapshot) + throw new Error("permanent snapshot has an invalid event type"); return { inserted: result.inserted, snapshot: result.event.snapshot }; } return serializeAppend(location, async () => { const events = await readEvents(location); assertRecordIdContent(events, record); - const existing = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshot.id)?.snapshot; + const existing = events.find( + (event) => event.type === "report.snapshot" && event.snapshot?.id === snapshot.id, + )?.snapshot; if (existing) { if (existing.reportRecordId !== snapshot.reportRecordId || !sameRecordContent(existing.record, snapshot.record)) { throw new ReportRecordConflictError(snapshot.id); @@ -396,11 +480,21 @@ export async function appendReportSnapshot(location: ReportRecordLocation, recor } export async function readReportSnapshots(location: ReportRecordLocation): Promise { - return (await readLocationEvents(location)).filter((event): event is ReportRecordEvent & { snapshot: ReportSnapshot } => event.type === "report.snapshot" && !!event.snapshot).map((event) => event.snapshot); + return (await readLocationEvents(location)) + .filter( + (event): event is ReportRecordEvent & { snapshot: ReportSnapshot } => + event.type === "report.snapshot" && !!event.snapshot, + ) + .map((event) => event.snapshot); } /** Append a correction as a new record linked to an immutable snapshot. */ -export async function appendReportSnapshotCorrection(location: ReportRecordLocation, snapshotId: string, record: ReportRecord, correctedAt: string): Promise { +export async function appendReportSnapshotCorrection( + location: ReportRecordLocation, + snapshotId: string, + record: ReportRecord, + correctedAt: string, +): Promise { assertCanonicalRecord(record); requireIsoDate(correctedAt, "correctedAt"); const correction: ReportSnapshotCorrection = { @@ -412,7 +506,9 @@ export async function appendReportSnapshotCorrection(location: ReportRecordLocat }; if (typeof location !== "string") { const events = await readLocationEvents(location); - const snapshot = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId)?.snapshot; + const snapshot = events.find( + (event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId, + )?.snapshot; if (!snapshot) throw new Error(`snapshot does not exist: ${snapshotId}`); if (snapshot.record.period.id !== record.period.id) throw new Error("correction period must match the snapshot"); correction.originalRecordId = snapshot.reportRecordId; @@ -431,14 +527,22 @@ export async function appendReportSnapshotCorrection(location: ReportRecordLocat } return serializeAppend(location, async () => { const events = await readEvents(location); - const snapshot = events.find((event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId)?.snapshot; + const snapshot = events.find( + (event) => event.type === "report.snapshot" && event.snapshot?.id === snapshotId, + )?.snapshot; if (!snapshot) throw new Error(`snapshot does not exist: ${snapshotId}`); if (snapshot.record.period.id !== record.period.id) throw new Error("correction period must match the snapshot"); correction.originalRecordId = snapshot.reportRecordId; assertRecordIdContent(events, record); - const existing = events.find((event) => event.type === "report.snapshot-correction" && event.correction?.id === correction.id)?.correction; + const existing = events.find( + (event) => event.type === "report.snapshot-correction" && event.correction?.id === correction.id, + )?.correction; if (existing) { - if (existing.snapshotId !== correction.snapshotId || existing.originalRecordId !== correction.originalRecordId || !sameRecordContent(existing.record, correction.record)) { + if ( + existing.snapshotId !== correction.snapshotId || + existing.originalRecordId !== correction.originalRecordId || + !sameRecordContent(existing.record, correction.record) + ) { throw new ReportRecordConflictError(correction.id); } return { inserted: false, correction: existing }; @@ -456,7 +560,9 @@ export async function appendReportSnapshotCorrection(location: ReportRecordLocat }); } -export async function readReportSnapshotCorrections(location: ReportRecordLocation): Promise { +export async function readReportSnapshotCorrections( + location: ReportRecordLocation, +): Promise { return (await readLocationEvents(location)) .filter( ( @@ -470,7 +576,12 @@ export async function readReportSnapshotCorrections(location: ReportRecordLocati function assertRecordIdContent(events: ReportRecordEvent[], candidate: ReportRecord): void { for (const event of events) { - const persisted = event.type === "report.generated" ? event.record : event.type === "report.snapshot" ? event.snapshot?.record : event.correction?.record; + const persisted = + event.type === "report.generated" + ? event.record + : event.type === "report.snapshot" + ? event.snapshot?.record + : event.correction?.record; if (persisted?.id === candidate.id && !sameRecordContent(persisted, candidate)) { throw new ReportRecordConflictError(candidate.id); } diff --git a/pm-stack/aggregator/test/report-composer-c7.test.ts b/pm-stack/aggregator/test/report-composer-c7.test.ts index 4a09e43fe0..5b7df02d24 100644 --- a/pm-stack/aggregator/test/report-composer-c7.test.ts +++ b/pm-stack/aggregator/test/report-composer-c7.test.ts @@ -2,9 +2,20 @@ 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 { annualReportPeriod, monthlyReportPeriod, quarterlyReportPeriod, weeklyReportPeriod, dailyReportPeriod } from "../src/report-periods.ts"; +import { + annualReportPeriod, + monthlyReportPeriod, + quarterlyReportPeriod, + 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 { + appendReportRecord, + makeReportRecord, + readCurrentReportRecords, + type ReportRecord, +} from "../src/report-records.ts"; import { parseArgs } from "../scripts/generate-report.ts"; const tempDirs: string[] = []; @@ -26,29 +37,36 @@ function dailyRecord( ) { 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); + 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", () => { @@ -59,19 +77,47 @@ describe("C7 report composition", () => { 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/); - expect(() => parseArgs(["--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-22T12:00:00.000Z"])).toThrow(/within the report 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/); + expect(() => + parseArgs(["--kind", "daily", "--period", "2026-11-21", "--as-of", "2026-11-22T12:00:00.000Z"]), + ).toThrow(/within the report period/); }); 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 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"); @@ -81,7 +127,10 @@ describe("C7 report composition", () => { 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-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"), @@ -105,14 +154,24 @@ describe("C7 report composition", () => { 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(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.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); + 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"); + 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, { @@ -148,7 +207,9 @@ describe("C7 report composition", () => { const friday = dailyRecord("2026-03-06", "Friday before the spring DST transition."); const saturday = dailyRecord("2026-03-07", "Saturday must not be reach-back context."); const sunday = dailyRecord("2026-03-08", "Sunday must not be reach-back context."); - const result = composeReport(weeklyReportPeriod("2026-03-09"), [friday, saturday, sunday], { asOf: "2026-03-10T12:00:00.000Z" }); + const result = composeReport(weeklyReportPeriod("2026-03-09"), [friday, saturday, sunday], { + asOf: "2026-03-10T12:00:00.000Z", + }); expect(result.blocks.some((block) => block.text.startsWith("[Prior-Friday reach-back] Friday before"))).toBe(true); expect(result.blocks.some((block) => block.text.includes("Saturday must not"))).toBe(false); expect(result.blocks.some((block) => block.text.includes("Sunday must not"))).toBe(false); @@ -157,32 +218,65 @@ describe("C7 report composition", () => { test("keeps source provenance separate from classified member links", () => { const period = dailyReportPeriod("2026-11-21"); const at = "2026-11-21T18:00:00.000Z"; - const source = makeReportRecord({ - period, - asOf: at, - templateVersion: "daily-source-v1", - sourceCursor: "member-and-evidence", - sources: [{ id: "evidence", uri: "doc:evidence", observedAt: at }], - blocks: [{ id: "done", text: "Implemented one issue.", relatedAt: at, links: ["issue:one"], classification: "implemented" }], - }, at); + const source = makeReportRecord( + { + period, + asOf: at, + templateVersion: "daily-source-v1", + sourceCursor: "member-and-evidence", + sources: [{ id: "evidence", uri: "doc:evidence", observedAt: at }], + blocks: [ + { + id: "done", + text: "Implemented one issue.", + relatedAt: at, + links: ["issue:one"], + classification: "implemented", + }, + ], + }, + at, + ); const report = composeReport(period, [source], { asOf: at }); expect(report.classifiedActivity.implemented).toEqual(["issue:one"]); expect(report.sources.map((item) => item.uri)).toEqual(["doc:evidence"]); }); test("carries explicit higher-grain candidates without showing them at excluded grains", () => { - const source = makeReportRecord({ - period: dailyReportPeriod("2026-01-05"), - asOf: "2026-01-05T18:00:00.000Z", - templateVersion: "daily-source-v1", - sourceCursor: "annual-only-candidate", - sources: [{ id: "event", uri: "event:annual", observedAt: "2026-01-05T18:00:00.000Z" }], - blocks: [{ id: "candidate", text: "This item is explicitly annual.", relatedAt: "2026-01-05T18:00:00.000Z", importance: ["daily", "weekly", "annual"] }], - }, "2026-01-05T18:01:00.000Z"); - const daily = makeReportRecord(composeReport(dailyReportPeriod("2026-01-05"), [source], { asOf: "2026-01-05T18:00:00.000Z" }), "2026-01-05T18:02:00.000Z"); - const weekly = makeReportRecord(composeReport(weeklyReportPeriod("2026-01-05"), [source, daily], { asOf: "2026-01-11T18:00:00.000Z" }), "2026-01-11T18:01:00.000Z"); - const monthly = makeReportRecord(composeReport(monthlyReportPeriod("2026-01"), [weekly], { asOf: "2026-01-31T18:00:00.000Z" }), "2026-01-31T18:01:00.000Z"); - const quarterly = makeReportRecord(composeReport(quarterlyReportPeriod("2026-Q1"), [monthly], { asOf: "2026-03-31T18:00:00.000Z" }), "2026-03-31T18:01:00.000Z"); + const source = makeReportRecord( + { + period: dailyReportPeriod("2026-01-05"), + asOf: "2026-01-05T18:00:00.000Z", + templateVersion: "daily-source-v1", + sourceCursor: "annual-only-candidate", + sources: [{ id: "event", uri: "event:annual", observedAt: "2026-01-05T18:00:00.000Z" }], + blocks: [ + { + id: "candidate", + text: "This item is explicitly annual.", + relatedAt: "2026-01-05T18:00:00.000Z", + importance: ["daily", "weekly", "annual"], + }, + ], + }, + "2026-01-05T18:01:00.000Z", + ); + const daily = makeReportRecord( + composeReport(dailyReportPeriod("2026-01-05"), [source], { asOf: "2026-01-05T18:00:00.000Z" }), + "2026-01-05T18:02:00.000Z", + ); + const weekly = makeReportRecord( + composeReport(weeklyReportPeriod("2026-01-05"), [source, daily], { asOf: "2026-01-11T18:00:00.000Z" }), + "2026-01-11T18:01:00.000Z", + ); + const monthly = makeReportRecord( + composeReport(monthlyReportPeriod("2026-01"), [weekly], { asOf: "2026-01-31T18:00:00.000Z" }), + "2026-01-31T18:01:00.000Z", + ); + const quarterly = makeReportRecord( + composeReport(quarterlyReportPeriod("2026-Q1"), [monthly], { asOf: "2026-03-31T18:00:00.000Z" }), + "2026-03-31T18:01:00.000Z", + ); const annual = composeReport(annualReportPeriod("2026"), [quarterly], { asOf: "2026-12-31T18:00:00.000Z" }); expect(weekly.blocks.some((block) => block.text === "This item is explicitly annual.")).toBe(true); @@ -194,7 +288,9 @@ describe("C7 report composition", () => { test("excludes future records and activity from an earlier as-of view", () => { const monday = dailyRecord("2026-11-16", "Occurred before the requested point.", "implemented"); const saturday = dailyRecord("2026-11-21", "Occurred after the requested point.", "implemented"); - const result = composeReport(weeklyReportPeriod("2026-11-16"), [monday, saturday], { asOf: "2026-11-19T12:00:00.000Z" }); + const result = composeReport(weeklyReportPeriod("2026-11-16"), [monday, saturday], { + asOf: "2026-11-19T12:00:00.000Z", + }); expect(result.blocks.some((block) => block.text.includes("Occurred before"))).toBe(true); expect(result.blocks.some((block) => block.text.includes("Occurred after"))).toBe(false); expect(result.classifiedActivity.implemented).toEqual(["gh:developing-today/code/issues/2026-11-16"]); @@ -204,7 +300,10 @@ describe("C7 report composition", () => { const start = dailyRecord("2026-10-27", "October activity in a cross-month week.", "implemented"); const november = dailyRecord("2026-11-01", "November activity in a cross-month week.", "implemented"); const weekPeriod = weeklyReportPeriod("2026-10-26"); - const weekly = makeReportRecord(composeReport(weekPeriod, [start, november], { asOf: "2026-11-01T18:00:00.000Z" }), "2026-11-01T18:01:00.000Z"); + const weekly = makeReportRecord( + composeReport(weekPeriod, [start, november], { asOf: "2026-11-01T18:00:00.000Z" }), + "2026-11-01T18:01:00.000Z", + ); const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekly], { asOf: "2026-11-30T18:00:00.000Z" }); expect(monthly.blocks.some((block) => block.text.includes("October activity"))).toBe(false); expect(monthly.blocks.some((block) => block.text.includes("November activity"))).toBe(true); @@ -214,10 +313,18 @@ describe("C7 report composition", () => { test("preserves source identity across Friday reach-back and does not bubble the context copy", () => { const friday = dailyRecord("2026-11-06", "Friday living-item update.", "implemented"); const weekOnePeriod = weeklyReportPeriod("2026-11-02"); - const weekOne = makeReportRecord(composeReport(weekOnePeriod, [friday], { asOf: "2026-11-08T18:00:00.000Z" }), "2026-11-08T19:00:00.000Z"); + const weekOne = makeReportRecord( + composeReport(weekOnePeriod, [friday], { asOf: "2026-11-08T18:00:00.000Z" }), + "2026-11-08T19:00:00.000Z", + ); const weekTwoPeriod = weeklyReportPeriod("2026-11-09"); - const weekTwo = makeReportRecord(composeReport(weekTwoPeriod, [friday], { asOf: "2026-11-10T18:00:00.000Z" }), "2026-11-10T19:00:00.000Z"); - const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekOne, weekTwo], { asOf: "2026-11-30T18:00:00.000Z" }); + const weekTwo = makeReportRecord( + composeReport(weekTwoPeriod, [friday], { asOf: "2026-11-10T18:00:00.000Z" }), + "2026-11-10T19:00:00.000Z", + ); + const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekOne, weekTwo], { + asOf: "2026-11-30T18:00:00.000Z", + }); expect(weekTwo.bubblingCandidates?.some((block) => block.text.includes("Friday living-item update."))).toBe(false); expect(monthly.blocks.filter((block) => block.text.includes("Friday living-item update."))).toHaveLength(1); @@ -226,9 +333,12 @@ describe("C7 report composition", () => { test("regenerates activity summaries at the target grain instead of carrying weekly summaries upward", () => { const october = dailyRecord("2026-10-27", "October implementation.", "implemented"); const november = dailyRecord("2026-11-01", "November implementation.", "implemented"); - const weekly = makeReportRecord(composeReport(weeklyReportPeriod("2026-10-26"), [october, november], { - asOf: "2026-11-01T18:00:00.000Z", - }), "2026-11-01T19:00:00.000Z"); + const weekly = makeReportRecord( + composeReport(weeklyReportPeriod("2026-10-26"), [october, november], { + asOf: "2026-11-01T18:00:00.000Z", + }), + "2026-11-01T19:00:00.000Z", + ); const monthly = composeReport(monthlyReportPeriod("2026-11"), [weekly], { asOf: "2026-11-30T18:00:00.000Z" }); const summaries = monthly.blocks.filter((block) => block.id === "activity:implemented"); @@ -242,22 +352,38 @@ describe("C7 report composition", () => { const mondayAt = "2026-11-16T18:00:00.000Z"; const tuesdayAt = "2026-11-17T18:00:00.000Z"; const member = "gh:developing-today/code/issues/12345"; - const monday = makeReportRecord({ - period: dailyReportPeriod("2026-11-16"), - asOf: mondayAt, - templateVersion: "daily-source-v1", - sourceCursor: "monday-progress", - sources: [{ id: "monday-source", uri: "issue:12345", observedAt: mondayAt }], - blocks: [{ id: "started", text: "Started work.", relatedAt: mondayAt, links: [member], classification: "in-progress" }], - }, mondayAt); - const tuesday = makeReportRecord({ - period: dailyReportPeriod("2026-11-17"), - asOf: tuesdayAt, - templateVersion: "daily-source-v1", - sourceCursor: "tuesday-implemented", - sources: [{ id: "tuesday-source", uri: "issue:12345", observedAt: tuesdayAt }], - blocks: [{ id: "finished", text: "Finished work.", relatedAt: tuesdayAt, links: [member], classification: "implemented" }], - }, tuesdayAt); + const monday = makeReportRecord( + { + period: dailyReportPeriod("2026-11-16"), + asOf: mondayAt, + templateVersion: "daily-source-v1", + sourceCursor: "monday-progress", + sources: [{ id: "monday-source", uri: "issue:12345", observedAt: mondayAt }], + blocks: [ + { id: "started", text: "Started work.", relatedAt: mondayAt, links: [member], classification: "in-progress" }, + ], + }, + mondayAt, + ); + const tuesday = makeReportRecord( + { + period: dailyReportPeriod("2026-11-17"), + asOf: tuesdayAt, + templateVersion: "daily-source-v1", + sourceCursor: "tuesday-implemented", + sources: [{ id: "tuesday-source", uri: "issue:12345", observedAt: tuesdayAt }], + blocks: [ + { + id: "finished", + text: "Finished work.", + relatedAt: tuesdayAt, + links: [member], + classification: "implemented", + }, + ], + }, + tuesdayAt, + ); const period = weeklyReportPeriod("2026-11-16"); const mondayView = composeReport(period, [monday, tuesday], { asOf: "2026-11-16T23:00:00.000Z" }); const tuesdayView = composeReport(period, [monday, tuesday], { asOf: "2026-11-17T23:00:00.000Z" }); diff --git a/pm-stack/aggregator/test/report-periods-c7.test.ts b/pm-stack/aggregator/test/report-periods-c7.test.ts index 48a0fcace6..bab9460aaa 100644 --- a/pm-stack/aggregator/test/report-periods-c7.test.ts +++ b/pm-stack/aggregator/test/report-periods-c7.test.ts @@ -1,5 +1,11 @@ import { describe, expect, test } from "bun:test"; -import { annualReportPeriod, dailyReportPeriod, monthlyReportPeriod, quarterlyReportPeriod, weeklyReportPeriod } 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", () => { @@ -39,9 +45,8 @@ describe("C7 daily report periods", () => { minute: "2-digit", hourCycle: "h23", }); - const parts = (instant: string) => Object.fromEntries( - chicago.formatToParts(new Date(instant)).map(({ type, value }) => [type, value]), - ); + const parts = (instant: string) => + Object.fromEntries(chicago.formatToParts(new Date(instant)).map(({ type, value }) => [type, value])); const minDay = Date.UTC(1900, 0, 1); const dayCount = (Date.UTC(2100, 0, 1) - minDay) / 86_400_000; let state = 0x7c7c2026; @@ -52,10 +57,28 @@ describe("C7 daily report periods", () => { const period = dailyReportPeriod(date); const next = dailyReportPeriod(nextDate); - expect(parts(period.periodStart)).toMatchObject({ year: date.slice(0, 4), month: date.slice(5, 7), day: date.slice(8, 10), hour: "00", minute: "00" }); - expect(parts(period.periodEnd)).toMatchObject({ year: nextDate.slice(0, 4), month: nextDate.slice(5, 7), day: nextDate.slice(8, 10), hour: "00", minute: "00" }); + expect(parts(period.periodStart)).toMatchObject({ + year: date.slice(0, 4), + month: date.slice(5, 7), + day: date.slice(8, 10), + hour: "00", + minute: "00", + }); + expect(parts(period.periodEnd)).toMatchObject({ + year: nextDate.slice(0, 4), + month: nextDate.slice(5, 7), + day: nextDate.slice(8, 10), + hour: "00", + minute: "00", + }); expect(period.periodEnd).toBe(next.periodStart); - expect(parts(period.softCloseAt)).toMatchObject({ year: nextDate.slice(0, 4), month: nextDate.slice(5, 7), day: nextDate.slice(8, 10), hour: "08", minute: "00" }); + expect(parts(period.softCloseAt)).toMatchObject({ + year: nextDate.slice(0, 4), + month: nextDate.slice(5, 7), + day: nextDate.slice(8, 10), + hour: "08", + minute: "00", + }); } });