diff --git a/nixos/services/pm-stack/default.nix b/nixos/services/pm-stack/default.nix index 1f8f279ed1..e614526d7f 100644 --- a/nixos/services/pm-stack/default.nix +++ b/nixos/services/pm-stack/default.nix @@ -156,6 +156,12 @@ in # (pre-switch) unit resolves them identically. "PM_AGG_EVENTS_FILE=${aggState}/events.json" "PM_AGG_VIEWS_FILE=${aggState}/views.json" + # The activity-ingestion store (#3321) is runtime state + # too: left at its cwd default its first persisted + # delivery created activity-ingestion.json inside this + # checkout (Codex P1 on PR #5141, same failure class as + # code#4906 above). + "PM_AGG_ACTIVITY_FILE=${aggState}/activity-ingestion.json" ]; Restart = "on-failure"; RestartSec = 5; diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index 82ebd24b98..2870586479 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -452,10 +452,27 @@ Everything defaults to **fixtures** and works with no configuration: | `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` | `./activity-ingestion.json` | Activity-ingestion store (#3321) — per-source checkpoints + dedupe seen sets + gap records for the watchdog/Kaneo stream writers | Secrets are read from the environment only and are never committed or printed. Names here reference Bitwarden entries (`kaneo.*`, `grist.*`). +### 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. + ## Capability provenance matrix (#1200) The single source of truth for what the aggregator reads, facet by diff --git a/pm-stack/aggregator/install.sh b/pm-stack/aggregator/install.sh index c1acc4f4ee..400e1f7b18 100755 --- a/pm-stack/aggregator/install.sh +++ b/pm-stack/aggregator/install.sh @@ -104,6 +104,7 @@ if [ "$CHANGED" -eq 1 ]; then echo "PM_AGG_FEED_FILE=${STATE_DIR}/fleet-feed.json" echo "PM_AGG_COMMENTS_FILE=${STATE_DIR}/comments.json" echo "PM_AGG_EVENTS_FILE=${STATE_DIR}/events.json" + echo "PM_AGG_ACTIVITY_FILE=${STATE_DIR}/activity-ingestion.json" echo "PM_AGG_ACTIONS_FILE=${STATE_DIR}/actions.json" echo "PM_AGG_REGISTRY_FILE=${STATE_DIR}/registry.json" echo "PM_AGG_SNAPSHOTS_DIR=${STATE_DIR}/snapshots" diff --git a/pm-stack/aggregator/src/activity.ts b/pm-stack/aggregator/src/activity.ts new file mode 100644 index 0000000000..c2cdc6ebf0 --- /dev/null +++ b/pm-stack/aggregator/src/activity.ts @@ -0,0 +1,676 @@ +// Activity ingestion for the cross-stack stream (#3321): the +// watchdog-event and Kaneo-change writers that map external activity +// into the #1739 StreamEvent log, with the ingestion discipline the +// local fire-and-forget writers never needed: +// +// - Stable source IDs: every delivery carries a per-source stable id +// (`watchdog:@` for a watchdog breach episode, +// `kaneo:/:status:->:` for a +// Kaneo change). The same real-world change always produces the +// same id, which is what makes dedupe possible. Two refinements +// from the Codex review of PR #5141: a Kaneo card with no +// `updatedAt` gets a per-card transition sequence instead of the +// constant `undated` stamp (so a later repeat of the same +// transition is a new delivery, while a retry of the same observed +// transition keeps its id), and watchdog episodes pass through +// WatchdogEpisodeStabilizer, because watchdogTierItems assigns +// `now` (or a refreshed probe time) as `since` for several breach +// kinds and the raw derivation would mint a new episode id on +// every render. +// - A persisted per-source checkpoint + seen-id set (one JSON file, +// PM_AGG_ACTIVITY_FILE, following the events store's discipline: +// atomic temp+rename writes serialized through a promise chain, a +// missing file is the only silent empty start, a corrupt file is +// quarantined loudly). Replaying a duplicate delivery is a no-op, +// and a restart resumes from the checkpoint — the seen set and the +// checkpoint survive the process, so nothing is re-emitted. +// - Gap records: when a source is known to be breached / unreachable +// for a window, the window is recorded as a gap (source + time +// range) instead of silently passing as complete history. A later +// 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. +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { EventsStore } from "./events.ts"; +import type { TierItem } from "./model.ts"; + +export type ActivitySourceId = "watchdog" | "kaneo" | "github"; + +/** One normalized activity delivery, before it becomes a StreamEvent. */ +export interface ActivityDelivery { + source: ActivitySourceId; + /** Stable per-source event id — the dedupe key. */ + sourceId: string; + /** ISO timestamp of the change at the source. */ + at: string; + /** StreamEvent kind ("watchdog-event" | "kaneo-change"). */ + kind: string; + /** StreamEvent ref (the item the change concerns). */ + ref: string; + /** One-line human summary. */ + summary: string; + /** Source link (e.g. the Kaneo card URL), appended to the summary. */ + link?: string; +} + +/** Documented coverage for one activity source (#3321 acceptance: + * coverage distinguishes supported / unsupported / historical). */ +export interface ActivityCoverage { + source: ActivitySourceId; + status: "supported" | "unsupported"; + /** What is ingested today. */ + supported: string; + /** What is explicitly not ingested today. */ + unsupported: string; + /** How far back the ingested history reaches. */ + historical: string; +} + +export const ACTIVITY_SOURCE_COVERAGE: readonly ActivityCoverage[] = [ + { + source: "watchdog", + status: "supported", + supported: + "Watchdog breach episodes (fleet-feed stale/absent/future-dated, orchestration stale/invalid/absent, registry stale, Kaneo/Grist/Pad probe failures) are written to the stream as watchdog-event records, one per episode, keyed by the stable watchdog: id and the episode's since timestamp.", + unsupported: "Sub-threshold degradations the watchdog does not diagnose, and inputs outside watchdog.ts's diagnosed set.", + historical: + "From the first ingestion run forward. Watchdog diagnoses are derived live and were never persisted before #3321, so no pre-ingestion breach history exists or is claimed.", + }, + { + source: "kaneo", + status: "supported", + supported: + "Kaneo board changes observed by the live source's board polls: a card appearing in a WIP column, and a card's status (column) change, written as kaneo-change records with the card's Kaneo URL as the source link.", + unsupported: + "Card edits that change neither presence nor status (title/priority/body edits), cards in to-do columns the board does not fetch, and deletions (a vanished card is indistinguishable from the done-aging filter at this surface).", + historical: + "From the first board poll after ingestion starts: the first poll is a silent baseline (no events), so changes that happened while the aggregator was down surface only if they are still visible as a status/presence diff at the next poll — outages open gap records instead of claiming that history.", + }, + { + source: "github", + status: "unsupported", + supported: "Nothing yet.", + 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.", + }, +]; + +// -- writers: pure mappings from source observations to deliveries ------- + +/** Map watchdog tier items to deliveries, one per breach episode. + * Callers whose items come from repeated live derivations should + * pass them through WatchdogEpisodeStabilizer first (below): the + * delivery id `watchdog:@` is only as stable as the + * item's `since`, and not every breach kind derives a stable one. */ +export function watchdogDeliveries(items: readonly TierItem[]): ActivityDelivery[] { + return items.map((item) => ({ + source: "watchdog" as const, + sourceId: `${item.id}@${item.since}`, + at: item.since, + kind: "watchdog-event", + ref: item.id, + summary: item.title.slice(0, 500), + })); +} + +/** 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 + * absent/invalid orchestration sections, assigns the current `now` + * as `since`; failing probes carry each refresh's probe timestamp. + * Without this pin, every render of one continuous outage would mint + * a different delivery id and flood the bounded stream with + * duplicates of the same episode, evicting unrelated history. The + * pin is per item id and is forgotten as soon as the id stops being + * derived, so a later, genuinely new episode gets its own id. */ +export class WatchdogEpisodeStabilizer { + private firstSinceById = new Map(); + + stabilize(items: readonly TierItem[]): TierItem[] { + const present = new Set(items.map((i) => i.id)); + for (const id of [...this.firstSinceById.keys()]) { + if (!present.has(id)) this.firstSinceById.delete(id); + } + return items.map((item) => { + const first = this.firstSinceById.get(item.id); + if (first !== undefined) return first === item.since ? item : { ...item, since: first }; + this.firstSinceById.set(item.id, item.since); + return item; + }); + } +} + +/** The board-diffable shape of one Kaneo card. */ +export interface KaneoCardSnapshot { + id: string; + status: string; + title: string; + updatedAt?: string; + kaneoUrl?: string; + /** Per-card count of transitions the caller had already ingested + * for this card as of this snapshot (maintained across snapshots + * by the caller; see kaneoChangeDeliveries). Only used to key + * UNDATED deliveries, where no source timestamp exists. */ + seq?: number; +} + +/** Diff two successive Kaneo board snapshots into change deliveries. + * Pure. A card that appears produces one delivery; a card whose + * status changed produces one; unchanged cards produce none. The + * delivery id embeds the card's updatedAt when the source provides + * it, so two distinct changes to the same card are distinct + * deliveries while a re-diff of the same change is a duplicate. + * When the source omits updatedAt (which the live reader explicitly + * supports), the id instead carries the card's next transition + * sequence, (prev snapshot's `seq`) + 1: successive observed moves + * in-progress -> in-review -> in-progress -> in-review then get + * distinct ids instead of colliding on a constant `undated` stamp + * (Codex P2, PR #5141), while re-diffing the SAME observed + * transition against the SAME prev snapshot reproduces the same + * id, so a retry after a failed append stays a dedupe-safe replay. + * Callers persist the bumped seq in their stored snapshot once the + * delivery is acknowledged (see live.ts board()). */ +export function kaneoChangeDeliveries( + prev: ReadonlyMap, + next: readonly KaneoCardSnapshot[], +): ActivityDelivery[] { + const out: ActivityDelivery[] = []; + for (const card of next) { + const before = prev.get(card.id); + const stamp = card.updatedAt ?? `undated:${(card.seq ?? 0) + 1}`; + if (!before) { + out.push({ + source: "kaneo", + sourceId: `${card.id}:appeared:${stamp}`, + at: card.updatedAt ?? new Date().toISOString(), + kind: "kaneo-change", + ref: card.id, + summary: `Kaneo card appeared in ${card.status}: ${card.title}`.slice(0, 500), + ...(card.kaneoUrl ? { link: card.kaneoUrl } : {}), + }); + } else if (before.status !== card.status) { + const undatedSeq = (before.seq ?? card.seq ?? 0) + 1; + out.push({ + source: "kaneo", + sourceId: `${card.id}:status:${before.status}->${card.status}:${card.updatedAt ?? `undated:${undatedSeq}`}`, + at: card.updatedAt ?? new Date().toISOString(), + kind: "kaneo-change", + ref: card.id, + summary: `Kaneo card moved ${before.status} -> ${card.status}: ${card.title}`.slice(0, 500), + ...(card.kaneoUrl ? { link: card.kaneoUrl } : {}), + }); + } + } + return out; +} + +/** Highest undated transition sequence already used per card, parsed + * from persisted delivery ids (`:appeared:undated:` and + * `:status:->:undated:`). A restarted process seeds + * its in-memory counters from this so its next undated delivery for + * a card cannot reuse an id the ingestion store has already seen + * and silently dedupe-discard a genuine change (Codex P2, PR + * #5141). Ids without an undated stamp carry no sequence and are + * ignored. */ +export function maxUndatedSeqByCard(seenIds: readonly string[]): Map { + const out = new Map(); + for (const id of seenIds) { + const m = /^(.*):undated:(\d+)$/.exec(id); + if (!m) continue; + const head = m[1]!; + let cardId: string | null = null; + const statusAt = head.indexOf(":status:"); + if (statusAt >= 0) cardId = head.slice(0, statusAt); + else if (head.endsWith(":appeared")) cardId = head.slice(0, -":appeared".length); + if (!cardId) continue; + const seq = Number(m[2]); + if (Number.isFinite(seq) && seq > (out.get(cardId) ?? 0)) out.set(cardId, seq); + } + return out; +} + +// -- gap records ----------------------------------------------------------- + +export type GapStatus = "open" | "backfilled" | "unrecoverable"; + +export interface GapRecord { + id: string; + /** Source the hole belongs to ("watchdog:fleet-feed", "kaneo", ...). */ + source: string; + /** ISO start of the known-missing window. */ + from: string; + /** ISO end of the known-missing window (extends while open). */ + to: string; + status: GapStatus; + detectedAt: string; + resolvedAt?: string; +} + +// -- the ingestion store --------------------------------------------------- + +export interface SourceCheckpoint { + source: string; + /** sourceId of the most recently ingested delivery. */ + lastSourceId: string | null; + /** `at` of the most recently ingested delivery. */ + lastEventAt: string | null; + /** Deliveries ingested (duplicates excluded). */ + deliveries: number; + /** Deliveries dropped as duplicates. */ + duplicates: number; + updatedAt: string; +} + +export interface IngestionFile { + version: 1; + checkpoints: Record; + seen: Record; + gaps: GapRecord[]; +} + +/** Per-source seen-id bound: dedupe memory is finite by design; an id + * older than the newest 2000 deliveries from its source can be + * re-ingested if replayed (the stream's own 30-day retention makes + * that window consistent). */ +export const SEEN_RETENTION_MAX = 2000; + +function isGapRecord(v: unknown): v is GapRecord { + if (typeof v !== "object" || v === null) return false; + const g = v as Record; + return ( + typeof g.id === "string" && + typeof g.source === "string" && + typeof g.from === "string" && + typeof g.to === "string" && + (g.status === "open" || g.status === "backfilled" || g.status === "unrecoverable") && + typeof g.detectedAt === "string" + ); +} + +function isCheckpoint(v: unknown): v is SourceCheckpoint { + if (typeof v !== "object" || v === null) return false; + const c = v as Record; + return ( + typeof c.source === "string" && + (c.lastSourceId === null || typeof c.lastSourceId === "string") && + (c.lastEventAt === null || typeof c.lastEventAt === "string") && + Number.isInteger(c.deliveries) && + Number.isInteger(c.duplicates) && + typeof c.updatedAt === "string" + ); +} + +export class IngestionStore { + private data: IngestionFile = { version: 1, checkpoints: {}, seen: {}, gaps: [] }; + private loadPromise: Promise | null = null; + private ingestChain: Promise = Promise.resolve(); + private writeChain: Promise = Promise.resolve(); + private writeSeq = 0; + + constructor(private readonly file: string) {} + + async load(): Promise { + if (!this.loadPromise) this.loadPromise = this.doLoad(); + return this.loadPromise; + } + + private async doLoad(): Promise { + let raw: string; + try { + raw = await readFile(this.file, "utf8"); + } catch (err) { + if ((err as { code?: unknown })?.code === "ENOENT") return; + await this.quarantine(`could not be read (${err instanceof Error ? err.message : String(err)})`); + return; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed !== "object" || parsed === null) throw new Error("not an object"); + const f = parsed as Partial; + if (typeof f.checkpoints !== "object" || f.checkpoints === null || Array.isArray(f.checkpoints)) { + throw new Error("checkpoints is not an object"); + } + if (typeof f.seen !== "object" || f.seen === null || Array.isArray(f.seen)) { + throw new Error("seen is not an object"); + } + if (!Array.isArray(f.gaps)) throw new Error("gaps is not an array"); + for (const cp of Object.values(f.checkpoints)) { + if (!isCheckpoint(cp)) throw new Error("a checkpoint row is malformed"); + } + for (const ids of Object.values(f.seen)) { + if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string")) { + throw new Error("a seen row is malformed"); + } + } + for (const gap of f.gaps) { + if (!isGapRecord(gap)) throw new Error("a gap row is malformed"); + } + this.data = { + version: 1, + checkpoints: f.checkpoints as Record, + seen: f.seen as Record, + gaps: f.gaps as GapRecord[], + }; + } catch (err) { + await this.quarantine(`is unparseable (${err instanceof Error ? err.message : String(err)})`); + } + } + + private async quarantine(why: string): Promise { + const quarantined = `${this.file}.corrupt-${new Date().toISOString().replace(/[:.]/g, "-")}`; + try { + await rename(this.file, quarantined); + console.error( + `[activity] WARNING: ingestion store ${this.file} ${why}; quarantined the original bytes to ${quarantined} and started empty. ` + + `Dedupe memory was reset — replays may re-emit already-streamed activity once.`, + ); + } catch (renameErr) { + console.error( + `[activity] WARNING: ingestion store ${this.file} ${why} and could not be quarantined ` + + `(${renameErr instanceof Error ? renameErr.message : String(renameErr)}); starting empty.`, + ); + } + } + + private persist(): Promise { + const run = this.writeChain.then(async () => { + await mkdir(dirname(this.file), { recursive: true }); + const tmp = `${this.file}.tmp-${process.pid}-${++this.writeSeq}`; + await writeFile(tmp, JSON.stringify(this.data, null, 2)); + await rename(tmp, this.file); + }); + this.writeChain = run.catch(() => {}); + return run; + } + + async checkpoint(source: string): Promise { + await this.load(); + return this.data.checkpoints[source] ?? null; + } + + async checkpoints(): Promise { + await this.load(); + return Object.values(this.data.checkpoints).sort((a, b) => a.source.localeCompare(b.source)); + } + + /** The persisted seen-id set for a source (dedupe memory). Read + * by callers that keep in-memory counters keyed to those ids — + * e.g. the live source's undated Kaneo sequence — so a restart + * can resume above every id already ingested (#3321). */ + async seenIds(source: string): Promise { + await this.load(); + return [...(this.data.seen[source] ?? [])]; + } + + async gaps(): Promise { + await this.load(); + return [...this.data.gaps].sort((a, b) => Date.parse(a.from) - Date.parse(b.from)); + } + + /** + * Ingest deliveries into the stream with dedupe + checkpointing. + * A delivery whose sourceId is already in the source's seen set is + * a duplicate: dropped, counted, never re-emitted (so replaying a + * delivery batch is a no-op). A delivery the stream rejects is NOT + * marked seen, so a later replay can retry it. The checkpoint and + * seen set persist before returning, so a restart resumes exactly + * here. + */ + /** Serialize whole ingest operations (Codex P2, PR #5141): the + * dedupe check and the stream append are a check-and-act pair, so + * two concurrent ingest calls carrying the same delivery must not + * both pass the seen check before either appends. The persist + * write chain alone does not prevent that — it serializes file + * writes, not this operation. A failed operation does not wedge + * the chain: later calls still run, and unappended deliveries stay + * unseen so a replay can retry them. */ + async ingest( + events: Pick, + deliveries: readonly ActivityDelivery[], + ): Promise<{ ingested: number; duplicates: number; failed: number; failedIds: string[] }> { + const run = this.ingestChain.then(() => this.ingestSerialized(events, deliveries)); + this.ingestChain = run.then( + () => {}, + () => {}, + ); + return run; + } + + private async ingestSerialized( + events: Pick, + deliveries: readonly ActivityDelivery[], + ): Promise<{ ingested: number; duplicates: number; failed: number; failedIds: string[] }> { + await this.load(); + let ingested = 0; + let duplicates = 0; + let failed = 0; + const failedIds: string[] = []; + let dirty = false; + for (const d of deliveries) { + const seen = (this.data.seen[d.source] ??= []); + const cp = (this.data.checkpoints[d.source] ??= { + source: d.source, + lastSourceId: null, + lastEventAt: null, + deliveries: 0, + duplicates: 0, + updatedAt: new Date().toISOString(), + }); + if (seen.includes(d.sourceId)) { + duplicates++; + cp.duplicates++; + cp.updatedAt = new Date().toISOString(); + dirty = true; + continue; + } + try { + // Stable id (#3322 v2 record contract): a persist failure queues + // the record in the retry outbox and rethrows; the replay of this + // delivery re-presents the same id and returns the landed record + // instead of appending a duplicate (the v1 rollback this replaces). + await events.record({ + id: `activity:${d.source}:${d.sourceId}`, + at: d.at, + actor: d.source, + kind: d.kind, + ref: d.ref, + summary: (d.link ? `${d.summary} — ${d.link}` : d.summary).slice(0, 500), + }); + } catch (err) { + failed++; + failedIds.push(d.sourceId); + console.error( + `[activity] WARNING: stream append failed for ${d.source} delivery ${d.sourceId} ` + + `(${err instanceof Error ? err.message : String(err)}); left unseen so a replay can retry it.`, + ); + continue; + } + seen.push(d.sourceId); + if (seen.length > SEEN_RETENTION_MAX) seen.splice(0, seen.length - SEEN_RETENTION_MAX); + cp.deliveries++; + cp.lastSourceId = d.sourceId; + if (!cp.lastEventAt || Date.parse(d.at) >= Date.parse(cp.lastEventAt)) cp.lastEventAt = d.at; + cp.updatedAt = new Date().toISOString(); + ingested++; + dirty = true; + } + if (dirty) await this.persist(); + return { ingested, duplicates, failed, failedIds }; + } + + /** Record (or extend) an open gap for a source window. An already + * open gap for the same source absorbs the window, so a continuing + * outage is one record, not a pile. */ + async recordGap(source: string, from: string, to: string): Promise { + await this.load(); + const open = this.data.gaps.find((g) => g.source === source && g.status === "open"); + if (open) { + if (Date.parse(from) < Date.parse(open.from)) open.from = from; + if (Date.parse(to) > Date.parse(open.to)) open.to = to; + await this.persist(); + return open; + } + const gap: GapRecord = { + id: `gap:${source}:${from}`, + source, + from, + to, + status: "open", + detectedAt: new Date().toISOString(), + }; + this.data.gaps.push(gap); + await this.persist(); + return gap; + } + + /** Flip a gap's status (backfill landed, or the window aged past + * any possible recovery). Unknown / already-resolved ids no-op. + * When the caller knows when the outage actually ended (`to`, + * Codex P2 on PR #5141), the gap's window extends to that moment + * before resolving: a gap recorded from failure timestamps alone + * otherwise reports a zero/short duration that understates the + * interruption, which ran until recovery, not until the last + * failed poll. */ + async resolveGap( + id: string, + status: Exclude, + to?: string, + ): Promise { + await this.load(); + const gap = 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; + gap.resolvedAt = new Date().toISOString(); + await this.persist(); + return gap; + } +} + +/** Ingestion for call sites that must never throw on it (page + * renders, board polls): failures are logged, never thrown — but + * the outcome is RETURNED, so a caller that holds state it may only + * discard once a delivery is durable (the live source's Kaneo + * baseline, Codex P2 on PR #5141) can check `failed` and retain + * the delivery for retry instead of dropping it. */ +export async function ingestActivity( + store: IngestionStore, + events: Pick, + deliveries: readonly ActivityDelivery[], +): Promise<{ ingested: number; duplicates: number; failed: number; failedIds: string[] }> { + if (!deliveries.length) return { ingested: 0, duplicates: 0, failed: 0, failedIds: [] }; + try { + return await store.ingest(events, deliveries); + } catch (err) { + console.error( + `[activity] WARNING: ingestion failed (${err instanceof Error ? err.message : String(err)}); ` + + `deliveries stay unseen and a later pass can retry them.`, + ); + return { ingested: 0, duplicates: 0, failed: deliveries.length, failedIds: deliveries.map((d) => d.sourceId) }; + } +} + +/** Keep watchdog gap records in sync with the current breaches: each + * breached input (`watchdog:`) has an open gap from its + * episode's since until now; an input that is no longer breached has + * its open gap resolved as backfilled (the aggregator's live + * re-derivation on recovery is the backfill pass for diagnoses). */ +export async function syncWatchdogGaps( + store: IngestionStore, + items: readonly TierItem[], + now: Date = new Date(), +): Promise { + const breached = new Set(items.map((i) => i.id)); + for (const item of items) { + await store.recordGap(item.id, item.since, now.toISOString()); + } + for (const gap of await store.gaps()) { + if (gap.status === "open" && gap.source.startsWith("watchdog:") && !breached.has(gap.source)) { + await store.resolveGap(gap.id, "backfilled", now.toISOString()); + } + } +} + +/** Serialize whole watchdog gap-sync passes in observation order + * (Codex P2, PR #5141 round 5). A pass is a multi-step + * reconciliation — record a gap per current breach, then resolve + * the open gaps whose breach is gone — and the store's write chain + * serializes only the individual persists, not the pass. Two + * passes started fire-and-forget from overlapping derivations can + * interleave: an older pass that observed breaches A and B pauses + * while persisting A, a newer healthy pass resolves A and + * finishes, and the older pass then creates B — an outage the + * newest observation says is over stays reported as open until + * some later derivation repairs it. Chaining the passes whole, in + * the order they were enqueued, makes the newest observation the + * last word. A failed pass does not wedge the chain. */ +export function createWatchdogGapSyncQueue(): ( + store: IngestionStore, + items: readonly TierItem[], + now?: Date, +) => Promise { + let chain: Promise = Promise.resolve(); + return (store, items, now) => { + const run = chain.then( + () => syncWatchdogGaps(store, items, now), + () => syncWatchdogGaps(store, items, now), + ); + chain = run.then( + () => {}, + () => {}, + ); + return run; + }; +} + +// -- rendering --------------------------------------------------------------- + +function esc(s: unknown): string { + return String(s ?? "") + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/"/g, """); +} + +/** Render gap records for the /events page: a gap is a hole in the + * history, stated as one — never smoothed into apparent coverage. */ +export function gapsHtml(gaps: readonly GapRecord[]): string { + if (!gaps.length) return `

