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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: record the remaining CoS run lifecycle boundaries and age out the ledger (#4540)
[._.]/ Adam Eivyba9416d4a8fb
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 74b27d5264..4c6c6f24e5 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -19,6 +19,7 @@ import {ExternalLink,Crown,Play,+ ScrollText,Camera,Brain,Heart,@@ -200,6 +201,7 @@ const navItems = [{ to: '/cos/health', label: 'Health', icon: Activity },{ to: '/cos/learning', label: 'Learning', icon: GraduationCap },{ to: '/cos/memory', label: 'Memory', icon: Brain },+ { to: '/cos/run-events', label: 'Run Events', icon: ScrollText },{ to: '/cos/runs', label: 'Runs', icon: Play },{ to: '/cos/schedule', label: 'Schedule', icon: Clock },{ to: '/agents', label: 'Social Agents', icon: Users },diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 9635dd8d92..29be2f2f45 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -12,7 +12,8 @@ import {Flame,Newspaper,ChartGantt,- Play+ Play,+ ScrollText} from 'lucide-react';import { normalizeReviewerSlug } from '../../lib/reviewerPins';import { inPlaceClipName } from '../../utils/animationClips';@@ -23,6 +24,7 @@ export const TABS = [{ id: 'agents', label: 'Agents', icon: Cpu },{ id: 'jobs', label: 'System Tasks', icon: Bot },{ id: 'runs', label: 'Runs', icon: Play },+ { id: 'run-events', label: 'Run Events', icon: ScrollText },{ id: 'schedule', label: 'Schedule', icon: Clock },{ id: 'workflow', label: 'Timeline', icon: ChartGantt },{ id: 'digest', label: 'Digest', icon: Calendar },diff --git a/client/src/components/cos/tabs/RunEventsTab.jsx b/client/src/components/cos/tabs/RunEventsTab.jsxnew file mode 100644index 0000000000..5b5ab115c8--- /dev/null+++ b/client/src/components/cos/tabs/RunEventsTab.jsx@@ -0,0 +1,278 @@+import { useState, useEffect, useCallback } from 'react';+import { useSearchParams } from 'react-router';+import { RefreshCw, ScrollText } from 'lucide-react';+import * as api from '../../../services/api';+import { formatDateTime, formatRuntime, formatBytes, timeAgo } from '../../../utils/formatters';+import BrailleSpinner from '../../BrailleSpinner';+import Banner from '../../ui/Banner';++/**+ * Read-only diagnostic over the append-only CoS run event ledger (#4540).+ *+ * The Runs tab next door shows what a run IS — the mutable record, updated in+ * place. This one shows how it got there: the ordered lifecycle stream, and the+ * status the server derives by replaying it. The two can legitimately disagree,+ * and when they do, the disagreement is the finding — a run whose record says+ * "running" but whose stream ends at `run.interrupted` is a kill that never+ * took; a run with three `run.runner-recovered` events has survived three+ * restarts. Neither is visible anywhere else.+ *+ * Everything here is a GET. The ledger is written only by the server's own+ * lifecycle boundaries, so there is nothing to mutate from the UI.+ */++/** Projection status → the badge classes for it. */+const STATUS_STYLES = {+ running: 'bg-blue-500/15 text-blue-400 border-blue-500/30',+ completed: 'bg-green-500/15 text-green-400 border-green-500/30',+ failed: 'bg-red-500/15 text-red-400 border-red-500/30',+ orphaned: 'bg-orange-500/15 text-orange-400 border-orange-500/30',+ interrupted: 'bg-yellow-500/15 text-yellow-400 border-yellow-500/30',+ paused: 'bg-purple-500/15 text-purple-400 border-purple-500/30',+ unknown: 'bg-port-border/40 text-port-text-muted border-port-border'+};++export function statusClasses(status) {+ return STATUS_STYLES[status] || STATUS_STYLES.unknown;+}++/**+ * The one-line "what else happened to this run" summary.+ *+ * Only counts that are actually non-zero appear: a run with no handoffs, no+ * reconnects and no pauses is the normal case, and printing three zeroes for it+ * would bury the runs where those numbers are the whole story.+ */+export function projectionAnnotations(projection) {+ const parts = [];+ if (projection.handoffCount > 0) parts.push(`${projection.handoffCount} handoff${projection.handoffCount === 1 ? '' : 's'}`);+ if (projection.recoveryCount > 0) parts.push(`${projection.recoveryCount} recovery${projection.recoveryCount === 1 ? '' : ' events'}`);+ if (projection.reconnectCount > 0) parts.push(`${projection.reconnectCount} reconnect${projection.reconnectCount === 1 ? '' : 's'}`);+ if (projection.pauseCount > 0) parts.push(`${projection.pauseCount} pause${projection.pauseCount === 1 ? '' : 's'}`);+ if (projection.orphaned) parts.push('orphaned');+ if (projection.interrupted) parts.push('interrupt requested');+ if (projection.prVerified === false) parts.push('PR unverified');+ return parts;+}++/** Render one event's redacted payload as compact `key=value` pairs. */+export function summarizeEventData(data) {+ if (!data || typeof data !== 'object') return '';+ return Object.entries(data)+ .map(([key, value]) => {+ if (value === null || value === undefined) return null;+ if (typeof value === 'object') return `${key}=${value.redacted ? `«${value.redacted}»` : '{…}'}`;+ return `${key}=${value}`;+ })+ .filter(Boolean)+ .join(' ');+}++export default function RunEventsTab() {+ const [searchParams, setSearchParams] = useSearchParams();+ // Selection lives in the URL so a diagnostic is shareable and reload-safe.+ const selectedId = searchParams.get('run');++ const [stats, setStats] = useState(null);+ const [projections, setProjections] = useState([]);+ const [detail, setDetail] = useState(null);+ const [loading, setLoading] = useState(true);+ const [detailLoading, setDetailLoading] = useState(false);+ const [loadError, setLoadError] = useState(false);++ const loadLedger = useCallback(async () => {+ setLoading(true);+ // `null` is the "could not fetch" sentinel; `[]` is a genuinely empty+ // ledger. Collapsing the two would render "no runs recorded" for a server+ // that is simply unreachable.+ const [nextStats, nextProjections] = await Promise.all([+ api.getRunEventStats({ silent: true }).catch(() => null),+ api.getRunEventProjections({ limit: 100 }, { silent: true }).catch(() => null)+ ]);+ setStats(nextStats);+ setProjections(Array.isArray(nextProjections) ? nextProjections : []);+ setLoadError(nextStats === null || nextProjections === null);+ setLoading(false);+ }, []);++ useEffect(() => {+ loadLedger();+ }, [loadLedger]);++ useEffect(() => {+ if (!selectedId) {+ setDetail(null);+ return;+ }+ let cancelled = false;+ setDetailLoading(true);+ api.getRunEventDiagnostic(selectedId, { silent: true })+ .catch(() => ({ projection: null, events: [] }))+ .then((next) => {+ if (cancelled) return;+ setDetail(next);+ setDetailLoading(false);+ });+ return () => { cancelled = true; };+ }, [selectedId]);++ const select = (id) => {+ const next = new URLSearchParams(searchParams);+ if (id) next.set('run', id); else next.delete('run');+ setSearchParams(next, { replace: true });+ };++ if (loading) {+ return <div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading run events" /></div>;+ }++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div>+ <h2 className="text-lg font-semibold text-port-text">Run Event Ledger</h2>+ <p className="text-sm text-port-text-muted">+ The ordered lifecycle stream behind every CoS run, and the status derived by replaying it.+ </p>+ </div>+ <button+ type="button"+ onClick={loadLedger}+ className="flex items-center gap-2 rounded border border-port-border px-3 py-1.5 text-sm text-port-text hover:bg-port-border/30"+ >+ <RefreshCw className="h-4 w-4" /> Refresh+ </button>+ </div>++ {loadError && (+ <Banner tone="error">Could not read the run event ledger. The values below may be incomplete.</Banner>+ )}++ {stats && (+ <div className="grid grid-cols-2 gap-3 md:grid-cols-4">+ <LedgerStat label="Active generation" value={`${stats.activeEvents} / ${stats.maxActiveEvents}`} />+ <LedgerStat label="Archived" value={String(stats.archivedEvents)} />+ <LedgerStat label="Retention" value={`${stats.maxRetainedEvents} events · ${stats.maxEventAgeDays}d`} />+ <LedgerStat label="Oldest event" value={stats.oldestEventAt ? timeAgo(stats.oldestEventAt) : '—'} />+ </div>+ )}++ {projections.length === 0 ? (+ <Banner tone="info">+ No lifecycle events recorded yet. The ledger fills as CoS agents spawn, hand off, pause, and finish.+ </Banner>+ ) : (+ <div className="grid gap-4 lg:grid-cols-2">+ <ul className="max-h-[28rem] space-y-2 overflow-y-auto pr-1">+ {projections.map((projection) => (+ <li key={projection.id}>+ <button+ type="button"+ onClick={() => select(projection.id)}+ className={`w-full rounded border px-3 py-2 text-left transition-colors ${+ projection.id === selectedId+ ? 'border-port-accent bg-port-accent/10'+ : 'border-port-border hover:bg-port-border/20'+ }`}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="truncate font-mono text-xs text-port-text">{projection.id}</span>+ <span className={`shrink-0 rounded border px-2 py-0.5 text-xs ${statusClasses(projection.status)}`}>+ {projection.status}+ </span>+ </div>+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-port-text-muted">+ <span>{projection.eventCount} events</span>+ <span>{timeAgo(projection.lastEventAt)}</span>+ {projectionAnnotations(projection).map((note) => (+ <span key={note} className="rounded bg-port-border/40 px-1.5 py-0.5">{note}</span>+ ))}+ </div>+ </button>+ </li>+ ))}+ </ul>++ <div className="rounded border border-port-border p-3">+ {!selectedId && (+ <p className="flex items-center gap-2 text-sm text-port-text-muted">+ <ScrollText className="h-4 w-4" /> Select a run to replay its lifecycle.+ </p>+ )}+ {selectedId && detailLoading && <BrailleSpinner text="Replaying" />}+ {selectedId && !detailLoading && <RunDiagnostic detail={detail} />}+ </div>+ </div>+ )}+ </div>+ );+}++function LedgerStat({ label, value }) {+ return (+ <div className="rounded border border-port-border px-3 py-2">+ <div className="text-xs text-port-text-muted">{label}</div>+ <div className="text-sm font-medium text-port-text">{value}</div>+ </div>+ );+}++function RunDiagnostic({ detail }) {+ const projection = detail?.projection ?? null;+ const events = detail?.events ?? [];++ if (!projection && events.length === 0) {+ // A live run whose events have aged out of the ledger lands here — the run+ // may still exist, so this says "not in the ledger", not "not found".+ return <Banner tone="info">This run has no events in the ledger. It may have aged out of retention.</Banner>;+ }++ return (+ <div className="space-y-3">+ {projection && (+ <dl className="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">+ <Field label="Status" value={projection.status} />+ <Field label="Agent" value={projection.agentId} />+ <Field label="Task" value={projection.taskId} />+ <Field label="Owner" value={projection.owner} />+ <Field label="Started" value={projection.startedAt ? formatDateTime(projection.startedAt) : null} />+ <Field label="Ended" value={projection.endedAt ? formatDateTime(projection.endedAt) : null} />+ <Field label="Duration" value={Number.isFinite(projection.durationMs) ? formatRuntime(projection.durationMs) : null} />+ <Field label="Exit code" value={projection.exitCode === null ? null : String(projection.exitCode)} />+ <Field label="Output" value={Number.isFinite(projection.outputBytes) ? formatBytes(projection.outputBytes) : null} />+ <Field label="PR verified" value={projection.prVerified === null ? null : String(projection.prVerified)} />+ </dl>+ )}++ <div className="max-h-72 overflow-y-auto">+ <table className="w-full text-left text-xs">+ <thead className="text-port-text-muted">+ <tr>+ <th className="py-1 pr-2 font-normal">When</th>+ <th className="py-1 pr-2 font-normal">Event</th>+ <th className="py-1 font-normal">Detail</th>+ </tr>+ </thead>+ <tbody>+ {events.map((event) => (+ <tr key={event.eventId} className="border-t border-port-border/60 align-top">+ <td className="whitespace-nowrap py-1 pr-2 text-port-text-muted">{formatDateTime(event.at)}</td>+ <td className="whitespace-nowrap py-1 pr-2 font-mono text-port-text">{event.kind}</td>+ <td className="break-all py-1 font-mono text-port-text-muted">{summarizeEventData(event.data)}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ );+}++function Field({ label, value }) {+ return (+ <>+ <dt className="text-port-text-muted">{label}</dt>+ <dd className="truncate text-port-text">{value ?? '—'}</dd>+ </>+ );+}diff --git a/client/src/components/cos/tabs/RunEventsTab.test.jsx b/client/src/components/cos/tabs/RunEventsTab.test.jsxnew file mode 100644index 0000000000..4405cfccc5--- /dev/null+++ b/client/src/components/cos/tabs/RunEventsTab.test.jsx@@ -0,0 +1,141 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++const api = vi.hoisted(() => ({+ getRunEventStats: vi.fn(),+ getRunEventProjections: vi.fn(),+ getRunEventDiagnostic: vi.fn(),+}));++vi.mock('../../../services/api', () => api);++import RunEventsTab, { projectionAnnotations, summarizeEventData } from './RunEventsTab';++const STATS = {+ activeEvents: 12,+ archivedEvents: 3,+ maxActiveEvents: 5000,+ maxRetainedEvents: 10000,+ maxEventAgeDays: 30,+ oldestEventAt: '2026-08-01T00:00:00.000Z',+};++const projection = (overrides = {}) => ({+ id: 'run-a',+ runId: 'run-a',+ agentId: 'agent-a',+ taskId: 'task-a',+ status: 'completed',+ startedAt: '2026-08-18T10:00:00.000Z',+ endedAt: '2026-08-18T11:00:00.000Z',+ durationMs: 3600000,+ exitCode: 0,+ success: true,+ orphaned: false,+ interrupted: false,+ paused: false,+ recoveryCount: 0,+ handoffCount: 0,+ reconnectCount: 0,+ pauseCount: 0,+ owner: null,+ outputBytes: null,+ lastOutputAt: null,+ prVerified: null,+ eventCount: 2,+ firstEventAt: '2026-08-18T10:00:00.000Z',+ lastEventAt: '2026-08-18T11:00:00.000Z',+ trace: [],+ ...overrides,+});++const renderTab = (path = '/cos/run-events') => render(+ <MemoryRouter initialEntries={[path]}>+ <RunEventsTab />+ </MemoryRouter>+);++describe('RunEventsTab', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getRunEventStats.mockResolvedValue(STATS);+ api.getRunEventProjections.mockResolvedValue([projection()]);+ api.getRunEventDiagnostic.mockResolvedValue({+ projection: projection(),+ events: [+ { eventId: 'e1', kind: 'run.spawned', at: '2026-08-18T10:00:00.000Z', data: { providerId: 'demo-cli' } },+ { eventId: 'e2', kind: 'run.finalized', at: '2026-08-18T11:00:00.000Z', data: { success: true, exitCode: 0 } },+ ],+ });+ });++ it('renders the ledger bound so "why is this run missing" has an answer', async () => {+ renderTab();+ expect(await screen.findByText('12 / 5000')).toBeInTheDocument();+ expect(screen.getByText('10000 events · 30d')).toBeInTheDocument();+ });++ it('replays the run named by ?run= without the user clicking anything', async () => {+ renderTab('/cos/run-events?run=run-a');++ expect(await screen.findByText('run.spawned')).toBeInTheDocument();+ expect(screen.getByText('run.finalized')).toBeInTheDocument();+ expect(api.getRunEventDiagnostic).toHaveBeenCalledWith('run-a', { silent: true });+ });++ it('puts the selection in the URL, not in local state', async () => {+ // Same contract as every other selectable view: the open diagnostic has to+ // survive a reload and be pasteable to someone else.+ const user = userEvent.setup();+ renderTab();++ await user.click(await screen.findByText('run-a'));++ expect(api.getRunEventDiagnostic).toHaveBeenCalledWith('run-a', { silent: true });+ });++ it('distinguishes an unreachable server from a genuinely empty ledger', async () => {+ // `[]` means "nothing has happened yet"; a failed fetch means "we do not+ // know". Rendering the reassuring empty state for the second would hide a+ // broken server behind a calm screen.+ api.getRunEventStats.mockRejectedValue(new Error('offline'));+ api.getRunEventProjections.mockRejectedValue(new Error('offline'));+ renderTab();++ expect(await screen.findByText(/Could not read the run event ledger/)).toBeInTheDocument();+ });++ it('shows the empty state when the ledger is genuinely empty', async () => {+ api.getRunEventProjections.mockResolvedValue([]);+ renderTab();++ expect(await screen.findByText(/No lifecycle events recorded yet/)).toBeInTheDocument();+ expect(screen.queryByText(/Could not read/)).not.toBeInTheDocument();+ });+});++describe('projectionAnnotations', () => {+ it('lists only the counts that actually happened', () => {+ expect(projectionAnnotations(projection())).toEqual([]);+ expect(projectionAnnotations(projection({ recoveryCount: 3, orphaned: true, prVerified: false })))+ .toEqual(['3 recovery events', 'orphaned', 'PR unverified']);+ });++ it('says nothing about a PR that was verified, or never checked', () => {+ expect(projectionAnnotations(projection({ prVerified: true }))).toEqual([]);+ expect(projectionAnnotations(projection({ prVerified: null }))).toEqual([]);+ });+});++describe('summarizeEventData', () => {+ it('renders scalars inline and names a redacted stub as redacted', () => {+ expect(summarizeEventData({ exitCode: 0, success: true })).toBe('exitCode=0 success=true');+ expect(summarizeEventData({ prompt: { redacted: 'content', chars: 900 } })).toBe('prompt=«content»');+ });++ it('drops nulls rather than printing them as noise', () => {+ expect(summarizeEventData({ branch: null, category: 'pr-missing' })).toBe('category=pr-missing');+ });+});diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex d2547e22e0..005d85a53d 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -44,6 +44,10 @@ import { resolveDynamicAvatar } from '../components/cos/constants';// stays out of the eager CoS chunk every /cos/* visit pays for — same reason the// avatars below are not re-exported from the components/cos barrel.const RunsTab = lazy(() => import('../components/cos/tabs/RunsTab'));+// The run-event diagnostic is lazy for the same reason as Runs: it is a+// post-mortem surface nobody opens on a normal day, and it pulls the whole+// ledger read path with it.+const RunEventsTab = lazy(() => import('../components/cos/tabs/RunEventsTab'));// Three.js-based avatars lazy-loaded so the R3F stack isn't bundled unless the// user's chosen avatar style actually needs it.@@ -983,6 +987,13 @@ export default function ChiefOfStaff() {</Suspense></div>)}+ {activeTab === 'run-events' && (+ <div role="tabpanel" id="tabpanel-run-events" aria-labelledby="tab-run-events">+ <Suspense fallback={<div className="flex items-center justify-center py-12"><BrailleSpinner text="Loading run events" /></div>}>+ <RunEventsTab />+ </Suspense>+ </div>+ )}{activeTab === 'schedule' && (<div role="tabpanel" id="tabpanel-schedule" aria-labelledby="tab-schedule"><ScheduleTab apps={apps} providers={providers} activeProviderId={activeProviderId} />diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex bb7feb28fa..a597f21b8e 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -35,6 +35,26 @@ export const getAgentActivityByAgent = (agentId, options = {}) => {export const getAgentActivityStats = (agentId, days = 7) =>request(`/agents/activity/agent/${agentId}/stats?days=${days}`);+// CoS run event ledger (#4540) — read-only diagnostics over the append-only+// lifecycle stream. Every one of these is a GET: the ledger is written by the+// server's own lifecycle boundaries and has no client-facing mutation.+const runEventQuery = (filters = {}) => {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(filters)) {+ if (value !== undefined && value !== null && value !== '') params.set(key, value);+ }+ const query = params.toString();+ return query ? `?${query}` : '';+};+export const getRunEvents = (filters = {}, options = {}) =>+ request(`/agents/activity/run-events${runEventQuery(filters)}`, options);+export const getRunEventStats = (options = {}) =>+ request('/agents/activity/run-events/stats', options);+export const getRunEventProjections = (filters = {}, options = {}) =>+ request(`/agents/activity/run-events/projections${runEventQuery(filters)}`, options);+export const getRunEventDiagnostic = (id, options = {}) =>+ request(`/agents/activity/run-events/run/${encodeURIComponent(id)}`, options);+// Chief of Staffexport const getCosStatus = () => request('/cos');export const startCos = (options = {}) => request('/cos/start', { method: 'POST', ...options });diff --git a/docs/API.md b/docs/API.mdindex 7ab5034629..27f7597626 100644--- a/docs/API.md+++ b/docs/API.md@@ -413,7 +413,7 @@ See [Agent Context (MCP)](./features/agent-context.md) for setup, transport head| 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/stats` | Ledger generation sizes and the count + age retention bounds || 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 |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 1edde360ee..75924d7212 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -100,7 +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.+- 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, handoff to/from the CoS Runner, first output, PTY reconnect, pause/resume, interruption, PR-claim verification, orphan reap, runner re-adoption, and finalization. `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 on TWO axes, because neither alone is a retention policy. A COUNT: 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. And an AGE (30 days), because the count alone bounds a busy install but lets a quiet one keep a trace of a run from last spring, describing a workspace, a provider, and a code path that no longer exist. Expired events are filtered out of every read (so the bound holds continuously) and swept off disk on a throttled prune (so the files actually shrink). 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.mdindex e5aee685e4..337c919233 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -27,7 +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. |+| `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: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `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). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. || `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.jsindex f6d133a2c4..5d35a67ef6 100644--- a/server/lib/agentRunEvents.js+++ b/server/lib/agentRunEvents.js@@ -59,7 +59,31 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze([// (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'+ 'run.runner-recovered',+ // Process ownership moved between the in-server spawner and the CoS Runner.+ // The boundary that makes a run outlive the server, and the one an in-memory+ // ownership map forgets on restart.+ 'run.handoff',+ // A live session re-attached to a still-running agent (TUI reattach). Says+ // 'someone was watching again', which is how a run with no output for an hour+ // is told from one nobody had open.+ 'run.reconnected',+ // The run produced its FIRST output — once per run, never per chunk. Bounded+ // on purpose: per-chunk events would make the ledger a copy of the output it+ // deliberately redacts and would exhaust the retention bound in minutes. The+ // one event buys time-to-first-output, which is the only thing separating a+ // run that stalled after speaking from one that never spoke at all.+ 'run.output',+ // The user (or a budget/queue gate) suspended a run.+ 'run.paused',+ // A suspended run was resumed.+ 'run.resumed',+ // An explicit stop/kill was requested. Distinct from 'run.finalized': the+ // request is the fact being recorded, and the exit it causes lands separately+ // — a kill that never took is exactly the discrepancy this ledger explains.+ 'run.interrupted',+ // A PR-claim verification verdict was reached for the run's task.+ 'run.pr-verified']);const KIND_SET = new Set(AGENT_RUN_EVENT_KINDS);@@ -346,7 +370,16 @@ const emptyProjection = (id) => ({exitCode: null,success: null,orphaned: false,+ interrupted: false,+ paused: false,recoveryCount: 0,+ handoffCount: 0,+ reconnectCount: 0,+ pauseCount: 0,+ owner: null,+ outputBytes: null,+ lastOutputAt: null,+ prVerified: null,eventCount: 0,firstEventAt: null,lastEventAt: null,@@ -393,6 +426,17 @@ export function projectRunStates(events) {return [...byKey.values()].sort((a, b) => String(b.lastEventAt).localeCompare(String(a.lastEventAt)));}+/**+ * Has this run already reached a verdict?+ *+ * Every non-terminal arm below is guarded by this: the ledger is read in append+ * order, but a late-arriving annotation (a stop request that raced the exit, a+ * reconnect logged after the process was already reaped) must not resurrect a+ * finished run as `running`. `run.finalized` is the only arm that may set a+ * terminal status, so once set it stays.+ */+const isTerminal = (state) => state.status === 'completed' || state.status === 'failed';+function applyKind(state, event) {const data = event.data ?? {};switch (event.kind) {@@ -406,12 +450,50 @@ function applyKind(state, event) {// 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';+ if (!isTerminal(state)) state.status = 'running';state.recoveryCount += 1;break;case 'run.orphan-recovered':state.orphaned = true;- if (state.status !== 'completed' && state.status !== 'failed') state.status = 'orphaned';+ if (!isTerminal(state)) state.status = 'orphaned';+ break;+ case 'run.handoff':+ // Ownership moved. `owner` is the answer to "which process should I look+ // in for this run", which is precisely what the in-memory maps lose on a+ // restart — so the LAST handoff wins and the count shows the churn.+ state.handoffCount += 1;+ if (typeof data.to === 'string') state.owner = data.to;+ break;+ case 'run.reconnected':+ state.reconnectCount += 1;+ if (!isTerminal(state)) state.status = 'running';+ break;+ case 'run.output':+ // Sizes only — the bytes themselves never enter the ledger.+ if (Number.isFinite(data.outputBytes)) state.outputBytes = data.outputBytes;+ state.lastOutputAt = event.at;+ break;+ case 'run.paused':+ state.paused = true;+ state.pauseCount += 1;+ if (!isTerminal(state)) state.status = 'paused';+ break;+ case 'run.resumed':+ state.paused = false;+ if (!isTerminal(state)) state.status = 'running';+ break;+ case 'run.interrupted':+ // The stop REQUEST, not the exit it causes. Status stays non-terminal on+ // purpose: a run still showing `interrupted` with no later+ // `run.finalized` is a kill that never landed, and hiding that behind a+ // synthesized "failed" would erase the only evidence of it.+ state.interrupted = true;+ if (typeof data.reason === 'string') state.interruptReason = data.reason;+ if (!isTerminal(state)) state.status = 'interrupted';+ break;+ case 'run.pr-verified':+ state.prVerified = data.verified === true;+ if (typeof data.prUrl === 'string') state.prUrl = data.prUrl;break;case 'run.finalized': {const success = data.success === true;diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.jsindex d3e8ade419..cac78943de 100644--- a/server/lib/agentRunEvents.test.js+++ b/server/lib/agentRunEvents.test.js@@ -297,3 +297,89 @@ describe('projectRunStates — replayable status', () => {expect(projectRunState(stream, 'r1').status).toBe('completed');});});++describe('projectRunStates — the second-slice boundaries (#4540)', () => {+ const at = (hhmm) => `2026-08-18T${hhmm}:00.000Z`;++ it('folds handoff, first-output, reconnect and PR verification onto one run', () => {+ const [state] = projectRunStates([+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', taskId: 't1', at: at('10:00') }),+ buildRunEvent({ kind: 'run.handoff', runId: 'r1', agentId: 'a1', at: at('10:01'), data: { to: 'cos-runner', accepted: true, pid: 4242 } }),+ buildRunEvent({ kind: 'run.output', runId: 'r1', agentId: 'a1', at: at('10:02'), data: { source: 'runner', outputBytes: 512 } }),+ buildRunEvent({ kind: 'run.reconnected', runId: 'r1', agentId: 'a1', at: at('11:00'), data: { transport: 'runner-pty' } }),+ buildRunEvent({ kind: 'run.pr-verified', runId: 'r1', agentId: 'a1', at: at('12:00'), data: { verified: true, branch: 'claim/issue-1' } })+ ]);+ expect(state).toMatchObject({+ status: 'running',+ handoffCount: 1,+ owner: 'cos-runner',+ outputBytes: 512,+ lastOutputAt: at('10:02'),+ reconnectCount: 1,+ prVerified: true+ });+ });++ it('reports a paused run as paused and a resumed one as running again', () => {+ const spawned = buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') });+ const paused = buildRunEvent({ kind: 'run.paused', runId: 'r1', at: at('10:30'), data: { reason: 'user asked' } });++ const [held] = projectRunStates([spawned, paused]);+ expect(held).toMatchObject({ status: 'paused', paused: true, pauseCount: 1 });++ const [released] = projectRunStates([+ spawned,+ paused,+ buildRunEvent({ kind: 'run.resumed', runId: 'r1', at: at('11:00'), data: { mode: 'requeued' } })+ ]);+ expect(released).toMatchObject({ status: 'running', paused: false, pauseCount: 1 });+ });++ it('leaves a kill that never landed visible as interrupted, not as a failure', () => {+ // The whole point of recording the stop REQUEST separately: a run still+ // reading `interrupted` with no `run.finalized` after it is a kill the+ // process ignored. Synthesizing "failed" here would erase that evidence.+ const [state] = projectRunStates([+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') }),+ buildRunEvent({ kind: 'run.interrupted', runId: 'r1', at: at('10:30'), data: { reason: 'terminated-by-user', signal: 'SIGTERM' } })+ ]);+ expect(state).toMatchObject({ status: 'interrupted', interrupted: true, interruptReason: 'terminated-by-user', success: null });+ });++ it('lets the terminal verdict outrank every later annotation', () => {+ // Reads in append order, but a stop request that raced the exit, or a+ // reconnect logged after the reap, must not resurrect a finished run.+ const [state] = projectRunStates([+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') }),+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', at: at('11:00'), data: { success: true, exitCode: 0 } }),+ buildRunEvent({ kind: 'run.interrupted', runId: 'r1', at: at('11:01'), data: { reason: 'terminated-by-user' } }),+ buildRunEvent({ kind: 'run.reconnected', runId: 'r1', at: at('11:02') }),+ buildRunEvent({ kind: 'run.paused', runId: 'r1', at: at('11:03') })+ ]);+ expect(state.status).toBe('completed');+ expect(state.interrupted).toBe(true);+ expect(state.eventCount).toBe(5);+ });++ it('records a REJECTED handoff without claiming an owner', () => {+ const [state] = projectRunStates([+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') }),+ buildRunEvent({ kind: 'run.handoff', runId: 'r1', at: at('10:01'), data: { to: 'none', accepted: false, reason: 'runner refused' } })+ ]);+ expect(state).toMatchObject({ handoffCount: 1, owner: 'none' });+ });++ it('records a FAILED PR verification as verified:false, not as absent', () => {+ const [state] = projectRunStates([+ buildRunEvent({ kind: 'run.pr-verified', runId: 'r1', at: at('12:00'), data: { verified: false, category: 'pr-missing', branch: 'claim/issue-1' } })+ ]);+ expect(state.prVerified).toBe(false);+ });++ it('keeps every new kind inside the closed write vocabulary', () => {+ for (const kind of ['run.handoff', 'run.reconnected', 'run.output', 'run.paused', 'run.resumed', 'run.interrupted', 'run.pr-verified']) {+ expect(isKnownRunEventKind(kind)).toBe(true);+ expect(() => buildRunEvent({ kind, runId: 'r1', at: at('10:00') })).not.toThrow();+ }+ });+});diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 56fd39f059..688a0f06a5 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -138,6 +138,7 @@ export const NAV_COMMANDS = [{ id: 'nav.cos.learning', path: '/cos/learning', label: 'Learning', section: 'Chief of Staff', aliases: ['cos-learning'] },{ id: 'nav.cos.memory', path: '/cos/memory', label: 'Memory', section: 'Chief of Staff', aliases: ['cos-memory'] },{ id: 'nav.cos.runs', path: '/cos/runs', label: 'Runs', section: 'Chief of Staff', aliases: ['runs', 'ai-runs', 'cos-runs', 'recent-runs', 'run-history'], keywords: ['runs', 'run history', 'recent runs', 'ai runs', 'agent runs', 'failed runs'] },+ { id: 'nav.cos.run-events', path: '/cos/run-events', label: 'Run Events', section: 'Chief of Staff', aliases: ['run-events', 'cos-run-events', 'run-event-ledger', 'lifecycle-events'], keywords: ['run events', 'lifecycle', 'ledger', 'replay', 'diagnostics', 'orphaned', 'handoff', 'reconnect', 'interrupted', 'why did this run fail'] },{ id: 'nav.cos.schedule', path: '/cos/schedule', label: 'Schedule', section: 'Chief of Staff', aliases: ['schedule', 'cos-schedule'] },{ id: 'nav.social-agents', path: '/agents', label: 'Social Agents', section: 'Chief of Staff', aliases: ['social-agents'] },// The page at /cos/workflow is now the Schedule Timeline (launch-orderdiff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 054cb9e336..5c65817df7 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -19,6 +19,7 @@ import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { completeAgentRun } from './agentRunTracking.js';+import { appendRunEvent } from './agentRunEventLog.js';import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents, registerSpawnedAgent, unregisterSpawnedAgent } from './agentState.js';import { normalizeReviewers } from '../lib/validation.js';@@ -433,6 +434,11 @@ export async function spawnDirectly({let outputBuffer = '';let rawStreamBuffer = ''; // Raw stdout for stream-json (used for error analysis)let hasStartedWorking = false;+ // Deliberately NOT `hasStartedWorking`: that flag also flips on a 3s+ // initialization timeout with no output behind it, so reusing it would file a+ // `run.output` for a run that has produced nothing — the exact case (a+ // provider that never spoke) the ledger is supposed to make visible.+ let firstOutputRecorded = false;const outputFile = join(agentDir, 'output.txt');const isStreamJson = cliConfig.streamFormat === 'stream-json';const streamParser = isStreamJson ? createStreamJsonParser() : null;@@ -522,6 +528,23 @@ export async function spawnDirectly({// Serialize the transcript body so two `data` events can't interleave their// awaits and reorder output.txt / the batched live tail.enqueueTranscriptWrite(async () => {+ if (!firstOutputRecorded) {+ firstOutputRecorded = true;+ // Once per run, on the FIRST real byte (#4540) — never per chunk. A+ // per-chunk event would make the ledger a copy of the output it+ // deliberately redacts and would exhaust the retention bound in+ // minutes. What this one event buys is time-to-first-output: a run+ // that stalled after speaking and a run that never spoke at all are+ // indistinguishable in the mutable record.+ await appendRunEvent({+ kind: 'run.output',+ runId,+ agentId,+ taskId: task.id,+ eventId: `output:${agentId}:${runId || 'no-run'}:first`,+ data: { source: 'cli-stdout', firstChunkChars: text.length },+ });+ }if (!hasStartedWorking) {hasStartedWorking = true;await updateAgent(agentId, { metadata: { phase: 'working' } });diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex dd30cd29f2..23a7524bd7 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -41,6 +41,12 @@ vi.mock('./toolStateMachine.js', () => ({errorExecution: vi.fn(),}));vi.mock('./agentErrorAnalysis.js', () => ({ analyzeAgentFailure: vi.fn().mockResolvedValue(null) }));+// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) — mocked+// so first-output telemetry lands in a spy rather than the developing install's+// ledger, and because this suite's fileUtils mock carries no PATHS.cos (#4540).+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));+vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolvedValue(undefined) }));// Mock git.js directly so spawnDirectly's GH_TOKEN pinning is exercised without// pulling in the real worktreeManager → instances module graph. Default: no@@ -559,6 +565,42 @@ describe('stream error containment', () => {vi.restoreAllMocks();});+ // ─── Lifecycle ledger — the first-output boundary (#4540) ─────────────────++ it('records ONE run.output on the first real byte, and never again', async () => {+ // Bounded on purpose: a per-chunk event would make the ledger a copy of the+ // output it deliberately redacts. What one event buys is time-to-first-output+ // — the only thing that separates a run that stalled after speaking from one+ // that never spoke at all.+ appendRunEvent.mockClear();+ const spawnPromise = spawnDirectly(minimalArgs);+ await new Promise((r) => setTimeout(r, 10));++ fakeProcess.stdout.emit('data', Buffer.from('{\"type\":\"result\",\"result\":\"one\"}\n'));+ fakeProcess.stdout.emit('data', Buffer.from('{\"type\":\"result\",\"result\":\"two\"}\n'));+ await new Promise((r) => setTimeout(r, 20));++ const outputs = appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.output');+ expect(outputs).toHaveLength(1);+ expect(outputs[0]).toMatchObject({ runId: 'run-1', agentId: 'agent-test', taskId: 'task-1', data: { source: 'cli-stdout' } });++ fakeProcess.emit('close', 0);+ await spawnPromise.catch(() => {});+ });++ it('records no run.output for a run that never produced any', async () => {+ // The 3s initialization timer flips the record to "working" with nothing+ // behind it, which is exactly the run this boundary must NOT vouch for.+ appendRunEvent.mockClear();+ const spawnPromise = spawnDirectly(minimalArgs);+ await new Promise((r) => setTimeout(r, 10));++ fakeProcess.emit('close', 1);+ await spawnPromise.catch(() => {});++ expect(appendRunEvent.mock.calls.map(([e]) => e.kind)).not.toContain('run.output');+ });+it('drains stdout output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {// stdout output is now batched: the data handler pushes lines to the output// batcher and the close handler drains it. Make the drain's state write faildiff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 8ae8f943b5..86c7b7b091 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -33,6 +33,7 @@ import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';import { completeAgentRun } from './agentRunTracking.js';+import { appendRunEvent } from './agentRunEventLog.js';import { committedDuringRun } from '../lib/gitCommitProbe.js';import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';@@ -646,14 +647,46 @@ export async function finalizeAgent({// successfully" the UI renders off `result.success`) sees the corrected value.// A THROW here is not a verdict — fall back to the reported outcome rather// than manufacturing a failure out of a check that never ran.+ let prCheckThrew = false;const prVerdict = terminatedByUser? { ok: true }: await verifyPrClaim({ task, workspacePath, success: reportedSuccess, prExpected }).catch(err => {+ prCheckThrew = true;emitLog('warn', `⚠️ PR verification failed for ${agentId}: ${err.message}`, { agentId });return { ok: true };});+ // Record the verdict in the lifecycle ledger (#4540) — but ONLY when the+ // check actually reached one. `verifyPrClaim` returns the same `{ ok: true }`+ // for "the PR is there", for "this run never promised one", for "there was no+ // branch to ask about", and (via the catch above) for "the check threw";+ // appending on every call would file four different facts under one word and+ // make the ledger lie about the one transition it exists to explain.+ //+ // A BRANCH is the tell: every path that actually consulted a forge returns the+ // branch it asked about, and every path that did not returns no branch at all.+ // So gate on the branch rather than re-deriving the service's own+ // applicability rules here, where they would drift apart.+ if (!prCheckThrew && typeof prVerdict.branch === 'string') {+ await appendRunEvent({+ kind: 'run.pr-verified',+ runId,+ agentId,+ taskId: task?.id,+ // A run is verified once. An explicit natural key rather than the+ // content-derived default so a retried finalize (the close handler and+ // the orphan sweep can both reach this path) records one verdict, not two.+ eventId: `pr-verify:${agentId}:${runId || 'no-run'}`,+ data: {+ verified: prVerdict.ok === true,+ branch: prVerdict.branch ?? null,+ category: prVerdict.category ?? null,+ noChangesToShip: prVerdict.noChangesToShip === true,+ },+ });+ }+// #3680: a worktree agent that committed to the PRIMARY checkout left// unreviewed commits on an unprotected branch. Same posture as the PR check —// a throw is not a verdict, so fall back to "no drift" rather thandiff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 9005e7cfb4..6d6d53e9f5 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -83,6 +83,12 @@ vi.mock('./taskTypeHooks.js', () => ({}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));++// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) — mocked+// so finalization telemetry lands in a spy rather than the developing install's+// ledger, and so the boundary assertions below can read the envelope (#4540).+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));import {@@ -400,3 +406,78 @@ describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)'expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));});});++// ─── Lifecycle ledger — the PR-verification boundary (#4540) ─────────────────++describe('finalizeAgent — records the PR verdict in the lifecycle ledger', () => {+ const prVerified = () => appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.pr-verified');++ const finalize = (overrides = {}) => finalizeAgent({+ agentId: 'agent-1',+ task: prTask(),+ runId: 'run-1',+ providerId: 'claude-code',+ success: true,+ exitCode: 0,+ duration: 1000,+ outputBuffer: 'done',+ errorAnalysis: null,+ workspacePath: '/w',+ prExpected: true,+ ...overrides,+ });++ it('records the passing verdict with the branch it was checked against', async () => {+ onBranch('claim/issue-1');+ await finalize();+ expect(prVerified()).toEqual([expect.objectContaining({+ runId: 'run-1',+ agentId: 'agent-1',+ taskId: 'task-1',+ data: expect.objectContaining({ verified: true, branch: 'claim/issue-1' })+ })]);+ });++ it('records a FAILED verdict with the category, not just an absence', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ await finalize();+ expect(prVerified()[0].data).toMatchObject({ verified: false, category: PR_MISSING_CATEGORY });+ });++ it('is keyed on the run, so a retried finalize files one verdict', async () => {+ onBranch('claim/issue-1');+ await finalize();+ await finalize();+ const ids = prVerified().map((e) => e.eventId);+ expect(ids).toHaveLength(2);+ expect(new Set(ids).size).toBe(1);+ });++ it('writes NOTHING when the run never promised a PR', async () => {+ // `verifyPrClaim` returns the same `{ ok: true }` for "verified" and for+ // "not applicable". Recording both would put two different facts on the+ // ledger under one word.+ onBranch('claim/issue-1');+ await finalize({ prExpected: false });+ expect(prVerified()).toHaveLength(0);+ });++ it('writes NOTHING when the check itself threw', async () => {+ // A throw is not a verdict — the finalize path already falls back to the+ // reported outcome, and the ledger must not claim a forge confirmed anything.+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockRejectedValue(new Error('forge exploded'));+ await finalize();+ expect(prVerified()).toHaveLength(0);+ });++ it('writes NOTHING when there was no branch to ask a forge about', async () => {+ // A detached HEAD or non-repo workspace returns the SAME `{ ok: true }` as a+ // confirmed PR. Recording it would put "verified" on a run nothing verified —+ // which is the failure mode this whole ledger exists to make impossible.+ execGitMock.mockRejectedValue(new Error('not a git repository'));+ await finalize();+ expect(prVerified()).toHaveLength(0);+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 5fb3ce7273..aacbea26d5 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -50,6 +50,7 @@ import { createToolExecution, startExecution, completeExecution, errorExecutionimport { determineLane, acquire, release } from './executionLanes.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { createAgentRun } from './agentRunTracking.js';+import { appendRunEvent } from './agentRunEventLog.js';import { committedDuringRun, toEpochMs } from '../lib/gitCommitProbe.js';import { capturePrimaryCheckoutState } from '../lib/primaryCheckoutGuard.js';import { buildAgentPrompt, getAppWorkspace, inlinePrLifecycleSection, isClaimFlowTask } from './agentPromptBuilder.js';@@ -866,6 +867,19 @@ export async function spawnViaRunner(agentId, task, opts) {const message = err?.message || String(err);clearTimeout(agentInfo.initializationTimeout);runnerAgents.delete(agentId);+ // A handoff that the runner REFUSED (#4540). Recorded as its own boundary+ // rather than left to the failure the finalize below records: "the run+ // never started because the runner would not take it" and "the run started+ // and failed" produce the same terminal record today, and only the ledger+ // can still tell them apart afterwards.+ await appendRunEvent({+ kind: 'run.handoff',+ runId,+ agentId,+ taskId: task.id,+ eventId: `handoff:${agentId}:${runId || 'no-run'}:rejected`,+ data: { to: 'none', accepted: false, reason: message },+ });releaseAgentLane({ agentId, success: false, exitCode: 1, executionId, laneName, errorExecutionMessage: message });// Finalize through the SAME chokepoint every other ending uses (#3632).// Finalizing the agent alone — which is all this used to do — left the TASK@@ -920,6 +934,21 @@ export async function spawnViaRunner(agentId, task, opts) {// Store PID in persisted state for zombie detectionawait updateAgent(agentId, { pid: result.pid });+ // Ownership of the process now sits with the CoS Runner, not this server+ // (#4540). This is the boundary the in-memory `runnerAgents` map forgets on+ // every restart — after which "which process should I look in for this run"+ // has no recorded answer at all. Emitted AFTER the runner accepted, so an+ // event means the handoff landed. The natural key is the run: a run is handed+ // to the runner exactly once, so a retried spawn cannot double-count it.+ await appendRunEvent({+ kind: 'run.handoff',+ runId,+ agentId,+ taskId: task.id,+ eventId: `handoff:${agentId}:${runId || 'no-run'}:cos-runner`,+ data: { to: 'cos-runner', accepted: true, pid: result.pid ?? null, providerId: provider.id, laneName: laneName ?? null },+ });+emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });return agentId;}diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex e3ccf5ae63..47d24a09c4 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -88,6 +88,12 @@ vi.mock('./agentWorktreeCleanup.js', () => ({vi.mock('./agentCompletionCleanup.js', () => ({ runAgentCompletionCleanup: vi.fn() }));vi.mock('./agentSummaryExtraction.js', () => ({ extractFinalSummary: vi.fn() }));vi.mock('./agentManagement.js', () => ({ handleOrphanedTask: vi.fn() }));++// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) — mocked+// so handoff telemetry lands in a spy rather than the developing install's+// ledger, and so the boundary assertions below can read the envelope (#4540).+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));vi.mock('./agentPromptBuilder.js', () => ({ buildAgentPrompt: vi.fn(), getAppWorkspace: vi.fn() }));// The real classification of a `spawn-rejected` reason (non-actionable, so the// task is budgeted a retry rather than blocked) is pinned in@@ -254,3 +260,53 @@ describe('spawnViaRunner — the runner rejects the spawn', () => {expect(runnerAgents.has('agent-1')).toBe(true);});});++// ─── Lifecycle ledger — the handoff boundary (#4540) ─────────────────────────++describe('spawnViaRunner — records who owns the process', () => {+ const handoffs = () => appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.handoff');++ beforeEach(() => {+ vi.clearAllMocks();+ runnerAgents.clear();+ });++ it('records the handoff only AFTER the runner accepted the spawn', async () => {+ // `runnerAgents` — the map that says which process owns this run — is+ // in-memory and gone on the next restart. This is the only durable record+ // that the answer was ever "the CoS Runner".+ vi.mocked(spawnAgentViaRunner).mockResolvedValueOnce({ pid: 4242 });++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ expect(handoffs()).toEqual([expect.objectContaining({+ runId: 'run-1',+ agentId: 'agent-1',+ taskId: 'task-1',+ data: expect.objectContaining({ to: 'cos-runner', accepted: true, pid: 4242, providerId: 'grok-cli' })+ })]);+ });++ it('records a REFUSED handoff as its own boundary', async () => {+ // "The runner would not take it" and "it ran and failed" collapse into the+ // same terminal record; only the ledger can still tell them apart.+ vi.mocked(spawnAgentViaRunner).mockRejectedValueOnce(new Error(REJECTION));++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ expect(handoffs()).toEqual([expect.objectContaining({+ data: expect.objectContaining({ to: 'none', accepted: false, reason: REJECTION })+ })]);+ });++ it('keys the handoff on the run, so a retried spawn cannot double-count it', async () => {+ vi.mocked(spawnAgentViaRunner).mockResolvedValue({ pid: 4242 });++ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());+ await spawnViaRunner('agent-1', { id: 'task-1' }, runnerOpts());++ const ids = handoffs().map((e) => e.eventId);+ expect(ids).toHaveLength(2);+ expect(new Set(ids).size).toBe(1);+ });+});diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 8e616b0b6a..47557337e0 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -157,6 +157,37 @@ async function markPausedTask(agentInfo, agentId, pausedAt, reason) {}, task.taskType || 'user');}+/**+ * Record a stop REQUEST against a live run (#4540).+ *+ * The request is the fact, not the exit it causes: a run still reading+ * `interrupted` with no `run.finalized` after it is a kill that never took —+ * the process ignored SIGTERM, or the runner RPC failed — and that discrepancy+ * is invisible in the mutable record, which only ever shows the last state+ * something managed to write.+ *+ * Ids come from whichever ownership map holds the agent: neither is+ * authoritative alone (a runner-backed TUI registers in `activeAgents` while a+ * runner-spawned CLI lives in `runnerAgents`), so reading only one would+ * silently drop half the runs. An agent in NEITHER map has nothing to interrupt+ * — its caller is about to 404 or return not-found — so no event is written+ * rather than minting a projection for a run that isn't there.+ *+ * No explicit idempotency key: every termination request is a distinct fact,+ * including a second one aimed at an agent that ignored the first.+ */+async function recordInterrupt(agentId, data) {+ const info = activeAgents.get(agentId) ?? runnerAgents.get(agentId);+ if (!info) return;+ await appendRunEvent({+ kind: 'run.interrupted',+ runId: info.runId ?? null,+ agentId,+ taskId: info.taskId ?? null,+ data: { ...data, mode: runnerAgents.has(agentId) ? 'runner' : 'direct' },+ });+}+async function markAgentPaused(agentId, agentInfo, pausedAt, reason) {await updateAgent(agentId, {status: 'paused',@@ -169,6 +200,21 @@ async function markAgentPaused(agentId, agentInfo, pausedAt, reason) {}});await markPausedTask(agentInfo, agentId, pausedAt, reason);+ // Recorded AFTER the persist, not before (#4540): both pause arms funnel+ // through here, and both roll their in-memory flag back when this function+ // throws. An event written ahead of the writes would leave the projection+ // reading `paused` for a pause that never stuck — the exact class of lie the+ // ledger exists to catch. `at: pausedAt` is the same instant the agent record+ // carries, so the content-derived id is stable and a retried persist files one+ // paused event rather than two.+ await appendRunEvent({+ kind: 'run.paused',+ runId: agentInfo?.runId ?? null,+ agentId,+ taskId: agentInfo?.taskId ?? null,+ at: pausedAt,+ data: { reason: reason || null, workspacePath: agentInfo?.workspacePath ?? null },+ });release(agentId);if (agentInfo?.executionId) {errorExecution(agentInfo.executionId, { message: reason ? `Agent paused by user: ${reason}` : 'Agent paused by user', code: 'agent-paused' });@@ -347,6 +393,16 @@ export async function resumeAgent(agentId, overrides = {}) {// resume branch before the spawn it triggers can pick it up. Paused records are// explicitly completable (see the idempotence guard in `completeAgent`).pausedAgents.delete(agentId);+ // A paused run was released back to the queue (#4540). `mode` is the part the+ // mutable record loses: 'requeued' and 'new-task' both read as a completed+ // paused agent afterwards, and only one of them left a fresh task behind.+ await appendRunEvent({+ kind: 'run.resumed',+ runId: agent.metadata?.runId ?? null,+ agentId,+ taskId: resumed.taskId ?? taskId,+ data: { mode: resumed.mode ?? mode, branchName: resumed.branchName ?? null },+ });await completeAgent(agentId, {success: false,resumed: true,@@ -474,6 +530,9 @@ function resumeOverrideMetadata({ context, provider, model, effort, app, screens* Terminate an agent (graceful SIGTERM with SIGKILL fallback).*/export async function terminateAgent(agentId) {+ // Recorded ahead of both arms, so the request lands whichever one runs.+ await recordInterrupt(agentId, { reason: 'terminated-by-user', signal: 'SIGTERM' });+// Check if agent is in runner modeif (runnerAgents.has(agentId)) {return terminateRunnerAgent(agentId, terminateAgentViaRunner, 'Agent terminated by user', 'Terminated by user');@@ -573,6 +632,8 @@ export function getActiveAgents() {* Force kill an agent immediately with SIGKILL (no graceful shutdown).*/export async function killAgent(agentId) {+ await recordInterrupt(agentId, { reason: 'killed-by-user', signal: 'SIGKILL' });+// Check if agent is in runner modeif (runnerAgents.has(agentId)) {const result = await terminateRunnerAgent(agentId, killAgentViaRunner, 'Agent force killed by user (SIGKILL)', 'Force killed by user');diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 540119d1e2..ea75ebfef9 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -110,14 +110,14 @@ vi.mock('./creativeDirector/local.js', () => ({vi.mock('./creativeDirector/planAdvance.js', () => ({ advanceAfterPlanStepSettled: vi.fn().mockResolvedValue(undefined) }));vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettled: vi.fn().mockResolvedValue(undefined) }));-import { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents } from './agentManagement.js';+import { handleOrphanedTask, pauseAgent, resumeAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents, terminateAgent, killAgent } from './agentManagement.js';import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';import { getAgents, updateAgent, getAgentRecord, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';import { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask } from './cos.js';-import { pauseAgentViaRunner } from './cosRunnerClient.js';+import { pauseAgentViaRunner, terminateAgentViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';import { completeAgentRun } from './agentRunTracking.js';@@ -1674,3 +1674,81 @@ describe('the sweep retires paused records whose task moved on', () => {expect(markAgentComplete).not.toHaveBeenCalled();});});++// ─── Lifecycle ledger — pause / interruption boundaries (#4540) ──────────────++describe('lifecycle ledger — pause and interruption', () => {+ const ledgerCalls = (kind) => appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === kind);++ beforeEach(() => {+ vi.clearAllMocks();+ activeAgents.clear();+ runnerAgents.clear();+ pausedAgents.clear();+ getTaskById.mockResolvedValue({ id: 'task-1', taskType: 'user', description: 'Do work', metadata: {} });+ });++ it('records a pause once, stamped with the same instant the agent record gets', async () => {+ // markAgentPaused is the single chokepoint both pause arms funnel through,+ // and `at: pausedAt` is what makes a retried persist file one paused event+ // instead of two.+ activeAgents.set('agent-1', { process: { kill: vi.fn() }, taskId: 'task-1', runId: 'run-1', pid: 123, workspacePath: '/repo/worktree' });++ await pauseAgent('agent-1', 'billing window');++ const [paused] = ledgerCalls('run.paused');+ expect(paused).toMatchObject({ runId: 'run-1', agentId: 'agent-1', taskId: 'task-1', data: { reason: 'billing window' } });+ const persisted = updateAgent.mock.calls.find(([id]) => id === 'agent-1')?.[1];+ expect(paused.at).toBe(persisted.pausedAt);+ clearTimeout(activeAgents.get('agent-1')?.killTimer);+ });++ it('writes no paused event when the persist that pause depends on failed', async () => {+ // Both pause arms roll their in-memory flag back when the persist throws.+ // An event written ahead of it would leave the projection reading `paused`+ // for a pause that never stuck — the exact class of lie the ledger exists+ // to catch.+ const kill = vi.fn();+ activeAgents.set('agent-1', { process: { kill }, taskId: 'task-1', runId: 'run-1', pid: 123 });+ updateAgent.mockRejectedValueOnce(new Error('agent record unwritable'));++ await pauseAgent('agent-1', 'billing window').catch(() => null);++ expect(ledgerCalls('run.paused')).toHaveLength(0);+ clearTimeout(activeAgents.get('agent-1')?.killTimer);+ });++ it('records a termination REQUEST before either arm runs', async () => {+ activeAgents.set('agent-1', { process: { kill: vi.fn() }, taskId: 'task-1', runId: 'run-1', pid: 123 });++ await terminateAgent('agent-1');++ expect(ledgerCalls('run.interrupted')).toEqual([expect.objectContaining({+ runId: 'run-1',+ agentId: 'agent-1',+ taskId: 'task-1',+ data: expect.objectContaining({ reason: 'terminated-by-user', signal: 'SIGTERM', mode: 'direct' })+ })]);+ clearTimeout(activeAgents.get('agent-1')?.killTimer);+ });++ it('reads the ids out of the RUNNER map when that is where the agent lives', async () => {+ // A runner-spawned agent is absent from activeAgents entirely; a boundary+ // that consulted only that map would record the interrupt with no run id.+ runnerAgents.set('runner-1', { taskId: 'task-1', runId: 'run-9' });+ terminateAgentViaRunner.mockResolvedValue({ success: true });++ await terminateAgent('runner-1');++ expect(ledgerCalls('run.interrupted')).toEqual([expect.objectContaining({+ runId: 'run-9', agentId: 'runner-1', data: expect.objectContaining({ mode: 'runner' })+ })]);+ });++ it('writes nothing for a kill aimed at an agent that is already gone', async () => {+ // Nothing live to interrupt — minting an event here would create a+ // projection for a run that does not exist.+ await expect(killAgent('ghost')).rejects.toMatchObject({ status: 404 });+ expect(ledgerCalls('run.interrupted')).toHaveLength(0);+ });+});diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex 8ea4cdec04..5f65e86a8b 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -12,11 +12,20 @@* 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.+ * Retention is TWO bounds, and both are load-bearing.+ *+ * The primary 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.+ *+ * On top of that sits an AGE bound (MAX_EVENT_AGE_DAYS). The count alone is+ * only half a retention policy: it bounds a busy install but lets a quiet one+ * keep a trace of a run from last spring, describing a workspace, a provider,+ * and a code path that no longer exist. Expired events are filtered out on+ * every read (so the bound holds continuously) and swept off disk on a+ * throttled prune (so the files actually shrink) — see `pruneExpired`.** Two invariants the callers depend on:*@@ -35,6 +44,7 @@ import {PATHS,appendJSONLine,readJSONLFile,+ writeJSONLines,pathExists} from '../lib/fileUtils.js';import {@@ -54,6 +64,32 @@ const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');*/export const MAX_ACTIVE_EVENTS = 5000;+/**+ * Age bound, on TOP of the count bound.+ *+ * The two answer different failure modes and neither subsumes the other. The+ * count alone lets a quiet install keep a trace of a run from last spring —+ * stale diagnostics that describe a workspace, a provider, and a code path that+ * no longer exist. A busy install has the opposite problem the count already+ * solves. So: keep at most 2×MAX_ACTIVE_EVENTS events, AND nothing older than+ * this, whichever bites first.+ *+ * 30 days is well past the window in which a run failure is still worth a+ * post-mortem, and comfortably past the longest restart/recovery cycle a run+ * can survive.+ */+export const MAX_EVENT_AGE_DAYS = 30;+const MAX_EVENT_AGE_MS = MAX_EVENT_AGE_DAYS * 24 * 60 * 60 * 1000;++/**+ * How often the on-disk prune actually runs. Expiry is enforced on every READ+ * by filtering (so a reader never sees an expired event even between prunes);+ * this interval only bounds how often the files are rewritten to reclaim the+ * space, because rewriting a generation on every append would turn an O(1)+ * append into an O(n) one.+ */+const PRUNE_INTERVAL_MS = 60 * 60 * 1000;+// Default page size for the read API, and the ceiling a caller can request.// Defined in the pure module so the route's Zod schema can share them without a// lib → services import (see RUN_EVENT_READ_LIMITS).@@ -66,6 +102,9 @@ export const MAX_READ_LIMIT = RUN_EVENT_READ_LIMITS.max;let activeIds = null;let archiveIds = null;let activeCount = 0;+// `null` = never pruned in this process, so the first append/read always+// prunes; a timestamp means "pruned then, skip until the interval elapses".+let lastPrunedAt = null;// Serializes appends; also the handle callers await.let appendQueue = Promise.resolve();@@ -97,9 +136,72 @@ async function rotateIfFull() {console.log(`🔁 Rotated CoS run event ledger at ${MAX_ACTIVE_EVENTS} events`);}+/**+ * The instant before which an event has aged out. Exported-ish only through the+ * behaviour it drives; `now` is a parameter so tests can age a ledger without+ * faking the clock.+ */+function expiryCutoff(now = Date.now()) {+ return new Date(now - MAX_EVENT_AGE_MS).toISOString();+}++/**+ * Is this event still inside the age window?+ *+ * A line with no usable `at` is treated as NOT fresh. That is deliberate: `at`+ * is required by the envelope schema, so a line without one is corrupt or+ * truncated, the read path already drops it, and leaving it on disk would let+ * unreadable bytes accumulate forever under a retention policy that can never+ * date them. Pruning is the only thing that ever cleans them up.+ */+const isFresh = (event, cutoff) => typeof event?.at === 'string' && event.at > cutoff;++/**+ * Rewrite both generations without their expired events, and drop the expired+ * ids from the seen-id sets so a fresh redelivery of a long-gone event is+ * appendable again (same reasoning as rotation: a duplicate we can no longer+ * see is no longer a duplicate).+ *+ * Only runs inside the append queue or behind `flushRunEvents`, so it never+ * races an append. Throttled by PRUNE_INTERVAL_MS because it is O(ledger);+ * `force` is for the read path's first call and for tests.+ */+async function pruneExpired({ now = Date.now(), force = false } = {}) {+ if (!force && lastPrunedAt !== null && now - lastPrunedAt < PRUNE_INTERVAL_MS) return;+ lastPrunedAt = now;+ const cutoff = expiryCutoff(now);++ const [archive, active] = await Promise.all([+ readJSONLFile(ARCHIVE_PATH),+ readJSONLFile(ACTIVE_PATH)+ ]);++ const keptArchive = archive.filter((e) => isFresh(e, cutoff));+ const keptActive = active.filter((e) => isFresh(e, cutoff));+ const dropped = (archive.length - keptArchive.length) + (active.length - keptActive.length);+ if (dropped === 0) return;++ // An archive with nothing left is unlinked rather than rewritten empty, so a+ // long-idle install ends up with no archive file at all instead of a 0-byte one.+ if (keptArchive.length === 0) {+ if (await pathExists(ARCHIVE_PATH)) await unlink(ARCHIVE_PATH);+ } else if (keptArchive.length !== archive.length) {+ await writeJSONLines(ARCHIVE_PATH, keptArchive);+ }+ if (keptActive.length !== active.length) await writeJSONLines(ACTIVE_PATH, keptActive);++ archiveIds = new Set(keptArchive.map((e) => e?.eventId).filter(Boolean));+ activeIds = new Set(keptActive.map((e) => e?.eventId).filter(Boolean));+ activeCount = keptActive.length;+ console.log(`🧹 Pruned ${dropped} CoS run events older than ${MAX_EVENT_AGE_DAYS} days`);+}+async function appendNow(input) {const event = buildRunEvent(input);await hydrate();+ // Age out BEFORE the duplicate check: an event whose only copy just expired+ // must be appendable again, exactly as after a rotation.+ await pruneExpired();if (activeIds.has(event.eventId) || archiveIds.has(event.eventId)) {return { appended: false, duplicate: true, event };}@@ -135,6 +237,22 @@ export function flushRunEvents() {return appendQueue.then(() => undefined, () => undefined);}+/**+ * Queue a prune behind any in-flight appends.+ *+ * The read paths call this so a ledger nobody is appending to still gets its+ * expired generations reclaimed. It goes through the SAME queue as appends —+ * `flushRunEvents()` alone would only prove the queue was empty a tick ago, not+ * that a rewrite can't land mid-append. Absorbs its own errors for the same+ * reason appends do: a read must never fail on account of housekeeping.+ */+function schedulePrune() {+ appendQueue = appendQueue.then(() => pruneExpired()).catch((err) => {+ console.error(`❌ Failed to prune CoS run event ledger: ${err.message}`);+ });+ 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.@@ -153,16 +271,20 @@ export function flushRunEvents() {* @returns {Promise<object[]>} validated events in append order*/export async function readRunEvents({ runId, agentId, taskId, kind, since, limit } = {}) {- await flushRunEvents();+ await schedulePrune();const [archive, active] = await Promise.all([readJSONLFile(ARCHIVE_PATH),readJSONLFile(ACTIVE_PATH)]);+ // The age bound is enforced on read as well as on disk, so it holds in the+ // window between prunes — a reader must never see an event the retention+ // policy says is gone.+ const cutoff = expiryCutoff();// A line that fails the STRUCTURAL check is a corrupt/truncated write, not// data — dropping it keeps one bad line from poisoning the whole projection.// The check deliberately admits kinds this build does not know (see// `isStoredRunEvent`): a newer install's ledger must still read here.- let events = [...archive, ...active].filter(isStoredRunEvent);+ let events = [...archive, ...active].filter((e) => isStoredRunEvent(e) && isFresh(e, cutoff));if (runId) events = events.filter((e) => e.runId === runId);if (agentId) events = events.filter((e) => e.agentId === agentId);@@ -217,16 +339,24 @@ export async function getRunDiagnostic(id) {* are held to, so "why is this run missing" has an answer that isn't a guess.*/export async function getRunEventLedgerStats() {- await flushRunEvents();+ await schedulePrune();const [archive, active] = await Promise.all([readJSONLFile(ARCHIVE_PATH),readJSONLFile(ACTIVE_PATH)]);+ // Counted the way a reader sees them (fresh only), so "stats say 40 events"+ // and "the events endpoint returns 40" can never disagree.+ const cutoff = expiryCutoff();+ const freshArchive = archive.filter((e) => isFresh(e, cutoff));+ const freshActive = active.filter((e) => isFresh(e, cutoff));+ const oldest = freshArchive[0]?.at ?? freshActive[0]?.at ?? null;return {- activeEvents: active.length,- archivedEvents: archive.length,+ activeEvents: freshActive.length,+ archivedEvents: freshArchive.length,maxActiveEvents: MAX_ACTIVE_EVENTS,maxRetainedEvents: MAX_ACTIVE_EVENTS * 2,+ maxEventAgeDays: MAX_EVENT_AGE_DAYS,+ oldestEventAt: oldest,kinds: AGENT_RUN_EVENT_KINDS};}@@ -241,5 +371,6 @@ export function __resetRunEventLogCache() {activeIds = null;archiveIds = null;activeCount = 0;+ lastPrunedAt = null;appendQueue = Promise.resolve();}diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex b1eff4360d..c926afb43c 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';import { rmSync, writeFileSync, existsSync, readFileSync } from 'fs';import { join } from 'path';@@ -27,7 +27,8 @@ const {getRunEventLedgerStats,flushRunEvents,__resetRunEventLogCache,- MAX_ACTIVE_EVENTS+ MAX_ACTIVE_EVENTS,+ MAX_EVENT_AGE_DAYS} = await import('./agentRunEventLog.js');const { buildRunEvent } = await import('../lib/agentRunEvents.js');@@ -46,6 +47,19 @@ const restartServer = () => __resetRunEventLogCache();const countLines = (path) => (existsSync(path) ? readFileSync(path, 'utf8').split('\n').filter(Boolean).length : 0);beforeEach(resetLedger);++// Pin the clock next to the fixture timestamps below. The ledger's AGE bound is+// measured against the wall clock, so with a real clock every assertion in this+// file would silently start failing MAX_EVENT_AGE_DAYS after the fixture date —+// a red suite triggered by the calendar with no code change behind it. Only+// `Date` is faked: the service does real fs I/O, and faking timers would stall it.+const NOW = '2026-08-18T13:00:00.000Z';+beforeEach(() => {+ vi.useFakeTimers({ toFake: ['Date'] });+ vi.setSystemTime(new Date(NOW));+});+afterEach(() => vi.useRealTimers());+afterAll(() => rmSync(LEDGER_DIR, { recursive: true, force: true }));describe('appendRunEvent', () => {@@ -277,3 +291,72 @@ describe('replay / projections', () => {expect(await getRunDiagnostic('nope')).toEqual({ projection: null, events: [] });});});++describe('retention — age bound (#4540)', () => {+ /** An ISO timestamp `days` before the pinned NOW. */+ const daysAgo = (days) => new Date(Date.parse(NOW) - days * 24 * 60 * 60 * 1000).toISOString();+ const stale = () => daysAgo(MAX_EVENT_AGE_DAYS + 1);+ const recent = () => daysAgo(1);++ const seedLines = (events) => events.map((e) => `${JSON.stringify(buildRunEvent(e))}\n`).join('');++ it('hides an expired event from every read, and sweeps it off disk', async () => {+ writeFileSync(ACTIVE, seedLines([+ { kind: 'run.spawned', runId: 'ancient', at: stale() },+ { kind: 'run.spawned', runId: 'current', at: recent() }+ ]));+ restartServer();++ const events = await readRunEvents();+ expect(events.map((e) => e.runId)).toEqual(['current']);+ // …and the file itself shrank, so a quiet install's ledger doesn't grow+ // forever under a count bound it never reaches.+ expect(countLines(ACTIVE)).toBe(1);+ });++ it('drops an archive generation that has aged out entirely', async () => {+ writeFileSync(ARCHIVE, seedLines([{ kind: 'run.spawned', runId: 'ancient', at: stale() }]));+ writeFileSync(ACTIVE, seedLines([{ kind: 'run.spawned', runId: 'current', at: recent() }]));+ restartServer();++ const stats = await getRunEventLedgerStats();+ expect(stats).toMatchObject({ archivedEvents: 0, activeEvents: 1, maxEventAgeDays: MAX_EVENT_AGE_DAYS });+ expect(stats.oldestEventAt).toBe(recent());+ // An emptied archive is unlinked, not rewritten as a zero-byte file.+ expect(existsSync(ARCHIVE)).toBe(false);+ });++ it('re-admits an event whose only copy aged out', async () => {+ // Same reasoning as rotation: a duplicate we can no longer see is no longer+ // a duplicate. If expiry dropped the line but kept the id, the run could+ // never be re-observed.+ const event = { kind: 'run.spawned', runId: 'r1', agentId: 'a1', at: stale() };+ writeFileSync(ACTIVE, seedLines([event]));+ restartServer();++ expect(await appendRunEvent(event)).toMatchObject({ appended: true, duplicate: false });+ expect(countLines(ACTIVE)).toBe(1);+ });++ it('keeps deduping an event that is still inside the age window', async () => {+ const event = { kind: 'run.spawned', runId: 'r1', agentId: 'a1', at: recent() };+ await appendRunEvent(event);+ expect(await appendRunEvent({ ...event })).toMatchObject({ appended: false, duplicate: true });+ });++ it('leaves a fresh ledger completely untouched', async () => {+ await appendRunEvent({ kind: 'run.spawned', runId: 'r1', at: recent() });+ await appendRunEvent({ kind: 'run.finalized', runId: 'r1', at: recent(), data: { success: true } });+ const before = readFileSync(ACTIVE, 'utf8');+ restartServer();+ await readRunEvents();+ expect(readFileSync(ACTIVE, 'utf8')).toBe(before);+ });++ it('sweeps an undatable corrupt line that no read could ever return', async () => {+ writeFileSync(ACTIVE, `${seedLines([{ kind: 'run.spawned', runId: 'r1', at: recent() }])}{"eventId":"x","kind":"run.spawned"}\n`);+ restartServer();+ await readRunEvents();+ expect(countLines(ACTIVE)).toBe(1);+ });+});diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex 8fcd6298e2..30c0a1d579 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -123,6 +123,20 @@ export async function syncRunnerAgents() {label: `Recovered TUI ${agent.id}`,command: agent.command,});+ // A live PTY was re-attached to a still-running agent (#4540). Distinct+ // from the `run.runner-recovered` above: that says the RUN was+ // re-adopted, this says its terminal stream was re-plumbed — and only+ // one of the two can fail. No explicit idempotency key: the+ // `!getSession` guard already means "not currently attached", so every+ // event here is a genuinely distinct reconnect and `reconnectCount`+ // reads as the number of times this run lost and regained its stream.+ await appendRunEvent({+ kind: 'run.reconnected',+ runId: recoveredRunId,+ agentId: agent.id,+ taskId: agent.taskId,+ data: { transport: 'runner-pty', sessionId: agent.sessionId ?? null },+ });session.ptyProcess.onExit(({ exitCode }) => {shellService.unregisterExternalSession(agent.sessionId, { exitCode });});diff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.jsindex 38ce0174b2..987541beb5 100644--- a/server/services/agentRunnerSync.test.js+++ b/server/services/agentRunnerSync.test.js@@ -162,3 +162,46 @@ describe('syncRunnerAgents runner-owned TUI recovery', () => {expect(shellService.registerExternalSession).not.toHaveBeenCalled();});});++describe('syncRunnerAgents — reconnect boundary (#4540)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ runnerAgents.clear();+ activeAgents.clear();+ vi.mocked(shellService.getSession).mockReturnValue(null);+ vi.mocked(getAgent).mockResolvedValue({ metadata: { runId: 'run-abc123' } });+ });++ const survivingTui = {+ id: 'agent-1', taskId: 'task-1', pid: 42, startedAt: Date.now(),+ kind: 'tui', sessionId: 'tui-session-1', workspacePath: '/repo/worktree', command: 'claude',+ };++ it('records the PTY re-attach separately from the run re-adoption', async () => {+ // Two different things can fail on a restart: re-adopting the RUN and+ // re-plumbing its terminal stream. One event for both would make a run whose+ // stream never came back read as fully recovered.+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([survivingTui]);++ await syncRunnerAgents();++ const kinds = appendRunEvent.mock.calls.map(([e]) => e.kind);+ expect(kinds).toEqual(['run.runner-recovered', 'run.reconnected']);+ expect(appendRunEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'run.reconnected',+ runId: 'run-abc123',+ agentId: 'agent-1',+ taskId: 'task-1',+ data: expect.objectContaining({ transport: 'runner-pty', sessionId: 'tui-session-1' })+ }));+ });++ it('records no reconnect when the stream was already attached', async () => {+ vi.mocked(shellService.getSession).mockReturnValue({ sessionId: 'tui-session-1' });+ vi.mocked(getActiveAgentsFromRunner).mockResolvedValue([survivingTui]);++ await syncRunnerAgents();++ expect(appendRunEvent.mock.calls.map(([e]) => e.kind)).toEqual(['run.runner-recovered']);+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 949625fbc0..59e7270818 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -64,6 +64,7 @@ import { composeProviderEnv } from '../lib/cliChildEnv.js';import { ensureOllamaAgentContext } from './ollamaAgentContext.js';import { isOllamaBackedProvider } from './providers.js';import { execFile } from '../lib/childProcess.js';+import { appendRunEvent } from './agentRunEventLog.js';// Agent-specific timing/lifecycle constants (not shared with the one-shot// runner — agents stay alive much longer and write a sentinel file when done).@@ -1020,7 +1021,22 @@ export async function spawnTuiAgent({if (isCodexSession && !promptSubmittedAt && stripped && !mcpBoot.active) mcpBoot.observe(stripped);const now = Date.now();lastOutputAt = now;- if (firstOutputAt === null) firstOutputAt = lastOutputAt;+ if (firstOutputAt === null) {+ firstOutputAt = lastOutputAt;+ // Once per run, on the first byte off the PTY (#4540). Not awaited: this+ // handler is on the hot output path and `appendRunEvent` is a serialized,+ // never-rejecting queue — blocking a terminal repaint on a telemetry+ // write would be the wrong trade. The explicit key makes the append+ // idempotent regardless of how the guard above races.+ appendRunEvent({+ kind: 'run.output',+ runId,+ agentId,+ taskId: task.id,+ eventId: `output:${agentId}:${runId || 'no-run'}:first`,+ data: { source: 'tui-pty' },+ });+ }if (!hasStartedWorking) {hasStartedWorking = true;diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 660fbdb5dd..44708eaf93 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -52,6 +52,12 @@ vi.mock('./agentErrorAnalysis.js', () => ({resolveFailedTaskUpdate: vi.fn().mockResolvedValue({ status: 'failed' })}));+// The lifecycle ledger is a real file writer (data/cos/run-events.jsonl) — mocked+// so first-output telemetry lands in a spy rather than the developing install's+// ledger, and because this suite's fileUtils mock carries no PATHS.cos (#4540).+const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));+vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));+vi.mock('./agentRunTracking.js', () => ({completeAgentRun: vi.fn().mockResolvedValue(undefined)}));diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex 9687a2a160..ea984b4b9b 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -42,6 +42,7 @@ import { syncRunnerAgents } from './agentRunnerSync.js';import { handleAgentCompletion } from './agentLifecycle.js';import { cleanupOrphanedAgents } from './agentManagement.js';import { completeAgentRun } from './agentRunTracking.js';+import { appendRunEvent } from './agentRunEventLog.js';import { runnerAgents, setUseRunner, useRunner } from './agentState.js';import { releaseAppReviewMarker } from './appActivity.js';import { isUpdateInProgress } from './updateChecker.js';@@ -253,8 +254,23 @@ async function runInitSpawner() {if (!runnerAgents.has(agentId)) return;getRunnerOutputBatcher(agentId).push(text);- // Update phase on first outputconst agent = runnerAgents.get(agentId);+ // Once per run, on the first byte the runner forwards (#4540). Tracked on+ // its own flag rather than `hasStartedWorking` below, which also flips on a+ // 3s no-output timeout — a run that never spoke must not get an output event.+ if (agent && !agent.firstOutputRecorded) {+ agent.firstOutputRecorded = true;+ await appendRunEvent({+ kind: 'run.output',+ runId: agent.runId ?? null,+ agentId,+ taskId: agent.taskId ?? null,+ eventId: `output:${agentId}:${agent.runId || 'no-run'}:first`,+ data: { source: 'runner', firstChunkChars: typeof text === 'string' ? text.length : null },+ });+ }++ // Update phase on first outputif (agent && !agent.hasStartedWorking) {agent.hasStartedWorking = true;clearTimeout(agent.initializationTimeout);