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
111 changes: 100 additions & 11 deletions pm-stack/aggregator/src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,29 +326,118 @@ export function pruneEvents<T extends StreamEvent>(events: readonly T[], now = n
export interface EventFilter {
kind?: string;
ref?: string;
refs?: readonly string[];
actor?: string;
project?: string;
epic?: string;
search?: string;
/** Metadata resolved from the live project pool; event records stay source-native. */
itemContext?: ReadonlyMap<string, { project?: string | null; epic?: string | null }>;
}

/** The read surface: newest first, exact-match filters on
* kind / ref / actor (case-insensitive, like the views matcher). */
/** The read surface: newest first, with stable ids breaking equal-time ties. */
export function filterEvents<T extends StreamEvent>(events: readonly T[], filter: EventFilter = {}): T[] {
const eq = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
// Newest first by PARSED time (#4489 Codex re-review): accepted
// timestamps may carry offsets or omit fractional seconds, where a
// string comparison misorders them; equal instants keep the later
// arrival first, matching append order.
const normalizeRef = (ref: string) => ref.replace(/^gh:/i, "").toLowerCase();
const refs = [filter.ref, ...(filter.refs ?? [])].filter((ref): ref is string => Boolean(ref));
const search = filter.search?.trim().toLowerCase();
// Newest first by parsed time. Audit ids break equal-time ties so a
// cursor remains stable when later records are appended; legacy
// StreamEvent callers without ids retain append-order tie handling.
return [...events]
.map((event, index) => ({ event, index }))
.sort((a, b) => Date.parse(b.event.at) - Date.parse(a.event.at) || b.index - a.index)
.sort((a, b) => {
const time = Date.parse(b.event.at) - Date.parse(a.event.at);
if (time) return time;
const aId = "id" in a.event && typeof a.event.id === "string" ? a.event.id : null;
const bId = "id" in b.event && typeof b.event.id === "string" ? b.event.id : null;
return aId !== null && bId !== null ? bId.localeCompare(aId) : b.index - a.index;
})
.map(({ event }) => event)
.filter(
(e) =>
(!filter.kind || eq(e.kind, filter.kind)) &&
(!filter.ref || eq(e.ref, filter.ref)) &&
(!filter.actor || eq(e.actor, filter.actor)),
(e) => {
const context = filter.itemContext?.get(normalizeRef(e.ref));
return (
(!filter.kind || eq(e.kind, filter.kind)) &&
(!refs.length || refs.some((ref) => normalizeRef(e.ref) === normalizeRef(ref))) &&
(!filter.actor || eq(e.actor, filter.actor)) &&
(!filter.project || Boolean(context?.project && eq(context.project, filter.project))) &&
(!filter.epic || Boolean(context?.epic && eq(context.epic, filter.epic))) &&
(!search || `${e.actor} ${e.kind} ${e.ref} ${e.summary}`.toLowerCase().includes(search))
);
},
);
}

export interface EventPageCursor {
at: string;
id: string;
snapshotAt: string;
}

export interface EventPage {
events: AuditEvent[];
nextCursor: string | null;
snapshotAt: string;
}

function compareEventOrder(a: Pick<AuditEvent, "at" | "id">, b: Pick<AuditEvent, "at" | "id">): number {
return Date.parse(b.at) - Date.parse(a.at) || b.id.localeCompare(a.id);
}

export function encodeEventCursor(cursor: EventPageCursor): string {
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
}

export function decodeEventCursor(value: string | null | undefined): EventPageCursor | null {
if (!value) return null;
try {
const parsed: unknown = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
if (
typeof parsed === "object" && parsed !== null &&
typeof (parsed as EventPageCursor).at === "string" &&
Number.isFinite(Date.parse((parsed as EventPageCursor).at)) &&
typeof (parsed as EventPageCursor).id === "string" &&
typeof (parsed as EventPageCursor).snapshotAt === "string" &&
Number.isFinite(Date.parse((parsed as EventPageCursor).snapshotAt))
) return parsed as EventPageCursor;
} catch {
// An invalid cursor starts a new first page; it never becomes a filter.
}
return null;
}

/** Stable descending keyset pagination over a fixed ingestion snapshot. */
export function pageEvents(
events: readonly AuditEvent[],
options: { cursor?: string | null; limit?: number } = {},
): EventPage {
const limit = Math.max(1, Math.min(100, Math.floor(options.limit ?? 50) || 50));
const cursor = decodeEventCursor(options.cursor);
// Compare ingestion timestamps as instants, never lexicographically:
// migrated v1 rows keep their original timestamp as `ingestedAt`,
// including UTC offsets and missing fractional seconds, and string
// order disagrees with instant order for those (Codex P2, PR #5266).
const snapshotAt = cursor?.snapshotAt ?? events.reduce(
(latest, event) => Date.parse(event.ingestedAt) > Date.parse(latest) ? event.ingestedAt : latest,
"1970-01-01T00:00:00.000Z",
);
Comment on lines +421 to +424

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare ingestion snapshot timestamps as instants

For stores migrated from v1, migrateV1Event() preserves the original event timestamp as ingestedAt, including supported ISO offsets and timestamps without fractional seconds. Comparing these strings lexicographically can select an incorrect snapshot cutoff: 2026-11-04T15:00:00+08:00 represents 07:00Z but sorts above native ingestion timestamps around 08:00Z. Consequently, a backfill ingested at 08:01Z after the first page can pass the snapshot cutoff and appear on a subsequent page, violating fixed-snapshot pagination. Compare parsed instants, or normalize ingestion timestamps before both selecting and applying the cutoff.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9728b71: pageEvents now compares ingestion timestamps as instants (Date.parse) both when selecting the snapshot maximum and when filtering events against the snapshot, so migrated v1 rows with UTC offsets or missing fractional seconds are ordered correctly. Regression test in test/events.test.ts ("pageEvents compares ingestion timestamps as instants, not strings"); full aggregator suite passes on the laptop (1521 pass, 0 fail).

const snapshotMs = Date.parse(snapshotAt);
const visible = events.filter((event) =>
Date.parse(event.ingestedAt) <= snapshotMs && (!cursor || compareEventOrder(event, cursor) > 0),
);
const page = visible.slice(0, limit);
const last = page.at(-1);
return {
events: page,
snapshotAt,
nextCursor:
visible.length > limit && last
? encodeEventCursor({ at: last.at, id: last.id, snapshotAt })
: null,
};
}

/**
* The fire-and-forget writer every emission point uses (#1739
* acceptance: writing an event never blocks the underlying action).
Expand Down
23 changes: 21 additions & 2 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import {
} from "./tier-items.ts";
import { commentKindCounts, githubCommentUrl, queuedComments, type CommentKindCounts } from "./comments.ts";
import { serviceHomeLinks, type ItemServiceLink } from "./service-links.ts";
import { activityCoverageHtml, gapsHtml, type ActivityCoverage, type GapRecord } from "./activity.ts";
import type { AuditEvent } from "./events.ts";
import { aaCaiPoints, aaPoints, summarizeAa } from "./aa.ts";
import {
applyInequalityFilters,
Expand Down Expand Up @@ -2092,6 +2094,8 @@ export interface ItemExtras {
epicRollup?: EpicRollup;
/** Project-pool briefs for linked refs (#1279). */
briefs?: Map<RefKey, ItemBrief>;
/** The shared audit stream, scoped to the item's canonical refs. */
activity?: { events: AuditEvent[]; globalHref: string; gaps: GapRecord[]; coverage?: readonly ActivityCoverage[] };
}