No known activity gaps.

`; + const rows = gaps + .map( + (g) => + `${esc(g.source)}${esc(g.from)}${esc(g.to)}` + + `${esc(g.status)}${esc(g.detectedAt)}`, + ) + .join("\n"); + return ( + `

These windows are KNOWN HOLES in the activity history for their source — ` + + `the stream is not complete there, and nothing in it should be read as if it were.

` + + `` + + `${rows}
sourcefromtostatusdetected
` + ); +} + +/** Render the activity-source coverage table (#3321 documentation + * surface, kept next to the data it describes). */ +export function activityCoverageHtml(coverage: readonly ActivityCoverage[] = ACTIVITY_SOURCE_COVERAGE): string { + const rows = coverage + .map( + (c) => + `${esc(c.source)}${esc(c.status)}${esc(c.supported)}` + + `${esc(c.unsupported)}${esc(c.historical)}`, + ) + .join("\n"); + return ( + `` + + `${rows}
sourcestatussupportedunsupportedhistorical
` + ); +} diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 296e9db33b..45b36e2f2c 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -43,6 +43,7 @@ export interface Config { viewsFile: string; /** Cross-stack event log store (#1739) — one chronological stream. */ eventsFile: string; + activityFile: string; /** Durable identity-registry store (#906 §3), merged on every read. */ registryFile: string; /** Usage snapshot store (hub §4): a directory of monthly JSONL files. */ @@ -113,6 +114,7 @@ export function loadConfig(env: Record = process.env actionsFile: s(env.PM_AGG_ACTIONS_FILE, join(process.cwd(), "actions.json")), viewsFile: s(env.PM_AGG_VIEWS_FILE, join(process.cwd(), "views.json")), eventsFile: s(env.PM_AGG_EVENTS_FILE, join(process.cwd(), "events.json")), + activityFile: s(env.PM_AGG_ACTIVITY_FILE, join(process.cwd(), "activity-ingestion.json")), registryFile: s(env.PM_AGG_REGISTRY_FILE, join(process.cwd(), "registry.json")), snapshotsDir: s(env.PM_AGG_SNAPSHOTS_DIR, join(process.cwd(), "snapshots")), quotaViewFile: s( diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 699ffc5ef6..f00a427a06 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -21,6 +21,16 @@ import { commentKindCounts, CommentsStore, queuedComments, validateNewComment } import type { SavedView, ViewFilters, ViewItemLike } from "./views.ts"; import { ViewsStore, filtersFromQuery, itemMatchesView, ownerKey } from "./views.ts"; import { EventsStore, emitEvent } from "./events.ts"; +import { + IngestionStore, + WatchdogEpisodeStabilizer, + ingestActivity, + createWatchdogGapSyncQueue, + watchdogDeliveries, + activityCoverageHtml, + gapsHtml, + ACTIVITY_SOURCE_COVERAGE, +} from "./activity.ts"; import { RoadmapAnnotationsStore, validateNewRoadmapAnnotation } from "./roadmap-annotations.ts"; import { computeCoverage, @@ -153,6 +163,7 @@ async function coverageSnapshot( const actionsStore = new ActionsStore(cfg.actionsFile); const viewsStore = new ViewsStore(cfg.viewsFile); const eventsStore = new EventsStore(cfg.eventsFile); +const activityStore = new IngestionStore(cfg.activityFile); /** #1739: the event log's fire-and-forget sink for source-side * writers (orchestration publishes, registry merges). Never awaited, @@ -160,6 +171,54 @@ const eventsStore = new EventsStore(cfg.eventsFile); function recordStreamEvent(event: Parameters[1]): void { void emitEvent(eventsStore, event); } + +/** #3321: the activity-ingestion sink for the source-side writers + * (watchdog episodes, Kaneo board changes). 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 + * Kaneo baseline (Codex P2, PR #5141) — failed deliveries retain + * their cards' baseline entries so the next poll retries the same + * stable delivery ids, while acknowledged cards advance. */ +async function recordActivity( + deliveries: Parameters[2], +): Promise<{ failed: number; failedIds: string[] }> { + const result = await ingestActivity(activityStore, eventsStore, deliveries); + return { failed: result.failed, failedIds: result.failedIds }; +} + +/** #3321: the source-gap sink for the live source's polling gaps + * (Codex P2, PR #5141): a non-null `to` records (or extends) the + * open gap for the source; a null `to` is recovery — the open gap + * resolves as backfilled, since polling has resumed and the next + * diff lands against the preserved baseline. Never throws into the + * source's read path. */ +async function recordSourceGap(source: string, from: string, to: string | null): Promise { + try { + if (to !== null) { + await activityStore.recordGap(source, from, to); + return; + } + for (const gap of await activityStore.gaps()) { + if (gap.source === source && gap.status === "open") { + // Recovery happened now, not at the last failed poll: extend + // the gap window to the recovery moment as it resolves + // (Codex P2, PR #5141). + await activityStore.resolveGap(gap.id, "backfilled", new Date().toISOString()); + } + } + } catch (err) { + console.error( + `[activity] WARNING: source gap record failed for ${source}: ${err instanceof Error ? err.message : String(err)}`, + ); + } +} + +/** #3321: pins watchdog episodes to their first-observed `since` + * (Codex P2, PR #5141) — watchdogTierItems assigns `now` for + * several breach kinds, so without this the stream would gain a + * new "episode" on every attention render of one outage. */ +const watchdogEpisodes = new WatchdogEpisodeStabilizer(); async function hasStreamEvent(kind: string, ref: string): Promise { return eventsStore.has(kind, ref); } @@ -173,6 +232,9 @@ function pickSource(): Source { standingAuto: async () => effectiveStandingAuto(await actionsStore.all()).standingAuto, onEvent: recordStreamEvent, hasEvent: hasStreamEvent, + onActivity: recordActivity, + onSourceGap: recordSourceGap, + seenActivityIds: (source) => activityStore.seenIds(source), }) : fixtureSource(); } @@ -442,6 +504,12 @@ async function searchContext(query: string) { return { query, results: searchWork(board, rows, items, query), items }; } +// #3321: watchdog gap-sync passes run whole and in observation +// order through this queue (Codex P2, PR #5141 round 5) — see +// createWatchdogGapSyncQueue in activity.ts for why the bare +// fire-and-forget sync interleaved. +const enqueueWatchdogGapSync = createWatchdogGapSyncQueue(); + // #1148: the watchdog derives NEEDS ORCHESTRATOR items from the // current diagnoses (feed age + probes via the health assembly — // its probe cache keeps this cheap — plus the orchestration @@ -454,7 +522,7 @@ async function searchContext(query: string) { async function deriveWatchdogItems(diagnosis?: ReturnType>["orchestration"]) { if (cfg.source !== "live") return []; const health = await healthContext(false); - return watchdogTierItems({ + const items = watchdogTierItems({ now: Date.now(), feedAgeMs: health.feed.ageMs, feedGeneratedAt: health.feed.generatedAt, @@ -470,6 +538,19 @@ async function deriveWatchdogItems(diagnosis?: ReturnType { + console.error( + `[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`, + ); + }); + return items; } async function attentionContext(opts: { census?: boolean } = {}) { @@ -1056,9 +1137,21 @@ async function handler(req: Request): Promise { `

Events

` + `` + - `${rows}
atactorkindrefsummary
`, + `${rows}` + + `

Activity gaps

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

Activity source coverage

` + + activityCoverageHtml() + + ``, ); } + if (path === "/api/activity.json") { + // #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 }); + } if (path === "/api/views.json") { // #1276: the saved views, per owner (?owner=:) or all. const owner = url.searchParams.get("owner"); diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index d2b87523b2..9bc9a0f277 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -25,6 +25,12 @@ import { import type { RepoCensus } from "../coverage.ts"; import { isSessionRecord, mergeRecords, recordFromSessionEntry } from "../registry.ts"; import type { NewStreamEvent } from "../events.ts"; +import { + kaneoChangeDeliveries, + maxUndatedSeqByCard, + type ActivityDelivery, + type KaneoCardSnapshot, +} from "../activity.ts"; import { isRecord } from "../validate.ts"; import { buildAttentionFlags } from "../derive.ts"; import { summarizeDns } from "../dns.ts"; @@ -161,9 +167,16 @@ async function kaneoProjects( })); } -async function kaneoBoard(cfg: Config, cookie: string): Promise { +async function kaneoBoard(cfg: Config, cookie: string): Promise<{ items: BoardItem[]; complete: boolean }> { const projects = await kaneoProjects(cfg, cookie); const out: BoardItem[] = []; + // #3321 (Codex P2, PR #5141): a poll is only `complete` when every + // project page read succeeded. A failed page breaks that project's + // loop and serves what was read, but the result is partial: cards + // from the failed reads are missing, so the caller must not treat + // the result as a full snapshot (activity diffing / baseline + // replacement) until a complete poll lands. + let complete = true; // A task read that fails on every project is a failed fetch, not a // successfully empty board (Codex review, PR #2430): board() must // reach its catch path and serve fixtures with that provenance, @@ -174,7 +187,10 @@ async function kaneoBoard(cfg: Config, cookie: string): Promise { const all: KaneoColumn[] = []; for (let page = 1; ; page++) { const r = await getJson(`${cfg.kaneo.baseUrl}/api/task/tasks/${p.id}?page=${page}`, { Cookie: cookie }); - if (!r.ok) break; + if (!r.ok) { + complete = false; + break; + } anyTaskPageRead = true; const body = r.json as { data?: { columns?: KaneoColumn[] }; pagination?: { totalPages: number } }; const cols = body.data?.columns ?? []; @@ -224,7 +240,7 @@ async function kaneoBoard(cfg: Config, cookie: string): Promise { } } if (projects.length > 0 && !anyTaskPageRead) throw new Error("kaneo task reads failed for every project"); - return applyBoardDonePolicy(out); + return { items: applyBoardDonePolicy(out), complete }; } // --- Grist -------------------------------------------------------------- @@ -672,6 +688,26 @@ export function liveSource( standingAuto?: () => Promise; onEvent?: (event: NewStreamEvent) => void; hasEvent?: (kind: string, ref: string) => Promise; + // The handler's return is the ingestion acknowledgment (#3321, + // Codex P2 on PR #5141): `false`, or a result with failed > 0, + // means the deliveries are NOT durable and the board baseline + // must be retained so the next poll retries them. A handler + // returning void is treated as acknowledged (legacy callers). + onActivity?: ( + deliveries: ActivityDelivery[], + ) => Promise | boolean | { failed: number; failedIds?: string[] } | void; + // Kaneo polling-gap sink (#3321, Codex P2 on PR #5141): called + // with (source, gapFrom, failureTime) while polls are failing or + // partial, and with (source, gapFrom, null) on the first complete + // poll after a gap, so the server can record the missed interval + // as an activity gap and resolve it on recovery. + onSourceGap?: (source: string, from: string, to: string | null) => Promise | void; + // Persisted ingestion seen-ids reader (#3321, Codex P2 on PR + // #5141): on the first complete poll the live source seeds its + // in-memory undated Kaneo sequence counters from the ids the + // ingestion store has already persisted, so a restart cannot + // reissue an undated delivery id that dedupe would discard. + seenActivityIds?: (source: string) => Promise | readonly string[]; }, ): Source { const fix = fixtureSource(); @@ -694,6 +730,131 @@ export function liveSource( // surfaces (Source.diagnostics) read it from here, never from a // null section, so absent/invalid/stale stay distinguishable. let lastOrchestrationDiagnosis: SectionDiagnosis = { state: "absent" }; + // #3321: the previous board poll's Kaneo cards, for change diffing. + // In-memory on purpose: a restart re-baselines silently, and the + // ingestion store's persisted seen set is the durable dedupe. + let prevKaneoCards: Map | null = null; + // #3321: per-card ingested-transition counters (the `seq` on + // KaneoCardSnapshot), kept outside the snapshot map so a card that + // leaves the board and later reappears resumes its count instead + // of restarting at a colliding undated delivery id. A card's count + // only advances when its change delivery is acknowledged. + const kaneoCardSeq = new Map(); + // #3321: when the current Kaneo polling gap opened (first failed + // or partial poll), or null when polls are healthy. + let kaneoGapFrom: string | null = null; + async function noteKaneoGap(at: Date): Promise { + if (!kaneoGapFrom) kaneoGapFrom = at.toISOString(); + if (!opts?.onSourceGap) return; + try { + await opts.onSourceGap("kaneo", kaneoGapFrom, at.toISOString()); + } catch (err) { + console.error( + `[activity] WARNING: kaneo gap record failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + // #3321: whether this process has already sent a gap-recovery + // reconciliation. A gap recorded just before a restart is open in + // the persisted store but invisible to this process (kaneoGapFrom + // starts null), so the FIRST complete poll after startup reports + // recovery even with no in-memory gap — the server's sink resolves + // every open gap for the source — and later healthy polls do not + // repeat it (Codex P2, PR #5141). + let kaneoGapReconciled = false; + async function noteKaneoRecovered(): Promise { + const from = kaneoGapFrom; + if (!from && kaneoGapReconciled) return; + kaneoGapReconciled = true; + kaneoGapFrom = null; + if (!opts?.onSourceGap) return; + try { + // On the startup reconciliation there is no in-memory gap, so + // `from` is empty; the sink resolves open gaps by source when + // `to` is null and does not use `from`. + await opts.onSourceGap("kaneo", from ?? "", null); + } catch (err) { + console.error( + `[activity] WARNING: kaneo gap recovery record failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + // #3321: seed the undated sequence counters from the ingestion + // store's persisted seen ids, once, before the first diff. The + // counters are in-memory; without this a restarted process starts + // them at zero and its next undated transition reuses an id the + // store already saw, so dedupe silently discards a genuine change + // (Codex P2, PR #5141). Seeding only ever raises a counter. + let kaneoSeqSeeded = false; + async function seedKaneoSeqFromPersisted(): Promise { + if (kaneoSeqSeeded || !opts?.seenActivityIds) return; + try { + const ids = await opts.seenActivityIds("kaneo"); + for (const [cardId, seq] of maxUndatedSeqByCard(ids)) { + if (seq > (kaneoCardSeq.get(cardId) ?? 0)) kaneoCardSeq.set(cardId, seq); + } + kaneoSeqSeeded = true; + } catch (err) { + console.error( + `[activity] WARNING: kaneo seq seeding from persisted seen ids failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + /** Advance the Kaneo baseline to `cards` (whose `seq` fields carry + * the pre-change counters): bump the stored counter for every card + * that appeared or changed status vs the old baseline, keep it for + * unchanged cards. Only call once the change deliveries for this + * transition are acknowledged durable — or when there were none. */ + function advanceKaneoBaseline(cards: readonly KaneoCardSnapshot[], retain?: ReadonlySet): void { + const next = new Map(); + for (const c of cards) { + // Partial ingestion failure (Codex P2, PR #5141): a card whose + // delivery was NOT acknowledged keeps its previous baseline + // entry (and its seq counter), so the next poll re-diffs exactly + // that card with the same stable delivery ids; acknowledged + // cards advance normally, so their later moves are never lost + // behind another card's retry. + if (retain?.has(c.id)) { + const before = prevKaneoCards?.get(c.id); + if (before) next.set(c.id, before); + continue; + } + const before = prevKaneoCards?.get(c.id); + const changed = !before || before.status !== c.status; + const seq = changed ? (c.seq ?? 0) + 1 : (c.seq ?? 0); + if (changed) kaneoCardSeq.set(c.id, seq); + next.set(c.id, { ...c, seq: kaneoCardSeq.get(c.id) ?? seq }); + } + prevKaneoCards = next; + } + // #3321: serialize the whole diff -> ingest -> baseline-advance + // sequence across board() calls (Codex P2, PR #5141). board() + // callers (boardContext, searchContext, page renders) run + // concurrently; while one poll awaits its ingestion acknowledgment + // the shared baseline must not be read by a second poll, or that + // poll diffs against the pre-change baseline and derives + // deliveries for a transition that never happened (A->C instead + // of B->C). A failed step does not wedge the chain. + let kaneoIngestionChain: Promise = Promise.resolve(); + function enqueueKaneoIngestion(fn: () => Promise): Promise { + const run = kaneoIngestionChain.then(fn, fn); + kaneoIngestionChain = run.then( + () => {}, + () => {}, + ); + return run; + } + // #3321: gap transitions take the SAME chain (Codex P2, PR #5141 + // round 4). A failed or partial poll that notes its gap immediately + // can interleave with a complete poll already queued behind a + // blocked ingestion: the queued poll's recovery then resolves a + // gap that opened AFTER its successful observation, marking an + // ongoing outage backfilled with no successful poll since the + // failure. Queuing the gap behind the ingestion orders every + // gap/recovery transition by the poll that produced it. + function enqueueKaneoGap(at: Date): Promise { + return enqueueKaneoIngestion(() => noteKaneoGap(at)); + } // #1739: the last orchestration run whose publish was recorded in // the event log, plus its tier membership — a new runId is a publish // step, and the tier diff between successive publishes is the @@ -848,8 +1009,109 @@ export function liveSource( return { async board() { try { - const cookie = await kaneoCookie(); - const board = await kaneoBoard(cfg, cookie); + // A failed Kaneo poll (auth or task reads) is an activity + // gap, not just a fixtures fallback (#3321, Codex P2 on + // PR #5141): record the missed interval via onSourceGap + // before rethrowing into the fixtures path below. + let cookie: string; + let kaneoResult: { items: BoardItem[]; complete: boolean }; + try { + cookie = await kaneoCookie(); + kaneoResult = await kaneoBoard(cfg, cookie); + } catch (err) { + await enqueueKaneoGap(new Date()); + throw err; + } + const board = kaneoResult.items; + // #3321: Kaneo activity ingestion — diff this poll against the + // previous one and hand the changes to the server's ingestion + // hook. The first poll after start is a silent baseline (no + // deliveries): pre-start changes are not claimed as history, + // and dedupe lives in the ingestion store, so re-diffs of the + // same change never re-emit. Fire-and-forget like onEvent. + if (!kaneoResult.complete) { + // Partial poll (#3321, Codex P2 on PR #5141): cards from + // the failed reads are missing, so diffing would invent + // appearance events for them when the reads recover, and + // replacing the baseline would lose their last known + // state. Skip diffing AND baseline replacement, and record + // the poll as an activity gap; the next complete poll + // diffs against the preserved baseline. + console.error( + "[activity] WARNING: kaneo board poll was partial; activity diff skipped and baseline preserved", + ); + await enqueueKaneoGap(new Date()); + } else { + await enqueueKaneoIngestion(async () => { + await seedKaneoSeqFromPersisted(); + await noteKaneoRecovered(); + try { + const cards: KaneoCardSnapshot[] = board + .filter((b) => b.source === "kaneo") + .map((b) => ({ + id: b.id, + status: b.status, + title: b.title, + seq: kaneoCardSeq.get(b.id) ?? prevKaneoCards?.get(b.id)?.seq ?? 0, + ...(b.updatedAt ? { updatedAt: b.updatedAt } : {}), + ...(b.kaneoUrl ? { kaneoUrl: b.kaneoUrl } : {}), + })); + if (!prevKaneoCards) { + // First poll: silent baseline, no deliveries, and the + // seq counters do not advance (nothing was ingested). + prevKaneoCards = new Map(cards.map((c) => [c.id, c])); + } else if (opts?.onActivity) { + const deliveries = kaneoChangeDeliveries(prevKaneoCards, cards); + if (!deliveries.length) { + advanceKaneoBaseline(cards); + } else { + // Await the ingestion acknowledgment before + // discarding the previous snapshot (Codex P2, + // PR #5141): if the append failed, the baseline — + // and the seq counters — stay put, so the next poll + // re-diffs the same change with the same stable + // delivery ids and the ingestion store can retry it + // (deliveries it did persist dedupe as duplicates). + const ack = await opts.onActivity(deliveries); + const failed = + ack === false + ? deliveries.length + : typeof ack === "object" && ack !== null + ? (ack.failed ?? 0) + : 0; + const failedIds = + typeof ack === "object" && ack !== null && Array.isArray(ack.failedIds) ? ack.failedIds : null; + if (failed === 0) { + advanceKaneoBaseline(cards); + } else if (failedIds) { + // Advance every acknowledged card; retain only the + // failed deliveries' cards for retry (Codex P2, + // PR #5141). + const failedCards = new Set( + deliveries.filter((d) => failedIds.includes(d.sourceId)).map((d) => d.ref), + ); + console.error( + `[activity] WARNING: ${failed} kaneo deliveries were not ingested; ` + + "baseline retained for the failed cards only, so the next poll retries them", + ); + advanceKaneoBaseline(cards, failedCards); + } else { + console.error( + `[activity] WARNING: ${failed} kaneo deliveries were not ingested; ` + + "board baseline retained so the next poll retries them", + ); + } + } + } else { + advanceKaneoBaseline(cards); + } + } catch (err) { + console.error( + `[activity] WARNING: kaneo change diff failed: ${err instanceof Error ? err.message : String(err)}`, + ); + } + }); + } // A successfully fetched board is live data even when the // done policy (#1146) filters it to empty: falling through to // fixtures would replace the real (empty) board with diff --git a/pm-stack/aggregator/test/activity-3321.test.ts b/pm-stack/aggregator/test/activity-3321.test.ts new file mode 100644 index 0000000000..5eff3152d9 --- /dev/null +++ b/pm-stack/aggregator/test/activity-3321.test.ts @@ -0,0 +1,351 @@ +// #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). +import { describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + ACTIVITY_SOURCE_COVERAGE, + IngestionStore, + WatchdogEpisodeStabilizer, + activityCoverageHtml, + createWatchdogGapSyncQueue, + gapsHtml, + ingestActivity, + kaneoChangeDeliveries, + maxUndatedSeqByCard, + syncWatchdogGaps, + watchdogDeliveries, + type ActivityDelivery, + type KaneoCardSnapshot, +} from "../src/activity.ts"; +import { EventsStore } from "../src/events.ts"; +import type { TierItem } from "../src/model.ts"; + +function tmpStores(): { eventsFile: string; activityFile: string; events: EventsStore; store: IngestionStore } { + const dir = mkdtempSync(join(tmpdir(), "agg-activity-")); + const eventsFile = join(dir, "events.json"); + const activityFile = join(dir, "activity.json"); + return { eventsFile, activityFile, events: new EventsStore(eventsFile), store: new IngestionStore(activityFile) }; +} + +const iso = (msAgo: number) => new Date(Date.now() - msAgo).toISOString(); + +function watchdogItem(id: string, sinceMsAgo: number, title = "Watchdog: fleet feed is stale"): TierItem { + return { + id, + kind: "gap", + title, + source: "watchdog", + state: "watchdog: feed stale", + reason: "test", + since: iso(sinceMsAgo), + lastSeenAt: iso(0), + ref: "developing-today/code#1148", + recommendedAction: "test", + }; +} + +const kaneoCard = (id: string, status: string, updatedMsAgo = 60_000): KaneoCardSnapshot => ({ + id, + status, + title: `Card ${id}`, + updatedAt: iso(updatedMsAgo), + kaneoUrl: `https://kaneo.security.cab/dashboard/workspace/ws/project/p/task/${id}`, +}); + +describe("activity writers (#3321)", () => { + test("watchdog deliveries carry stable per-episode source ids", () => { + const item = watchdogItem("watchdog:fleet-feed", 300_000); + const [d] = watchdogDeliveries([item]); + expect(d?.source).toBe("watchdog"); + expect(d?.kind).toBe("watchdog-event"); + expect(d?.ref).toBe("watchdog:fleet-feed"); + expect(d?.sourceId).toBe(`watchdog:fleet-feed@${item.since}`); + // Same episode re-derived -> identical delivery (dedupe can work). + expect(watchdogDeliveries([item])[0]?.sourceId).toBe(d?.sourceId); + }); + + test("kaneo diff: appearance and status change emit; unchanged is silent", () => { + const a = kaneoCard("kaneo:p/t1", "in-progress"); + const b = kaneoCard("kaneo:p/t2", "todo"); + const prev = new Map([[a.id, a]]); + const moved = { ...a, status: "in-review", updatedAt: iso(30_000) }; + const deliveries = kaneoChangeDeliveries(prev, [moved, b]); + expect(deliveries.map((d) => d.kind)).toEqual(["kaneo-change", "kaneo-change"]); + expect(deliveries[0]?.summary).toContain("in-progress -> in-review"); + expect(deliveries[0]?.link).toContain("kaneo.security.cab"); + expect(deliveries[1]?.summary).toContain("appeared"); + expect(kaneoChangeDeliveries(new Map([[a.id, a]]), [a])).toEqual([]); + }); +}); + +describe("codex findings on PR #5141 (#3321)", () => { + test("watchdog stabilizer pins an episode to its first-observed since until it clears", () => { + const stab = new WatchdogEpisodeStabilizer(); + const first = stab.stabilize([watchdogItem("watchdog:fleet-feed", 300_000)]); + // A later derivation of the SAME breach carries a different + // (now-based) since; the delivery id must not move. + const laterItem = { ...watchdogItem("watchdog:fleet-feed", 60_000) }; + const second = stab.stabilize([laterItem]); + expect(second[0]?.since).toBe(first[0]?.since); + expect(watchdogDeliveries(second)[0]?.sourceId).toBe(watchdogDeliveries(first)[0]?.sourceId); + // The episode clears; a genuinely new episode gets its own id. + stab.stabilize([]); + const third = stab.stabilize([laterItem]); + expect(third[0]?.since).toBe(laterItem.since); + }); + + test("undated kaneo transitions get per-transition ids; a re-diff keeps its id", () => { + const undated = (status: string, seq: number): KaneoCardSnapshot => ({ + id: "kaneo:p/t1", + status, + title: "Card t1", + seq, + }); + // in-progress (seq 0) -> in-review: first undated transition. + const d1 = kaneoChangeDeliveries(new Map([["kaneo:p/t1", undated("in-progress", 0)]]), [ + undated("in-review", 0), + ]); + // Re-diffing the same observed transition (retry after a failed + // append, baseline not advanced) reproduces the same id. + const retry = kaneoChangeDeliveries(new Map([["kaneo:p/t1", undated("in-progress", 0)]]), [ + undated("in-review", 0), + ]); + expect(retry[0]?.sourceId).toBe(d1[0]?.sourceId); + // The cycle continues: in-review (seq 1) -> in-progress -> in-review. + const d2 = kaneoChangeDeliveries(new Map([["kaneo:p/t1", undated("in-review", 1)]]), [ + undated("in-progress", 1), + ]); + const d3 = kaneoChangeDeliveries(new Map([["kaneo:p/t1", undated("in-progress", 2)]]), [ + undated("in-review", 2), + ]); + expect(d2[0]?.sourceId).not.toBe(d1[0]?.sourceId); + // Same from->to as d1, but a distinct real transition: new id. + expect(d3[0]?.sourceId).not.toBe(d1[0]?.sourceId); + expect(d1[0]?.sourceId).toContain("undated:1"); + expect(d3[0]?.sourceId).toContain("undated:3"); + }); + + test("concurrent ingestion of the same delivery ingests it exactly once", async () => { + const { events, store } = tmpStores(); + const deliveries = watchdogDeliveries([watchdogItem("watchdog:registry", 120_000)]); + let records = 0; + const slow = { + record: async (e: Parameters[0]) => { + records++; + await new Promise((r) => setTimeout(r, 25)); + return events.record(e); + }, + }; + const [a, b] = await Promise.all([store.ingest(slow, deliveries), store.ingest(slow, deliveries)]); + expect(records).toBe(1); + expect(a.ingested + b.ingested).toBe(1); + expect(a.duplicates + b.duplicates).toBe(1); + expect(await events.list()).toHaveLength(1); + }); + + test("ingestActivity reports failed appends so callers can retain deliveries", async () => { + const { store } = tmpStores(); + const deliveries = watchdogDeliveries([watchdogItem("watchdog:registry", 60_000)]); + const failing = { + record: async () => { + throw new Error("disk full"); + }, + }; + const result = await ingestActivity(store, failing, deliveries); + expect(result.failed).toBe(1); + expect(result.ingested).toBe(0); + }); +}); + +describe("undated seq seeding (#3321, PR #5141 codex round 2)", () => { + test("maxUndatedSeqByCard parses appeared and status ids, ignores dated ones", () => { + const m = maxUndatedSeqByCard([ + "card-a:appeared:undated:2", + "card-a:status:in-progress->in-review:undated:5", + "card-a:status:in-review->in-progress:undated:3", + "card-b:status:in-progress->in-review:2026-11-03T00:00:00.000Z", + "watchdog:episode-1", + ]); + expect(m.get("card-a")).toBe(5); + expect(m.has("card-b")).toBe(false); + expect(m.size).toBe(1); + }); + + test("seenIds returns the persisted set per source after a restart", async () => { + const { activityFile, events, store } = tmpStores(); + const delivery: ActivityDelivery = { + source: "kaneo", + sourceId: "card-a:status:in-progress->in-review:undated:1", + at: iso(0), + kind: "kaneo-change", + ref: "card-a", + summary: "moved", + }; + await ingestActivity(store, events, [delivery]); + const restarted = new IngestionStore(activityFile); + expect(await restarted.seenIds("kaneo")).toEqual([delivery.sourceId]); + expect(await restarted.seenIds("watchdog")).toEqual([]); + expect(maxUndatedSeqByCard(await restarted.seenIds("kaneo")).get("card-a")).toBe(1); + }); +}); + +describe("ingestion store (#3321)", () => { + test("duplicate delivery replay is a no-op; checkpoint counts both", async () => { + const { events, store } = tmpStores(); + const deliveries = watchdogDeliveries([watchdogItem("watchdog:fleet-feed", 120_000)]); + const first = await store.ingest(events, deliveries); + expect(first).toEqual({ ingested: 1, duplicates: 0, failed: 0, failedIds: [] }); + const second = await store.ingest(events, deliveries); + expect(second).toEqual({ ingested: 0, duplicates: 1, failed: 0, failedIds: [] }); + const stream = await events.list(); + expect(stream).toHaveLength(1); + expect(stream[0]?.kind).toBe("watchdog-event"); + const cp = await store.checkpoint("watchdog"); + expect(cp?.deliveries).toBe(1); + expect(cp?.duplicates).toBe(1); + expect(cp?.lastSourceId).toBe(deliveries[0]?.sourceId); + }); + + test("restart resumes from the persisted checkpoint: replay stays duplicate", async () => { + const { eventsFile, activityFile, events, store } = tmpStores(); + const deliveries: ActivityDelivery[] = [ + { + source: "kaneo", + sourceId: "kaneo:p/t1:appeared:stamp-1", + at: iso(90_000), + kind: "kaneo-change", + ref: "kaneo:p/t1", + summary: "Kaneo card appeared in in-progress: Card t1", + link: "https://kaneo.security.cab/x", + }, + ]; + await store.ingest(events, deliveries); + // Fresh store instances over the same files = a process restart. + const store2 = new IngestionStore(activityFile); + const events2 = new EventsStore(eventsFile); + const replay = await store2.ingest(events2, deliveries); + expect(replay).toEqual({ ingested: 0, duplicates: 1, failed: 0, failedIds: [] }); + expect(await events2.list()).toHaveLength(1); + const cp = await store2.checkpoint("kaneo"); + expect(cp?.deliveries).toBe(1); + expect(cp?.lastSourceId).toBe("kaneo:p/t1:appeared:stamp-1"); + }); + + test("a failed stream append is not marked seen, so a replay retries it", async () => { + const { events, store } = tmpStores(); + const deliveries = watchdogDeliveries([watchdogItem("watchdog:registry", 60_000)]); + const failing = { + record: async () => { + throw new Error("disk full"); + }, + }; + const first = await store.ingest(failing, deliveries); + expect(first).toEqual({ ingested: 0, duplicates: 0, failed: 1, failedIds: [deliveries[0]!.sourceId] }); + const retry = await store.ingest(events, deliveries); + expect(retry).toEqual({ ingested: 1, duplicates: 0, failed: 0, failedIds: [] }); + }); + + test("gap lifecycle end-to-end: outage opens a rendered hole, backfill flips it", async () => { + const { store } = tmpStores(); + const from = iso(3_600_000); + const to = iso(1_800_000); + const gap = await store.recordGap("kaneo", from, to); + expect(gap.status).toBe("open"); + // A continuing outage extends the SAME open gap, never a second one. + const extended = await store.recordGap("kaneo", from, iso(900_000)); + expect(extended.id).toBe(gap.id); + expect((await store.gaps()).filter((g) => g.source === "kaneo")).toHaveLength(1); + let html = gapsHtml(await store.gaps()); + expect(html).toContain("KNOWN HOLES"); + expect(html).toContain("open"); + // Backfill lands -> status flips, and the render says so. + const resolved = await store.resolveGap(gap.id, "backfilled"); + expect(resolved?.status).toBe("backfilled"); + html = gapsHtml(await store.gaps()); + expect(html).toContain("backfilled"); + }); + + test("resolveGap extends the gap window to the recovery time (PR #5141 codex)", async () => { + const { store } = tmpStores(); + const gap = await store.recordGap("kaneo", iso(3_600_000), iso(1_800_000)); + const recoveredAt = iso(60_000); + const resolved = await store.resolveGap(gap.id, "backfilled", recoveredAt); + expect(resolved?.status).toBe("backfilled"); + // The outage ran until recovery, not until the last failed poll: + // the resolved window ends at the recovery moment. + expect(resolved?.to).toBe(recoveredAt); + // An earlier `to` never shrinks the window. + const gap2End = iso(900_000); + const gap2 = await store.recordGap("watchdog:x", iso(3_600_000), gap2End); + const resolved2 = await store.resolveGap(gap2.id, "backfilled", iso(1_800_000)); + expect(resolved2?.to).toBe(gap2End); + }); + + test("watchdog gap sync: breach opens a gap, recovery resolves it as backfilled", async () => { + const { store } = tmpStores(); + const item = watchdogItem("watchdog:fleet-feed", 600_000); + await syncWatchdogGaps(store, [item], new Date()); + let gaps = await store.gaps(); + expect(gaps).toHaveLength(1); + expect(gaps[0]?.source).toBe("watchdog:fleet-feed"); + expect(gaps[0]?.status).toBe("open"); + expect(gaps[0]?.from).toBe(item.since); + await syncWatchdogGaps(store, [], new Date()); + gaps = await store.gaps(); + expect(gaps[0]?.status).toBe("backfilled"); + expect(gaps[0]?.resolvedAt).toBeTruthy(); + }); + + test("watchdog gap sync queue: an older overlapping pass cannot resurrect a gap the newest pass resolved (PR #5141 codex round 5)", async () => { + const { store } = tmpStores(); + const itemA = watchdogItem("watchdog:a", 600_000); + const itemB = watchdogItem("watchdog:b", 600_000); + // Gate the older pass mid-reconciliation: its second recordGap + // waits until the test releases it. Without the queue, the + // newer healthy pass would run inside that window — resolving + // A and finishing — and the older pass would then create B, + // leaving an outage the newest observation says is over still + // reported open. + let releaseB: () => void = () => {}; + const gateB = new Promise((resolve) => { + releaseB = resolve; + }); + let recordCalls = 0; + const realRecord = store.recordGap.bind(store); + store.recordGap = async (source: string, from: string, to: string) => { + recordCalls += 1; + if (recordCalls === 2) await gateB; + return realRecord(source, from, to); + }; + const enqueue = createWatchdogGapSyncQueue(); + const older = enqueue(store, [itemA, itemB], new Date()); + const newer = enqueue(store, [], new Date()); + // Wait until the older pass is provably parked on B's record, + // then release it; the newer pass may only run after it. + for (let i = 0; i < 200 && recordCalls < 2; i += 1) { + await new Promise((r) => setTimeout(r, 10)); + } + expect(recordCalls).toBe(2); + releaseB(); + await Promise.all([older, newer]); + const gaps = await store.gaps(); + expect(gaps.map((g) => g.source).sort()).toEqual(["watchdog:a", "watchdog:b"]); + expect(gaps.filter((g) => g.status === "open")).toHaveLength(0); + expect(gaps.every((g) => g.status === "backfilled")).toBe(true); + }); + + test("coverage documents github as unsupported pending #2072", () => { + const github = ACTIVITY_SOURCE_COVERAGE.find((c) => c.source === "github"); + expect(github?.status).toBe("unsupported"); + expect(github?.unsupported).toContain("#2072"); + const html = activityCoverageHtml(); + expect(html).toContain("watchdog"); + expect(html).toContain("kaneo"); + expect(html).toContain("unsupported"); + }); +}); diff --git a/pm-stack/aggregator/test/activity-live-3321.test.ts b/pm-stack/aggregator/test/activity-live-3321.test.ts new file mode 100644 index 0000000000..702d8145a2 --- /dev/null +++ b/pm-stack/aggregator/test/activity-live-3321.test.ts @@ -0,0 +1,374 @@ +// #3321 (Codex P2s on PR #5141): live-source Kaneo activity discipline — +// deliveries are retained until ingestion is acknowledged, partial +// board polls neither diff nor replace the baseline, and polling +// failures/recoveries are reported as activity gaps. +import { describe, expect, test } from "bun:test"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadConfig } from "../src/config.ts"; +import { liveSource } from "../src/sources/live.ts"; +import type { ActivityDelivery } from "../src/activity.ts"; + +const FEED = { + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], +}; + +interface HarnessState { + // projectId -> columnId for the single test card in that project + cardStatus: Record; + failProjects: Set; // task reads 500 for these projects + failAll: boolean; +} + +async function makeSource( + state: HarnessState, + opts: { + onActivity?: (d: ActivityDelivery[]) => Promise | boolean | { failed: number; failedIds?: string[] }; + onSourceGap?: (source: string, from: string, to: string | null) => void; + seenActivityIds?: (source: string) => Promise | readonly string[]; + }, +) { + const dir = await mkdtemp(join(tmpdir(), "pm-activity-live-")); + const feedFile = join(dir, "fleet-feed.json"); + await writeFile(feedFile, JSON.stringify(FEED)); + const projectsFile = join(dir, "kaneo-projects.json"); + await writeFile(projectsFile, JSON.stringify({ projects: [] })); + const cfg = loadConfig({ + ...Bun.env, + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_PROJECTOR_URL: "off", + PM_KANEO_PROJECTS_FILE: projectsFile, + KANEO_URL: "http://kaneo.test", + KANEO_ADMIN_EMAIL: "test@example.com", + KANEO_ADMIN_PASSWORD: "test-password", + }); + return liveSource(cfg, opts); +} + +function installFetch(state: HarnessState): () => void { + const realFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + const json = (body: unknown, headers: Record = {}) => + new Response(JSON.stringify(body), { + status: 200, + headers: { "Content-Type": "application/json", ...headers }, + }); + if (url.includes("/api/auth/sign-in/email")) return json({}, { "set-cookie": "session=test; Path=/" }); + if (url.includes("/api/workspace")) return json([{ id: "ws1" }]); + if (url.includes("/api/project?")) { + return json([ + { id: "p1", slug: "one", name: "One" }, + { id: "p2", slug: "two", name: "Two" }, + ]); + } + if (url.includes("/api/task/tasks/")) { + const pid = url.split("/api/task/tasks/")[1]!.split("?")[0]!; + if (state.failAll || state.failProjects.has(pid)) return new Response("boom", { status: 500 }); + const status = state.cardStatus[pid] ?? "in-progress"; + return json({ + data: { + columns: [ + { + id: status, + name: status, + // No updatedAt: the undated-card path is under test. + tasks: [{ id: `t-${pid}`, number: 7, title: `Card ${pid}`, status, externalLinks: [] }], + }, + ], + }, + pagination: { totalPages: 1 }, + }); + } + return new Response("not found", { status: 404 }); + }) as typeof fetch; + return () => { + globalThis.fetch = realFetch; + }; +} + +describe("live kaneo activity (#3321, PR #5141 codex)", () => { + test("unacknowledged deliveries are retried with the same id; the undated cycle advances seq", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const attempts: ActivityDelivery[][] = []; + let ack = false; + try { + const src = await makeSource(state, { + onActivity: async (d) => { + attempts.push(d); + return ack; + }, + }); + await src.board(); // baseline + state.cardStatus.p1 = "in-review"; + await src.board(); // ingestion fails (ack=false): baseline retained + expect(attempts).toHaveLength(1); + await src.board(); // retry: same change, same stable delivery id + expect(attempts).toHaveLength(2); + expect(attempts[1]![0]!.sourceId).toBe(attempts[0]![0]!.sourceId); + ack = true; + await src.board(); // retry now acknowledged: baseline advances + expect(attempts).toHaveLength(3); + state.cardStatus.p1 = "in-progress"; + await src.board(); + state.cardStatus.p1 = "in-review"; + await src.board(); + // attempts[0..2] are the first transition and its retries (same + // id by design); attempts[3] and attempts[4] are the next two + // transitions of the undated cycle and must be distinct from + // the first and from each other, with advancing seq stamps. + expect(attempts).toHaveLength(5); + const transitionIds = [attempts[2]![0]!.sourceId, attempts[3]![0]!.sourceId, attempts[4]![0]!.sourceId]; + expect(new Set(transitionIds).size).toBe(3); + expect(transitionIds[0]).toContain("undated:1"); + expect(transitionIds[1]).toContain("undated:2"); + expect(transitionIds[2]).toContain("undated:3"); + } finally { + restore(); + } + }); + + test("undated seq resumes above the persisted seen ids after a restart", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const seen: ActivityDelivery[] = []; + try { + // A previous process already ingested two undated transitions + // for card t-p1; the store's persisted seen set is the only + // memory of them. This process must not reissue undated:1. + const src = await makeSource(state, { + onActivity: async (d) => { + seen.push(...d); + return true; + }, + seenActivityIds: () => [ + "kaneo:one/t-p1:status:in-progress->in-review:undated:1", + "kaneo:one/t-p1:status:in-review->in-progress:undated:2", + "kaneo:two/t-p2:appeared:2026-11-03T00:00:00.000Z", + ], + }); + await src.board(); // baseline (seeds the counters) + expect(seen).toHaveLength(0); + state.cardStatus.p1 = "in-review"; + await src.board(); + expect(seen).toHaveLength(1); + expect(seen[0]!.sourceId).toContain("undated:3"); + } finally { + restore(); + } + }); + + test("a partial poll does not diff or replace the baseline", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const seen: ActivityDelivery[] = []; + try { + const src = await makeSource(state, { + onActivity: async (d) => { + seen.push(...d); + return true; + }, + }); + await src.board(); // baseline + // p2's read fails (partial poll) while p1's card moves. + state.failProjects.add("p2"); + state.cardStatus.p1 = "in-review"; + await src.board(); + expect(seen).toHaveLength(0); // no diff from a partial snapshot + // Reads recover: the preserved baseline still yields the change. + state.failProjects.clear(); + await src.board(); + expect(seen).toHaveLength(1); + expect(seen[0]!.summary).toContain("in-progress -> in-review"); + } finally { + restore(); + } + }); + + test("overlapping board polls serialize diffing: no A->C phantom transition (PR #5141 codex)", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const deliveries: ActivityDelivery[] = []; + let releaseFirst: (() => void) | null = null; + let firstCallSeen: (() => void) | null = null; + const firstCall = new Promise((r) => { firstCallSeen = r; }); + let calls = 0; + try { + const src = await makeSource(state, { + onActivity: async (d) => { + deliveries.push(...d); + calls++; + if (calls === 1) { + firstCallSeen!(); + await new Promise((r) => { releaseFirst = r; }); + } + return true; + }, + }); + await src.board(); // baseline: both cards in-progress + state.cardStatus.p1 = "in-review"; + const b1 = src.board(); // diffs in-progress -> in-review, then blocks in onActivity + await firstCall; + state.cardStatus.p1 = "in-progress"; + const b2 = src.board(); // fetches the return to in-progress while the first poll is still ingesting + releaseFirst!(); + await Promise.all([b1, b2]); + const p1Moves = deliveries.filter((d) => d.ref.includes("t-p1")).map((d) => d.summary); + // Serialized: the second poll diffed against the ADVANCED + // baseline, so history is in-progress -> in-review -> in-progress. + // Unserialized it would diff in-progress -> in-progress and + // derive no delivery at all for the second move. + expect(p1Moves.some((s) => s.includes("in-progress -> in-review"))).toBe(true); + expect(p1Moves.some((s) => s.includes("in-review -> in-progress"))).toBe(true); + expect(p1Moves).toHaveLength(2); + } finally { + restore(); + } + }); + + test("partial failure advances acknowledged cards only: the succeeded card's return move is not lost (PR #5141 codex)", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const attempts: ActivityDelivery[][] = []; + let failP2 = true; + try { + const src = await makeSource(state, { + onActivity: async (d) => { + attempts.push(d); + if (failP2) { + const p2 = d.filter((x) => x.ref.includes("t-p2")); + return { failed: p2.length, failedIds: p2.map((x) => x.sourceId) }; + } + return { failed: 0, failedIds: [] }; + }, + }); + await src.board(); // baseline: both cards in-progress + state.cardStatus.p1 = "in-review"; + state.cardStatus.p2 = "in-review"; + await src.board(); // both move; p2's delivery fails, p1's lands + expect(attempts).toHaveLength(1); + const p2FailedId = attempts[0]!.find((x) => x.ref.includes("t-p2"))!.sourceId; + // p1 returns before the next poll; p2 stays in-review. Because + // p1's baseline advanced, its return move diffs and emits; p2's + // retained baseline re-diffs its failed change with the same id. + state.cardStatus.p1 = "in-progress"; + failP2 = false; + await src.board(); + expect(attempts).toHaveLength(2); + const second = attempts[1]!; + const p1Return = second.find((x) => x.ref.includes("t-p1")); + expect(p1Return?.summary).toContain("in-review -> in-progress"); + const p2Retry = second.find((x) => x.ref.includes("t-p2")); + expect(p2Retry?.sourceId).toBe(p2FailedId); + // A third identical poll emits nothing: both baselines advanced. + await src.board(); + expect(attempts).toHaveLength(2); + } finally { + restore(); + } + }); + + test("polling failure opens a gap; the next complete poll reports recovery", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + const gaps: { source: string; from: string; to: string | null }[] = []; + try { + const src = await makeSource(state, { + onSourceGap: (source, from, to) => { + gaps.push({ source, from, to }); + }, + }); + await src.board(); // healthy baseline: exactly one startup gap + // reconciliation (to=null), so a gap persisted by a previous + // process that died mid-outage gets resolved by the server sink + expect(gaps).toHaveLength(1); + expect(gaps[0]!.source).toBe("kaneo"); + expect(gaps[0]!.to).toBeNull(); + state.failAll = true; // every task read fails -> fixtures fallback + await src.board(); + expect(gaps.length).toBeGreaterThan(1); + expect(gaps[1]!.source).toBe("kaneo"); + expect(gaps[1]!.to).not.toBeNull(); + state.failAll = false; + const beforeRecovery = gaps.length; + await src.board(); // recovery is reported with to=null + expect(gaps.length).toBe(beforeRecovery + 1); + expect(gaps[gaps.length - 1]!.to).toBeNull(); + await src.board(); // healthy again: the reconciliation does not repeat + expect(gaps.length).toBe(beforeRecovery + 1); + } finally { + restore(); + } + }); + + test("a gap noted behind a queued complete poll is not resolved by that poll (PR #5141 codex round 4)", async () => { + const state: HarnessState = { cardStatus: { p1: "in-progress", p2: "in-progress" }, failProjects: new Set(), failAll: false }; + const restore = installFetch(state); + // Counting wrapper: the queued complete poll (b1) has finished + // fetching once 6 task reads have been served (baseline 2 + + // blocked poll 2 + b1 2), so the failure flag can flip without + // failing b1's own reads. + let taskFetches = 0; + let resolveQueuedFetched: (() => void) | null = null; + const queuedFetched = new Promise((r) => { resolveQueuedFetched = r; }); + const mockFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown, init?: unknown) => { + const res = await (mockFetch as (i: unknown, i2?: unknown) => Promise)(input, init); + if (String(input).includes("/api/task/tasks/")) { + taskFetches++; + if (taskFetches === 6) resolveQueuedFetched!(); + } + return res; + }) as typeof fetch; + const gaps: { source: string; from: string; to: string | null }[] = []; + let releaseFirst: (() => void) | null = null; + let firstCallSeen: (() => void) | null = null; + const firstCall = new Promise((r) => { firstCallSeen = r; }); + let calls = 0; + try { + const src = await makeSource(state, { + onActivity: async () => { + calls++; + if (calls === 1) { + firstCallSeen!(); + await new Promise((r) => { releaseFirst = r; }); + } + return true; + }, + onSourceGap: (source, from, to) => { + gaps.push({ source, from, to }); + }, + }); + await src.board(); // baseline: startup reconciliation only + expect(gaps).toHaveLength(1); + state.cardStatus.p1 = "in-review"; + const b0 = src.board(); // diffs, then blocks in onActivity + await firstCall; + const b1 = src.board(); // complete poll: queues behind b0's ingestion + await queuedFetched; // b1 has fetched; its ingestion is queued + state.failAll = true; + const b2 = src.board(); // failing poll: its gap must queue behind b1 + await new Promise((r) => setTimeout(r, 25)); // let b2 reach its gap transition + releaseFirst!(); + await Promise.all([b0, b1, b2]); + // Serialized: b1's recovery ran BEFORE b2's gap existed, so the + // gap is still open — no recovery entry follows it. Unserialized + // (gap noted immediately), b1 would emit a recovery (to=null) + // after the gap and close an outage no poll has recovered from. + expect(gaps).toHaveLength(2); + expect(gaps[1]!.to).not.toBeNull(); + state.failAll = false; + await src.board(); // a genuinely later complete poll recovers it + expect(gaps).toHaveLength(3); + expect(gaps[2]!.to).toBeNull(); + } finally { + restore(); + } + }); +}); diff --git a/pm-stack/aggregator/test/events.test.ts b/pm-stack/aggregator/test/events.test.ts index 54d805ad24..98efae9bbd 100644 --- a/pm-stack/aggregator/test/events.test.ts +++ b/pm-stack/aggregator/test/events.test.ts @@ -43,6 +43,33 @@ describe("events store (#1739)", () => { expect(list[0]?.at).toBe(secondAt); }); + test("a failed append cannot duplicate on retry: a stable id replays to the single record (PR #5141 codex; mechanism superseded by #3322 v2)", async () => { + // The v1 mechanism (rolling the in-memory append back) was replaced + // when main landed the #3322 v2 record() (PR #5137): on a persist + // failure the record is queued in the durable retry outbox and kept + // in memory, and a caller-supplied stable id makes a retry return + // the existing record instead of appending a twin. The #3321 + // ingestion writer passes id = activity::. + const dir = mkdtempSync(join(tmpdir(), "agg-events-blocked-")); + const blocker = join(dir, "blocker"); + writeFileSync(blocker, "not a directory"); + const store = new EventsStore(join(blocker, "events.json")); + await expect(store.record({ ...base, id: "activity:test:1" })).rejects.toThrow(); + // The ingestion retry re-presents the same stable id: it resolves + // to the single retained record, never a second copy. + const replay = await store.record({ ...base, id: "activity:test:1" }); + expect(replay.id).toBe("activity:test:1"); + const blockedList = await store.list(); + expect(blockedList).toHaveLength(1); + expect(blockedList[0]?.id).toBe("activity:test:1"); + // Same contract on a healthy store: one stable id lands once. + const { store: healthy } = tmpStore(); + const first = await healthy.record({ ...base, id: "activity:test:2" }); + const second = await healthy.record({ ...base, id: "activity:test:2" }); + expect(second.id).toBe(first.id); + expect(await healthy.list()).toHaveLength(1); + }); + test("record stamps `at` when the writer omits it", async () => { const { store } = tmpStore(); const e = await store.record({ ...base });

${events.length} event(s), newest first. ` + `Machine twin: /api/events.json (filters: kind, ref, actor).