Repository navigation
feat(pm-stack): compose C7 period rollups #12486
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| #!/usr/bin/env bun | ||
| // CLI contract: generate-report.ts --kind <daily|weekly|monthly|quarterly|annual> --period <explicit-identity> --as-of <ISO-8601> [--store <jsonl-path>] | ||
| // 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 <daily|weekly|monthly|quarterly|annual> --period <explicit-identity> --as-of <ISO-8601> [--store <jsonl-path>]"; | ||
|
|
||
| interface Command { | ||
| kind: ReportPeriodKind; | ||
| identity: string; | ||
| asOf: string; | ||
| store?: string; | ||
| } | ||
|
|
||
| const kinds = new Set<ReportPeriodKind>(["daily", "weekly", "monthly", "quarterly", "annual"]); | ||
| const valueFlags = new Set(["--kind", "--period", "--as-of", "--store"]); | ||
|
|
||
| export function parseArgs(args: string[]): Command { | ||
| const values = new Map<string, string>(); | ||
| 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<void> { | ||
| 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; | ||
| }); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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<Record<ReportPeriodKind, readonly string[]>> = { | ||
| 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<string, ReportRecord[]>(); | ||
| 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)) | ||
|
Comment on lines
+68
to
+70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
After the first daily generation is persisted, Useful? React with 👍 / 👎.
Comment on lines
+68
to
+70
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Select daily source records before preferring composed children. After the first daily generation, A newer daily source record is also suppressed. Select non-composed records directly for daily generation. Keep composed-child preference for parent reports.
|
||
| .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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Restrict prior-Friday context to Friday records. For the week starting November 16, 2026, this interval also selects November 14 and November 15. Those Saturday and Sunday records receive the Match the prior Friday's daily identity or its single-day interval. This preserves Friday context across DST without including the weekend.
|
||
| .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 })); | ||
|
Comment on lines
+93
to
+95
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For monthly composition, an overlapping weekly record is selected wholesale, and all its eligible blocks are copied without checking whether they belong to the target month. For example, the week beginning 2026-10-26 overlaps November, so a November report generated later in November includes October 27 activity and counts it as November activity. This remains wrong even when every input predates Useful? React with 👍 / 👎. |
||
| } | ||
|
|
||
| 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)) | ||
|
Comment on lines
+116
to
+118
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When generating an earlier point-in-time report from a populated store, selection checks only period overlap and never compares record or block timestamps with Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
An explicit importance set can name a higher grain without every intermediate grain, but filtering permanently removes the block from the only records that higher-grain composition reads. For example, a block marked Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep blocks that a higher grain requests when the weekly filter excludes them. When a block's The required behavior is that a block reaches the composition of every grain named in its
|
||
| .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(), | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a source record contains multiple issues or other provenance sources, this union adds every source URI to every block regardless of that block's classification. The activity loop subsequently counts all those links as classified members. For example, a daily record with one implemented issue and one cancelled issue makes both issues appear in both categories; consuming a composed daily report amplifies this because its sources cover the entire day. Preserve the block's explicit member links for classification and carry report-level provenance separately. Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep attribution URIs out of classified member links. If an implemented block links one issue and its record cites a separate evidence document, this merge gives the block two links. The activity accumulator then reports two implemented members. Later rollups retain the incorrect membership. Keep
|
||
| 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(","); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Generating a weekly or higher-grain report again with unchanged inputs but a later valid Useful? React with 👍 / 👎. |
||
| 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); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Validate
--as-ofagainst the period before store I/O.For
--period 2026-11-21, the canonical timestamp2026-11-22T12:00:00.000Zpasses this parser. Generation then reads the selected file or Turso store beforecomposeReportrejects the timestamp.Keep the resolved period here and check its half-open bounds before returning. Invalid arguments must fail as usage errors before store access, as the command promises.