diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index 8f3b3a9441..f807427277 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -585,10 +585,11 @@ of silently showing canned data. `bun run dev` sets the switch for you. | `GRIST_API_KEY` | — | Grist API key (Bitwarden `grist.api-key`) | | `GRIST_ROADMAP_DOC` | `czYHYKgG9SHcm9CPwiKEq1` | The `Program roadmap` document id (Phase 2 seed) | | `PM_PROJECTOR_URL` | `http://127.0.0.1:7801` | Projector + link registry base URL (`/items`, `/comments`, `/links`); `off` disables it | +| `PM_PROJECTOR_API_TOKEN` | — | Projector bearer token; the GitHub hot-list consumer uses it to acknowledge completed checkpoints (copy the same secret configured on the projector into the aggregator environment) | | `PM_AGG_COMMENTS_FILE` | `./comments.json` | Dashboard comment store (#906) — aggregator-local; created on first comment | | `PM_AGG_ACTIONS_FILE` | `./actions.json` | Dashboard action store (#1152/#1154/#1156) — aggregator-local; created on first action | | `PM_AGG_REGISTRY_FILE` | `./registry.json` | Durable session identity registry (#906) — merged records persist across restarts | -| `PM_AGG_ACTIVITY_FILE` | `~/.local/state/pm-aggregator/activity-ingestion.json` | Activity-ingestion store (#3321) — per-source checkpoints + dedupe seen sets + gap records for the watchdog/Kaneo stream writers | +| `PM_AGG_ACTIVITY_FILE` | `~/.local/state/pm-aggregator/activity-ingestion.json` | Activity-ingestion store (#3321) — per-source checkpoints, dedupe seen sets, source status, and gap records for watchdog/Kaneo/GitHub writers | Secrets are read from the environment only and are never committed or printed. Names here reference Bitwarden entries (`kaneo.*`, `grist.*`). @@ -609,19 +610,31 @@ are completion history and are not counted as WIP. ### Activity ingestion into the event stream (#3321) -Watchdog breach episodes and Kaneo board changes are ingested into the -#1739 event stream by `src/activity.ts`, with persisted per-source -checkpoints: replaying a duplicate delivery is a no-op, and a restart -resumes from the checkpoint instead of re-emitting. Known source -outages are recorded as gap records (source + time range) and rendered -on `/events` as holes in the history — never as complete coverage; a -backfill/recovery pass flips a gap's status. Per-source coverage -(supported / unsupported / historical ranges) is documented in -`ACTIVITY_SOURCE_COVERAGE` in `src/activity.ts`, rendered on `/events`, -and served at `/api/activity.json` together with the checkpoints and -gaps. GitHub activity is explicitly **unsupported** until the #2072 -webhook/hot-list ingestion lands — #3321's boundary forbids a -competing receiver. +Watchdog breach episodes, Kaneo board changes, and GitHub events from +the #2072/#5204 projector hot list are ingested into the #1739 event +stream by `src/activity.ts`. The GitHub consumer in +`src/github-hot-list.ts` pins each sweep to the projector's high-water +and acknowledges the remote consumer checkpoint only after every row in +that sweep is durably ingested. A duplicate replay is a no-op, and an +aggregator restart resumes from the projector's persisted checkpoint +with the local seen-id store as a second idempotency guard. Set +`PM_PROJECTOR_API_TOKEN` in the aggregator environment to the same +bearer token configured for the projector; `install.sh` copies only that +one variable from the projector's state `.env` and does not expose the +GitHub App credentials to the aggregator. Without the token the GitHub +source is reported as `unconfigured` and is not represented as complete. + +Known source outages and consumer lag are recorded as gap records +(source + time range) and rendered on `/events` as holes in the history; +recovery closes a gap as backfilled, while malformed/unrecoverable +checkpoint state is marked `unrecoverable`. `/api/activity.json` exposes +checkpoints, gaps, source status, and `completeHistory: false` for the +GitHub source: `current` means caught up to the hot-list high-water, not +complete GitHub history. Per-source coverage (supported / unsupported / +historical ranges) is documented in `ACTIVITY_SOURCE_COVERAGE` in +`src/activity.ts` and rendered on `/events`. GitHub coverage begins only +with rows retained in the hot list; upstream webhook deliveries the +projector never received and pre-hot-list history remain unsupported. ## Capability provenance matrix (#1200) diff --git a/pm-stack/aggregator/install.sh b/pm-stack/aggregator/install.sh index ff9d14ec42..a269102e26 100755 --- a/pm-stack/aggregator/install.sh +++ b/pm-stack/aggregator/install.sh @@ -27,6 +27,7 @@ if [ "$SRC" != "$EXPECTED_SRC" ]; then fi STATE_DIR="$HOME/.local/state/pm-aggregator" SOPS="$HOME/secrets/pm-stack.sops.yaml" +PROJECTOR_ENV="$HOME/.local/state/pm-projector/.env" # Resolve the unit against the checkout root via the logical parent of # $SRC: "$SRC/../systemd" would be resolved by the kernel through the # package dir itself, so a symlinked package dir (smoke fixture, legacy @@ -52,7 +53,7 @@ DEPLOY_COMMIT="$(git -C "$SRC" rev-parse HEAD 2>/dev/null || true)" tree_hash() { local root="$1" (cd "$root" && { - for f in package.json bun.lock tsconfig.json; do + for f in package.json bun.lock tsconfig.json install.sh; do [ -f "$f" ] && echo "$f" done find src test scripts opencode-tools systemd -type f 2>/dev/null @@ -73,6 +74,7 @@ deploy_inputs_hash() { printf 'TAILNET_IP=%s\n' "$TAILNET_IP" printf 'STATE_DIR=%s\n' "$STATE_DIR" if [ -f "$SOPS" ]; then sha256sum "$SOPS"; else echo "sops:absent"; fi + if [ -f "$PROJECTOR_ENV" ]; then sha256sum "$PROJECTOR_ENV"; else echo "projector-env:absent"; fi if [ -f "$UNIT_SRC" ]; then sha256sum "$UNIT_SRC"; else echo "unit:absent"; fi } | sha256sum | cut -d' ' -f1 } @@ -176,6 +178,12 @@ if [ "$CHANGED" -eq 1 ]; then echo "PM_AGG_COVERAGE_SNAPSHOT_FILE=${STATE_DIR}/coverage-snapshot.json" echo "PM_AGG_ROADMAP_ANNOTATIONS_FILE=${STATE_DIR}/roadmap-annotations.json" echo "PM_PROJECTOR_URL=http://127.0.0.1:7801" + # The hot-list consumer shares only the projector's checkpoint-ack + # credential, not its webhook secret or GitHub App private key. + if [ -f "$PROJECTOR_ENV" ]; then + projector_token_line="$(grep -m 1 '^PM_PROJECTOR_API_TOKEN=' "$PROJECTOR_ENV" || true)" + if [ -n "$projector_token_line" ]; then printf '%s\n' "$projector_token_line"; fi + fi for key in kaneo_admin_email:KANEO_ADMIN_EMAIL kaneo_admin_password:KANEO_ADMIN_PASSWORD grist_api_key:GRIST_API_KEY; do sops_key="${key%%:*}" env_name="${key##*:}" diff --git a/pm-stack/aggregator/src/activity.ts b/pm-stack/aggregator/src/activity.ts index 5b5f5f55c0..96992c1981 100644 --- a/pm-stack/aggregator/src/activity.ts +++ b/pm-stack/aggregator/src/activity.ts @@ -1,5 +1,5 @@ // Activity ingestion for the cross-stack stream (#3321): the -// watchdog-event and Kaneo-change writers that map external activity +// watchdog-event, Kaneo-change, and GitHub-hot-list writers that map external activity // into the #1739 StreamEvent log, with the ingestion discipline the // local fire-and-forget writers never needed: // @@ -30,11 +30,9 @@ // recovery/backfill pass flips the gap's status; the /events page // renders open gaps as holes, never as coverage. // -// The GitHub slice is deliberately NOT here: #3321's boundary says -// GitHub activity reuses the #2072 webhook/hot-list ingestion rather -// than a competing receiver, and #2072 has not landed. The coverage -// table below states that plainly (github: unsupported) instead of -// implying coverage that does not exist. +// GitHub activity is consumed from #2072's append-only hot list; this +// module does not create a competing webhook receiver. Coverage below +// describes exactly what that bounded source can and cannot represent. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { dirname } from "node:path"; import type { EventsStore } from "./events.ts"; @@ -50,7 +48,7 @@ export interface ActivityDelivery { sourceId: string; /** ISO timestamp of the change at the source. */ at: string; - /** StreamEvent kind ("watchdog-event" | "kaneo-change"). */ + /** StreamEvent kind ("watchdog-event" | "kaneo-change" | "github-event"). */ kind: string; /** StreamEvent ref (the item the change concerns). */ ref: string; @@ -96,14 +94,36 @@ export const ACTIVITY_SOURCE_COVERAGE: readonly ActivityCoverage[] = [ }, { source: "github", - status: "unsupported", - supported: "Nothing yet.", + status: "supported", + supported: + "Normalized issue, pull-request, comment/review, and push-commit rows present in the #2072/#5204 projector hot list are consumed into github-event records with the hot-list event id and source URL. The consumer checkpoint advances only after a complete fixed-high-water sweep is durably ingested.", unsupported: - "All GitHub activity. #3321's boundary forbids a competing receiver: GitHub events enter through the #2072 webhook/hot-list ingestion, which has not landed. When it does, its writer joins this module with the same checkpoint/dedupe discipline.", - historical: "None claimed. GitHub's own history stays in GitHub until #2072 lands.", + "GitHub activity not represented by the hot-list webhook mapping, raw webhook bodies, and webhook deliveries the projector never received. This consumer cannot independently detect or reconstruct missing upstream webhook deliveries; a receiver outage or hot-list API outage is surfaced as a source gap instead of complete history.", + historical: + "Only rows retained in the #5204 hot list, from that ledger's start. A new consumer begins at the persisted checkpoint (zero on first use) and can consume rows already in the ledger; no pre-ledger GitHub history is claimed.", }, ]; +export type ActivitySourceState = "unconfigured" | "current" | "lagging" | "outage" | "unrecoverable"; + +/** Durable operational status for a source consumer. Cursor distance is + * intentionally not named an event count: hot-list sequence numbers are + * monotonic but not necessarily dense. */ +export interface ActivitySourceStatus { + source: string; + state: ActivitySourceState; + consumer: string | null; + /** Last source seq processed locally, including an in-progress fixed sweep. */ + cursor: number | null; + /** Last cursor the projector has durably acknowledged. */ + checkpointCursor: number | null; + highWater: number | null; + lastAttemptAt: string | null; + lastSuccessAt: string | null; + updatedAt: string; + error?: string; +} + // Cap `t` at `max` UTF-16 code units, but never leave half of a surrogate // pair at the cut (#7725, mirroring the #7694/#7711 capUnits guard in // actions.ts): an astral character straddling the cap is dropped whole, so @@ -135,6 +155,80 @@ export function watchdogDeliveries(items: readonly TierItem[]): ActivityDelivery })); } +export interface GithubHotEvent { + seq: number; + event_id: string; + delivery_id: string | null; + repo: string; + event: string; + action: string | null; + ref: string | null; + actor: string | null; + source_url: string | null; + source_timestamp: string | null; + received_at: string; +} + +function validGithubTimestamp(value: string | null): string | null { + if (!value || !Number.isFinite(Date.parse(value))) return null; + return new Date(value).toISOString(); +} + +function githubSourceLink(event: GithubHotEvent): string { + if (event.source_url) { + try { + const url = new URL(event.source_url); + if ( + url.protocol === "https:" && + !url.username && + !url.password && + (url.hostname === "github.com" || url.hostname === "www.github.com") + ) { + return url.toString(); + } + } catch { + // Fall through to the canonical repository link. + } + } + const repo = event.repo.trim(); + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new Error("invalid_hot_event_repo"); + return `https://github.com/${repo}`; +} + +/** Map one normalized #5204 hot-list row into the #1739 activity contract. + * `event_id` is the source identity, so EventsStore persists the stable + * `activity:github:` id and retries remain dedupe-safe. */ +export function githubHotEventDelivery(event: GithubHotEvent): ActivityDelivery { + const sourceId = event.event_id.trim(); + const repo = event.repo.trim(); + const kind = event.event.trim(); + if (!sourceId) throw new Error("invalid_hot_event_id"); + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) throw new Error("invalid_hot_event_repo"); + if (!kind) throw new Error("invalid_hot_event_kind"); + const at = validGithubTimestamp(event.source_timestamp) ?? validGithubTimestamp(event.received_at); + if (!at) throw new Error("invalid_hot_event_timestamp"); + const sourceRef = event.ref?.trim() ?? ""; + // EventsStore rejects refs longer than 300 characters or containing + // whitespace. Keep the original source ref visible in the bounded + // summary, but use the repository as a valid contract ref so one odd + // upstream branch name cannot permanently stall this hot-list page. + const ref = sourceRef && sourceRef.length <= 300 && !/\s/.test(sourceRef) ? sourceRef : repo; + const action = event.action?.trim(); + const actor = event.actor?.trim(); + const description = [event.event, action].filter(Boolean).join(" "); + const subject = sourceRef ? ` ref ${capUnits(sourceRef, 300)}` : ""; + const by = actor ? ` by ${actor}` : ""; + return { + source: "github", + sourceId, + at, + kind: "github-event", + ref, + summary: capUnits(`GitHub ${description} in ${repo}${subject}${by}`, 500), + link: githubSourceLink(event), + }; +} + /** Pins each watchdog breach episode to the `since` it was FIRST * observed with, until the episode clears (Codex P2, PR #5141). * watchdogTierItems is pure and, for absent/future-dated feeds and @@ -288,6 +382,7 @@ export interface IngestionFile { checkpoints: Record; seen: Record; gaps: GapRecord[]; + sourceStatus?: Record; } /** Per-source seen-id bound: dedupe memory is finite by design; an id @@ -325,8 +420,30 @@ function isCheckpoint(v: unknown): v is SourceCheckpoint { ); } +function isActivitySourceStatus(v: unknown): v is ActivitySourceStatus { + if (typeof v !== "object" || v === null) return false; + const s = v as Record; + const cursor = (n: unknown): boolean => n === null || (Number.isSafeInteger(n) && Number(n) >= 0); + return ( + typeof s.source === "string" && + (s.state === "unconfigured" || + s.state === "current" || + s.state === "lagging" || + s.state === "outage" || + s.state === "unrecoverable") && + (s.consumer === null || typeof s.consumer === "string") && + cursor(s.cursor) && + cursor(s.checkpointCursor) && + cursor(s.highWater) && + (s.lastAttemptAt === null || typeof s.lastAttemptAt === "string") && + (s.lastSuccessAt === null || typeof s.lastSuccessAt === "string") && + typeof s.updatedAt === "string" && + (s.error === undefined || typeof s.error === "string") + ); +} + export class IngestionStore { - private data: IngestionFile = { version: 1, checkpoints: {}, seen: {}, gaps: [] }; + private data: IngestionFile = { version: 1, checkpoints: {}, seen: {}, gaps: [], sourceStatus: {} }; private loadPromise: Promise | null = null; private ingestChain: Promise = Promise.resolve(); private writeChain: Promise = Promise.resolve(); @@ -359,6 +476,12 @@ export class IngestionStore { throw new Error("seen is not an object"); } if (!Array.isArray(f.gaps)) throw new Error("gaps is not an array"); + if ( + f.sourceStatus !== undefined && + (typeof f.sourceStatus !== "object" || f.sourceStatus === null || Array.isArray(f.sourceStatus)) + ) { + throw new Error("sourceStatus is not an object"); + } for (const cp of Object.values(f.checkpoints)) { if (!isCheckpoint(cp)) throw new Error("a checkpoint row is malformed"); } @@ -370,11 +493,15 @@ export class IngestionStore { for (const gap of f.gaps) { if (!isGapRecord(gap)) throw new Error("a gap row is malformed"); } + for (const status of Object.values(f.sourceStatus ?? {})) { + if (!isActivitySourceStatus(status)) throw new Error("a source status row is malformed"); + } this.data = { version: 1, checkpoints: f.checkpoints as Record, seen: f.seen as Record, gaps: f.gaps as GapRecord[], + sourceStatus: (f.sourceStatus ?? {}) as Record, }; } catch (err) { await this.quarantine(`is unparseable (${err instanceof Error ? err.message : String(err)})`); @@ -432,6 +559,18 @@ export class IngestionStore { return [...this.data.gaps].sort((a, b) => Date.parse(a.from) - Date.parse(b.from)); } + async sourceStatuses(): Promise { + await this.load(); + return Object.values(this.data.sourceStatus ?? {}).sort((a, b) => a.source.localeCompare(b.source)); + } + + async setSourceStatus(status: ActivitySourceStatus): Promise { + await this.load(); + if (!this.data.sourceStatus) this.data.sourceStatus = {}; + this.data.sourceStatus[status.source] = status; + await this.persist(); + } + /** * Ingest deliveries into the stream with dedupe + checkpointing. * A delivery whose sourceId is already in the source's seen set is @@ -535,8 +674,13 @@ export class IngestionStore { await this.persist(); return open; } + const baseId = `gap:${source}:${from}`; + let id = baseId; + for (let suffix = 1; this.data.gaps.some((gap) => gap.id === id); suffix++) { + id = `${baseId}:${suffix}`; + } const gap: GapRecord = { - id: `gap:${source}:${from}`, + id, source, from, to, @@ -558,7 +702,10 @@ export class IngestionStore { * failed poll. */ async resolveGap(id: string, status: Exclude, to?: string): Promise { await this.load(); - const gap = this.data.gaps.find((g) => g.id === id); + // Prefer an open row if older persisted data contains duplicate IDs + // from a previously resolved episode and a later reopened gap. + const gap = + this.data.gaps.find((g) => g.id === id && g.status === "open") ?? this.data.gaps.find((g) => g.id === id); if (!gap || gap.status !== "open") return gap ?? null; if (to && Date.parse(to) > Date.parse(gap.to)) gap.to = to; gap.status = status; diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 6561e9bbcd..2f4ac4b54b 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -140,6 +140,8 @@ export interface Config { }; projector: { baseUrl: string | null; + /** Shared projector bearer token used only to ack the GitHub hot-list cursor. */ + apiToken: string | null; }; /** Probe targets for the /health page (#1147): the stack services the * aggregator does not otherwise read. Kaneo/Grist/projector targets @@ -294,6 +296,7 @@ export function loadConfig(env: Record = process.env env.PM_PROJECTOR_URL === "off" || env.PM_PROJECTOR_URL === "none" ? null : s(env.PM_PROJECTOR_URL, "http://127.0.0.1:7801"), + apiToken: env.PM_PROJECTOR_API_TOKEN?.trim() || null, }, pad: { baseUrl: s(env.PM_AGG_PAD_URL, "http://127.0.0.1:7777"), diff --git a/pm-stack/aggregator/src/github-hot-list.ts b/pm-stack/aggregator/src/github-hot-list.ts new file mode 100644 index 0000000000..47ead3d301 --- /dev/null +++ b/pm-stack/aggregator/src/github-hot-list.ts @@ -0,0 +1,351 @@ +// Durable consumer for the projector's #5204 GitHub hot list. The +// projector owns webhook intake; this module only sweeps its append-only +// ledger and acknowledges the fixed high-water after activity writes land. +import { + type ActivitySourceStatus, + type GithubHotEvent, + githubHotEventDelivery, + type IngestionStore, +} from "./activity.ts"; +import type { EventsStore } from "./events.ts"; + +const DEFAULT_CONSUMER = "pm-aggregator-activity-v1"; +const DEFAULT_PAGE_SIZE = 200; +const DEFAULT_MAX_PAGES = 100; + +interface HotPage { + events: GithubHotEvent[]; + high_water: number; + next_cursor: number; +} + +class HotListError extends Error { + constructor( + message: string, + readonly disposition: "outage" | "unrecoverable" = "outage", + ) { + super(message); + } +} + +function isCursor(value: unknown): value is number { + return Number.isSafeInteger(value) && Number(value) >= 0; +} + +function isNullableString(value: unknown): value is string | null { + return value === null || typeof value === "string"; +} + +function isHotEvent(value: unknown): value is GithubHotEvent { + if (typeof value !== "object" || value === null) return false; + const event = value as Record; + return ( + isCursor(event.seq) && + typeof event.event_id === "string" && + isNullableString(event.delivery_id) && + typeof event.repo === "string" && + typeof event.event === "string" && + isNullableString(event.action) && + isNullableString(event.ref) && + isNullableString(event.actor) && + isNullableString(event.source_url) && + isNullableString(event.source_timestamp) && + typeof event.received_at === "string" + ); +} + +function isHotPage(value: unknown): value is HotPage { + if (typeof value !== "object" || value === null) return false; + const page = value as Record; + return ( + Array.isArray(page.events) && + page.events.every(isHotEvent) && + isCursor(page.high_water) && + isCursor(page.next_cursor) + ); +} + +function errorMessage(error: unknown): string { + return (error instanceof Error ? error.message : String(error)).slice(0, 500); +} + +export function unconfiguredGithubStatus(at = new Date()): ActivitySourceStatus { + const now = at.toISOString(); + return { + source: "github", + state: "unconfigured", + consumer: null, + cursor: null, + checkpointCursor: null, + highWater: null, + lastAttemptAt: null, + lastSuccessAt: null, + updatedAt: now, + error: "Set PM_PROJECTOR_URL and PM_PROJECTOR_API_TOKEN to enable the hot-list consumer.", + }; +} + +export interface GithubHotListConsumerOptions { + baseUrl: string; + token: string; + store: IngestionStore; + events: Pick; + consumer?: string; + pageSize?: number; + maxPages?: number; + fetch?: typeof fetch; + now?: () => Date; +} + +/** Reads one fixed high-water sweep from the projector hot list. A failed + * page, append, or checkpoint ack leaves the projector cursor untouched; + * the next run safely replays stable `event_id`s through IngestionStore. */ +export class GithubHotListConsumer { + private readonly consumer: string; + private readonly pageSize: number; + private readonly maxPages: number; + private readonly fetcher: typeof fetch; + private readonly clock: () => Date; + private inFlight: Promise | null = null; + + constructor(private readonly options: GithubHotListConsumerOptions) { + this.consumer = options.consumer ?? DEFAULT_CONSUMER; + this.pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE; + this.maxPages = options.maxPages ?? DEFAULT_MAX_PAGES; + this.fetcher = options.fetch ?? fetch; + this.clock = options.now ?? (() => new Date()); + } + + sync(): Promise { + if (this.inFlight) return this.inFlight; + const run = this.syncOnce().finally(() => { + if (this.inFlight === run) this.inFlight = null; + }); + this.inFlight = run; + return run; + } + + private async syncOnce(): Promise { + const previous = (await this.options.store.sourceStatuses()).find((row) => row.source === "github"); + const attemptedAt = this.clock().toISOString(); + const base: ActivitySourceStatus = { + source: "github", + state: "lagging", + consumer: this.consumer, + cursor: previous?.cursor ?? null, + checkpointCursor: previous?.checkpointCursor ?? null, + highWater: previous?.highWater ?? null, + lastAttemptAt: attemptedAt, + lastSuccessAt: previous?.lastSuccessAt ?? null, + updatedAt: attemptedAt, + }; + await this.options.store.setSourceStatus(base); + + let remoteCursor: number | null = null; + let sweepCursor: number | null = null; + let sweepHighWater: number | null = null; + try { + remoteCursor = await this.getCheckpoint(); + // If a prior run persisted rows but hit its page budget or lost the + // connection before the remote ack, resume inside that same pinned + // sweep. IngestionStore has durably recorded every page before this + // cursor, so continuing here cannot skip an unpersisted activity. + let cursor = remoteCursor; + let highWater: number | null = null; + if ( + previous !== undefined && + previous.checkpointCursor === remoteCursor && + previous.cursor !== null && + previous.cursor > remoteCursor && + previous.highWater !== null + ) { + cursor = previous.cursor; + highWater = previous.highWater; + } + sweepCursor = cursor; + sweepHighWater = highWater; + await this.options.store.setSourceStatus({ + ...base, + cursor, + checkpointCursor: remoteCursor, + highWater, + updatedAt: this.clock().toISOString(), + }); + let pages = 0; + let completed = false; + + while (pages < this.maxPages) { + const page = await this.getPage(cursor, highWater); + pages++; + if (highWater === null) highWater = page.high_water; + sweepHighWater = highWater; + if (page.high_water !== highWater) throw new HotListError("hot_list_high_water_changed", "unrecoverable"); + if (remoteCursor > highWater) throw new HotListError("checkpoint_past_hot_list_high_water", "unrecoverable"); + + let priorSeq = cursor; + for (const event of page.events) { + if (event.seq <= priorSeq || event.seq > highWater) { + throw new HotListError("hot_list_page_sequence_invalid", "unrecoverable"); + } + priorSeq = event.seq; + } + const expectedNext = page.events.at(-1)?.seq ?? cursor; + if (page.next_cursor !== expectedNext) throw new HotListError("hot_list_next_cursor_invalid", "unrecoverable"); + if (page.events.length === 0 && cursor < highWater) { + // `high_water` is the maximum existing row seq, so an empty + // page before that cursor is reached would skip source rows. + throw new HotListError("hot_list_cursor_stalled_before_high_water", "unrecoverable"); + } + + if (page.events.length) { + const deliveries = page.events.map(githubHotEventDelivery); + const ingested = await this.options.store.ingest(this.options.events, deliveries); + if (ingested.failed > 0) throw new HotListError(`activity_append_failed:${ingested.failed}`); + cursor = page.next_cursor; + sweepCursor = cursor; + } + + await this.options.store.setSourceStatus({ + ...base, + cursor, + checkpointCursor: remoteCursor, + highWater, + updatedAt: this.clock().toISOString(), + }); + if (page.events.length < this.pageSize && cursor < highWater) { + throw new HotListError("hot_list_page_ended_before_high_water", "unrecoverable"); + } + if (cursor >= highWater) { + completed = true; + break; + } + } + + if (!completed || highWater === null) { + const status: ActivitySourceStatus = { + ...base, + state: "lagging", + cursor: sweepCursor, + checkpointCursor: remoteCursor, + highWater, + error: `sweep_exceeded_${this.maxPages}_pages`, + updatedAt: this.clock().toISOString(), + }; + await this.openGap(previous, status.updatedAt); + await this.options.store.setSourceStatus(status); + return status; + } + + const ackedCursor = await this.acknowledge(cursor, highWater); + const completedAt = this.clock().toISOString(); + const state = ackedCursor < highWater ? "lagging" : "current"; + const status: ActivitySourceStatus = { + source: "github", + state, + consumer: this.consumer, + cursor: ackedCursor, + checkpointCursor: ackedCursor, + highWater, + lastAttemptAt: attemptedAt, + lastSuccessAt: completedAt, + updatedAt: completedAt, + ...(state === "lagging" ? { error: "remote_checkpoint_ahead_of_completed_sweep" } : {}), + }; + if (state === "current") await this.resolveOpenGaps(completedAt); + else await this.openGap(previous, completedAt); + await this.options.store.setSourceStatus(status); + return status; + } catch (error) { + const disposition = error instanceof HotListError ? error.disposition : "outage"; + const failedAt = this.clock().toISOString(); + const message = errorMessage(error); + const status: ActivitySourceStatus = { + ...base, + state: disposition, + cursor: sweepCursor ?? base.cursor, + checkpointCursor: remoteCursor ?? base.checkpointCursor, + highWater: sweepHighWater ?? base.highWater, + updatedAt: failedAt, + error: message, + }; + const gap = await this.openGap(previous, failedAt); + if (disposition === "unrecoverable") await this.options.store.resolveGap(gap.id, "unrecoverable", failedAt); + await this.options.store.setSourceStatus(status); + console.error(`[activity] WARNING: GitHub hot-list sync ${disposition}: ${message}`); + return status; + } + } + + private endpoint(path: string): string { + return `${this.options.baseUrl.replace(/\/+$/, "")}${path}`; + } + + private async json(path: string, init?: RequestInit): Promise { + let response: Response; + try { + response = await this.fetcher(this.endpoint(path), { + ...init, + headers: { + Accept: "application/json", + ...(init?.headers ?? {}), + }, + signal: init?.signal ?? AbortSignal.timeout(8_000), + }); + } catch (error) { + throw new HotListError(`projector_request_failed:${errorMessage(error)}`); + } + if (!response.ok) throw new HotListError(`projector_http_${response.status}`); + try { + return await response.json(); + } catch { + throw new HotListError("projector_response_invalid_json", "unrecoverable"); + } + } + + private async getCheckpoint(): Promise { + const query = new URLSearchParams({ consumer: this.consumer }); + const value = await this.json(`/hot/checkpoints?${query}`); + if (typeof value !== "object" || value === null || !isCursor((value as Record).cursor)) { + throw new HotListError("projector_checkpoint_shape_invalid", "unrecoverable"); + } + return (value as { cursor: number }).cursor; + } + + private async getPage(after: number, highWater: number | null): Promise { + const query = new URLSearchParams({ after: String(after), limit: String(this.pageSize) }); + if (highWater !== null) query.set("high_water", String(highWater)); + const value = await this.json(`/hot?${query}`); + if (!isHotPage(value)) throw new HotListError("projector_hot_page_shape_invalid", "unrecoverable"); + return value; + } + + private async acknowledge(cursor: number, highWater: number): Promise { + const value = await this.json("/hot/checkpoints", { + method: "POST", + headers: { + Authorization: `Bearer ${this.options.token}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ consumer: this.consumer, cursor, highWater }), + }); + if (typeof value !== "object" || value === null || !isCursor((value as Record).cursor)) { + throw new HotListError("projector_ack_shape_invalid", "unrecoverable"); + } + const acked = (value as { cursor: number }).cursor; + if (acked < cursor) throw new HotListError("projector_checkpoint_did_not_advance", "unrecoverable"); + return acked; + } + + private async openGap(previous: ActivitySourceStatus | undefined, to: string) { + const existing = (await this.options.store.gaps()).find((gap) => gap.source === "github" && gap.status === "open"); + const from = existing?.from ?? previous?.lastSuccessAt ?? previous?.lastAttemptAt ?? to; + return this.options.store.recordGap("github", from, to); + } + + private async resolveOpenGaps(at: string): Promise { + for (const gap of await this.options.store.gaps()) { + if (gap.source === "github" && gap.status === "open") + await this.options.store.resolveGap(gap.id, "backfilled", at); + } + } +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index e52c58a682..e22a824f5d 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -43,7 +43,9 @@ import { activityCoverageHtml, gapsHtml, ACTIVITY_SOURCE_COVERAGE, + type ActivitySourceStatus, } from "./activity.ts"; +import { GithubHotListConsumer, unconfiguredGithubStatus } from "./github-hot-list.ts"; import { RoadmapAnnotationsStore, validateNewRoadmapAnnotation } from "./roadmap-annotations.ts"; import { createAccessAuthorEnforcer, enforceAccessAuthor } from "./access-identity.ts"; import { @@ -343,6 +345,41 @@ const freshnessStore = new FreshnessStore(cfg.freshnessFile); * Its health view feeds /health + /api/health via healthContext. */ const freshnessReconciler = new FreshnessReconciler(freshnessStore, [fleetFeedRevisionReader(cfg.feedFile)]); const activityStore = new IngestionStore(cfg.activityFile); +const githubHotListConsumer = + cfg.source === "live" && cfg.projector.baseUrl && cfg.projector.apiToken + ? new GithubHotListConsumer({ + baseUrl: cfg.projector.baseUrl, + token: cfg.projector.apiToken, + store: activityStore, + events: eventsStore, + }) + : null; + +async function githubActivityStatus(): Promise { + return ( + (await activityStore.sourceStatuses()).find((status) => status.source === "github") ?? unconfiguredGithubStatus() + ); +} + +function activitySourceStatusHtml(status: ActivitySourceStatus): string { + const cursorDistance = + status.checkpointCursor !== null && status.highWater !== null + ? Math.max(0, status.highWater - status.checkpointCursor) + : null; + const cursorText = status.cursor === null ? "not checkpointed" : String(status.cursor); + const checkpointText = status.checkpointCursor === null ? "not checkpointed" : String(status.checkpointCursor); + const highWaterText = status.highWater === null ? "unknown" : String(status.highWater); + const lagText = cursorDistance === null ? "unknown" : String(cursorDistance); + const escapeHtml = (value: string) => + value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + const error = status.error ? `; detail: ${escapeHtml(status.error)}` : ""; + return ( + `

GitHub hot-list consumer: ${status.state}; processed cursor ${cursorText}; ` + + `acknowledged cursor ${checkpointText}; high-water ${highWaterText}; unacknowledged cursor distance ${lagText}; ` + + `last successful sweep ${escapeHtml(status.lastSuccessAt ?? "never")}${error}. ` + + `Current means caught up to the hot-list high-water, not complete GitHub history.

` + ); +} /** #1739: the event log's fire-and-forget sink for source-side * writers (orchestration publishes, registry merges). Never awaited, @@ -352,7 +389,7 @@ function recordStreamEvent(event: Parameters[1]): void { } /** #3321: the activity-ingestion sink for the source-side writers - * (watchdog episodes, Kaneo board changes). Dedupe + checkpoints + * (watchdog episodes, Kaneo board changes, GitHub hot-list rows). Dedupe + checkpoints * live in the store. The returned promise resolves true only when * every delivery is durable (ingested or already seen): the live * source awaits it as the acknowledgment that lets it discard its @@ -2415,6 +2452,7 @@ async function handler(req: Request): Promise { `` + eventTableHtml(page.events) + (nextUrl ? `

` : "") + + `

Activity source status

${activitySourceStatusHtml(await githubActivityStatus())}` + `

Activity gaps

` + gapsHtml(await activityStore.gaps()) + `

Activity source coverage

` + @@ -2427,8 +2465,18 @@ async function handler(req: Request): Promise { // #3321: activity-ingestion state — per-source checkpoints, gap // records, and the documented source coverage. The machine twin // of the sections the /events page renders below its table. - const [checkpoints, gaps] = await Promise.all([activityStore.checkpoints(), activityStore.gaps()]); - return json({ checkpoints, gaps, coverage: ACTIVITY_SOURCE_COVERAGE }); + const [checkpoints, gaps, sources] = await Promise.all([ + activityStore.checkpoints(), + activityStore.gaps(), + activityStore.sourceStatuses(), + ]); + const github = sources.find((status) => status.source === "github") ?? unconfiguredGithubStatus(); + return json({ + checkpoints, + gaps, + sources: [{ ...github, completeHistory: false }], + coverage: ACTIVITY_SOURCE_COVERAGE, + }); } if (path === "/api/views.json") { // #1276: the saved views, per owner (?owner=:) or all. @@ -4294,6 +4342,37 @@ if (source.ingestSnapshots) { setInterval(() => void ingestSnapshots(), SNAPSHOT_INGEST_INTERVAL_MS); } +// The hot-list consumer is a server-owned writer just like snapshot +// ingestion: it runs immediately on startup and then periodically, never +// as a side effect of rendering a page. A failed sweep leaves the remote +// checkpoint untouched and is retried on the next tick. +const GITHUB_HOT_LIST_INTERVAL_MS = 60_000; +if (githubHotListConsumer) { + let githubSyncRunning = false; + const syncGithubHotList = async (): Promise => { + if (githubSyncRunning) return; + githubSyncRunning = true; + try { + await githubHotListConsumer.sync(); + } catch (error) { + console.error( + `[activity] WARNING: GitHub hot-list worker failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } finally { + githubSyncRunning = false; + } + }; + void syncGithubHotList(); + const timer = setInterval(() => void syncGithubHotList(), GITHUB_HOT_LIST_INTERVAL_MS); + timer.unref?.(); +} else { + void activityStore.setSourceStatus(unconfiguredGithubStatus()).catch((error) => { + console.error( + `[activity] WARNING: could not persist unconfigured GitHub source status: ${error instanceof Error ? error.message : String(error)}`, + ); + }); +} + // The alert throat's engine (#3676): the ~60s delivery/escalation // tick (live mode only, fail-soft — see src/alerts.ts). startAlertEngine(cfg, async (): Promise => { diff --git a/pm-stack/aggregator/test/activity-3321.test.ts b/pm-stack/aggregator/test/activity-3321.test.ts index 09d4fee83a..6815142729 100644 --- a/pm-stack/aggregator/test/activity-3321.test.ts +++ b/pm-stack/aggregator/test/activity-3321.test.ts @@ -1,26 +1,26 @@ // #3321: activity ingestion — watchdog-event and Kaneo-change writers // into the #1739 stream, with per-source persisted checkpoints, // duplicate-delivery dedupe, restart resume, and gap records that a -// backfill flips. GitHub stays unsupported pending #2072 (asserted in -// the coverage table so the gap is documented, not implied away). +// backfill flips. GitHub coverage is limited to retained #2072 hot-list +// rows; pre-hot-list history and missed upstream deliveries stay explicit. import { describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { ACTIVITY_SOURCE_COVERAGE, - IngestionStore, - WatchdogEpisodeStabilizer, + type ActivityDelivery, activityCoverageHtml, createWatchdogGapSyncQueue, gapsHtml, + IngestionStore, ingestActivity, + type KaneoCardSnapshot, kaneoChangeDeliveries, maxUndatedSeqByCard, syncWatchdogGaps, + WatchdogEpisodeStabilizer, watchdogDeliveries, - type ActivityDelivery, - type KaneoCardSnapshot, } from "../src/activity.ts"; import { EventsStore } from "../src/events.ts"; import type { TierItem } from "../src/model.ts"; @@ -377,10 +377,12 @@ describe("ingestion store (#3321)", () => { expect(gaps.every((g) => g.status === "backfilled")).toBe(true); }); - test("coverage documents github as unsupported pending #2072", () => { + test("coverage documents bounded GitHub hot-list support", () => { const github = ACTIVITY_SOURCE_COVERAGE.find((c) => c.source === "github"); - expect(github?.status).toBe("unsupported"); - expect(github?.unsupported).toContain("#2072"); + expect(github?.status).toBe("supported"); + expect(github?.supported).toContain("#2072"); + expect(github?.unsupported).toContain("never received"); + expect(github?.historical).toContain("no pre-ledger"); const html = activityCoverageHtml(); expect(html).toContain("watchdog"); expect(html).toContain("kaneo"); diff --git a/pm-stack/aggregator/test/activity-github-7084.test.ts b/pm-stack/aggregator/test/activity-github-7084.test.ts new file mode 100644 index 0000000000..23f161c87b --- /dev/null +++ b/pm-stack/aggregator/test/activity-github-7084.test.ts @@ -0,0 +1,525 @@ +// #7084 (#3321 GitHub slice): consume the #5204 projector hot list into +// the #1739 activity stream. The oracle is the persisted hot-list consumer +// cursor: it may advance only after every event in one fixed-high-water +// sweep has landed in the activity stream, and replay/restart must stay +// idempotent through the stable `activity:github:` ids. +import { describe, expect, test } from "bun:test"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { type GapRecord, type GithubHotEvent, githubHotEventDelivery, IngestionStore } from "../src/activity.ts"; +import { EventsStore } from "../src/events.ts"; +import { GithubHotListConsumer } from "../src/github-hot-list.ts"; + +interface FakeLedger { + rows: GithubHotEvent[]; + cursor: number; + consumer: string; + ackCalls: Array<{ cursor: number; highWater: number }>; + checkpointViolations: number[]; +} + +function stores(): { + dir: string; + eventsFile: string; + activityFile: string; + events: EventsStore; + store: IngestionStore; +} { + const dir = mkdtempSync(join(tmpdir(), "agg-github-7084-")); + const eventsFile = join(dir, "events.json"); + const activityFile = join(dir, "activity.json"); + return { + dir, + eventsFile, + activityFile, + events: new EventsStore(eventsFile), + store: new IngestionStore(activityFile), + }; +} + +function hotEvent(seq: number, id: string, repo = "developing-today/code"): GithubHotEvent { + return { + seq, + event_id: id, + delivery_id: `delivery-${id}`, + repo, + event: "issues", + action: "opened", + ref: `${repo}#${seq}`, + actor: "dezren39", + source_url: `https://github.com/${repo}/issues/${seq}`, + source_timestamp: `2026-11-08T12:00:${String(seq % 60).padStart(2, "0")}.000Z`, + received_at: "2026-11-08T12:01:00.000Z", + }; +} + +/** Minimal projector hot-list protocol; a `failAck` injection models the + * dangerous window where activity rows are durable but the remote + * checkpoint was never acknowledged. */ +function projector( + rows: GithubHotEvent[], + opts: { + failAck?: boolean; + beforeAck?: (ack: { cursor: number; highWater: number }) => Promise; + } = {}, +) { + const ledger: FakeLedger = { + rows: [...rows], + cursor: 0, + consumer: "unset", + ackCalls: [], + checkpointViolations: [], + }; + const fetchMock = (async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)); + const highWater = Math.max(0, ...ledger.rows.map((row) => row.seq)); + if (url.pathname === "/hot/checkpoints" && (!init?.method || init.method === "GET")) { + return Response.json({ consumer: url.searchParams.get("consumer"), cursor: ledger.cursor }); + } + if (url.pathname === "/hot" && (!init?.method || init.method === "GET")) { + ledger.consumer = String(url.searchParams.get("consumer") ?? ledger.consumer); + const after = Number(url.searchParams.get("after") ?? 0); + const limit = Number(url.searchParams.get("limit") ?? 200); + const pinned = Number(url.searchParams.get("high_water") ?? highWater); + const events = ledger.rows + .filter((row) => row.seq > after && row.seq <= Math.min(pinned, highWater)) + .sort((a, b) => a.seq - b.seq) + .slice(0, limit); + return Response.json({ + events, + high_water: Math.min(pinned, highWater), + next_cursor: events.at(-1)?.seq ?? after, + }); + } + if (url.pathname === "/hot/checkpoints" && init?.method === "POST") { + if (opts.failAck) return Response.json({ error: "unavailable" }, { status: 503 }); + const body = JSON.parse(String(init.body)) as { consumer: string; cursor: number; highWater: number }; + if (body.cursor > body.highWater || body.highWater > highWater) { + return Response.json({ error: "checkpoint_past_high_water" }, { status: 400 }); + } + if (opts.beforeAck && !(await opts.beforeAck(body))) { + ledger.checkpointViolations.push(body.cursor); + return Response.json({ error: "checkpoint_before_rows_durable" }, { status: 409 }); + } + ledger.ackCalls.push({ cursor: body.cursor, highWater: body.highWater }); + ledger.cursor = Math.max(ledger.cursor, body.cursor); + ledger.consumer = body.consumer; + return Response.json({ consumer: body.consumer, cursor: ledger.cursor }); + } + return Response.json({ error: "not_found" }, { status: 404 }); + }) as typeof fetch; + return { ledger, fetchMock }; +} + +function consumer( + parts: ReturnType, + fetchMock: typeof fetch, + opts: { + pageSize?: number; + maxPages?: number; + events?: Pick; + now?: () => Date; + } = {}, +): GithubHotListConsumer { + return new GithubHotListConsumer({ + baseUrl: "http://projector.test", + token: "test-token", + store: parts.store, + events: opts.events ?? parts.events, + fetch: fetchMock, + pageSize: opts.pageSize ?? 2, + maxPages: opts.maxPages ?? 20, + now: opts.now ?? (() => new Date("2026-11-08T12:05:00.000Z")), + }); +} + +function seededInt(seed: number): (limit: number) => number { + let state = seed >>> 0; + return (limit) => { + state = (Math.imul(state, 1_664_525) + 1_013_904_223) >>> 0; + return state % limit; + }; +} + +describe("GitHub hot-list writer (#7084)", () => { + test("maps a hot-list row to the common event contract with a stable source id and link", () => { + const row = hotEvent(7, "delivery:issues.opened:1"); + const delivery = githubHotEventDelivery(row); + expect(delivery).toMatchObject({ + source: "github", + sourceId: "delivery:issues.opened:1", + kind: "github-event", + ref: "developing-today/code#7", + link: "https://github.com/developing-today/code/issues/7", + }); + expect(delivery.summary).toContain("issues opened"); + expect(delivery.summary).toContain("dezren39"); + // Same source row -> same delivery; the store persists the + // `activity:github:` stream id. + expect(githubHotEventDelivery(row).sourceId).toBe(delivery.sourceId); + }); + + test("rejects a source link outside GitHub and falls back to the repository URL", () => { + const row = { ...hotEvent(8, "delivery:issues.opened:2"), source_url: "javascript:alert(1)" }; + const delivery = githubHotEventDelivery(row); + expect(delivery.link).toBe("https://github.com/developing-today/code"); + }); + + test("maps an oversized push ref to a valid ref without losing it from the summary", () => { + const branch = `refs/heads/${"feature".repeat(60)}`; + const delivery = githubHotEventDelivery({ + ...hotEvent(9, "delivery:push:9"), + event: "push", + action: null, + ref: branch, + }); + expect(delivery.ref).toBe("developing-today/code"); + expect(delivery.summary).toContain("ref refs/heads/"); + expect(delivery.link).toBe("https://github.com/developing-today/code/issues/9"); + }); +}); + +describe("GitHub hot-list consumer (#7084)", () => { + test("loads the existing v1 activity file before source-status metadata existed", async () => { + const parts = stores(); + writeFileSync(parts.activityFile, JSON.stringify({ version: 1, checkpoints: {}, seen: {}, gaps: [] }), "utf8"); + const legacy = new IngestionStore(parts.activityFile); + expect(await legacy.sourceStatuses()).toEqual([]); + await legacy.setSourceStatus({ + source: "github", + state: "unconfigured", + consumer: null, + cursor: null, + checkpointCursor: null, + highWater: null, + lastAttemptAt: null, + lastSuccessAt: null, + updatedAt: "2026-11-08T12:00:00.000Z", + }); + expect((await new IngestionStore(parts.activityFile).sourceStatuses())[0]?.source).toBe("github"); + }); + + test("sweeps every page, ingests each row once, then acks the completed high-water", async () => { + const parts = stores(); + const { ledger, fetchMock } = projector([ + hotEvent(1, "delivery:1"), + hotEvent(2, "delivery:2"), + hotEvent(3, "delivery:3"), + ]); + const status = await consumer(parts, fetchMock, { pageSize: 2 }).sync(); + expect(status.state).toBe("current"); + expect(status.cursor).toBe(3); + expect(status.highWater).toBe(3); + expect(ledger.ackCalls).toEqual([{ cursor: 3, highWater: 3 }]); + const stream = await parts.events.list(); + expect(stream.map((event) => event.id).sort()).toEqual([ + "activity:github:delivery:1", + "activity:github:delivery:2", + "activity:github:delivery:3", + ]); + expect(stream.every((event) => event.kind === "github-event")).toBe(true); + expect(stream.find((event) => event.id === "activity:github:delivery:1")?.summary).toContain( + "https://github.com/developing-today/code/issues/1", + ); + }); + + test("an oversized push ref falls back to the repo ref instead of stalling the sweep", async () => { + const parts = stores(); + const branch = `refs/heads/${"feature".repeat(60)}`; + const row = { ...hotEvent(1, "delivery:push:1"), event: "push", action: null, ref: branch }; + const { ledger, fetchMock } = projector([row]); + + const status = await consumer(parts, fetchMock).sync(); + + expect(status.state).toBe("current"); + expect(ledger.cursor).toBe(1); + expect((await parts.events.list())[0]).toMatchObject({ + id: "activity:github:delivery:push:1", + ref: "developing-today/code", + }); + expect((await parts.events.list())[0]?.summary).toContain("ref refs/heads/"); + }); + + test("a duplicate delivery replay is a no-op and the checkpoint still advances", async () => { + const parts = stores(); + const first = projector([hotEvent(1, "delivery:1"), hotEvent(2, "delivery:2")]); + await consumer(parts, first.fetchMock).sync(); + expect(await parts.events.list()).toHaveLength(2); + // The projector loses/replays its checkpoint but reissues the same + // stable event ids: a fresh local process/store dedupes them too. + first.ledger.cursor = 0; + const restarted = { + ...parts, + store: new IngestionStore(parts.activityFile), + events: new EventsStore(parts.eventsFile), + }; + const replay = await consumer(restarted, first.fetchMock).sync(); + expect(replay.state).toBe("current"); + expect(await restarted.events.list()).toHaveLength(2); + const checkpoint = await restarted.store.checkpoint("github"); + expect(checkpoint?.duplicates).toBe(2); + expect(checkpoint?.deliveries).toBe(2); + }); + + test("a failed ack never loses rows: the next sweep replays and advances only then", async () => { + const parts = stores(); + const broken = projector([hotEvent(1, "delivery:1"), hotEvent(2, "delivery:2")], { failAck: true }); + const failed = await consumer(parts, broken.fetchMock).sync(); + expect(failed.state).toBe("outage"); + expect(broken.ledger.cursor).toBe(0); + expect(await parts.events.list()).toHaveLength(2); + const gap = (await parts.store.gaps()).find((row) => row.source === "github"); + expect(gap?.status).toBe("open"); + + // Same projector, healthy ack path: the replay dedupes the two rows + // after a process restart, and only then moves the remote cursor. + const restarted = { + ...parts, + store: new IngestionStore(parts.activityFile), + events: new EventsStore(parts.eventsFile), + }; + expect(await restarted.store.sourceStatuses()).toMatchObject([ + { source: "github", state: "outage", cursor: 2, checkpointCursor: 0, highWater: 2 }, + ]); + const healthy = projector(broken.ledger.rows); + const recovered = await consumer(restarted, healthy.fetchMock).sync(); + expect(recovered.state).toBe("current"); + expect(healthy.ledger.cursor).toBe(2); + expect(await restarted.events.list()).toHaveLength(2); + expect((await restarted.store.gaps()).find((row) => row.source === "github")?.status).toBe("backfilled"); + expect((await restarted.store.checkpoint("github"))?.deliveries).toBe(2); + expect((await restarted.store.checkpoint("github"))?.duplicates).toBe(0); + }); + + test("restart resumes from the persisted projector checkpoint without re-acking old rows", async () => { + const parts = stores(); + const { ledger, fetchMock } = projector([hotEvent(1, "delivery:1"), hotEvent(2, "delivery:2")]); + await consumer(parts, fetchMock).sync(); + const beforeRestart = await parts.events.list(); + ledger.rows.push(hotEvent(3, "delivery:3")); + + // Fresh store + consumer instances over the same files: the projector + // still holds cursor 2, so only the new row is delivered. + const store2 = new IngestionStore(parts.activityFile); + const events2 = new EventsStore(parts.eventsFile); + const restarted = new GithubHotListConsumer({ + baseUrl: "http://projector.test", + token: "test-token", + store: store2, + events: events2, + fetch: fetchMock, + pageSize: 1, + now: () => new Date("2026-11-08T12:06:00.000Z"), + }); + const status = await restarted.sync(); + expect(status.state).toBe("current"); + expect(status.cursor).toBe(3); + expect((await events2.list()).map((event) => event.id).sort()).toEqual( + [...beforeRestart.map((event) => event.id).sort(), "activity:github:delivery:3"].sort(), + ); + expect(ledger.ackCalls.map((ack) => ack.cursor)).toEqual([2, 3]); + }); + + test("an exhausted page budget reports lag and never acks a partial sweep", async () => { + const parts = stores(); + const { ledger, fetchMock } = projector( + Array.from({ length: 5 }, (_, index) => hotEvent(index + 1, `delivery:${index + 1}`)), + ); + const status = await consumer(parts, fetchMock, { pageSize: 1, maxPages: 2 }).sync(); + expect(status.state).toBe("lagging"); + expect(status.cursor).toBe(2); + expect(status.checkpointCursor).toBe(0); + expect(status.error).toContain("sweep_exceeded_2_pages"); + expect(ledger.ackCalls).toEqual([]); + expect(await parts.events.list()).toHaveLength(2); + const gap = (await parts.store.gaps()).find((row) => row.source === "github"); + expect(gap?.status).toBe("open"); + expect(Number.isFinite(Date.parse(gap?.from ?? ""))).toBe(true); + expect(Number.isFinite(Date.parse(gap?.to ?? ""))).toBe(true); + + const resumed = await consumer(parts, fetchMock, { pageSize: 2, maxPages: 20 }).sync(); + expect(resumed.state).toBe("current"); + expect(resumed.cursor).toBe(5); + expect(resumed.checkpointCursor).toBe(5); + expect(ledger.ackCalls).toEqual([{ cursor: 5, highWater: 5 }]); + expect(await parts.events.list()).toHaveLength(5); + expect((await parts.store.gaps()).find((row) => row.source === "github")?.status).toBe("backfilled"); + }); + + test("a projector outage is exposed as an open github gap with a time range", async () => { + const parts = stores(); + const failed = (async () => { + throw new Error("connection refused"); + }) as unknown as typeof fetch; + const status = await consumer(parts, failed).sync(); + expect(status.state).toBe("outage"); + expect(status.error).toContain("connection refused"); + const gaps = await parts.store.gaps(); + const github = gaps.find((row: GapRecord) => row.source === "github"); + expect(github?.status).toBe("open"); + expect(Number.isFinite(Date.parse(github?.from ?? ""))).toBe(true); + expect(Number.isFinite(Date.parse(github?.to ?? ""))).toBe(true); + // The render never presents the source as complete history. + expect(status.state).not.toBe("current"); + }); + + test("a repeated failure after an unrecoverable gap creates a distinct, recoverable gap", async () => { + const parts = stores(); + const baseline = await consumer(parts, projector([]).fetchMock).sync(); + expect(baseline.state).toBe("current"); + + const badCheckpoint = projector([hotEvent(1, "delivery:1")]); + badCheckpoint.ledger.cursor = 9; + const unrecoverable = await consumer(parts, badCheckpoint.fetchMock).sync(); + expect(unrecoverable.state).toBe("unrecoverable"); + const firstGap = (await parts.store.gaps()).find((gap) => gap.source === "github"); + expect(firstGap?.status).toBe("unrecoverable"); + + const failedFetch = (async () => { + throw new Error("connection refused"); + }) as unknown as typeof fetch; + expect((await consumer(parts, failedFetch).sync()).state).toBe("outage"); + const secondGap = (await parts.store.gaps()).find((gap) => gap.status === "open"); + expect(secondGap).toBeDefined(); + expect(secondGap?.id).not.toBe(firstGap?.id); + + const recovered = await consumer(parts, projector([hotEvent(1, "delivery:1")]).fetchMock).sync(); + expect(recovered.state).toBe("current"); + expect(await parts.store.gaps()).toEqual( + expect.arrayContaining([ + expect.objectContaining({ id: firstGap?.id, status: "unrecoverable" }), + expect.objectContaining({ id: secondGap?.id, status: "backfilled" }), + ]), + ); + }); + + test("gap resolution prefers an open row in legacy state with a reused id", async () => { + const parts = stores(); + const id = "gap:github:2026-11-08T12:00:00.000Z"; + writeFileSync( + parts.activityFile, + JSON.stringify({ + version: 1, + checkpoints: {}, + seen: {}, + gaps: [ + { + id, + source: "github", + from: "2026-11-08T12:00:00.000Z", + to: "2026-11-08T12:01:00.000Z", + status: "unrecoverable", + detectedAt: "2026-11-08T12:01:00.000Z", + resolvedAt: "2026-11-08T12:02:00.000Z", + }, + { + id, + source: "github", + from: "2026-11-08T12:00:00.000Z", + to: "2026-11-08T12:03:00.000Z", + status: "open", + detectedAt: "2026-11-08T12:03:00.000Z", + }, + ], + }), + "utf8", + ); + + const store = new IngestionStore(parts.activityFile); + await store.resolveGap(id, "backfilled", "2026-11-08T12:04:00.000Z"); + + expect((await store.gaps()).map((gap) => gap.status)).toEqual(["unrecoverable", "backfilled"]); + }); + + test("generated failure/restart schedules never checkpoint undurable rows or duplicate activity", async () => { + // Deterministic generated traces exercise sparse sequence numbers, + // varying page sizes, repeated append failures, and process restarts. + // The oracle checks each remote ack against a fresh read of the durable + // event log, then checks exact stable-id set equality after recovery. + for (let seed = 1; seed <= 48; seed++) { + const draw = seededInt(seed); + const parts = stores(); + const count = 1 + draw(8); + let seq = 0; + const rows = Array.from({ length: count }, (_, index) => { + seq += 1 + draw(4); + const kinds = ["issues", "pull_request", "issue_comment", "pull_request_review", "push"]; + const row = hotEvent(seq, `generated:${seed}:${index}`); + return { + ...row, + event: kinds[draw(kinds.length)]!, + action: draw(4) === 0 ? null : ["opened", "edited", "submitted"][draw(3)]!, + ref: draw(5) === 0 ? null : row.ref, + }; + }); + const failedEvent = rows[draw(rows.length)]!; + const failureAttempts = 1 + draw(3); + let failuresRemaining = failureAttempts; + const { ledger, fetchMock } = projector(rows, { + beforeAck: async ({ cursor }) => { + const durable = await new EventsStore(parts.eventsFile).list(); + const ids = new Set(durable.map((event) => event.id)); + return rows + .filter((row) => row.seq <= cursor) + .every((row) => ids.has(`activity:github:${row.event_id}`)); + }, + }); + + for (let attempt = 0; attempt < failureAttempts; attempt++) { + const restarted = { + ...parts, + store: new IngestionStore(parts.activityFile), + events: new EventsStore(parts.eventsFile), + }; + const failOnce: Pick = { + record: async (event) => { + if (event.id === `activity:github:${failedEvent.event_id}` && failuresRemaining > 0) { + failuresRemaining--; + throw new Error(`generated_append_failure:${seed}:${attempt}`); + } + return restarted.events.record(event); + }, + }; + const status = await consumer(restarted, fetchMock, { + events: failOnce, + pageSize: 1 + draw(4), + maxPages: 40, + }).sync(); + expect(status.state).toBe("outage"); + expect(ledger.cursor).toBe(0); + expect(ledger.ackCalls).toEqual([]); + expect(ledger.checkpointViolations).toEqual([]); + } + + const recovered = { + ...parts, + store: new IngestionStore(parts.activityFile), + events: new EventsStore(parts.eventsFile), + }; + const status = await consumer(recovered, fetchMock, { + pageSize: 1 + draw(4), + maxPages: 40, + }).sync(); + expect(status.state).toBe("current"); + expect(ledger.cursor).toBe(seq); + expect(ledger.ackCalls).toEqual([{ cursor: seq, highWater: seq }]); + expect(ledger.checkpointViolations).toEqual([]); + expect((await recovered.events.list()).map((event) => event.id).sort()).toEqual( + rows.map((row) => `activity:github:${row.event_id}`).sort(), + ); + } + }); + + test("a cursor past the hot-list high-water is unrecoverable, never silently reset", async () => { + const parts = stores(); + const { ledger, fetchMock } = projector([hotEvent(1, "delivery:1")]); + ledger.cursor = 9; + const status = await consumer(parts, fetchMock).sync(); + expect(status.state).toBe("unrecoverable"); + expect(status.error).toContain("checkpoint_past"); + expect(ledger.ackCalls).toEqual([]); + const gap = (await parts.store.gaps()).find((row) => row.source === "github"); + expect(gap?.status).toBe("unrecoverable"); + }); +}); diff --git a/pm-stack/aggregator/test/config.test.ts b/pm-stack/aggregator/test/config.test.ts index a12b17778d..5749d8064f 100644 --- a/pm-stack/aggregator/test/config.test.ts +++ b/pm-stack/aggregator/test/config.test.ts @@ -1,6 +1,14 @@ import { describe, expect, test } from "bun:test"; import { loadConfig } from "../src/config.ts"; +describe("loadConfig projector hot-list credentials", () => { + test("trims the optional projector bearer token and leaves it unset by default", () => { + expect(loadConfig({ PM_AGG_DEV: "1" }).projector.apiToken).toBeNull(); + expect(loadConfig({ PM_AGG_DEV: "1", PM_PROJECTOR_API_TOKEN: " token " }).projector.apiToken).toBe("token"); + expect(loadConfig({ PM_AGG_DEV: "1", PM_PROJECTOR_API_TOKEN: " " }).projector.apiToken).toBeNull(); + }); +}); + describe("loadConfig PM_AGG_PORT", () => { test("keeps the existing default for unset and empty values", () => { expect(loadConfig({ PM_AGG_DEV: "1" }).port).toBe(4870);