Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pm-stack/SHARED-SCHEMA-MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ backend, and the local JSON is then only a rebuildable cache):
| `activity-ingestion.json` | `public.agg_activity_ingestion`, `public.agg_activity_gaps` | `20261116_0001_aggregator_remote_stores` |
| `snapshots/usage-YYYY-MM.jsonl` | `public.agg_usage_snapshots` | `20261116_0001_aggregator_remote_stores` |
| `aa-last-good.json` | `public.agg_store_documents` (key `aa-last-good`) | `20261116_0001_aggregator_remote_stores` |
| C7 report events | `public.agg_store_documents` (keys `c7-report:v1:*`) | `20261116_0001_aggregator_remote_stores` |

The sibling stores (`freshness.json`, `notifications.jsonl`,
`needs-drew.json`, `decisions.json`, `decision-events*.jsonl`,
Expand Down
61 changes: 61 additions & 0 deletions pm-stack/aggregator/report-records-c7.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# C7 report-record storage seam

`src/report-records.ts` is the canonical record interface for C7 callers. It
stores versioned report-generation and snapshot events in one append-only
PM-stack JSONL log. The default is
`~/.local/state/pm-aggregator/report-records.jsonl`; set
`PM_AGG_REPORT_RECORDS_FILE` to select another persistent location. This
follows the aggregator's existing append-only event-log pattern rather than
adding a database or writing into the disposable projector.

## Caller interface

- `makeReportRecord(input, generatedAt?)` validates timestamps, source
attribution, stable block IDs and the Chicago period, then derives the
stable record ID from `(period.id, templateVersion, sourceCursor)`.
- `appendReportRecord(file, record)` appends a generated event. A rerun with
the same ID and content returns the original record without another write;
changed content at the same ID throws `ReportRecordConflictError`.
- `readReportRecords(file)` reads retained cursor versions;
`readCurrentReportRecords(file)` projects the latest cursor per
`(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
without mutating the snapshot; correction records must match the snapshot
period. `readReportSnapshots(file)` reads immutable snapshots, and
`readReportSnapshotCorrections(file)` reads their correction history.
- `assertReportUpdateAllowed(period, operation, at)` enforces the daily
08:00 CT soft-close and its quote/append/banner/event-log/feedback allowlist.
`reportBlockConflict(stored, rendered)` treats whitespace-only differences
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.

## Storage contract and current scope

The caller-facing append/read functions accept either a JSONL path or the
append-only document capability returned by `createTursoDocumentRemote`.
The file backend is local to the PM aggregator state path; writes are
serialized within one process and do not claim cross-process locking or remote
replication. It remains useful for development and rollback.

The durable adapter uses the existing `public.agg_store_documents` table from
#6815; it creates no table or separate report database. Each generated record,
snapshot, and correction is stored as one immutable document under
`c7-report:v1:<event-type>:<sha256(event-id)>`. A shared atomic content claim
under `c7-report-record:v1:<sha256(record-id)>` prevents conflicting payloads
for the same record ID across concurrent event types. `insertIfAbsent` provides
the atomic idempotency boundary: a duplicate key reads back and compares the
canonical content, returning the original event for an identical rerun and
raising a conflict for changed content. Prefix reads return the event set; projections sort by the canonical event
timestamp and stable event ID. The generic overwrite API is not used for C7
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.
7 changes: 7 additions & 0 deletions pm-stack/aggregator/src/aa-last-good.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ export interface DocumentRemote {
save(store: string, version: number, document: unknown): Promise<void>;
}

/** Append-only capabilities over the same durable document table. */
export interface AppendOnlyDocumentRemote {
load(store: string): Promise<{ version: number; document: unknown } | null>;
insertIfAbsent(store: string, version: number, document: unknown): Promise<boolean>;
listPrefix(prefix: string): Promise<Array<{ store: string; version: number; document: unknown }>>;
}

export class AaLastGoodStore {
constructor(
private readonly file: string,
Expand Down
25 changes: 22 additions & 3 deletions pm-stack/aggregator/src/remote-stores.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// copy would recreate exactly the laptop-only state #6815 removes.
import { ACTION_STATES, type ActionsRemote, type DashAction } from "./actions.ts";
import type { ActivityRemote, ActivitySourceStatus, GapRecord, IngestionFile, SourceCheckpoint } from "./activity.ts";
import type { DocumentRemote } from "./aa-last-good.ts";
import type { AppendOnlyDocumentRemote, DocumentRemote } from "./aa-last-good.ts";
import type { SnapshotsRemote } from "./snapshots.ts";
import type { SnapshotRecord } from "./model.ts";
import { snapshotKey } from "./snapshots.ts";
Expand Down Expand Up @@ -315,13 +315,13 @@ export function createTursoSnapshotsRemote(getClient: GetClient = getTursoStoreC
}

// ---------------------------------------------------------------------
// aa-last-good.json -> public.agg_store_documents
// namespaced PM documents -> public.agg_store_documents
// ---------------------------------------------------------------------

export function createTursoDocumentRemote(
getClient: GetClient = getTursoStoreClient,
writer: string = storeWriterIdentity(),
): DocumentRemote {
): DocumentRemote & AppendOnlyDocumentRemote {
return {
async load(store: string): Promise<{ version: number; document: unknown } | null> {
const db = await requireClient(getClient);
Expand All @@ -342,6 +342,25 @@ export function createTursoDocumentRemote(
`writer = excluded.writer, updated_at = now()`,
);
},

async insertIfAbsent(store: string, version: number, document: unknown): Promise<boolean> {
const db = await requireClient(getClient);
const rows = await db.query<Record<string, unknown>>(
`insert into public.agg_store_documents (store, version, document, writer, updated_at) ` +
`values (${sqlStr(store)}, ${version}, ${sqlJson(document)}, ${sqlStr(writer)}, now()) ` +
`on conflict (store) do nothing returning store`,
);
return rows.length > 0;
},

async listPrefix(prefix: string): Promise<Array<{ store: string; version: number; document: unknown }>> {
const db = await requireClient(getClient);
return db.query<{ store: string; version: number; document: unknown }>(
`select store, version, document from public.agg_store_documents ` +
`where substr(store, 1, length(${sqlStr(prefix)})) = ${sqlStr(prefix)} ` +
`order by store asc`,
);
},
};
}

Expand Down
67 changes: 67 additions & 0 deletions pm-stack/aggregator/src/report-periods.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
export interface DailyReportPeriod {
id: string;
kind: "daily";
timezone: "America/Chicago";
periodStart: string;
periodEnd: string;
softCloseAt: string;
}

const TIME_ZONE = "America/Chicago" as const;
const localFormatter = new Intl.DateTimeFormat("en-US", {
timeZone: TIME_ZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hourCycle: "h23",
});

function localWallTimeToUtc(date: string, hour: number): string {
const [year, month, day] = date.split("-").map(Number) as [number, number, number];
const wanted = Date.UTC(year, month - 1, day, hour);
let guess = wanted;

// Solve local wall time = UTC instant + zone offset. Iterating also
// handles offset changes at midnight without assuming a fixed UTC offset.
for (let i = 0; i < 4; i++) {
const parts = Object.fromEntries(localFormatter.formatToParts(new Date(guess)).map((p) => [p.type, p.value]));
const represented = Date.UTC(
Number(parts.year),
Number(parts.month) - 1,
Number(parts.day),
Number(parts.hour),
Number(parts.minute),
Number(parts.second),
);
const nextGuess = wanted - (represented - guess);
if (nextGuess === guess) break;
guess = nextGuess;
}
return new Date(guess).toISOString();
}

function nextCalendarDate(date: string): string {
const [year, month, day] = date.split("-").map(Number) as [number, number, number];
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 {
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 nextDate = nextCalendarDate(date);
return {
id: `daily:${date}:${TIME_ZONE}`,
kind: "daily",
timezone: TIME_ZONE,
periodStart: localWallTimeToUtc(date, 0),
periodEnd: localWallTimeToUtc(nextDate, 0),
softCloseAt: localWallTimeToUtc(nextDate, 8),
};
}
Loading