function roadmapAnnotationFormHtml(objectRef: string, identities: AuthorIdentity[]): string {
Expand All @@ -2113,6 +2117,18 @@ function epicRollupHtml(rollup: EpicRollup): string {
return `<p class="muted epic-rollup"><strong>Epic rollup</strong> — ${children} · Status mix: ${statusMix} · Blocked: ${rollup.blocked}</p>`;
}

export function eventTableHtml(events: readonly AuditEvent[]): string {
const rows = events.map((event) => {
const source = event.source.link
? `<a href="${esc(event.source.link)}" rel="noopener">${esc(event.source.identity)}</a>`
: esc(event.source.identity);
const delay = Date.parse(event.ingestedAt) - Date.parse(event.at);
const ingested = Number.isFinite(delay) && delay > 0 ? `<span class="muted">(+${Math.round(delay / 1000)}s ingest)</span>` : "";
return `<tr><td>${esc(event.at)} ${ingested}</td><td>${esc(event.actor)} <span class="muted">(${esc(event.attribution.confidence)})</span></td><td>${esc(event.kind)}</td><td><code>${esc(event.ref)}</code></td><td>${esc(event.summary)}</td><td>${source}</td></tr>`;
}).join("\n");
return `<div class="tblwrap"><table class="activity-events"><caption>Shared activity events</caption><thead><tr><th scope="col">When</th><th scope="col">Actor</th><th scope="col">Kind</th><th scope="col">Ref</th><th scope="col">Summary</th><th scope="col">Source</th></tr></thead><tbody>${rows || '<tr><td colspan="6" class="muted">No matching events; this does not establish complete coverage.</td></tr>'}</tbody></table></div>`;
}

export function renderItem(
title: string,
subject: string,
Expand Down Expand Up @@ -2160,6 +2176,9 @@ export function renderItem(
? `<p>Live services: ${extras.serviceLinks.map((s) => `<a href="${esc(s.url)}">${esc(s.label)} ↗</a>`).join(" · ")}</p>`
: "";
const epicRollup = extras?.epicRollup ? epicRollupHtml(extras.epicRollup) : "";
const activitySection = extras?.activity
? `<h2>Activity stream</h2><p><a href="${esc(extras.activity.globalHref)}">View these events in the global river</a></p><p class="muted"><strong>Freshness: unknown.</strong> The ingestion checkpoint records deliveries, not successful source polls. An empty event list does not establish complete coverage. Known gaps and documented source coverage are shown below.</p>${eventTableHtml(extras.activity.events)}<h3>Known activity gaps</h3><p class="muted">Gap records are source-scoped and do not currently identify affected item refs, so this is the global known-gap list.</p><div class="tblwrap">${gapsHtml(extras.activity.gaps)}</div><h3>Activity source coverage</h3><div class="tblwrap">${activityCoverageHtml(extras.activity.coverage)}</div>`
: "";
return layout(
title,
`<h1>${esc(title)}</h1><p class="muted">subject: <code>${esc(subject)}</code></p>${epicRollup}${svcLinks}${stripHtml(items, links)}
Expand All @@ -2172,8 +2191,8 @@ ${
: ""
}
<h2>Linked issues / PRs</h2><div class="tblwrap"><table><caption>Linked issues and pull requests</caption><tr><th scope="col">Ref</th><th scope="col">Title</th><th scope="col">Labels</th><th scope="col">Updated</th></tr>${refRows || '<tr><td colspan="4" class="muted">none resolved</td></tr>'}</table></div>
<h2>Activity stream</h2><div class="tblwrap"><table><caption>Activity stream</caption><tr><th scope="col">When</th><th scope="col">Kind</th><th scope="col">Author</th><th scope="col">Body</th></tr>${commentRows || '<tr><td colspan="4" class="muted">no comments</td></tr>'}</table></div>
${sessionSection}${statusSection}${roadmapAnnotationSection}${dashSection}`,
<h2>Activity stream comments</h2><div class="tblwrap"><table><caption>Comments</caption><tr><th scope="col">When</th><th scope="col">Kind</th><th scope="col">Author</th><th scope="col">Body</th></tr>${commentRows || '<tr><td colspan="4" class="muted">no comments</td></tr>'}</table></div>
${activitySection}${sessionSection}${statusSection}${roadmapAnnotationSection}${dashSection}`,
provenance,
"/board",
extras
Expand Down
Loading
Loading