Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: record CoS run lifecycle in an append-only event ledger you can replay (#4540)

[._.]/ Adam Eivyaa46a4a3aca2
diff --git a/docs/API.md b/docs/API.md
index edc55f8d5e..c2819c4f19 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -407,6 +407,10 @@ See [Agent Context (MCP)](./features/agent-context.md) for setup, transport head
| GET | `/agents/activity/agent/:agentId` | Get agent's activity |
| GET | `/agents/activity/agent/:agentId/stats` | Get agent statistics |
| POST | `/agents/activity/cleanup` | Clean up old activity logs |
+| GET | `/agents/activity/run-events` | Read the append-only CoS run lifecycle ledger (filters: `runId`, `agentId`, `taskId`, `kind`, `since`, `limit`) |
+| GET | `/agents/activity/run-events/stats` | Ledger generation sizes and the retention bound |
+| GET | `/agents/activity/run-events/projections` | Current run status derived by replaying the ledger |
+| GET | `/agents/activity/run-events/run/:id` | One run's projection plus the events behind it |
### Notifications
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 432df42e96..fd7a005343 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -100,6 +100,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Media job queue — runtime queue state can stay file-backed short term, but **job history and artifact lineage are `db-primary`** and should move to the DB.
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
+- CoS run event ledger — `data/cos/run-events.jsonl` + one retained archive generation `run-events.1.jsonl` (`server/services/agentRunEventLog.js`, #4540). The ordered, append-only trace of how a CoS agent run reached its current state: spawn, finalization, orphan reap, runner re-adoption. `ephemeral-file` because the DURABLE record of a run is still `data/runs/{id}/metadata.json` — this is a regenerable-by-observation diagnostic over it, with no cross-record queries, no relationships, and no sync cursor; the projection that derives current status is a pure fold (`server/lib/agentRunEvents.js`), so losing the ledger costs post-mortem detail and nothing else. **Intentionally machine-local — never federated**: every line describes a process on THIS box, so a peer would inherit a trace of runs that never existed there. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Bounded by a count, not a byte size — the active generation rotates at 5000 events and exactly one archive is kept, so the ledger is capped at ~2×5000 events forever with no cleanup job. No migration and no `data.reference/` seed: an absent file reads as an empty ledger. Payloads are redacted at APPEND time (prompt/description/output/result keys dropped to a `{ redacted, chars }` stub, home-dir prefix scrubbed, string/array/key/depth capped), so no reader has to re-redact. Backed up with the rest of `data/cos/` — it is small, bounded, and the thing you most want after the crash you are debugging.
- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).
---
diff --git a/server/lib/README.md b/server/lib/README.md
index c4cb6077bd..4eb05c68e0 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,6 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `validation.js` | Catch-all Zod schemas (app/process/provider, social accounts, GitHub, backup/sharing, document/legacy-export) + the `validateRequest` middleware + shared helpers (`optionalBooleanMap`, `isSafeRecordId`, `parsePagination`). Re-exports the per-domain validation files below so existing deep imports keep working. |
| `sharedSchemas.js` | Cross-domain Zod fragments that `validation.js` and the per-domain `*Validation.js` files both need, kept in a leaf module so the domain files never import back through `validation.js` (its hoisted `export * from` lines would TDZ). `grokVideoDurationSchema` (grok clip-length union), `cloudModelIdString(message)` (cloud-CLI model-id charset/bounds), `recordRenderPinFields` (the `imageMode`/`imageModelId` per-record render pin pair), and `isSafeSubdirFilter(v)` (relative path with no wildcard, `..` segment, or leading `/`), and `csvIdsParam({ max, maxIdLength, truncate })` (the `?ids=a,b,c` batch-by-id query param: trims, drops empties, reads all-blank as absent, and either 400s or silently slices an over-cap batch). |
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
+| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). |
| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
new file mode 100644
index 0000000000..88b490fc4b
--- /dev/null
+++ b/server/lib/agentRunEvents.js
@@ -0,0 +1,391 @@
+/**
+ * CoS run event envelope — pure schema, redaction, and projection.
+ *
+ * The append-only ledger this describes is the *ordered* record of how a CoS
+ * agent run reached its current state. It exists alongside the mutable run
+ * record (`data/runs/{id}/metadata.json`), never instead of it: the record says
+ * what a run is now, the ledger says how it got there, which is the question
+ * the in-place record can never answer after an interruption or a recovery.
+ *
+ * Three properties make the stream trustworthy, and all three live here rather
+ * than in the I/O service so they can be exercised without touching disk:
+ *
+ * - **Idempotent ids.** `buildRunEvent` derives `eventId` from the envelope's
+ * own content, so a boundary that fires twice for one logical transition (a
+ * retried orphan sweep, a duplicated runner completion) mints the SAME id and
+ * the ledger suppresses the second copy. A random id would have made every
+ * redelivery a new "fact" and quietly doubled every count derived from it.
+ * - **Redaction at construction.** `redactRunEventData` runs inside
+ * `buildRunEvent`, so an unredacted payload can never reach the append path
+ * even if a future caller forgets. Prompts and record bodies are dropped, not
+ * truncated — a truncated prompt is still a prompt.
+ * - **A pure fold.** `projectRunStates` derives status from the stream with no
+ * I/O and no clock, so "replay after restart" is the same code path as "read
+ * the current status", and a test can assert both with one call.
+ *
+ * The ledger is machine-local and never federated (see `docs/STORAGE.md`).
+ * I/O, rotation, and the seen-id sets live in
+ * `server/services/agentRunEventLog.js`.
+ */
+
+import { z } from 'zod';
+import { homedir } from 'os';
+import { sha256Text } from './fileUtils.js';
+import { canonicalStringify, POLLUTING_KEYS } from './objects.js';
+import { redactOutput } from './commandSecurity.js';
+
+/**
+ * Envelope schema version. Bump when the envelope SHAPE changes in a way a
+ * reader must notice; adding a new value to `AGENT_RUN_EVENT_KINDS` is not
+ * such a change (unknown kinds fold into the projection as no-ops).
+ *
+ * This is deliberately NOT a `PORTOS_SCHEMA_VERSIONS` entry: the ledger never
+ * crosses the wire, so no peer ever has to agree with this number.
+ */
+export const AGENT_RUN_EVENT_SCHEMA_VERSION = 1;
+
+/**
+ * The lifecycle boundaries this slice records. Kept a closed vocabulary so the
+ * projection below can be exhaustive and a typo in a call site fails schema
+ * validation instead of silently writing an event nothing ever folds.
+ */
+export const AGENT_RUN_EVENT_KINDS = Object.freeze([
+ // A run was created and its process handed off (createAgentRun).
+ 'run.spawned',
+ // A run was closed with a verdict (completeAgentRun) — including the closes
+ // driven by orphan cleanup, so `finalized` is genuinely terminal.
+ 'run.finalized',
+ // A "running" agent record was found with no live process and reaped
+ // (cleanupOrphanedAgents). Distinguishes a crash/restart from a clean exit.
+ 'run.orphan-recovered',
+ // A restart survivor was re-adopted from the CoS Runner (syncRunnerAgents).
+ 'run.runner-recovered'
+]);
+
+const KIND_SET = new Set(AGENT_RUN_EVENT_KINDS);
+
+// ---------------------------------------------------------------------------
+// Redaction
+// ---------------------------------------------------------------------------
+
+/**
+ * Keys whose values are prompts, model output, or record bodies. Dropped
+ * wholesale — replaced by a `{ redacted, chars }` stub that preserves the one
+ * diagnostically useful fact (how much there was) without preserving any of it.
+ *
+ * Matched case-insensitively so `taskDescription` and `promptText` are covered
+ * by their stems.
+ */
+const DROPPED_KEY_PATTERNS = [
+ /prompt/i,
+ /description/i,
+ /^output/i,
+ /^content$/i,
+ /^body$/i,
+ /^text$/i,
+ /^notes?$/i,
+ /^summary$/i,
+ /^title$/i,
+ /^result$/i,
+ /^params$/i,
+ /^payload$/i,
+ /^transcript/i
+];
+
+/** Bounds. A ledger line must stay a diagnostic, not become a record copy. */
+export const RUN_EVENT_LIMITS = Object.freeze({
+ maxStringChars: 200,
+ maxArrayItems: 20,
+ maxObjectKeys: 40,
+ maxDepth: 3
+});
+
+const isDroppedKey = (key) => DROPPED_KEY_PATTERNS.some((re) => re.test(key));
+
+/**
+ * Replace the user's home directory prefix with `~` anywhere in a string.
+ *
+ * Workspace paths are the most common thing a lifecycle payload carries, and
+ * `/Users/<name>/…` embeds the OS username. The ledger is machine-local, but a
+ * diagnostic is exactly the thing a user pastes into a bug report, so the
+ * username never gets written down in the first place.
+ */
+export function scrubHomePath(value) {
+ const home = homedir();
+ if (typeof value !== 'string' || !home) return value;
+ return value.split(home).join('~');
+}
+
+/**
+ * Scrub + bound one free-form string: home path, then the shared secret filter,
+ * then a hard length cap.
+ */
+function scrubString(value) {
+ const scrubbed = redactOutput(scrubHomePath(value)) ?? '';
+ return scrubbed.length > RUN_EVENT_LIMITS.maxStringChars
+ ? `${scrubbed.slice(0, RUN_EVENT_LIMITS.maxStringChars)}…`
+ : scrubbed;
+}
+
+/**
+ * Redact an event payload for the ledger.
+ *
+ * Recursive, bounded on every axis (depth, key count, array length, string
+ * length), and it drops prototype-polluting keys the way every other sanitizer
+ * in the codebase does. Non-JSON values (functions, symbols, undefined) are
+ * dropped rather than stringified — a ledger line must round-trip through JSON.
+ *
+ * @param {*} data - arbitrary payload from a lifecycle call site
+ * @param {number} [depth] - internal recursion depth
+ * @returns {object} redacted, JSON-safe payload
+ */
+export function redactRunEventData(data, depth = 0) {
+ if (data === null || data === undefined) return {};
+ // The envelope's `data` is always an object (the schema is `z.record`), so a
+ // scalar or array payload is boxed rather than rejected — a call site passing
+ // one is imprecise, not a reason to lose the event.
+ if (typeof data !== 'object') return { value: redactScalar(data) };
+ if (Array.isArray(data)) return { items: redactValue(data, depth) };
+ return redactValue(data, depth);
+}
+
+function redactScalar(value) {
+ if (typeof value === 'string') return scrubString(value);
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null;
+ if (typeof value === 'boolean') return value;
+ return null;
+}
+
+function redactValue(value, depth) {
+ if (value === null || value === undefined) return null;
+ if (typeof value !== 'object') return redactScalar(value);
+ // A value nested past the depth cap is summarized, not walked — the cap is
+ // what keeps a whole record from arriving as one deeply nested payload.
+ if (depth >= RUN_EVENT_LIMITS.maxDepth) return { redacted: 'depth' };
+
+ if (Array.isArray(value)) {
+ const kept = value.slice(0, RUN_EVENT_LIMITS.maxArrayItems).map((item) => redactValue(item, depth + 1));
+ return value.length > RUN_EVENT_LIMITS.maxArrayItems
+ ? [...kept, { redacted: 'truncated', dropped: value.length - RUN_EVENT_LIMITS.maxArrayItems }]
+ : kept;
+ }
+
+ const out = {};
+ let kept = 0;
+ for (const [key, raw] of Object.entries(value)) {
+ if (POLLUTING_KEYS.has(key)) continue;
+ if (typeof raw === 'function' || typeof raw === 'symbol' || raw === undefined) continue;
+ if (kept >= RUN_EVENT_LIMITS.maxObjectKeys) {
+ out.redacted = 'keys';
+ break;
+ }
+ // Only content-bearing values are dropped. A NUMBER or boolean under a
+ // dropped key is a size or a flag (`promptChars`, `hasOutput`), never the
+ // content itself — stubbing those out would delete the only part of the
+ // payload that was already safe.
+ if (isDroppedKey(key) && (typeof raw === 'string' || (raw !== null && typeof raw === 'object'))) {
+ out[key] = { redacted: 'content', chars: typeof raw === 'string' ? raw.length : null };
+ } else {
+ out[key] = redactValue(raw, depth + 1);
+ }
+ kept += 1;
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Envelope
+// ---------------------------------------------------------------------------
+
+/**
+ * Zod schema for one ledger line. `.strict()` so a call site cannot smuggle an
+ * extra top-level field past redaction (redaction only walks `data`).
+ */
+export const agentRunEventSchema = z.object({
+ schemaVersion: z.literal(AGENT_RUN_EVENT_SCHEMA_VERSION),
+ eventId: z.string().min(1).max(128),
+ kind: z.enum(AGENT_RUN_EVENT_KINDS),
+ runId: z.string().min(1).max(128).nullable(),
+ agentId: z.string().min(1).max(128).nullable(),
+ taskId: z.string().min(1).max(128).nullable(),
+ at: z.string().datetime(),
+ data: z.record(z.unknown())
+}).strict();
+
+const nullableId = (value) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, 128) : null);
+
+/**
+ * Build a validated, redacted ledger envelope.
+ *
+ * `eventId` is content-derived by default: the sha256 of the canonicalized
+ * envelope (kind + ids + timestamp + redacted data), truncated to 32 hex chars.
+ * Two deliveries of the same logical transition therefore collide by design and
+ * the ledger keeps one. Pass an explicit `eventId` only when a call site has a
+ * better natural key than its own content.
+ *
+ * Throws on an invalid envelope — a malformed event is a bug at the call site,
+ * and the append path (which owns the "never break a run for telemetry" rule)
+ * is where that throw gets absorbed.
+ *
+ * @param {object} input
+ * @param {string} input.kind - one of AGENT_RUN_EVENT_KINDS
+ * @param {string} [input.runId]
+ * @param {string} [input.agentId]
+ * @param {string} [input.taskId]
+ * @param {string|Date} [input.at] - defaults to now
+ * @param {object} [input.data] - redacted before it is hashed or stored
+ * @param {string} [input.eventId] - explicit idempotency key
+ * @returns {object} validated envelope
+ */
+export function buildRunEvent({ kind, runId, agentId, taskId, at, data, eventId } = {}) {
+ const timestamp = at instanceof Date ? at.toISOString() : (typeof at === 'string' && at ? at : new Date().toISOString());
+ const core = {
+ schemaVersion: AGENT_RUN_EVENT_SCHEMA_VERSION,
+ kind,
+ runId: nullableId(runId),
+ agentId: nullableId(agentId),
+ taskId: nullableId(taskId),
+ at: timestamp,
+ data: redactRunEventData(data)
+ };
+ const envelope = {
+ ...core,
+ eventId: typeof eventId === 'string' && eventId ? eventId.slice(0, 128) : deriveEventId(core)
+ };
+ return agentRunEventSchema.parse(envelope);
+}
+
+/** Content-derived idempotency key for an envelope (sans its own id). */
+export function deriveEventId(core) {
+ return sha256Text(canonicalStringify(core) ?? '').slice(0, 32);
+}
+
+/** Is this parsed line a well-formed ledger event? Used by the read path. */
+export function isValidRunEvent(value) {
+ return agentRunEventSchema.safeParse(value).success;
+}
+
+/** Does this kind belong to the closed vocabulary? */
+export function isKnownRunEventKind(kind) {
+ return KIND_SET.has(kind);
+}
+
+// ---------------------------------------------------------------------------
+// Projection
+// ---------------------------------------------------------------------------
+
+/**
+ * The projection key for an event.
+ *
+ * Prefers `runId` — the durable identity a run keeps across restarts. Events
+ * that legitimately have no run id (an orphan reaped before its run record was
+ * written, or one whose `runId` never made it onto the agent record) fall back
+ * to the agent, so they surface in diagnostics instead of vanishing. That case
+ * is the exact failure this ledger exists to explain, so it must not be the one
+ * the projection drops.
+ */
+export function runEventKey(event) {
+ if (event?.runId) return event.runId;
+ if (event?.agentId) return `agent:${event.agentId}`;
+ return null;
+}
+
+const emptyProjection = (id) => ({
+ id,
+ runId: null,
+ agentId: null,
+ taskId: null,
+ status: 'unknown',
+ startedAt: null,
+ endedAt: null,
+ durationMs: null,
+ exitCode: null,
+ success: null,
+ orphaned: false,
+ recoveryCount: 0,
+ eventCount: 0,
+ firstEventAt: null,
+ lastEventAt: null,
+ trace: []
+});
+
+/**
+ * Fold an ordered event stream into per-run current state.
+ *
+ * Pure and clock-free: replaying the ledger after a restart produces exactly
+ * the state the live process had, which is the whole point of the ledger. Later
+ * events win on every field, so `run.finalized` correctly overrides an earlier
+ * `run.orphan-recovered` (orphan cleanup emits both, in that order).
+ *
+ * Unknown kinds still count toward `eventCount` and the trace but leave status
+ * alone, so a ledger written by a newer install replays on an older one.
+ *
+ * @param {object[]} events - ledger events in append order
+ * @returns {object[]} projections, newest activity first
+ */
+export function projectRunStates(events) {
+ const byKey = new Map();
+
+ for (const event of Array.isArray(events) ? events : []) {
+ const key = runEventKey(event);
+ if (!key) continue;
+
+ const state = byKey.get(key) ?? emptyProjection(key);
+ if (!byKey.has(key)) byKey.set(key, state);
+
+ // Ids are sticky: an event that omits one must not erase what an earlier
+ // event established (the finalize path carries no taskId, for instance).
+ state.runId = event.runId ?? state.runId;
+ state.agentId = event.agentId ?? state.agentId;
+ state.taskId = event.taskId ?? state.taskId;
+ state.eventCount += 1;
+ state.firstEventAt = state.firstEventAt ?? event.at;
+ state.lastEventAt = event.at;
+ state.trace.push({ eventId: event.eventId, kind: event.kind, at: event.at });
+
+ applyKind(state, event);
+ }
+
+ return [...byKey.values()].sort((a, b) => String(b.lastEventAt).localeCompare(String(a.lastEventAt)));
+}
+
+function applyKind(state, event) {
+ const data = event.data ?? {};
+ switch (event.kind) {
+ case 'run.spawned':
+ state.status = 'running';
+ state.startedAt = event.at;
+ if (typeof data.providerId === 'string') state.providerId = data.providerId;
+ if (typeof data.model === 'string') state.model = data.model;
+ break;
+ case 'run.runner-recovered':
+ // A survivor is still running — recovery is an annotation on a live run,
+ // not a terminal state. Only the count changes so a diagnostic can show
+ // "this run has been re-adopted N times".
+ if (state.status !== 'completed' && state.status !== 'failed') state.status = 'running';
+ state.recoveryCount += 1;
+ break;
+ case 'run.orphan-recovered':
+ state.orphaned = true;
+ if (state.status !== 'completed' && state.status !== 'failed') state.status = 'orphaned';
+ break;
+ case 'run.finalized': {
+ const success = data.success === true;
+ state.status = success ? 'completed' : 'failed';
+ state.success = success;
+ state.endedAt = event.at;
+ state.exitCode = Number.isFinite(data.exitCode) ? data.exitCode : null;
+ state.durationMs = Number.isFinite(data.durationMs) ? data.durationMs : null;
+ if (typeof data.errorCategory === 'string') state.errorCategory = data.errorCategory;
+ break;
+ }
+ default:
+ // Unknown kind from a newer install — counted, not interpreted.
+ break;
+ }
+}
+
+/** Project a single key out of a stream (`runId`, or `agent:<agentId>`). */
+export function projectRunState(events, id) {
+ return projectRunStates(events).find((state) => state.id === id) ?? null;
+}
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
new file mode 100644
index 0000000000..7522c2768d
--- /dev/null
+++ b/server/lib/agentRunEvents.test.js
@@ -0,0 +1,270 @@
+import { describe, it, expect } from 'vitest';
+import { homedir } from 'os';
+import {
+ AGENT_RUN_EVENT_KINDS,
+ AGENT_RUN_EVENT_SCHEMA_VERSION,
+ RUN_EVENT_LIMITS,
+ agentRunEventSchema,
+ buildRunEvent,
+ isKnownRunEventKind,
+ isValidRunEvent,
+ projectRunState,
+ projectRunStates,
+ redactRunEventData,
+ runEventKey,
+ scrubHomePath
+} from './agentRunEvents.js';
+
+const AT = '2026-08-18T12:00:00.000Z';
+
+describe('buildRunEvent — envelope schema', () => {
+ it('produces an envelope the schema accepts', () => {
+ const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', taskId: 't1', at: AT });
+ expect(agentRunEventSchema.safeParse(event).success).toBe(true);
+ expect(event.schemaVersion).toBe(AGENT_RUN_EVENT_SCHEMA_VERSION);
+ expect(event.at).toBe(AT);
+ expect(event.data).toEqual({});
+ });
+
+ it('rejects a kind outside the closed vocabulary', () => {
+ expect(() => buildRunEvent({ kind: 'run.invented', runId: 'r1', at: AT })).toThrow();
+ });
+
+ it('normalizes absent / blank ids to null rather than empty strings', () => {
+ const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: ' ', at: AT });
+ expect(event.agentId).toBeNull();
+ expect(event.taskId).toBeNull();
+ });
+
+ it('accepts a Date for `at` and normalizes it to ISO', () => {
+ const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: new Date(AT) });
+ expect(event.at).toBe(AT);
+ });
+
+ it('isValidRunEvent rejects a line missing required fields', () => {
+ expect(isValidRunEvent({ kind: 'run.spawned' })).toBe(false);
+ expect(isValidRunEvent(buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }))).toBe(true);
+ });
+
+ it('isKnownRunEventKind tracks the exported vocabulary', () => {
+ for (const kind of AGENT_RUN_EVENT_KINDS) expect(isKnownRunEventKind(kind)).toBe(true);
+ expect(isKnownRunEventKind('run.nope')).toBe(false);
+ });
+});
+
+describe('buildRunEvent — idempotent event ids', () => {
+ const base = { kind: 'run.finalized', runId: 'r1', agentId: 'a1', taskId: 't1', at: AT, data: { success: true, exitCode: 0 } };
+
+ it('derives the SAME id for a redelivery of the same logical event', () => {
+ // The whole point: a lifecycle boundary that fires twice (retried orphan
+ // sweep, duplicated runner completion) must not become two facts.
+ expect(buildRunEvent(base).eventId).toBe(buildRunEvent({ ...base }).eventId);
+ });
+
+ it('derives the same id regardless of the order the data keys were written', () => {
+ const a = buildRunEvent({ ...base, data: { success: true, exitCode: 0 } });
+ const b = buildRunEvent({ ...base, data: { exitCode: 0, success: true } });
+ expect(a.eventId).toBe(b.eventId);
+ });
+
+ it('derives a DIFFERENT id when any envelope field differs', () => {
+ const id = buildRunEvent(base).eventId;
+ expect(buildRunEvent({ ...base, at: '2026-08-18T12:00:01.000Z' }).eventId).not.toBe(id);
+ expect(buildRunEvent({ ...base, runId: 'r2' }).eventId).not.toBe(id);
+ expect(buildRunEvent({ ...base, kind: 'run.orphan-recovered' }).eventId).not.toBe(id);
+ expect(buildRunEvent({ ...base, data: { success: false, exitCode: 1 } }).eventId).not.toBe(id);
+ });
+
+ it('honors an explicit idempotency key when a caller has a better one', () => {
+ expect(buildRunEvent({ ...base, eventId: 'natural-key-1' }).eventId).toBe('natural-key-1');
+ });
+});
+
+describe('redactRunEventData — privacy', () => {
+ it('drops prompt / description / output / result content to a size stub', () => {
+ const data = redactRunEventData({
+ prompt: 'ship the feature and mention Jane Doe',
+ taskDescription: 'rename the Example Universe series',
+ output: 'a very long transcript',
+ result: { body: 'nested record contents' },
+ params: ['secret', 'values'],
+ model: 'some-model'
+ });
+ expect(data.prompt).toEqual({ redacted: 'content', chars: 'ship the feature and mention Jane Doe'.length });
+ expect(data.taskDescription).toEqual({ redacted: 'content', chars: 'rename the Example Universe series'.length });
+ expect(data.output.redacted).toBe('content');
+ expect(data.result).toEqual({ redacted: 'content', chars: null });
+ expect(data.params).toEqual({ redacted: 'content', chars: null });
+ // Non-content metadata is exactly what a diagnostic needs, so it survives.
+ expect(data.model).toBe('some-model');
+ expect(JSON.stringify(data)).not.toContain('Jane Doe');
+ expect(JSON.stringify(data)).not.toContain('Example Universe');
+ });
+
+ it('keeps a NUMBER under a dropped key — a size is not content', () => {
+ // The size is the only part of a prompt that was already safe; stubbing it
+ // out would delete the diagnostic and protect nothing.
+ expect(redactRunEventData({ promptChars: 4096 })).toEqual({ promptChars: 4096 });
+ });
+
+ it('scrubs the home-directory prefix out of every remaining string', () => {
+ const workspacePath = `${homedir()}/github.com/example/app`;
+ const data = redactRunEventData({ workspacePath });
+ expect(data.workspacePath).toBe('~/github.com/example/app');
+ expect(data.workspacePath).not.toContain(homedir());
+ });
+
+ it('scrubHomePath replaces every occurrence, not just a leading one', () => {
+ const home = homedir();
+ expect(scrubHomePath(`from ${home}/a to ${home}/b`)).toBe('from ~/a to ~/b');
+ expect(scrubHomePath(42)).toBe(42);
+ });
+
+ it('redacts sensitive env values via the shared secret filter', () => {
+ const data = redactRunEventData({ detail: '{"API_KEY": "sk-live-abc123"}' });
+ expect(data.detail).not.toContain('sk-live-abc123');
+ expect(data.detail).toContain('[REDACTED]');
+ });
+
+ it('caps string length so a payload cannot smuggle a record body', () => {
+ const data = redactRunEventData({ detail: 'x'.repeat(5000) });
+ expect(data.detail.length).toBe(RUN_EVENT_LIMITS.maxStringChars + 1); // + the ellipsis
+ });
+
+ it('caps array length, key count, and nesting depth', () => {
+ const wide = Object.fromEntries(Array.from({ length: 100 }, (_, i) => [`k${i}`, i]));
+ const capped = redactRunEventData(wide);
+ expect(Object.keys(capped).length).toBeLessThanOrEqual(RUN_EVENT_LIMITS.maxObjectKeys + 1);
+ expect(capped.redacted).toBe('keys');
+
+ const long = redactRunEventData({ items: Array.from({ length: 100 }, (_, i) => i) });
+ expect(long.items.length).toBe(RUN_EVENT_LIMITS.maxArrayItems + 1);
+ expect(long.items.at(-1)).toEqual({ redacted: 'truncated', dropped: 80 });
+
+ const deep = redactRunEventData({ a: { b: { c: { d: { e: 'too deep' } } } } });
+ expect(JSON.stringify(deep)).toContain('"redacted":"depth"');
+ expect(JSON.stringify(deep)).not.toContain('too deep');
+ });
+
+ it('strips prototype-polluting keys and non-JSON values', () => {
+ const data = redactRunEventData(JSON.parse('{"__proto__": {"polluted": true}, "ok": 1}'));
+ expect(Object.hasOwn(data, '__proto__')).toBe(false);
+ expect({}.polluted).toBeUndefined();
+ expect(redactRunEventData({ fn: () => 1, sym: Symbol('s'), gone: undefined, kept: true }))
+ .toEqual({ kept: true });
+ });
+
+ it('boxes a scalar or array payload so the envelope stays a record', () => {
+ expect(redactRunEventData('hello')).toEqual({ value: 'hello' });
+ expect(redactRunEventData([1, 2])).toEqual({ items: [1, 2] });
+ expect(redactRunEventData(null)).toEqual({});
+ });
+
+ it('redacts inside buildRunEvent, so an unredacted payload cannot be constructed', () => {
+ const event = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT, data: { prompt: 'private words' } });
+ expect(event.data.prompt).toEqual({ redacted: 'content', chars: 13 });
+ });
+});
+
+describe('projectRunStates — replayable status', () => {
+ const stream = [
+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', taskId: 't1', at: '2026-08-18T10:00:00.000Z', data: { providerId: 'p1', model: 'm1' } }),
+ buildRunEvent({ kind: 'run.runner-recovered', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:30:00.000Z' }),
+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', agentId: 'a1', at: '2026-08-18T11:00:00.000Z', data: { success: true, exitCode: 0, durationMs: 3600000 } })
+ ];
+
+ it('folds a full lifecycle into a completed run', () => {
+ const [state] = projectRunStates(stream);
+ expect(state).toMatchObject({
+ id: 'r1',
+ runId: 'r1',
+ agentId: 'a1',
+ taskId: 't1',
+ status: 'completed',
+ success: true,
+ exitCode: 0,
+ durationMs: 3600000,
+ recoveryCount: 1,
+ eventCount: 3,
+ startedAt: '2026-08-18T10:00:00.000Z',
+ endedAt: '2026-08-18T11:00:00.000Z'
+ });
+ expect(state.trace.map((t) => t.kind)).toEqual(['run.spawned', 'run.runner-recovered', 'run.finalized']);
+ });
+
+ it('is pure — replaying the same stream twice yields the same state', () => {
+ // This is what makes "rebuild after a restart" and "read current status"
+ // one code path: no clock, no I/O, no accumulated module state.
+ expect(projectRunStates(stream)).toEqual(projectRunStates(stream));
+ });
+
+ it('reports a still-open run as running', () => {
+ const [state] = projectRunStates([stream[0]]);
+ expect(state.status).toBe('running');
+ expect(state.endedAt).toBeNull();
+ expect(state.success).toBeNull();
+ });
+
+ it('lets a later finalize outrank an earlier orphan recovery', () => {
+ // Orphan cleanup emits BOTH, in this order — the terminal verdict must win.
+ const [state] = projectRunStates([
+ stream[0],
+ buildRunEvent({ kind: 'run.orphan-recovered', runId: 'r1', at: '2026-08-18T10:45:00.000Z', data: { interruptedByRestart: true } }),
+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', at: '2026-08-18T10:46:00.000Z', data: { success: false, exitCode: 143, errorCategory: 'interrupted' } })
+ ]);
+ expect(state.status).toBe('failed');
+ expect(state.orphaned).toBe(true);
+ expect(state.errorCategory).toBe('interrupted');
+ });
+
+ it('leaves an orphan that was never finalized in the orphaned state', () => {
+ const [state] = projectRunStates([
+ stream[0],
+ buildRunEvent({ kind: 'run.orphan-recovered', runId: 'r1', at: '2026-08-18T10:45:00.000Z' })
+ ]);
+ expect(state.status).toBe('orphaned');
+ });
+
+ it('keeps a run that never got an id, keyed by its agent', () => {
+ // The un-idded orphan is exactly the failure this ledger exists to explain,
+ // so it must not be the case the projection silently drops.
+ const [state] = projectRunStates([
+ buildRunEvent({ kind: 'run.orphan-recovered', agentId: 'a9', taskId: 't9', at: AT, data: { hasRunId: false } })
+ ]);
+ expect(state.id).toBe('agent:a9');
+ expect(state.runId).toBeNull();
+ expect(state.status).toBe('orphaned');
+ expect(runEventKey({ agentId: 'a9' })).toBe('agent:a9');
+ expect(runEventKey({})).toBeNull();
+ });
+
+ it('carries ids forward when a later event omits them', () => {
+ const [state] = projectRunStates([
+ stream[0],
+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', at: AT, data: { success: true } })
+ ]);
+ expect(state.taskId).toBe('t1');
+ expect(state.agentId).toBe('a1');
+ });
+
+ it('counts an unknown kind without letting it change status', () => {
+ // A ledger written by a newer install must still replay on an older one.
+ const [state] = projectRunStates([stream[0], { ...stream[1], kind: 'run.from-the-future' }]);
+ expect(state.status).toBe('running');
+ expect(state.eventCount).toBe(2);
+ });
+
+ it('separates runs and orders them by most recent activity', () => {
+ const states = projectRunStates([
+ buildRunEvent({ kind: 'run.spawned', runId: 'old', at: '2026-08-18T09:00:00.000Z' }),
+ buildRunEvent({ kind: 'run.spawned', runId: 'new', at: '2026-08-18T13:00:00.000Z' })
+ ]);
+ expect(states.map((s) => s.id)).toEqual(['new', 'old']);
+ });
+
+ it('tolerates a non-array input', () => {
+ expect(projectRunStates(null)).toEqual([]);
+ expect(projectRunState(stream, 'nope')).toBeNull();
+ expect(projectRunState(stream, 'r1').status).toBe('completed');
+ });
+});
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 823f946efa..a7e9cd735c 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -15,6 +15,7 @@ import { EFFORT_LEVELS, effortLevelsForProvider, buildEffortArgs, splitAntigravi
import { ANTIGRAVITY_COMMAND } from './antigravity.js';
import { isValidSlashdoCommand } from './slashdoInvocation.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
+import { AGENT_RUN_EVENT_KINDS } from './agentRunEvents.js';
// =============================================================================
// COS TASK SCHEMAS
@@ -1635,3 +1636,33 @@ export function sanitizeTaskMetadata(raw) {
}
return hasKeys ? { ...clean } : null;
}
+
+// =============================================================================
+// CoS RUN EVENT LEDGER (read-only diagnostics, #4540)
+// =============================================================================
+
+// Query bounds for the read-only run-event diagnostics under
+// `/api/agents/activity/run-events`. `z.coerce` because these arrive as query
+// strings; the `limit` ceiling mirrors MAX_READ_LIMIT in
+// `services/agentRunEventLog.js` so a caller cannot ask the route to load and
+// serialize an unbounded slice of the ledger.
+export const runEventsQuerySchema = z.object({
+ runId: z.string().min(1).max(128).optional(),
+ agentId: z.string().min(1).max(128).optional(),
+ taskId: z.string().min(1).max(128).optional(),
+ kind: z.enum(AGENT_RUN_EVENT_KINDS).optional(),
+ since: z.string().datetime().optional(),
+ limit: z.coerce.number().int().min(1).max(1000).optional()
+}).strict();
+
+export const runEventProjectionsQuerySchema = z.object({
+ runId: z.string().min(1).max(128).optional(),
+ agentId: z.string().min(1).max(128).optional(),
+ limit: z.coerce.number().int().min(1).max(1000).optional()
+}).strict();
+
+// A projection id is either a run id or the `agent:<agentId>` fallback key a
+// run that never got an id folds under (see `runEventKey`).
+export const runEventProjectionIdSchema = z.object({
+ id: z.string().min(1).max(140)
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 42caa27740..ffc693a74c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -186,6 +186,7 @@ export * from './zipWriter.js';
// === Process execution ===
export * from './agentGuard/index.js';
export * from './agentOutputMarkers.js';
+export * from './agentRunEvents.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
export * from './bashResolver.js';
diff --git a/server/routes/agentActivity.js b/server/routes/agentActivity.js
index 3a54d9de8d..ba99b3a888 100644
--- a/server/routes/agentActivity.js
+++ b/server/routes/agentActivity.js
@@ -6,7 +6,10 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { runEventsQuerySchema, runEventProjectionsQuerySchema, runEventProjectionIdSchema } from '../lib/cosValidation.js';
import * as agentActivity from '../services/agentActivity.js';
+import * as runEventLog from '../services/agentRunEventLog.js';
const router = Router();
@@ -68,4 +71,39 @@ router.post('/cleanup', asyncHandler(async (req, res) => {
res.json({ success: true, deletedCount });
}));
+// ---------------------------------------------------------------------------
+// Run event ledger — read-only diagnostics (#4540)
+//
+// A literal `/run-events` prefix, disjoint from every path above it — the only
+// parameterized route here is `/agent/:agentId`, so registration order is not
+// load-bearing and these can stay at the bottom of the file.
+// Every handler is a pure read: the ledger is append-only and is written from
+// the agent lifecycle, never from HTTP. Payloads were redacted at append time
+// (see `lib/agentRunEvents.js`), so nothing here re-redacts — a route that had
+// to redact on read would mean unredacted bytes were already on disk.
+// ---------------------------------------------------------------------------
+
+// GET /run-events - Raw lifecycle events in append order (newest-N window)
+router.get('/run-events', asyncHandler(async (req, res) => {
+ const query = validateRequest(runEventsQuerySchema, req.query);
+ res.json(await runEventLog.readRunEvents(query));
+}));
+
+// GET /run-events/stats - Ledger size + the retention bound it is held to
+router.get('/run-events/stats', asyncHandler(async (req, res) => {
+ res.json(await runEventLog.getRunEventLedgerStats());
+}));
+
+// GET /run-events/projections - Current run status DERIVED from the stream
+router.get('/run-events/projections', asyncHandler(async (req, res) => {
+ const query = validateRequest(runEventProjectionsQuerySchema, req.query);
+ res.json(await runEventLog.getRunProjections(query));
+}));
+
+// GET /run-events/run/:id - One run's projection plus the events behind it
+router.get('/run-events/run/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(runEventProjectionIdSchema, req.params);
+ res.json(await runEventLog.getRunDiagnostic(id));
+}));
+
export default router;
diff --git a/server/routes/agentActivity.test.js b/server/routes/agentActivity.test.js
new file mode 100644
index 0000000000..7006753298
--- /dev/null
+++ b/server/routes/agentActivity.test.js
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mocks = vi.hoisted(() => ({
+ readRunEvents: vi.fn(),
+ getRunProjections: vi.fn(),
+ getRunDiagnostic: vi.fn(),
+ getRunEventLedgerStats: vi.fn(),
+}));
+
+vi.mock('../services/agentRunEventLog.js', () => mocks);
+vi.mock('../services/agentActivity.js', () => ({
+ getRecentActivities: vi.fn(async () => []),
+ getActivityTimeline: vi.fn(async () => []),
+ getActivities: vi.fn(async () => []),
+ getAgentStats: vi.fn(async () => ({})),
+ cleanupOldActivity: vi.fn(async () => 0),
+}));
+
+import agentActivityRoutes from './agentActivity.js';
+
+const app = () => {
+ const a = express();
+ a.use(express.json());
+ a.use('/api/agents/activity', agentActivityRoutes);
+ a.use(errorMiddleware);
+ return a;
+};
+
+const get = (path) => request(app()).get(`/api/agents/activity${path}`);
+
+describe('GET /run-events', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.readRunEvents.mockResolvedValue([]);
+ mocks.getRunProjections.mockResolvedValue([]);
+ mocks.getRunDiagnostic.mockResolvedValue({ projection: null, events: [] });
+ mocks.getRunEventLedgerStats.mockResolvedValue({ activeEvents: 0, archivedEvents: 0 });
+ });
+
+ it('passes validated, coerced filters through to the ledger', async () => {
+ const res = await get('/run-events?runId=r1&kind=run.finalized&limit=25&since=2026-08-18T10:00:00.000Z');
+ expect(res.status).toBe(200);
+ // `limit` must arrive as a NUMBER — the service compares it numerically, so a
+ // raw query string would silently disable the cap.
+ expect(mocks.readRunEvents).toHaveBeenCalledWith({
+ runId: 'r1',
+ kind: 'run.finalized',
+ limit: 25,
+ since: '2026-08-18T10:00:00.000Z',
+ });
+ });
+
+ it('rejects a kind outside the closed event vocabulary', async () => {
+ const res = await get('/run-events?kind=run.invented');
+ expect(res.status).toBe(400);
+ expect(mocks.readRunEvents).not.toHaveBeenCalled();
+ });
+
+ it('rejects a limit above the ledger read ceiling', async () => {
+ expect((await get('/run-events?limit=100000')).status).toBe(400);
+ expect((await get('/run-events?limit=0')).status).toBe(400);
+ expect(mocks.readRunEvents).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown query key rather than ignoring it', async () => {
+ expect((await get('/run-events?nope=1')).status).toBe(400);
+ });
+
+ it('returns the ledger rows verbatim — redaction already happened on append', async () => {
+ const event = { eventId: 'e1', kind: 'run.spawned', runId: 'r1', at: '2026-08-18T10:00:00.000Z', data: {} };
+ mocks.readRunEvents.mockResolvedValue([event]);
+ const res = await get('/run-events');
+ expect(res.body).toEqual([event]);
+ });
+});
+
+describe('GET /run-events/projections', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getRunProjections.mockResolvedValue([{ id: 'r1', status: 'completed' }]);
+ });
+
+ it('serves the replayed projections', async () => {
+ const res = await get('/run-events/projections?runId=r1&limit=5');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ id: 'r1', status: 'completed' }]);
+ expect(mocks.getRunProjections).toHaveBeenCalledWith({ runId: 'r1', limit: 5 });
+ });
+
+ it('rejects an unknown filter', async () => {
+ expect((await get('/run-events/projections?kind=run.spawned')).status).toBe(400);
+ });
+});
+
+describe('GET /run-events/run/:id', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getRunDiagnostic.mockResolvedValue({ projection: { id: 'r1' }, events: [] });
+ });
+
+ it('serves one run diagnostic', async () => {
+ const res = await get('/run-events/run/r1');
+ expect(res.status).toBe(200);
+ expect(res.body.projection).toEqual({ id: 'r1' });
+ expect(mocks.getRunDiagnostic).toHaveBeenCalledWith('r1');
+ });
+
+ it('resolves the `agent:<id>` fallback key for a run that never got an id', async () => {
+ await get(`/run-events/run/${encodeURIComponent('agent:a9')}`);
+ expect(mocks.getRunDiagnostic).toHaveBeenCalledWith('agent:a9');
+ });
+
+ it('does not shadow the sibling /run-events routes', async () => {
+ await get('/run-events/stats');
+ expect(mocks.getRunEventLedgerStats).toHaveBeenCalled();
+ expect(mocks.getRunDiagnostic).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 8a6eb38143..61f08339de 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -31,6 +31,7 @@ import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { syncRunnerAgents } from './agentRunnerSync.js';
import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';
import { completeAgentRun } from './agentRunTracking.js';
+import { appendRunEvent } from './agentRunEventLog.js';
import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';
import { dispatchRecoveredTaskOutputHook } from './agentFinalization.js';
import { fileInvestigationTask } from './investigationTaskProducer.js';
@@ -945,6 +946,24 @@ export async function cleanupOrphanedAgents() {
console.log(interrupted
? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`
: `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);
+ // Record the reap in the lifecycle ledger BEFORE the run is closed
+ // (#4540), so the ordered stream reads "orphaned, then finalized" and a
+ // replay can tell an agent that died from one that exited. Emitted even
+ // when the agent record carries no `runId` — a survivor whose run id
+ // never landed is precisely the case the mutable records cannot explain,
+ // so it keys off the agent instead of disappearing.
+ await appendRunEvent({
+ kind: 'run.orphan-recovered',
+ runId: agent.metadata?.runId,
+ agentId: agent.id,
+ taskId: agent.taskId,
+ data: {
+ interruptedByRestart: interrupted,
+ pid: agent.pid ?? null,
+ hasRunId: Boolean(agent.metadata?.runId),
+ startedAt: agent.startedAt ?? null,
+ },
+ });
const task = agent.taskId ? await getTaskById(agent.taskId).catch(() => null) : null;
await dispatchRecoveredTaskOutputHook({
agentId: agent.id,
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index b910657cfe..ec31dba2b5 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -41,6 +41,12 @@ const AGENT_TUI_SRC = normalizeEol(readFileSync(join(__dirname, 'agentTuiSpawnin
const AGENT_LIFECYCLE_SRC = normalizeEol(readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8'));
const AGENT_MANAGEMENT_SRC = normalizeEol(readFileSync(join(__dirname, 'agentManagement.js'), 'utf-8'));
+// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl). Mocked
+// so the sweep's telemetry lands in a spy instead of the developing install's
+// ledger — and so the orphan-boundary assertion below can read the envelope.
+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));
+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));
+
vi.mock('./cos.js', () => ({
updateTask: vi.fn().mockResolvedValue(true),
addTask: vi.fn().mockResolvedValue({ id: 'sys-mocked' }),
@@ -1132,6 +1138,20 @@ describe('orphan retries resume what the dead run left behind', () => {
runnerAgents.clear();
});
+ // The sweep is the only place that knows an agent DIED rather than exited, so
+ // it is the only place that can put that distinction in the ledger (#4540).
+ it('records the reap in the lifecycle ledger, keyed by agent when no run id survived', async () => {
+ await cleanupOrphanedAgents();
+
+ expect(appendRunEvent).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'run.orphan-recovered',
+ agentId: 'agent-dead',
+ taskId: 'task-1',
+ runId: undefined,
+ data: expect.objectContaining({ hasRunId: false, interruptedByRestart: false })
+ }));
+ });
+
it('hands the dead agent’s worktree metadata from the sweep to the retry handler', async () => {
await cleanupOrphanedAgents();
diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.js
new file mode 100644
index 0000000000..62c5efc583
--- /dev/null
+++ b/server/services/agentRunEventLog.js
@@ -0,0 +1,240 @@
+/**
+ * CoS run event ledger — machine-local, append-only, bounded.
+ *
+ * Storage class `ephemeral-file` (see `docs/STORAGE.md`): the durable record of
+ * a run is still `data/runs/{id}/metadata.json`; this file is the ordered trace
+ * of how that record got where it is. It is **intentionally machine-local and
+ * never federated** — every line describes a process on this box, so a peer's
+ * copy would describe nothing that exists there. No sync cursor, no tombstone,
+ * no `PORTOS_SCHEMA_VERSIONS` entry.
+ *
+ * On disk:
+ * data/cos/run-events.jsonl — active generation
+ * data/cos/run-events.1.jsonl — the one retained archive generation
+ *
+ * The bound is a count, not a byte size, because the useful question is "how
+ * many transitions back can I look", and a count survives a payload-shape change
+ * that a byte cap would not. Once the active file reaches MAX_ACTIVE_EVENTS it
+ * becomes the archive and the previous archive is dropped, so the ledger holds
+ * between MAX_ACTIVE_EVENTS and 2×MAX_ACTIVE_EVENTS events forever.
+ *
+ * Two invariants the callers depend on:
+ *
+ * - **Appends never reject.** These are called from agent lifecycle paths,
+ * several of them inside child-process exit handlers where a throw takes the
+ * Node process with it. Telemetry must never be able to fail a run, so the
+ * promise chain absorbs and logs instead of propagating.
+ * - **Appends are serialized.** Every append goes through one module-level
+ * promise queue, so the file order matches the call order and the seen-id set
+ * can't be read between another append's check and its write.
+ */
+
+import { join } from 'path';
+import { rename, unlink } from 'fs/promises';
+import {
+ PATHS,
+ appendJSONLine,
+ readJSONLFile,
+ pathExists
+} from '../lib/fileUtils.js';
+import {
+ buildRunEvent,
+ isValidRunEvent,
+ projectRunStates,
+ AGENT_RUN_EVENT_KINDS
+} from '../lib/agentRunEvents.js';
+
+const ACTIVE_PATH = join(PATHS.cos, 'run-events.jsonl');
+const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');
+
+/**
+ * Events per generation. 5000 covers weeks of a busy install's lifecycle
+ * boundaries at a few hundred bytes per line — a couple of MB per generation.
+ */
+export const MAX_ACTIVE_EVENTS = 5000;
+
+/** Default page size for the read API, and the ceiling a caller can request. */
+export const DEFAULT_READ_LIMIT = 200;
+export const MAX_READ_LIMIT = 1000;
+
+// Lazily hydrated on first append/read. `null` (not an empty Set) is the
+// "never loaded" sentinel, so a genuinely empty ledger caches as empty instead
+// of re-reading both files on every single append.
+let activeIds = null;
+let archiveIds = null;
+let activeCount = 0;
+
+// Serializes appends; also the handle callers await.
+let appendQueue = Promise.resolve();
+
+async function hydrate() {
+ if (activeIds) return;
+ const [active, archive] = await Promise.all([
+ readJSONLFile(ACTIVE_PATH),
+ readJSONLFile(ARCHIVE_PATH)
+ ]);
+ activeIds = new Set(active.map((e) => e?.eventId).filter(Boolean));
+ archiveIds = new Set(archive.map((e) => e?.eventId).filter(Boolean));
+ activeCount = active.length;
+}
+
+/**
+ * Rotate when the active generation is full: active becomes the archive, the
+ * previous archive is dropped. The seen-id sets move with the files, so an
+ * event whose only copy just aged out of the ledger is appendable again — which
+ * is correct: a duplicate we can no longer see is no longer a duplicate.
+ */
+async function rotateIfFull() {
+ if (activeCount < MAX_ACTIVE_EVENTS) return;
+ if (await pathExists(ARCHIVE_PATH)) await unlink(ARCHIVE_PATH);
+ await rename(ACTIVE_PATH, ARCHIVE_PATH);
+ archiveIds = activeIds;
+ activeIds = new Set();
+ activeCount = 0;
+ console.log(`🔁 Rotated CoS run event ledger at ${MAX_ACTIVE_EVENTS} events`);
+}
+
+async function appendNow(input) {
+ const event = buildRunEvent(input);
+ await hydrate();
+ if (activeIds.has(event.eventId) || archiveIds.has(event.eventId)) {
+ return { appended: false, duplicate: true, event };
+ }
+ await rotateIfFull();
+ await appendJSONLine(ACTIVE_PATH, event);
+ activeIds.add(event.eventId);
+ activeCount += 1;
+ return { appended: true, duplicate: false, event };
+}
+
+/**
+ * Append one lifecycle event.
+ *
+ * Never rejects and never throws: a bad envelope or an unwritable disk is
+ * logged and swallowed, because no run may fail on account of its own
+ * telemetry. Returns `{ appended, duplicate, event }` on success and
+ * `{ appended: false, error }` when the append was dropped, so a caller that
+ * wants to know can look — none currently needs to.
+ *
+ * @param {object} input - see `buildRunEvent` in `lib/agentRunEvents.js`
+ * @returns {Promise<{appended: boolean, duplicate?: boolean, event?: object, error?: string}>}
+ */
+export function appendRunEvent(input) {
+ appendQueue = appendQueue.then(() => appendNow(input)).catch((err) => {
+ console.error(`❌ Failed to append CoS run event (${input?.kind}): ${err.message}`);
+ return { appended: false, error: err.message };
+ });
+ return appendQueue;
+}
+
+/** Resolve once every queued append has landed. Used by the read path + tests. */
+export function flushRunEvents() {
+ return appendQueue.then(() => undefined, () => undefined);
+}
+
+/**
+ * Read the ledger, oldest generation first so the result is in append order —
+ * which is what `projectRunStates` folds and what a replay needs.
+ *
+ * Filters are applied before the limit, and the limit keeps the NEWEST events
+ * (the tail), because a diagnostic asking for 50 events wants the last 50, not
+ * the first 50 of an aged-out generation.
+ *
+ * @param {object} [options]
+ * @param {string} [options.runId] - exact run id
+ * @param {string} [options.agentId] - exact agent id
+ * @param {string} [options.taskId] - exact task id
+ * @param {string} [options.kind] - one of AGENT_RUN_EVENT_KINDS
+ * @param {string} [options.since] - ISO timestamp; events strictly after it
+ * @param {number} [options.limit] - newest-N cap (default DEFAULT_READ_LIMIT)
+ * @returns {Promise<object[]>} validated events in append order
+ */
+export async function readRunEvents({ runId, agentId, taskId, kind, since, limit } = {}) {
+ await flushRunEvents();
+ const [archive, active] = await Promise.all([
+ readJSONLFile(ARCHIVE_PATH),
+ readJSONLFile(ACTIVE_PATH)
+ ]);
+ // A line that fails validation is a corrupt/truncated write, not data —
+ // dropping it keeps one bad line from poisoning the whole projection.
+ let events = [...archive, ...active].filter(isValidRunEvent);
+
+ if (runId) events = events.filter((e) => e.runId === runId);
+ if (agentId) events = events.filter((e) => e.agentId === agentId);
+ if (taskId) events = events.filter((e) => e.taskId === taskId);
+ if (kind) events = events.filter((e) => e.kind === kind);
+ if (since) events = events.filter((e) => e.at > since);
+
+ const cap = Math.min(Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_READ_LIMIT, MAX_READ_LIMIT);
+ return events.length > cap ? events.slice(events.length - cap) : events;
+}
+
+/**
+ * Replay the ledger into per-run current state.
+ *
+ * This is the "how did it get here" answer the mutable run record can't give.
+ * `limit` bounds the PROJECTIONS returned (newest activity first), never the
+ * events folded — the fold always runs over the newest `MAX_READ_LIMIT` events,
+ * so a run's spawn and finalize are read together rather than a paged read
+ * lopping the head off a lifecycle. Pass `runId` to fold one run's full history
+ * regardless of how much unrelated traffic followed it.
+ *
+ * @param {object} [options]
+ * @param {string} [options.runId] - restrict the replay to one run
+ * @param {string} [options.agentId] - restrict the replay to one agent
+ * @param {number} [options.limit] - max projections returned
+ * @returns {Promise<object[]>}
+ */
+export async function getRunProjections({ runId, agentId, limit } = {}) {
+ const events = await readRunEvents({ runId, agentId, limit: MAX_READ_LIMIT });
+ const states = projectRunStates(events);
+ const cap = Math.min(Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : DEFAULT_READ_LIMIT, MAX_READ_LIMIT);
+ return states.slice(0, cap);
+}
+
+/**
+ * One run's projection plus the events it was folded from.
+ *
+ * @param {string} id - a run id, or `agent:<agentId>` for a run that never got one
+ * @returns {Promise<{projection: object|null, events: object[]}>}
+ */
+export async function getRunDiagnostic(id) {
+ const isAgentKey = typeof id === 'string' && id.startsWith('agent:');
+ const events = isAgentKey
+ ? (await readRunEvents({ agentId: id.slice('agent:'.length), limit: MAX_READ_LIMIT })).filter((e) => !e.runId)
+ : await readRunEvents({ runId: id, limit: MAX_READ_LIMIT });
+ const projection = projectRunStates(events).find((state) => state.id === id) ?? null;
+ return { projection, events };
+}
+
+/**
+ * Ledger health for the diagnostics route: generation sizes and the bound they
+ * are held to, so "why is this run missing" has an answer that isn't a guess.
+ */
+export async function getRunEventLedgerStats() {
+ await flushRunEvents();
+ const [archive, active] = await Promise.all([
+ readJSONLFile(ARCHIVE_PATH),
+ readJSONLFile(ACTIVE_PATH)
+ ]);
+ return {
+ activeEvents: active.length,
+ archivedEvents: archive.length,
+ maxActiveEvents: MAX_ACTIVE_EVENTS,
+ maxRetainedEvents: MAX_ACTIVE_EVENTS * 2,
+ kinds: AGENT_RUN_EVENT_KINDS
+ };
+}
+
+/**
+ * Drop every cached seen-id set so the next call re-reads from disk.
+ *
+ * Exported for tests, which write ledger files directly to simulate a restart —
+ * the in-process caches are exactly what a real restart discards.
+ */
+export function __resetRunEventLogCache() {
+ activeIds = null;
+ archiveIds = null;
+ activeCount = 0;
+ appendQueue = Promise.resolve();
+}
diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.js
new file mode 100644
index 0000000000..b5cff1c54b
--- /dev/null
+++ b/server/services/agentRunEventLog.test.js
@@ -0,0 +1,264 @@
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { rmSync, writeFileSync, existsSync, readFileSync } from 'fs';
+import { join } from 'path';
+
+// Point PATHS.cos at a throwaway dir so the suite never touches the real
+// install's ledger. Hoisted because the service resolves its file paths at
+// module load — the same reason a real restart is what re-reads them.
+// (async so the hoisted factory can `import` — hoisting runs it before this
+// module's own static imports have initialized.)
+const { LEDGER_DIR } = await vi.hoisted(async () => {
+ const { mkdtempSync: mk } = await import('fs');
+ const { tmpdir: tmp } = await import('os');
+ const { join: j } = await import('path');
+ return { LEDGER_DIR: mk(j(tmp(), 'portos-run-events-')) };
+});
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, cos: LEDGER_DIR } };
+});
+
+const {
+ appendRunEvent,
+ readRunEvents,
+ getRunProjections,
+ getRunDiagnostic,
+ getRunEventLedgerStats,
+ flushRunEvents,
+ __resetRunEventLogCache,
+ MAX_ACTIVE_EVENTS
+} = await import('./agentRunEventLog.js');
+const { buildRunEvent } = await import('../lib/agentRunEvents.js');
+
+const ACTIVE = join(LEDGER_DIR, 'run-events.jsonl');
+const ARCHIVE = join(LEDGER_DIR, 'run-events.1.jsonl');
+
+/** Wipe the on-disk ledger AND the in-process caches — i.e. a fresh install. */
+function resetLedger() {
+ for (const path of [ACTIVE, ARCHIVE]) if (existsSync(path)) rmSync(path);
+ __resetRunEventLogCache();
+}
+
+/** Drop only the in-process caches — i.e. a server restart over the same disk. */
+const restartServer = () => __resetRunEventLogCache();
+
+const countLines = (path) => (existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).length : 0);
+
+beforeEach(resetLedger);
+afterAll(() => rmSync(LEDGER_DIR, { recursive: true, force: true }));
+
+describe('appendRunEvent', () => {
+ it('appends one JSON line per event, in call order', async () => {
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:00:00.000Z' });
+ await appendRunEvent({ kind: 'run.finalized', runId: 'r1', at: '2026-08-18T11:00:00.000Z', data: { success: true, exitCode: 0 } });
+
+ const events = await readRunEvents();
+ expect(events.map((e) => e.kind)).toEqual(['run.spawned', 'run.finalized']);
+ expect(countLines(ACTIVE)).toBe(2);
+ });
+
+ it('serializes concurrent appends so the file order matches the call order', async () => {
+ // Several lifecycle boundaries can fire at once; interleaved appends would
+ // both read the seen-id set before either wrote, defeating deduplication.
+ await Promise.all(
+ Array.from({ length: 20 }, (_, i) =>
+ appendRunEvent({ kind: 'run.spawned', runId: `r${i}`, at: `2026-08-18T10:00:${String(i).padStart(2, '0')}.000Z` })
+ )
+ );
+ const events = await readRunEvents();
+ expect(events).toHaveLength(20);
+ expect(events.map((e) => e.runId)).toEqual(Array.from({ length: 20 }, (_, i) => `r${i}`));
+ });
+
+ it('never rejects when the envelope is invalid — telemetry cannot fail a run', async () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const result = await appendRunEvent({ kind: 'not-a-kind', runId: 'r1' });
+ expect(result.appended).toBe(false);
+ expect(result.error).toBeTruthy();
+ expect(await readRunEvents()).toEqual([]);
+ // A later good append still lands — one bad envelope must not wedge the queue.
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r2', at: '2026-08-18T10:00:00.000Z' });
+ expect(await readRunEvents()).toHaveLength(1);
+ spy.mockRestore();
+ });
+
+ it('redacts the payload before it reaches disk', async () => {
+ await appendRunEvent({
+ kind: 'run.spawned',
+ runId: 'r1',
+ at: '2026-08-18T10:00:00.000Z',
+ data: { prompt: 'a private task description', model: 'm1' }
+ });
+ const raw = readFileSync(ACTIVE, 'utf8');
+ expect(raw).not.toContain('a private task description');
+ expect(raw).toContain('"redacted":"content"');
+ expect(raw).toContain('"model":"m1"');
+ });
+});
+
+describe('duplicate-event idempotency', () => {
+ const event = { kind: 'run.finalized', runId: 'r1', agentId: 'a1', at: '2026-08-18T11:00:00.000Z', data: { success: true, exitCode: 0 } };
+
+ it('suppresses a redelivery of the same logical event', async () => {
+ const first = await appendRunEvent(event);
+ const second = await appendRunEvent({ ...event });
+ expect(first).toMatchObject({ appended: true, duplicate: false });
+ expect(second).toMatchObject({ appended: false, duplicate: true });
+ expect(countLines(ACTIVE)).toBe(1);
+ });
+
+ it('still suppresses it across a server restart', async () => {
+ // The seen-id set is in memory; a restart must rehydrate it from disk or
+ // every boundary that re-fires after a restart doubles.
+ await appendRunEvent(event);
+ restartServer();
+ expect(await appendRunEvent({ ...event })).toMatchObject({ appended: false, duplicate: true });
+ expect(countLines(ACTIVE)).toBe(1);
+ });
+
+ it('suppresses a redelivery of an event that has aged into the archive', async () => {
+ writeFileSync(ARCHIVE, `${JSON.stringify(buildRunEvent(event))}\n`);
+ restartServer();
+ expect(await appendRunEvent({ ...event })).toMatchObject({ appended: false, duplicate: true });
+ expect(countLines(ACTIVE)).toBe(0);
+ });
+
+ it('does NOT suppress a genuinely different event at the same boundary', async () => {
+ await appendRunEvent(event);
+ const other = await appendRunEvent({ ...event, at: '2026-08-18T11:00:01.000Z' });
+ expect(other.appended).toBe(true);
+ expect(countLines(ACTIVE)).toBe(2);
+ });
+});
+
+describe('retention / rotation bound', () => {
+ it('rotates at MAX_ACTIVE_EVENTS and keeps exactly one archive generation', async () => {
+ const seed = (n, offset = 0) => Array.from({ length: n }, (_, i) =>
+ `${JSON.stringify(buildRunEvent({ kind: 'run.spawned', runId: `r${offset + i}`, at: '2026-08-18T10:00:00.000Z' }))}\n`).join('');
+
+ // Pre-fill a full active generation and a full archive, then restart so the
+ // service counts them off disk the way it would after a reboot.
+ writeFileSync(ACTIVE, seed(MAX_ACTIVE_EVENTS));
+ writeFileSync(ARCHIVE, seed(MAX_ACTIVE_EVENTS, MAX_ACTIVE_EVENTS));
+ restartServer();
+
+ await appendRunEvent({ kind: 'run.spawned', runId: 'fresh', at: '2026-08-18T12:00:00.000Z' });
+
+ // The old archive is gone, the old active IS the archive, and the new event
+ // is alone in the new active generation.
+ expect(countLines(ACTIVE)).toBe(1);
+ expect(countLines(ARCHIVE)).toBe(MAX_ACTIVE_EVENTS);
+ const stats = await getRunEventLedgerStats();
+ expect(stats.activeEvents + stats.archivedEvents).toBeLessThanOrEqual(stats.maxRetainedEvents);
+ expect(stats.maxActiveEvents).toBe(MAX_ACTIVE_EVENTS);
+ });
+
+ it('rotates without an existing archive on the very first rollover', async () => {
+ writeFileSync(ACTIVE, Array.from({ length: MAX_ACTIVE_EVENTS }, (_, i) =>
+ `${JSON.stringify(buildRunEvent({ kind: 'run.spawned', runId: `r${i}`, at: '2026-08-18T10:00:00.000Z' }))}\n`).join(''));
+ restartServer();
+
+ await appendRunEvent({ kind: 'run.spawned', runId: 'fresh', at: '2026-08-18T12:00:00.000Z' });
+ expect(countLines(ARCHIVE)).toBe(MAX_ACTIVE_EVENTS);
+ expect(countLines(ACTIVE)).toBe(1);
+ });
+});
+
+describe('readRunEvents', () => {
+ beforeEach(async () => {
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', taskId: 't1', at: '2026-08-18T10:00:00.000Z' });
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r2', agentId: 'a2', taskId: 't2', at: '2026-08-18T10:05:00.000Z' });
+ await appendRunEvent({ kind: 'run.finalized', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:10:00.000Z', data: { success: true } });
+ });
+
+ it('reads an absent ledger as empty rather than failing', async () => {
+ resetLedger();
+ expect(await readRunEvents()).toEqual([]);
+ expect(await getRunProjections()).toEqual([]);
+ });
+
+ it('filters by run, agent, task, and kind', async () => {
+ expect(await readRunEvents({ runId: 'r1' })).toHaveLength(2);
+ expect(await readRunEvents({ agentId: 'a2' })).toHaveLength(1);
+ expect(await readRunEvents({ taskId: 't2' })).toHaveLength(1);
+ expect(await readRunEvents({ kind: 'run.finalized' })).toHaveLength(1);
+ expect(await readRunEvents({ since: '2026-08-18T10:04:00.000Z' })).toHaveLength(2);
+ });
+
+ it('keeps the NEWEST events when a limit truncates', async () => {
+ const events = await readRunEvents({ limit: 1 });
+ expect(events.map((e) => e.kind)).toEqual(['run.finalized']);
+ });
+
+ it('reads the archive generation before the active one, preserving append order', async () => {
+ const all = await readRunEvents();
+ writeFileSync(ARCHIVE, readFileSync(ACTIVE, 'utf8'));
+ writeFileSync(ACTIVE, '');
+ restartServer();
+ expect((await readRunEvents()).map((e) => e.eventId)).toEqual(all.map((e) => e.eventId));
+ });
+
+ it('drops a corrupt line instead of poisoning the whole read', async () => {
+ writeFileSync(ACTIVE, `${readFileSync(ACTIVE, 'utf8')}{"eventId":"x","kind":"nope"}\nnot json at all\n`);
+ restartServer();
+ const events = await readRunEvents();
+ expect(events).toHaveLength(3);
+ expect(events.every((e) => e.schemaVersion === 1)).toBe(true);
+ });
+});
+
+describe('replay / projections', () => {
+ it('derives current run status from the stream after a restart', async () => {
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', taskId: 't1', at: '2026-08-18T10:00:00.000Z', data: { model: 'm1' } });
+ await appendRunEvent({ kind: 'run.runner-recovered', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:30:00.000Z' });
+ await appendRunEvent({ kind: 'run.finalized', runId: 'r1', agentId: 'a1', at: '2026-08-18T11:00:00.000Z', data: { success: false, exitCode: 1, errorCategory: 'orphaned' } });
+ await flushRunEvents();
+
+ restartServer();
+
+ const [state] = await getRunProjections();
+ expect(state).toMatchObject({
+ id: 'r1',
+ status: 'failed',
+ success: false,
+ exitCode: 1,
+ errorCategory: 'orphaned',
+ recoveryCount: 1,
+ eventCount: 3
+ });
+ });
+
+ it('scopes projections to one run when asked', async () => {
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', at: '2026-08-18T10:00:00.000Z' });
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r2', at: '2026-08-18T10:01:00.000Z' });
+ const states = await getRunProjections({ runId: 'r2' });
+ expect(states.map((s) => s.id)).toEqual(['r2']);
+ });
+
+ it('getRunDiagnostic returns one run projection plus the events behind it', async () => {
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:00:00.000Z' });
+ await appendRunEvent({ kind: 'run.orphan-recovered', runId: 'r1', agentId: 'a1', at: '2026-08-18T10:05:00.000Z' });
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r2', at: '2026-08-18T10:06:00.000Z' });
+
+ const { projection, events } = await getRunDiagnostic('r1');
+ expect(projection.status).toBe('orphaned');
+ expect(events).toHaveLength(2);
+ expect(events.every((e) => e.runId === 'r1')).toBe(true);
+ });
+
+ it('getRunDiagnostic resolves the agent fallback key for a run that never got an id', async () => {
+ await appendRunEvent({ kind: 'run.orphan-recovered', agentId: 'a9', taskId: 't9', at: '2026-08-18T10:00:00.000Z', data: { hasRunId: false } });
+ // An id-bearing event for the same agent belongs to the run, not the fallback bucket.
+ await appendRunEvent({ kind: 'run.spawned', runId: 'r9', agentId: 'a9', at: '2026-08-18T10:01:00.000Z' });
+
+ const { projection, events } = await getRunDiagnostic('agent:a9');
+ expect(projection.id).toBe('agent:a9');
+ expect(projection.status).toBe('orphaned');
+ expect(events).toHaveLength(1);
+ });
+
+ it('reports an unknown id as no projection rather than throwing', async () => {
+ expect(await getRunDiagnostic('nope')).toEqual({ projection: null, events: [] });
+ });
+});
diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.js
index 831545f51a..e40e0143f3 100644
--- a/server/services/agentRunTracking.js
+++ b/server/services/agentRunTracking.js
@@ -11,6 +11,7 @@ import { recordSession } from './usage.js';
import { recordCompletedRunUsage } from './usageReconciler.js';
import { committedDuringRun } from '../lib/gitCommitProbe.js';
import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
+import { appendRunEvent } from './agentRunEventLog.js';
const RUNS_DIR = PATHS.runs;
@@ -66,6 +67,26 @@ export async function createAgentRun({ agentId, task, model, provider, workspace
console.error(`❌ Failed to record usage session: ${err.message}`);
});
+ // Open the run's entry in the append-only lifecycle ledger (#4540). Additive:
+ // `metadata.json` above remains the durable run record; this is the ordered
+ // trace that survives the in-place updates. Deliberately NOT given the task
+ // description — the ledger redacts prompts, so passing one would only produce
+ // a `{ redacted }` stub. `appendRunEvent` never rejects.
+ await appendRunEvent({
+ kind: 'run.spawned',
+ runId,
+ agentId,
+ taskId: task.id,
+ at: metadata.startTime,
+ data: {
+ providerId: provider.id,
+ model: metadata.model,
+ workspacePath,
+ workspaceName: metadata.workspaceName,
+ promptChars: metadata.promptLength
+ }
+ });
+
return { runId, runDir };
}
@@ -140,6 +161,28 @@ export async function completeAgentRun(runId, output, exitCode, duration, errorA
if (metadata.providerId && metadata.model) {
recordCompletedRunUsage(metadata, output);
}
+
+ // Close the run's ledger entry (#4540). This is the terminal event for every
+ // exit path — clean exits, spawn errors, and the orphan sweep all land here —
+ // so `projectRunStates` can trust `run.finalized` to outrank an earlier
+ // `run.orphan-recovered`. The verdict recorded is the RESOLVED one (after the
+ // commit rescue and the `successOverride`), not the raw exit code, because
+ // that is the verdict the run record now carries.
+ await appendRunEvent({
+ kind: 'run.finalized',
+ runId,
+ agentId: metadata.agentId,
+ taskId: metadata.taskId,
+ at: metadata.endTime,
+ data: {
+ success,
+ exitCode,
+ durationMs: Number.isFinite(duration) ? duration : null,
+ outputBytes: metadata.outputSize,
+ errorCategory: metadata.errorCategory ?? null,
+ successOverridden: successOverride === false
+ }
+ });
}
/**
diff --git a/server/services/agentRunTracking.test.js b/server/services/agentRunTracking.test.js
index 6dc37d1c16..bbc3f41aa7 100644
--- a/server/services/agentRunTracking.test.js
+++ b/server/services/agentRunTracking.test.js
@@ -1,6 +1,12 @@
import { describe, expect, it, vi } from 'vitest';
import { extractErrorFromOutput } from './agentRunTracking.js';
+// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl). Mocked
+// so these suites do not append test telemetry to the developing install's
+// ledger — and so the boundary assertion below can read the envelope.
+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));
+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));
+
// extractErrorFromOutput is the real home of the exit-code → message mapping
// and the output error-pattern scan. subAgentSpawner.test.js used to assert an
// inline `exitCodeMessages` literal copy that exercised no production code.
@@ -161,3 +167,62 @@ describe('completeAgentRun idempotency', () => {
);
});
});
+
+// The run record is mutated in place, so after a finalize it can no longer say
+// how the run got there. The ledger entry is what preserves that (#4540).
+describe('completeAgentRun lifecycle ledger', () => {
+ it('records the RESOLVED verdict, not the raw exit code', async () => {
+ vi.resetModules();
+ appendRunEvent.mockClear();
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue({
+ id: 'run-overridden',
+ endTime: null,
+ agentId: 'agent-1',
+ taskId: 'task-1',
+ startTime: '2026-07-29T00:00:00.000Z',
+ providerId: null,
+ }),
+ atomicWrite: vi.fn(),
+ }));
+ vi.doMock('fs/promises', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeFile: vi.fn(),
+ }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ // Exit 0, but the caller's successOverride says the deliverable never landed
+ // (#3358) — the ledger must agree with the run record, not with the process.
+ await completeAgentRun('run-overridden', 'output', 0, 4200, null, false);
+
+ expect(appendRunEvent).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'run.finalized',
+ runId: 'run-overridden',
+ agentId: 'agent-1',
+ taskId: 'task-1',
+ data: expect.objectContaining({
+ success: false,
+ exitCode: 0,
+ durationMs: 4200,
+ successOverridden: true,
+ }),
+ }));
+ });
+
+ it('appends nothing for a run that was already closed', async () => {
+ vi.resetModules();
+ appendRunEvent.mockClear();
+ vi.doMock('../lib/fileUtils.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readJSONFile: vi.fn().mockResolvedValue({ id: 'run-closed', endTime: '2026-07-29T00:00:00.000Z' }),
+ atomicWrite: vi.fn(),
+ }));
+ const { completeAgentRun } = await import('./agentRunTracking.js');
+
+ await completeAgentRun('run-closed', 'output', 1, 100);
+ await completeAgentRun(null, 'output', 1, 100);
+
+ expect(appendRunEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.js
index 6311998e1a..7bc99fad90 100644
--- a/server/services/agentRunnerSync.js
+++ b/server/services/agentRunnerSync.js
@@ -15,6 +15,7 @@ import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunn
import { isInternalTaskId } from '../lib/taskParser.js';
import { isAgentOwnedLocally, runnerAgents } from './agentState.js';
import { getAgent } from './cosAgentLifecycle.js';
+import { appendRunEvent } from './agentRunEventLog.js';
import * as shellService from './shell.js';
/**
@@ -92,6 +93,22 @@ export async function syncRunnerAgents() {
if (!recoveredRunId) {
console.warn(`⚠️ Recovered agent ${agent.id} has no run id on record — its run stays open and unbilled`);
}
+ // Record the re-adoption in the lifecycle ledger (#4540). `recoveryCount`
+ // in the projection is what turns "this run has been running for nine
+ // hours" into "this run has survived three restarts", and `hasRunId:false`
+ // is the durable trace of the unbilled-run warning above — today that
+ // warning only exists in a console line nothing retains.
+ await appendRunEvent({
+ kind: 'run.runner-recovered',
+ runId: recoveredRunId,
+ agentId: agent.id,
+ taskId: agent.taskId,
+ data: {
+ kind: agent.kind ?? null,
+ hasRunId: Boolean(recoveredRunId),
+ startedAt: agent.startedAt ?? null,
+ },
+ });
if (agent.kind === 'tui' && agent.sessionId && !shellService.getSession(agent.sessionId)) {
const session = connectTuiSessionViaRunner(agent);
shellService.registerExternalSession(agent.sessionId, session.ptyProcess, {
diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.js
index d7f2697dc9..38ce0174b2 100644
--- a/server/services/agentRunnerSync.test.js
+++ b/server/services/agentRunnerSync.test.js
@@ -34,6 +34,12 @@ vi.mock('./cosAgentLifecycle.js', () => ({
getAgent: vi.fn(),
}));
+// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) —
+// mocked so recovery telemetry lands in a spy rather than the developing
+// install's ledger, and so the boundary assertion below can read the envelope.
+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));
+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));
+
import { connectTuiSessionViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';
import * as shellService from './shell.js';
import { getAgent } from './cosAgentLifecycle.js';
@@ -113,6 +119,14 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {
await expect(syncRunnerAgents()).resolves.toBe(1);
expect(runnerAgents.get('agent-2')).toMatchObject({ runId: null });
+ // Today the unbilled-run warning exists only as a console line nothing
+ // retains; the ledger is what makes it answerable after the fact (#4540).
+ expect(appendRunEvent).toHaveBeenCalledWith(expect.objectContaining({
+ kind: 'run.runner-recovered',
+ agentId: 'agent-2',
+ runId: null,
+ data: expect.objectContaining({ hasRunId: false })
+ }));
});
// A live runner-TUI is owned by this process's spawnTuiAgent closure, which