Skip to content

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

reconcile CoS run records against the event ledger (#4540)

[._.]/ Adam Eivy6b037b3f0194
diff --git a/client/src/components/cos/tabs/RunEventsTab.jsx b/client/src/components/cos/tabs/RunEventsTab.jsx
index dae94020ce..80a812e25c 100644
--- a/client/src/components/cos/tabs/RunEventsTab.jsx
+++ b/client/src/components/cos/tabs/RunEventsTab.jsx
@@ -1,10 +1,11 @@
import { useState, useEffect, useCallback } from 'react';
import { useSearchParams } from 'react-router';
-import { RefreshCw, ScrollText } from 'lucide-react';
+import { RefreshCw, ScrollText, Wrench } 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';
+import ConfirmButtonPair from '../../ui/ConfirmButtonPair';
/**
* Read-only diagnostic over the append-only CoS run event ledger (#4540).
@@ -68,6 +69,41 @@ export function summarizeEventData(data) {
.join(' ');
}
+/**
+ * How each reconciliation finding reads to a human.
+ *
+ * `label` names the disagreement; `hint` says what it means, because the finding
+ * ids are precise but not self-explanatory — "ledger-open" is meaningless until
+ * you know it is the ledger that is missing something, not the run.
+ */
+export const RECONCILE_FINDINGS = {
+ 'record-open': {
+ label: 'Record still open',
+ hint: 'The ledger holds a verdict this run record never received. Repairable.'
+ },
+ 'record-missing': {
+ label: 'Run record missing',
+ hint: 'The ledger knows this run; no metadata.json exists for it.'
+ },
+ 'verdict-mismatch': {
+ label: 'Verdict disagrees',
+ hint: 'Both sides are closed and report different outcomes.'
+ },
+ 'ledger-open': {
+ label: 'Ledger missed the close',
+ hint: 'The record is closed but no finalize event ever landed.'
+ }
+};
+
+export function describeFinding(item) {
+ const detail = item?.detail ?? {};
+ if (item?.finding === 'verdict-mismatch') {
+ return `ledger ${detail.ledgerSuccess ? 'success' : 'failure'} vs record ${detail.recordSuccess ? 'success' : 'failure'}`;
+ }
+ if (item?.finding === 'ledger-open') return `ledger ${detail.ledgerStatus}, record closed`;
+ return `ledger ${detail.ledgerStatus ?? 'unknown'}`;
+}
+
export default function RunEventsTab() {
const [searchParams, setSearchParams] = useSearchParams();
// Selection lives in the URL so a diagnostic is shareable and reload-safe.
@@ -79,18 +115,27 @@ export default function RunEventsTab() {
const [loading, setLoading] = useState(true);
const [detailLoading, setDetailLoading] = useState(false);
const [loadError, setLoadError] = useState(false);
+ // `null` = not fetched / failed, never conflated with a report that found
+ // nothing — "the ledger and the records agree" and "we couldn't check" are
+ // opposite conclusions.
+ const [reconcile, setReconcile] = useState(null);
+ const [confirmingRepair, setConfirmingRepair] = useState(false);
+ const [repairing, setRepairing] = useState(false);
+ const [repairResult, setRepairResult] = useState(null);
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([
+ const [nextStats, nextProjections, nextReconcile] = await Promise.all([
api.getRunEventStats({ silent: true }).catch(() => null),
- api.getRunEventProjections({ limit: 100 }, { silent: true }).catch(() => null)
+ api.getRunEventProjections({ limit: 100 }, { silent: true }).catch(() => null),
+ api.getRunReconciliation({ limit: 100 }, { silent: true }).catch(() => null)
]);
setStats(nextStats);
setProjections(Array.isArray(nextProjections) ? nextProjections : []);
+ setReconcile(nextReconcile);
setLoadError(nextStats === null || nextProjections === null);
setLoading(false);
}, []);
@@ -119,6 +164,18 @@ export default function RunEventsTab() {
return () => { cancelled = true; };
}, [selectedId]);
+ // The one write on this page. Reloads the whole ledger afterwards rather than
+ // patching the report in place: a repair appends a `run.reconciled` event, so
+ // the projections and the stats it just changed have to be re-read anyway.
+ const repair = async () => {
+ setConfirmingRepair(false);
+ setRepairing(true);
+ const result = await api.repairRunRecords({ limit: 100 }).catch(() => null);
+ setRepairResult(result);
+ setRepairing(false);
+ if (result) await loadLedger();
+ };
+
const select = (id) => {
const next = new URLSearchParams(searchParams);
if (id) next.set('run', id); else next.delete('run');
@@ -160,6 +217,17 @@ export default function RunEventsTab() {
</div>
)}
+ <ReconciliationPanel
+ report={reconcile}
+ onSelect={select}
+ confirming={confirmingRepair}
+ onAskRepair={() => setConfirmingRepair(true)}
+ onCancelRepair={() => setConfirmingRepair(false)}
+ onRepair={repair}
+ repairing={repairing}
+ result={repairResult}
+ />
+
{projections.length === 0 ? (
<Banner tone="info">
No lifecycle events recorded yet. The ledger fills as CoS agents spawn, hand off, pause, and finish.
@@ -214,6 +282,101 @@ export default function RunEventsTab() {
);
}
+/**
+ * Ledger vs. run records.
+ *
+ * The rest of this page reads the ledger on its own terms. This panel is the
+ * only place the two halves of a run's history are put side by side, which is
+ * where the interesting failures live: a record left open by a crash the ledger
+ * saw, a verdict the two sides disagree on, a close event that never landed.
+ *
+ * Only `record-open` is repairable, and the repair is one-directional — the
+ * ledger can close a record it holds the verdict for, never the reverse.
+ */
+function ReconciliationPanel({ report, onSelect, confirming, onAskRepair, onCancelRepair, onRepair, repairing, result }) {
+ if (!report) {
+ return <Banner tone="warning">Could not compare the ledger against the run records.</Banner>;
+ }
+
+ const findings = Array.isArray(report.findings) ? report.findings : [];
+ const repairable = report.summary?.repairable ?? 0;
+ // A ledger with nothing in it has nothing to reconcile; rendering "0 runs
+ // compared" beside the empty-ledger banner below would say the same thing
+ // twice and imply a check that had no subject.
+ if ((report.summary?.checked ?? 0) === 0 && findings.length === 0) return null;
+
+ return (
+ <div className="rounded border border-port-border p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div>
+ <h3 className="text-sm font-semibold text-port-text">Ledger vs. run records</h3>
+ <p className="text-xs text-port-text-muted">
+ {report.summary?.checked ?? 0} run{(report.summary?.checked ?? 0) === 1 ? '' : 's'} compared · {findings.length} disagreement{findings.length === 1 ? '' : 's'}
+ </p>
+ </div>
+ {repairable > 0 && (confirming ? (
+ <ConfirmButtonPair
+ prompt={`Close ${repairable} run record${repairable === 1 ? '' : 's'}?`}
+ confirmText="Close records"
+ confirmIcon={Wrench}
+ tone="warning"
+ busy={repairing}
+ busyText="Closing"
+ onConfirm={onRepair}
+ onCancel={onCancelRepair}
+ ariaLabel="Confirm closing run records from the ledger"
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={onAskRepair}
+ className="flex min-h-[36px] items-center gap-2 rounded border border-port-border px-3 py-1.5 text-sm text-port-text hover:bg-port-border/30"
+ >
+ <Wrench className="h-4 w-4" /> Close {repairable} from ledger
+ </button>
+ ))}
+ </div>
+
+ {result && (
+ <Banner tone={result.repaired?.length ? 'success' : 'info'}>
+ {result.repaired?.length
+ ? `Closed ${result.repaired.length} run record${result.repaired.length === 1 ? '' : 's'} from the ledger.`
+ : 'Nothing left to close — every repairable record had already been closed.'}
+ </Banner>
+ )}
+
+ {findings.length === 0 ? (
+ <p className="mt-2 text-xs text-port-text-muted">
+ Every run record agrees with the stream that produced it.
+ </p>
+ ) : (
+ <ul className="mt-2 max-h-56 space-y-1 overflow-y-auto pr-1">
+ {findings.map((item) => (
+ <li key={`${item.runId}:${item.finding}`}>
+ <button
+ type="button"
+ onClick={() => onSelect(item.runId)}
+ className="w-full rounded border border-port-border px-2 py-1.5 text-left hover:bg-port-border/20"
+ >
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="truncate font-mono text-xs text-port-text">{item.runId}</span>
+ <span className="shrink-0 text-xs text-port-text-muted">
+ {RECONCILE_FINDINGS[item.finding]?.label || item.finding}
+ {item.repairable ? ' · repairable' : ''}
+ </span>
+ </div>
+ <div className="text-xs text-port-text-muted">
+ {describeFinding(item)} — {RECONCILE_FINDINGS[item.finding]?.hint || ''}
+ </div>
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
+
function LedgerStat({ label, value }) {
return (
<div className="rounded border border-port-border px-3 py-2">
diff --git a/client/src/components/cos/tabs/RunEventsTab.test.jsx b/client/src/components/cos/tabs/RunEventsTab.test.jsx
index 0813d46c07..8f974749b1 100644
--- a/client/src/components/cos/tabs/RunEventsTab.test.jsx
+++ b/client/src/components/cos/tabs/RunEventsTab.test.jsx
@@ -7,11 +7,30 @@ const api = vi.hoisted(() => ({
getRunEventStats: vi.fn(),
getRunEventProjections: vi.fn(),
getRunEventDiagnostic: vi.fn(),
+ getRunReconciliation: vi.fn(),
+ repairRunRecords: vi.fn(),
}));
vi.mock('../../../services/api', () => api);
-import RunEventsTab, { projectionAnnotations, summarizeEventData } from './RunEventsTab';
+import RunEventsTab, { projectionAnnotations, summarizeEventData, describeFinding } from './RunEventsTab';
+
+const CLEAN_REPORT = {
+ checkedAt: '2026-08-18T13:00:00.000Z',
+ findings: [],
+ summary: { checked: 1, agentOnly: 0, findings: 0, repairable: 0, byFinding: {} },
+};
+
+const finding = (overrides = {}) => ({
+ runId: 'run-a',
+ agentId: 'agent-a',
+ taskId: 'task-a',
+ lastEventAt: '2026-08-18T11:00:00.000Z',
+ finding: 'record-open',
+ repairable: true,
+ detail: { ledgerStatus: 'failed', ledgerEndedAt: '2026-08-18T11:00:00.000Z', ledgerSuccess: false },
+ ...overrides,
+});
const STATS = {
activeEvents: 12,
@@ -61,6 +80,8 @@ describe('RunEventsTab', () => {
beforeEach(() => {
vi.clearAllMocks();
api.getRunEventStats.mockResolvedValue(STATS);
+ api.getRunReconciliation.mockResolvedValue(CLEAN_REPORT);
+ api.repairRunRecords.mockResolvedValue({ ...CLEAN_REPORT, repaired: [], skipped: 0 });
api.getRunEventProjections.mockResolvedValue([projection()]);
api.getRunEventDiagnostic.mockResolvedValue({
projection: projection(),
@@ -164,3 +185,86 @@ describe('RunEventsTab — a failed detail fetch is not an empty run', () => {
expect(await screen.findByText(/may have aged out/)).toBeInTheDocument();
});
});
+
+describe('RunEventsTab — reconciliation panel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getRunEventStats.mockResolvedValue(STATS);
+ api.getRunEventProjections.mockResolvedValue([projection()]);
+ api.getRunEventDiagnostic.mockResolvedValue({ projection: projection(), events: [] });
+ api.getRunReconciliation.mockResolvedValue(CLEAN_REPORT);
+ api.repairRunRecords.mockResolvedValue({ ...CLEAN_REPORT, repaired: [], skipped: 0 });
+ });
+
+ it('says the record and the stream agree when nothing drifted', async () => {
+ renderTab();
+ expect(await screen.findByText('Every run record agrees with the stream that produced it.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /from ledger/ })).not.toBeInTheDocument();
+ });
+
+ it('distinguishes "could not check" from "nothing to fix"', async () => {
+ api.getRunReconciliation.mockRejectedValue(new Error('offline'));
+ renderTab();
+ expect(await screen.findByText(/Could not compare the ledger against the run records/)).toBeInTheDocument();
+ });
+
+ it('lists a drift finding and offers to repair only the repairable one', async () => {
+ api.getRunReconciliation.mockResolvedValue({
+ ...CLEAN_REPORT,
+ findings: [finding(), finding({ runId: 'run-b', finding: 'ledger-open', repairable: false, detail: { ledgerStatus: 'running', recordEndedAt: '2026-08-18T11:00:00.000Z' } })],
+ summary: { ...CLEAN_REPORT.summary, checked: 2, findings: 2, repairable: 1 },
+ });
+ renderTab();
+ expect(await screen.findByText(/Record still open · repairable/)).toBeInTheDocument();
+ expect(screen.getByText('Ledger missed the close')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /Close 1 from ledger/ })).toBeInTheDocument();
+ });
+
+ it('confirms before closing any record, and reloads the ledger afterwards', async () => {
+ api.getRunReconciliation.mockResolvedValue({
+ ...CLEAN_REPORT,
+ findings: [finding()],
+ summary: { ...CLEAN_REPORT.summary, findings: 1, repairable: 1 },
+ });
+ api.repairRunRecords.mockResolvedValue({
+ ...CLEAN_REPORT,
+ repaired: [{ runId: 'run-a', from: 'failed', success: false, endTime: '2026-08-18T11:00:00.000Z' }],
+ skipped: 0,
+ });
+ renderTab();
+
+ await userEvent.click(await screen.findByRole('button', { name: /Close 1 from ledger/ }));
+ expect(api.repairRunRecords).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Close records' }));
+ expect(api.repairRunRecords).toHaveBeenCalledWith({ limit: 100 });
+ expect(await screen.findByText('Closed 1 run record from the ledger.')).toBeInTheDocument();
+ // The repair appended an event, so the projections and stats it changed are re-read.
+ expect(api.getRunEventProjections).toHaveBeenCalledTimes(2);
+ });
+
+ it('hides the panel entirely for an empty ledger', async () => {
+ api.getRunEventProjections.mockResolvedValue([]);
+ api.getRunReconciliation.mockResolvedValue({ ...CLEAN_REPORT, summary: { ...CLEAN_REPORT.summary, checked: 0 } });
+ renderTab();
+ expect(await screen.findByText(/No lifecycle events recorded yet/)).toBeInTheDocument();
+ expect(screen.queryByText('Ledger vs. run records')).not.toBeInTheDocument();
+ });
+});
+
+describe('describeFinding', () => {
+ it('names both sides of a verdict disagreement', () => {
+ expect(describeFinding({ finding: 'verdict-mismatch', detail: { ledgerSuccess: true, recordSuccess: false } }))
+ .toBe('ledger success vs record failure');
+ });
+
+ it('says which side is behind for a missing close', () => {
+ expect(describeFinding({ finding: 'ledger-open', detail: { ledgerStatus: 'running' } }))
+ .toBe('ledger running, record closed');
+ });
+
+ it('falls back to the ledger status for the remaining findings', () => {
+ expect(describeFinding({ finding: 'record-open', detail: { ledgerStatus: 'failed' } })).toBe('ledger failed');
+ expect(describeFinding({ finding: 'record-missing', detail: {} })).toBe('ledger unknown');
+ });
+});
diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.js
index b627fda261..17ad60b674 100644
--- a/client/src/services/apiAgents.js
+++ b/client/src/services/apiAgents.js
@@ -35,9 +35,10 @@ 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.
+// CoS run event ledger (#4540) — diagnostics over the append-only lifecycle
+// stream. All reads except `repairRunRecords`, which is the one write: it closes
+// the run records the ledger proves are finished, and it is a POST because
+// rewriting a run record is a mutation a user has to ask for.
const runEventQuery = (filters = {}) => {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(filters)) {
@@ -54,6 +55,10 @@ 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);
+export const getRunReconciliation = (filters = {}, options = {}) =>
+ request(`/agents/activity/run-events/reconcile${runEventQuery(filters)}`, options);
+export const repairRunRecords = (body = {}, options = {}) =>
+ request('/agents/activity/run-events/reconcile', { method: 'POST', body: JSON.stringify(body), ...options });
// Chief of Staff
export const getCosStatus = () => request('/cos');
diff --git a/docs/API.md b/docs/API.md
index 2d3918a44f..cd63646051 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -417,6 +417,8 @@ See [Agent Context (MCP)](./features/agent-context.md) for setup, transport head
| 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 |
+| GET | `/agents/activity/run-events/reconcile` | Where the ledger and the durable run records disagree (filters: `runId`, `limit`) — read-only |
+| POST | `/agents/activity/run-events/reconcile` | Close the run records the ledger proves are finished; reports what it closed |
### Notifications
diff --git a/server/lib/README.md b/server/lib/README.md
index 2dd70e195a..da207b873f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -28,6 +28,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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: 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. |
+| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
| `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.js
index 37fcb22fcc..c3e9fc861e 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -83,7 +83,14 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze([
// — 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'
+ 'run.pr-verified',
+ // The durable run record was closed FROM this stream, because the ledger held
+ // a verdict the record never received (see `lib/agentRunReconcile.js`). The
+ // repair is itself a lifecycle fact: without it the record would show an
+ // `endTime` that no exit ever produced, and nothing would say where it came
+ // from. Adding this kind is not an envelope shape change — older builds fold
+ // unknown kinds as no-ops — so AGENT_RUN_EVENT_SCHEMA_VERSION stays at 1.
+ 'run.reconciled'
]);
const KIND_SET = new Set(AGENT_RUN_EVENT_KINDS);
@@ -380,6 +387,8 @@ const emptyProjection = (id) => ({
outputBytes: null,
lastOutputAt: null,
prVerified: null,
+ reconciled: false,
+ reconciledCount: 0,
eventCount: 0,
firstEventAt: null,
lastEventAt: null,
@@ -518,6 +527,21 @@ function applyKind(state, event) {
state.prVerified = data.verified === true;
if (typeof data.prUrl === 'string') state.prUrl = data.prUrl;
break;
+ case 'run.reconciled':
+ // The record was closed from the stream. Recorded as a terminal status so
+ // the projection agrees with the record it just repaired — otherwise the
+ // next replay would still read `orphaned` beside a record that now says
+ // `failed`, which is the exact disagreement the repair removed.
+ // `state.orphaned` and `state.interrupted` are untouched, so how it ended
+ // is not lost to how it was closed.
+ state.reconciled = true;
+ state.reconciledCount += 1;
+ state.endedAt = state.endedAt ?? event.at;
+ if (typeof data.success === 'boolean' && !isTerminal(state)) {
+ state.status = data.success ? 'completed' : 'failed';
+ state.success = data.success;
+ }
+ break;
case 'run.finalized': {
const success = data.success === true;
state.status = success ? 'completed' : 'failed';
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
index 78ce26e2de..80b463661e 100644
--- a/server/lib/agentRunEvents.test.js
+++ b/server/lib/agentRunEvents.test.js
@@ -428,3 +428,43 @@ describe('projectRunStates — the second-slice boundaries (#4540)', () => {
}
});
});
+
+describe('projectRunStates — run.reconciled (#4540)', () => {
+ const at = (hhmm) => `2026-08-18T${hhmm}:00.000Z`;
+
+ it('gives an orphaned run the terminal status its repaired record now carries', () => {
+ const [state] = projectRunStates([
+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', agentId: 'a1', at: at('10:00') }),
+ buildRunEvent({ kind: 'run.orphan-recovered', runId: 'r1', agentId: 'a1', at: at('10:30'), data: { pid: 4242 } }),
+ buildRunEvent({ kind: 'run.reconciled', runId: 'r1', agentId: 'a1', at: at('11:00'), data: { fromStatus: 'orphaned', success: false } })
+ ]);
+ expect(state).toMatchObject({ status: 'failed', success: false, reconciled: true, reconciledCount: 1 });
+ // How it ended is not lost to how it was closed.
+ expect(state.orphaned).toBe(true);
+ });
+
+ it('never overrides a verdict the run reported itself', () => {
+ const [state] = projectRunStates([
+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') }),
+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', at: at('10:30'), data: { success: true, exitCode: 0 } }),
+ buildRunEvent({ kind: 'run.reconciled', runId: 'r1', at: at('11:00'), data: { fromStatus: 'orphaned', success: false } })
+ ]);
+ expect(state).toMatchObject({ status: 'completed', success: true, reconciled: true });
+ expect(state.endedAt).toBe(at('10:30'));
+ });
+
+ it('leaves the status alone when the repair carried no verdict', () => {
+ const [state] = projectRunStates([
+ buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') }),
+ buildRunEvent({ kind: 'run.reconciled', runId: 'r1', at: at('11:00'), data: { fromStatus: 'running' } })
+ ]);
+ expect(state.status).toBe('running');
+ expect(state.reconciled).toBe(true);
+ expect(state.success).toBeNull();
+ });
+
+ it('reports no repair on a run that never needed one', () => {
+ const [state] = projectRunStates([buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: at('10:00') })]);
+ expect(state).toMatchObject({ reconciled: false, reconciledCount: 0 });
+ });
+});
diff --git a/server/lib/agentRunReconcile.js b/server/lib/agentRunReconcile.js
new file mode 100644
index 0000000000..a1756d1f57
--- /dev/null
+++ b/server/lib/agentRunReconcile.js
@@ -0,0 +1,229 @@
+/**
+ * CoS run reconciliation — the ledger read BACK against the run record.
+ *
+ * Slices 1 and 2 of #4540 made the lifecycle observable: every boundary appends
+ * to `data/cos/run-events.jsonl`, and `projectRunStates` folds that stream into
+ * "what this run is now". But the fold has been write-only so far — the ledger
+ * is appended *alongside* `data/runs/{id}/metadata.json` and nothing ever
+ * compared the two. When they disagree, the mutable record wins by default and
+ * the disagreement is invisible, which is precisely the class of failure the
+ * ledger exists to explain.
+ *
+ * This module is the comparison. It is pure — no disk, no clock — so every
+ * finding case is a table test rather than a fixture tree. The service half
+ * (`services/agentRunReconciler.js`) supplies the projections, the records, and
+ * the write.
+ *
+ * **Repairs run one direction only: ledger → record.** A run record left open
+ * because the process died between the ledger append and the metadata write can
+ * be closed from the stream, because the stream holds the verdict. The reverse
+ * — a record that is closed while the ledger never saw the close — is reported
+ * and never "fixed": inventing the missing lifecycle event would put a fact in
+ * the append-only stream that nothing ever observed, and a ledger that
+ * back-fills itself from the record it is supposed to audit can no longer audit
+ * it.
+ */
+
+/**
+ * The closed finding vocabulary. Closed for the same reason the event kinds are:
+ * the summary below is exhaustive over it, and a typo becomes a test failure
+ * rather than a finding nothing counts.
+ */
+export const RUN_RECONCILE_FINDINGS = Object.freeze([
+ // Ledger reached a verdict; the run record still has no `endTime`. The one
+ // repairable case — the stream holds everything the close needs.
+ 'record-open',
+ // The ledger names a run that has no `metadata.json` on disk. Not repairable:
+ // a run record is written by the run, and synthesizing one from redacted
+ // telemetry would fabricate a run history rather than recover one.
+ 'record-missing',
+ // Both sides are closed and disagree on the verdict. Reported, never
+ // repaired: the record's verdict is the one every other reader already used
+ // (usage billing, task status), so silently flipping it would rewrite history
+ // downstream of this module.
+ 'verdict-mismatch',
+ // The record is closed but the ledger still reads live. The close event never
+ // landed — a ledger gap, not a record defect.
+ 'ledger-open'
+]);
+
+/** Projection statuses that mean "this run is over, and the ledger knows how". */
+const TERMINAL_STATUSES = new Set(['completed', 'failed']);
+
+/**
+ * Projection statuses that mean the run is over *as far as the process goes*,
+ * even without a verdict event. `orphaned` belongs here and not in
+ * TERMINAL_STATUSES: the sweep observed the process gone, so the run is
+ * certainly not still working, but no `run.finalized` recorded a verdict — the
+ * repair has to supply "failed" itself rather than copy one.
+ */
+const PROCESS_ENDED_STATUSES = new Set([...TERMINAL_STATUSES, 'orphaned']);
+
+/** Projection statuses that contradict a CLOSED record. */
+const LIVE_STATUSES = new Set(['running', 'orphaned', 'paused', 'interrupted']);
+
+/**
+ * `unknown` is deliberately in none of the three sets above. A projection with
+ * only, say, a `run.pr-verified` event says nothing about whether the run is
+ * open, so pairing it with any record shape is not a finding — reporting it
+ * would fill the panel with rows that have no defect behind them.
+ */
+
+/** Is this projection key a real run id, or the `agent:<id>` fallback? */
+export const isAgentFallbackKey = (id) => typeof id === 'string' && id.startsWith('agent:');
+
+/**
+ * Compare one projection against one run record.
+ *
+ * @param {object} projection - a `projectRunStates` entry
+ * @param {object|null} record - the run's `metadata.json`, or null when absent
+ * @returns {{finding: string, repairable: boolean, detail: object}|null}
+ */
+export function diffRunRecord(projection, record) {
+ if (!projection || isAgentFallbackKey(projection.id)) return null;
+
+ if (!record) {
+ // Only worth reporting once the ledger believes the run actually started.
+ // A projection built solely from an annotation event (a PR verdict that
+ // outlived its run) has no missing record to speak of.
+ if (!projection.startedAt) return null;
+ return finding('record-missing', false, { ledgerStatus: projection.status });
+ }
+
+ const recordClosed = Boolean(record.endTime);
+
+ if (!recordClosed) {
+ if (!PROCESS_ENDED_STATUSES.has(projection.status)) return null;
+ return finding('record-open', true, {
+ ledgerStatus: projection.status,
+ ledgerEndedAt: projection.endedAt ?? projection.lastEventAt ?? null,
+ ledgerSuccess: projection.status === 'orphaned' ? false : projection.success === true
+ });
+ }
+
+ if (TERMINAL_STATUSES.has(projection.status)) {
+ const ledgerSuccess = projection.success === true;
+ const recordSuccess = record.success === true;
+ if (ledgerSuccess === recordSuccess) return null;
+ return finding('verdict-mismatch', false, {
+ ledgerStatus: projection.status,
+ ledgerSuccess,
+ recordSuccess
+ });
+ }
+
+ if (LIVE_STATUSES.has(projection.status)) {
+ return finding('ledger-open', false, {
+ ledgerStatus: projection.status,
+ recordEndedAt: record.endTime
+ });
+ }
+
+ return null;
+}
+
+const finding = (kind, repairable, detail) => ({ finding: kind, repairable, detail });
+
+/**
+ * Reconcile a batch of projections against the records supplied for them.
+ *
+ * @param {object} input
+ * @param {object[]} input.projections - `projectRunStates` output
+ * @param {Map<string, object|null>} input.records - runId → metadata (null = absent)
+ * @returns {{findings: object[], summary: object}}
+ */
+export function reconcileRunRecords({ projections = [], records = new Map() } = {}) {
+ const findings = [];
+ let agentOnly = 0;
+ let checked = 0;
+
+ for (const projection of projections) {
+ if (isAgentFallbackKey(projection?.id)) {
+ agentOnly += 1;
+ continue;
+ }
+ checked += 1;
+ const record = records.get(projection.id) ?? null;
+ const diff = diffRunRecord(projection, record);
+ if (!diff) continue;
+ findings.push({
+ runId: projection.id,
+ agentId: projection.agentId ?? null,
+ taskId: projection.taskId ?? null,
+ lastEventAt: projection.lastEventAt ?? null,
+ ...diff
+ });
+ }
+
+ return { findings, summary: summarize(findings, { checked, agentOnly }) };
+}
+
+/**
+ * Counts, one per finding kind, always present even at zero.
+ *
+ * Zero-filled on purpose: a UI reading `summary['record-open']` must get `0`
+ * for a healthy install rather than `undefined`, or "no drift" and "this build
+ * doesn't know that finding" render identically.
+ */
+function summarize(findings, { checked, agentOnly }) {
+ const byFinding = Object.fromEntries(RUN_RECONCILE_FINDINGS.map((kind) => [kind, 0]));
+ for (const item of findings) byFinding[item.finding] += 1;
+ return {
+ checked,
+ agentOnly,
+ findings: findings.length,
+ repairable: findings.filter((item) => item.repairable).length,
+ byFinding
+ };
+}
+
+/**
+ * The metadata patch that closes an open record from its ledger projection.
+ *
+ * Returns null unless the pair is genuinely a `record-open` finding, so the
+ * service can call this per candidate without re-deriving the diff and can
+ * never write from a finding that was only informational.
+ *
+ * The patch carries `reconciledFromLedger` so a later reader — a human, or the
+ * usage reconciler — can tell a verdict the run reported from one the ledger
+ * supplied after the fact. `duration` is derived rather than copied because a
+ * run whose `run.finalized` never landed has no recorded duration either.
+ *
+ * @param {object} projection
+ * @param {object|null} record
+ * @param {string} at - ISO timestamp for the repair itself
+ * @returns {object|null} shallow patch to merge into metadata.json
+ */
+export function planRunRecordRepair(projection, record, at) {
+ const diff = diffRunRecord(projection, record);
+ if (!diff || diff.finding !== 'record-open') return null;
+
+ // Prefer the ledger's own end stamp; fall back to the repair time so the
+ // record is never closed with a null `endTime` (the field every other reader
+ // uses as "is this run over").
+ const endTime = diff.detail.ledgerEndedAt || at;
+ const success = diff.detail.ledgerSuccess;
+ const startedMs = Date.parse(record?.startTime ?? '');
+ const endedMs = Date.parse(endTime);
+ const duration = Number.isFinite(record?.duration) ? record.duration
+ : (Number.isFinite(startedMs) && Number.isFinite(endedMs) && endedMs >= startedMs ? endedMs - startedMs : null);
+
+ const patch = {
+ endTime,
+ duration,
+ success,
+ exitCode: Number.isFinite(projection.exitCode) ? projection.exitCode : (record?.exitCode ?? null),
+ reconciledFromLedger: true,
+ reconciledAt: at,
+ reconciledFromStatus: projection.status
+ };
+
+ if (!success) {
+ patch.error = record?.error || (projection.status === 'orphaned'
+ ? 'Agent process terminated unexpectedly (closed by run-event reconciliation)'
+ : 'Run failed (closed by run-event reconciliation)');
+ patch.errorCategory = record?.errorCategory || projection.errorCategory || 'reconciled';
+ }
+
+ return patch;
+}
diff --git a/server/lib/agentRunReconcile.test.js b/server/lib/agentRunReconcile.test.js
new file mode 100644
index 0000000000..9b71fc7ed5
--- /dev/null
+++ b/server/lib/agentRunReconcile.test.js
@@ -0,0 +1,205 @@
+import { describe, it, expect } from 'vitest';
+import {
+ RUN_RECONCILE_FINDINGS,
+ isAgentFallbackKey,
+ diffRunRecord,
+ reconcileRunRecords,
+ planRunRecordRepair
+} from './agentRunReconcile.js';
+import { projectRunStates, buildRunEvent } from './agentRunEvents.js';
+
+const AT = '2026-08-18T12:00:00.000Z';
+const LATER = '2026-08-18T12:05:00.000Z';
+const REPAIR_AT = '2026-08-18T13:00:00.000Z';
+
+/**
+ * Projections are built by FOLDING real events rather than hand-written, so a
+ * change to the fold that breaks reconciliation fails here instead of shipping
+ * a diff engine that reads fields the projection no longer produces.
+ */
+const project = (events) => projectRunStates(events.map(buildRunEvent));
+
+const spawned = (runId = 'r1') => ({ kind: 'run.spawned', runId, agentId: 'a1', taskId: 't1', at: AT });
+const finalized = (success, runId = 'r1') => ({
+ kind: 'run.finalized', runId, agentId: 'a1', at: LATER, data: { success, exitCode: success ? 0 : 1, durationMs: 300000 }
+});
+const orphaned = (runId = 'r1') => ({ kind: 'run.orphan-recovered', runId, agentId: 'a1', at: LATER, data: { pid: 4242 } });
+
+const openRecord = (extra = {}) => ({ id: 'r1', startTime: AT, endTime: null, success: null, ...extra });
+const closedRecord = (success, extra = {}) => ({ id: 'r1', startTime: AT, endTime: LATER, success, ...extra });
+
+const one = (events) => project(events)[0];
+
+describe('diffRunRecord', () => {
+ it('reports nothing when an open record matches a still-running ledger', () => {
+ expect(diffRunRecord(one([spawned()]), openRecord())).toBeNull();
+ });
+
+ it('reports nothing when both sides agree the run succeeded', () => {
+ expect(diffRunRecord(one([spawned(), finalized(true)]), closedRecord(true))).toBeNull();
+ });
+
+ it('flags an open record the ledger has already finalized, and calls it repairable', () => {
+ const diff = diffRunRecord(one([spawned(), finalized(false)]), openRecord());
+ expect(diff).toMatchObject({ finding: 'record-open', repairable: true });
+ expect(diff.detail).toMatchObject({ ledgerStatus: 'failed', ledgerSuccess: false, ledgerEndedAt: LATER });
+ });
+
+ it('treats an orphaned run as a failure even though no verdict event exists', () => {
+ const diff = diffRunRecord(one([spawned(), orphaned()]), openRecord());
+ expect(diff).toMatchObject({ finding: 'record-open', repairable: true });
+ expect(diff.detail.ledgerSuccess).toBe(false);
+ });
+
+ it('flags a run the ledger knows but no record exists for, and refuses to repair it', () => {
+ const diff = diffRunRecord(one([spawned(), finalized(true)]), null);
+ expect(diff).toMatchObject({ finding: 'record-missing', repairable: false });
+ });
+
+ it('does not report a missing record for a projection that never saw a spawn', () => {
+ const annotationOnly = one([{ kind: 'run.pr-verified', runId: 'r1', at: AT, data: { verified: true } }]);
+ expect(diffRunRecord(annotationOnly, null)).toBeNull();
+ });
+
+ it('flags disagreeing verdicts without proposing a repair', () => {
+ const diff = diffRunRecord(one([spawned(), finalized(true)]), closedRecord(false));
+ expect(diff).toMatchObject({ finding: 'verdict-mismatch', repairable: false });
+ expect(diff.detail).toMatchObject({ ledgerSuccess: true, recordSuccess: false });
+ });
+
+ it('flags a closed record whose close never reached the ledger', () => {
+ const diff = diffRunRecord(one([spawned()]), closedRecord(true));
+ expect(diff).toMatchObject({ finding: 'ledger-open', repairable: false });
+ expect(diff.detail).toMatchObject({ ledgerStatus: 'running', recordEndedAt: LATER });
+ });
+
+ it('says nothing about a projection with no status opinion', () => {
+ // `unknown` belongs to none of the status sets: an annotation-only stream
+ // makes no claim about whether the run is open, so pairing it with a closed
+ // record is not a finding.
+ const annotationOnly = one([{ kind: 'run.pr-verified', runId: 'r1', at: AT, data: { verified: true } }]);
+ expect(annotationOnly.status).toBe('unknown');
+ expect(diffRunRecord(annotationOnly, closedRecord(true))).toBeNull();
+ });
+
+ it('skips the agent:<id> fallback key, which can have no run record', () => {
+ const agentOnly = one([{ kind: 'run.orphan-recovered', agentId: 'a9', at: AT, data: {} }]);
+ expect(isAgentFallbackKey(agentOnly.id)).toBe(true);
+ expect(diffRunRecord(agentOnly, null)).toBeNull();
+ });
+
+ it('only ever emits findings from the closed vocabulary', () => {
+ const cases = [
+ [one([spawned(), finalized(false)]), openRecord()],
+ [one([spawned(), finalized(true)]), null],
+ [one([spawned(), finalized(true)]), closedRecord(false)],
+ [one([spawned()]), closedRecord(true)]
+ ];
+ for (const [projection, record] of cases) {
+ expect(RUN_RECONCILE_FINDINGS).toContain(diffRunRecord(projection, record).finding);
+ }
+ });
+});
+
+describe('reconcileRunRecords', () => {
+ it('zero-fills every finding count so a healthy install reads 0, not undefined', () => {
+ const { findings, summary } = reconcileRunRecords({
+ projections: project([spawned(), finalized(true)]),
+ records: new Map([['r1', closedRecord(true)]])
+ });
+ expect(findings).toEqual([]);
+ expect(summary.checked).toBe(1);
+ for (const kind of RUN_RECONCILE_FINDINGS) expect(summary.byFinding[kind]).toBe(0);
+ });
+
+ it('counts repairable findings separately and carries the run ids through', () => {
+ const projections = project([
+ spawned('r1'), finalized(false, 'r1'),
+ spawned('r2'), finalized(true, 'r2')
+ ]);
+ const { findings, summary } = reconcileRunRecords({
+ projections,
+ records: new Map([['r1', openRecord()], ['r2', { id: 'r2', startTime: AT, endTime: LATER, success: false }]])
+ });
+ expect(summary).toMatchObject({ checked: 2, findings: 2, repairable: 1 });
+ expect(summary.byFinding['record-open']).toBe(1);
+ expect(summary.byFinding['verdict-mismatch']).toBe(1);
+ expect(findings.map((f) => f.runId).sort()).toEqual(['r1', 'r2']);
+ expect(findings.every((f) => f.agentId === 'a1')).toBe(true);
+ });
+
+ it('counts agent-only projections rather than checking them', () => {
+ const projections = project([{ kind: 'run.orphan-recovered', agentId: 'a9', at: AT, data: {} }]);
+ const { findings, summary } = reconcileRunRecords({ projections, records: new Map() });
+ expect(findings).toEqual([]);
+ expect(summary).toMatchObject({ checked: 0, agentOnly: 1 });
+ });
+
+ it('treats a record absent from the map the same as an explicit null', () => {
+ const projections = project([spawned(), finalized(true)]);
+ const viaNull = reconcileRunRecords({ projections, records: new Map([['r1', null]]) });
+ const viaAbsent = reconcileRunRecords({ projections, records: new Map() });
+ expect(viaAbsent.findings).toEqual(viaNull.findings);
+ expect(viaNull.findings[0].finding).toBe('record-missing');
+ });
+
+ it('tolerates being called with nothing', () => {
+ expect(reconcileRunRecords().summary).toMatchObject({ checked: 0, findings: 0, repairable: 0 });
+ });
+});
+
+describe('planRunRecordRepair', () => {
+ it('closes an open record with the ledger verdict and derives the duration', () => {
+ const patch = planRunRecordRepair(one([spawned(), finalized(false)]), openRecord(), REPAIR_AT);
+ expect(patch).toMatchObject({
+ endTime: LATER,
+ success: false,
+ exitCode: 1,
+ duration: 300000,
+ reconciledFromLedger: true,
+ reconciledAt: REPAIR_AT,
+ reconciledFromStatus: 'failed'
+ });
+ expect(patch.error).toContain('reconciliation');
+ expect(patch.errorCategory).toBe('reconciled');
+ });
+
+ it('derives the duration from the record start when the ledger has none', () => {
+ const patch = planRunRecordRepair(one([spawned(), orphaned()]), openRecord(), REPAIR_AT);
+ expect(patch.duration).toBe(Date.parse(LATER) - Date.parse(AT));
+ expect(patch.endTime).toBe(LATER);
+ expect(patch.success).toBe(false);
+ });
+
+ it('leaves a successful repair without a fabricated error', () => {
+ const patch = planRunRecordRepair(one([spawned(), finalized(true)]), openRecord(), REPAIR_AT);
+ expect(patch.success).toBe(true);
+ expect(patch.error).toBeUndefined();
+ expect(patch.errorCategory).toBeUndefined();
+ });
+
+ it('keeps the record own error text when it already has one', () => {
+ const patch = planRunRecordRepair(
+ one([spawned(), finalized(false)]),
+ openRecord({ error: 'Provider quota exhausted', errorCategory: 'quota' }),
+ REPAIR_AT
+ );
+ expect(patch.error).toBe('Provider quota exhausted');
+ expect(patch.errorCategory).toBe('quota');
+ });
+
+ it('never plans a repair for a finding that is not record-open', () => {
+ expect(planRunRecordRepair(one([spawned(), finalized(true)]), null, REPAIR_AT)).toBeNull();
+ expect(planRunRecordRepair(one([spawned(), finalized(true)]), closedRecord(false), REPAIR_AT)).toBeNull();
+ expect(planRunRecordRepair(one([spawned()]), closedRecord(true), REPAIR_AT)).toBeNull();
+ expect(planRunRecordRepair(one([spawned()]), openRecord(), REPAIR_AT)).toBeNull();
+ });
+
+ it('falls back to the repair time rather than closing a record with a null endTime', () => {
+ // A finalize whose projection carries no end stamp cannot happen through
+ // `run.finalized`, so this drives the fallback through an orphan-only
+ // stream with its own `at` stripped by the projection's key fallback.
+ const projection = { ...one([spawned(), orphaned()]), endedAt: null, lastEventAt: null };
+ expect(planRunRecordRepair(projection, openRecord(), REPAIR_AT).endTime).toBe(REPAIR_AT);
+ });
+});
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 5ed40c3b9a..f4628f916a 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1734,3 +1734,12 @@ export const runEventProjectionsQuerySchema = z.object({
export const runEventProjectionIdSchema = z.object({
id: z.string().min(1).max(140)
});
+
+// Reconciliation report/repair (#4540). `runId` narrows to one run; `limit`
+// shares the ledger's read ceiling because the projections being reconciled
+// come straight off that read path — a separate ceiling here could only
+// disagree with it.
+export const runEventReconcileSchema = z.object({
+ runId: z.string().min(1).max(128).optional(),
+ limit: z.coerce.number().int().min(1).max(RUN_EVENT_READ_LIMITS.max).optional()
+}).strict();
diff --git a/server/lib/index.js b/server/lib/index.js
index 83c8fa41a6..8139d1e22a 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -190,6 +190,7 @@ export * from './zipWriter.js';
export * from './agentGuard/index.js';
export * from './agentOutputMarkers.js';
export * from './agentRunEvents.js';
+export * from './agentRunReconcile.js';
export * from './agentSentinel.js';
export * from './bareUrl.js';
export * from './bashResolver.js';
diff --git a/server/routes/agentActivity.js b/server/routes/agentActivity.js
index ba99b3a888..09e5926bfc 100644
--- a/server/routes/agentActivity.js
+++ b/server/routes/agentActivity.js
@@ -7,9 +7,10 @@
import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
-import { runEventsQuerySchema, runEventProjectionsQuerySchema, runEventProjectionIdSchema } from '../lib/cosValidation.js';
+import { runEventsQuerySchema, runEventProjectionsQuerySchema, runEventProjectionIdSchema, runEventReconcileSchema } from '../lib/cosValidation.js';
import * as agentActivity from '../services/agentActivity.js';
import * as runEventLog from '../services/agentRunEventLog.js';
+import * as runReconciler from '../services/agentRunReconciler.js';
const router = Router();
@@ -100,6 +101,21 @@ router.get('/run-events/projections', asyncHandler(async (req, res) => {
res.json(await runEventLog.getRunProjections(query));
}));
+// GET /run-events/reconcile - Where the ledger and the run records disagree.
+// Read-only: it reports drift, it never resolves it. The POST below is the only
+// thing that writes, and it is a POST precisely because closing a run record is
+// a mutation a user has to ask for.
+router.get('/run-events/reconcile', asyncHandler(async (req, res) => {
+ const query = validateRequest(runEventReconcileSchema, req.query);
+ res.json(await runReconciler.getRunReconciliation(query));
+}));
+
+// POST /run-events/reconcile - Close the run records the ledger proves are done
+router.post('/run-events/reconcile', asyncHandler(async (req, res) => {
+ const body = validateRequest(runEventReconcileSchema, req.body ?? {});
+ res.json(await runReconciler.repairRunRecords(body));
+}));
+
// GET /run-events/run/:id - One run's projection plus the events behind it
router.get('/run-events/run/:id', asyncHandler(async (req, res) => {
const { id } = validateRequest(runEventProjectionIdSchema, req.params);
diff --git a/server/routes/agentActivity.test.js b/server/routes/agentActivity.test.js
index 7006753298..0de335f403 100644
--- a/server/routes/agentActivity.test.js
+++ b/server/routes/agentActivity.test.js
@@ -8,9 +8,12 @@ const mocks = vi.hoisted(() => ({
getRunProjections: vi.fn(),
getRunDiagnostic: vi.fn(),
getRunEventLedgerStats: vi.fn(),
+ getRunReconciliation: vi.fn(),
+ repairRunRecords: vi.fn(),
}));
vi.mock('../services/agentRunEventLog.js', () => mocks);
+vi.mock('../services/agentRunReconciler.js', () => mocks);
vi.mock('../services/agentActivity.js', () => ({
getRecentActivities: vi.fn(async () => []),
getActivityTimeline: vi.fn(async () => []),
@@ -30,6 +33,7 @@ const app = () => {
};
const get = (path) => request(app()).get(`/api/agents/activity${path}`);
+const post = (path, body) => request(app()).post(`/api/agents/activity${path}`).send(body);
describe('GET /run-events', () => {
beforeEach(() => {
@@ -119,3 +123,51 @@ describe('GET /run-events/run/:id', () => {
expect(mocks.getRunDiagnostic).not.toHaveBeenCalled();
});
});
+
+describe('/run-events/reconcile', () => {
+ const emptyReport = { checkedAt: '2026-08-18T13:00:00.000Z', findings: [], summary: { checked: 0 } };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getRunReconciliation.mockResolvedValue(emptyReport);
+ mocks.repairRunRecords.mockResolvedValue({ ...emptyReport, repaired: [], skipped: 0 });
+ });
+
+ it('serves the drift report and forwards the parsed filters', async () => {
+ const res = await get('/run-events/reconcile?runId=r1&limit=25');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual(emptyReport);
+ expect(mocks.getRunReconciliation).toHaveBeenCalledWith({ runId: 'r1', limit: 25 });
+ });
+
+ it('rejects an unknown filter rather than silently ignoring it', async () => {
+ expect((await get('/run-events/reconcile?nope=1')).status).toBe(400);
+ });
+
+ it('holds the report to the ledger read ceiling', async () => {
+ expect((await get('/run-events/reconcile?limit=100000')).status).toBe(400);
+ expect((await get('/run-events/reconcile?limit=0')).status).toBe(400);
+ });
+
+ it('never repairs from the GET', async () => {
+ await get('/run-events/reconcile');
+ expect(mocks.repairRunRecords).not.toHaveBeenCalled();
+ });
+
+ it('repairs only from the POST, and validates the body', async () => {
+ const res = await post('/run-events/reconcile', { runId: 'r1', limit: 10 });
+ expect(res.status).toBe(200);
+ expect(res.body.repaired).toEqual([]);
+ expect(mocks.repairRunRecords).toHaveBeenCalledWith({ runId: 'r1', limit: 10 });
+ });
+
+ it('accepts an empty POST body', async () => {
+ const res = await post('/run-events/reconcile');
+ expect(res.status).toBe(200);
+ expect(mocks.repairRunRecords).toHaveBeenCalledWith({});
+ });
+
+ it('rejects an unknown field in the POST body', async () => {
+ expect((await post('/run-events/reconcile', { force: true })).status).toBe(400);
+ });
+});
diff --git a/server/services/agentRunReconciler.js b/server/services/agentRunReconciler.js
new file mode 100644
index 0000000000..95a328c699
--- /dev/null
+++ b/server/services/agentRunReconciler.js
@@ -0,0 +1,143 @@
+/**
+ * CoS run reconciliation service — the I/O half of `lib/agentRunReconcile.js`.
+ *
+ * Completes the loop #4540 opened: slices 1 and 2 made every lifecycle boundary
+ * append to the ledger, and this reads that stream back against the durable run
+ * records in `data/runs/{id}/metadata.json`.
+ *
+ * Two operations, deliberately separated:
+ *
+ * - `getRunReconciliation()` is a pure read. It is what the diagnostic view and
+ * the GET route call, and it can never change anything.
+ * - `repairRunRecords()` closes the records the ledger proves are finished. It
+ * only ever runs from an explicit POST — never from boot, never from a timer.
+ * A repair rewrites a user-visible run record, and the situation that calls
+ * for one (a record left open by a crash) is also the situation where a
+ * background sweep is most likely to race whatever recovery is already in
+ * flight.
+ *
+ * The record load is bounded by the ledger, not by the filesystem: only run ids
+ * the projections actually name are read, so this never becomes a scan of a
+ * `data/runs` directory holding thousands of historical runs.
+ */
+
+import { join } from 'path';
+import { PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';
+import { RUN_EVENT_READ_LIMITS } from '../lib/agentRunEvents.js';
+import { reconcileRunRecords, planRunRecordRepair, isAgentFallbackKey } from '../lib/agentRunReconcile.js';
+import { getRunProjections, appendRunEvent } from './agentRunEventLog.js';
+
+const metadataPath = (runId) => join(PATHS.runs, runId, 'metadata.json');
+
+/**
+ * Load the run records the given projections name.
+ *
+ * Absent records are stored as an explicit `null` rather than left out of the
+ * map, so the diff can tell "no record on disk" from "not looked at" — the
+ * sentinel-over-truthiness rule that runs through this whole feature.
+ */
+async function loadRecordsFor(projections) {
+ const runIds = projections.map((p) => p.id).filter((id) => id && !isAgentFallbackKey(id));
+ const records = await Promise.all(runIds.map((id) => readJSONFile(metadataPath(id), null)));
+ return new Map(runIds.map((id, index) => [id, records[index] ?? null]));
+}
+
+const cap = (limit) => Math.min(
+ Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : RUN_EVENT_READ_LIMITS.default,
+ RUN_EVENT_READ_LIMITS.max
+);
+
+/**
+ * Compare the ledger's projections against the run records. Read-only.
+ *
+ * @param {object} [options]
+ * @param {string} [options.runId] - restrict to one run
+ * @param {number} [options.limit] - max projections examined
+ * @returns {Promise<{checkedAt: string, findings: object[], summary: object}>}
+ */
+export async function getRunReconciliation({ runId, limit } = {}) {
+ const projections = await getRunProjections({ runId, limit: cap(limit) });
+ const records = await loadRecordsFor(projections);
+ return { checkedAt: new Date().toISOString(), ...reconcileRunRecords({ projections, records }) };
+}
+
+// Re-entrancy guard: one repair pass at a time. Not a concurrency defense (see
+// the trust model) — a second pass launched while the first is mid-write would
+// read records the first has not closed yet and plan the same repairs twice,
+// producing a duplicate-looking result for work already done.
+let inFlight = null;
+
+/**
+ * Close every run record the ledger proves is finished.
+ *
+ * Each repair is a read-modify-write against the record itself, and the record
+ * is **re-read immediately before the write**: a run that finalized normally in
+ * the window between the report and the repair must be left exactly as its own
+ * completion path wrote it. `planRunRecordRepair` is re-run against that fresh
+ * copy, so a record that closed itself in the meantime plans to nothing.
+ *
+ * The returned `findings`/`summary` describe the state the pass STARTED from,
+ * not what is left afterwards — they are the evidence for `repaired`, and a
+ * caller wanting the post-repair picture calls `getRunReconciliation()` again.
+ *
+ * @param {object} [options]
+ * @param {string} [options.runId] - restrict to one run
+ * @param {number} [options.limit] - max projections examined
+ * @returns {Promise<{checkedAt: string, repaired: object[], skipped: number, findings: object[], summary: object}>}
+ */
+export function repairRunRecords(options = {}) {
+ if (inFlight) return inFlight;
+ inFlight = repairNow(options).finally(() => { inFlight = null; });
+ return inFlight;
+}
+
+async function repairNow({ runId, limit } = {}) {
+ const projections = await getRunProjections({ runId, limit: cap(limit) });
+ const records = await loadRecordsFor(projections);
+ const report = reconcileRunRecords({ projections, records });
+ const byId = new Map(projections.map((p) => [p.id, p]));
+
+ const repaired = [];
+ let skipped = 0;
+
+ for (const item of report.findings) {
+ if (!item.repairable) continue;
+ const projection = byId.get(item.runId);
+ const path = metadataPath(item.runId);
+ // Fresh read — the report above may be a few disk reads old, and the run's
+ // own completion path is the one writer allowed to win that race.
+ const record = await readJSONFile(path, null);
+ const patch = planRunRecordRepair(projection, record, new Date().toISOString());
+ if (!patch) {
+ skipped += 1;
+ continue;
+ }
+
+ await atomicWrite(path, { ...record, ...patch });
+ console.log(`🩹 Closed run ${item.runId} from the event ledger: ledger read ${item.detail.ledgerStatus}, record now ${patch.success ? 'success' : 'failure'}`);
+
+ // The repair is a lifecycle fact of its own. An explicit natural key rather
+ // than the content-derived default: re-running a repair for the same run
+ // and the same close stamp is the same fact, and the content hash covers
+ // the wall-clock `reconciledAt`, so it would otherwise mint a new event on
+ // every pass.
+ await appendRunEvent({
+ kind: 'run.reconciled',
+ eventId: `reconcile:${item.runId}:${patch.endTime}`,
+ runId: item.runId,
+ agentId: item.agentId,
+ taskId: item.taskId,
+ at: patch.reconciledAt,
+ data: {
+ fromStatus: patch.reconciledFromStatus,
+ success: patch.success,
+ exitCode: patch.exitCode,
+ durationMs: patch.duration
+ }
+ });
+
+ repaired.push({ runId: item.runId, from: item.detail.ledgerStatus, success: patch.success, endTime: patch.endTime });
+ }
+
+ return { checkedAt: new Date().toISOString(), repaired, skipped, ...report };
+}
diff --git a/server/services/agentRunReconciler.test.js b/server/services/agentRunReconciler.test.js
new file mode 100644
index 0000000000..be1a43cd6a
--- /dev/null
+++ b/server/services/agentRunReconciler.test.js
@@ -0,0 +1,235 @@
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest';
+import { rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { join } from 'path';
+
+// Both the ledger and the run records are redirected into throwaway dirs. The
+// service resolves `PATHS` at module load — the same reason a real restart is
+// what re-reads them — so the mock has to be hoisted above the imports.
+const { LEDGER_DIR, RUNS_DIR, hooks } = await vi.hoisted(async () => {
+ const { mkdtempSync: mk } = await import('fs');
+ const { tmpdir: tmp } = await import('os');
+ const { join: j } = await import('path');
+ return {
+ LEDGER_DIR: mk(j(tmp(), 'portos-reconcile-ledger-')),
+ RUNS_DIR: mk(j(tmp(), 'portos-reconcile-runs-')),
+ // A seam for the one test that has to interleave a write between the
+ // service's two reads of the same record. Nothing else installs a hook.
+ hooks: { afterRecordRead: null }
+ };
+});
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return {
+ ...actual,
+ PATHS: { ...actual.PATHS, cos: LEDGER_DIR, runs: RUNS_DIR },
+ readJSONFile: async (path, fallback) => {
+ const value = await actual.readJSONFile(path, fallback);
+ if (hooks.afterRecordRead) await hooks.afterRecordRead(path);
+ return value;
+ }
+ };
+});
+
+const { getRunReconciliation, repairRunRecords } = await import('./agentRunReconciler.js');
+const { appendRunEvent, readRunEvents, __resetRunEventLogCache } = await import('./agentRunEventLog.js');
+
+const ACTIVE = join(LEDGER_DIR, 'run-events.jsonl');
+const ARCHIVE = join(LEDGER_DIR, 'run-events.1.jsonl');
+
+const AT = '2026-08-18T12:00:00.000Z';
+const LATER = '2026-08-18T12:05:00.000Z';
+const NOW = '2026-08-18T13:00:00.000Z';
+
+const metaPath = (runId) => join(RUNS_DIR, runId, 'metadata.json');
+
+function writeRecord(runId, record) {
+ mkdirSync(join(RUNS_DIR, runId), { recursive: true });
+ writeFileSync(metaPath(runId), JSON.stringify({ id: runId, startTime: AT, ...record }));
+}
+
+const readRecord = (runId) => JSON.parse(readFileSync(metaPath(runId), 'utf8'));
+
+const spawn = (runId) => appendRunEvent({ kind: 'run.spawned', runId, agentId: 'a1', taskId: 't1', at: AT, data: {} });
+const finalize = (runId, success) => appendRunEvent({
+ kind: 'run.finalized', runId, agentId: 'a1', at: LATER,
+ data: { success, exitCode: success ? 0 : 1, durationMs: 300000 }
+});
+
+beforeEach(() => {
+ for (const path of [ACTIVE, ARCHIVE]) if (existsSync(path)) rmSync(path);
+ rmSync(RUNS_DIR, { recursive: true, force: true });
+ mkdirSync(RUNS_DIR, { recursive: true });
+ __resetRunEventLogCache();
+ // Pinned next to the fixture timestamps so the ledger's 30-day age bound
+ // can't age the fixtures out once the calendar passes them.
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date(NOW));
+});
+
+afterEach(() => {
+ hooks.afterRecordRead = null;
+ vi.useRealTimers();
+});
+afterAll(() => {
+ rmSync(LEDGER_DIR, { recursive: true, force: true });
+ rmSync(RUNS_DIR, { recursive: true, force: true });
+});
+
+describe('getRunReconciliation', () => {
+ it('reports nothing when the record matches the stream that produced it', async () => {
+ writeRecord('r1', { endTime: LATER, success: true });
+ await spawn('r1');
+ await finalize('r1', true);
+
+ const report = await getRunReconciliation();
+ expect(report.findings).toEqual([]);
+ expect(report.summary).toMatchObject({ checked: 1, repairable: 0 });
+ expect(report.checkedAt).toBe(NOW);
+ });
+
+ it('finds an open record the ledger already finalized', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ const report = await getRunReconciliation();
+ expect(report.findings).toHaveLength(1);
+ expect(report.findings[0]).toMatchObject({ runId: 'r1', finding: 'record-open', repairable: true });
+ });
+
+ it('never writes — the record is untouched by a report', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ const before = readFileSync(metaPath('r1'), 'utf8');
+ await getRunReconciliation();
+ expect(readFileSync(metaPath('r1'), 'utf8')).toBe(before);
+ });
+
+ it('narrows to one run when asked', async () => {
+ writeRecord('r1', { endTime: null });
+ writeRecord('r2', { endTime: null });
+ await spawn('r1'); await finalize('r1', false);
+ await spawn('r2'); await finalize('r2', false);
+
+ const report = await getRunReconciliation({ runId: 'r2' });
+ expect(report.summary.checked).toBe(1);
+ expect(report.findings.map((f) => f.runId)).toEqual(['r2']);
+ });
+
+ it('reports a run the ledger knows but that has no record on disk', async () => {
+ await spawn('gone');
+ await finalize('gone', true);
+
+ const report = await getRunReconciliation();
+ expect(report.findings[0]).toMatchObject({ runId: 'gone', finding: 'record-missing', repairable: false });
+ });
+});
+
+describe('repairRunRecords', () => {
+ it('closes an open record with the ledger verdict and records the repair as an event', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ const result = await repairRunRecords();
+ expect(result.repaired).toEqual([{ runId: 'r1', from: 'failed', success: false, endTime: LATER }]);
+
+ const record = readRecord('r1');
+ expect(record).toMatchObject({ endTime: LATER, success: false, exitCode: 1, reconciledFromLedger: true, reconciledAt: NOW });
+ // The run's own fields survive the merge — a repair closes a record, it
+ // does not replace it.
+ expect(record.startTime).toBe(AT);
+
+ const events = await readRunEvents({ runId: 'r1', kind: 'run.reconciled' });
+ expect(events).toHaveLength(1);
+ expect(events[0].data).toMatchObject({ fromStatus: 'failed', success: false });
+ });
+
+ it('is idempotent — a second pass finds the record already closed', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ await repairRunRecords();
+ const after = readFileSync(metaPath('r1'), 'utf8');
+ const second = await repairRunRecords();
+
+ expect(second.repaired).toEqual([]);
+ expect(second.findings).toEqual([]);
+ expect(readFileSync(metaPath('r1'), 'utf8')).toBe(after);
+ expect(await readRunEvents({ runId: 'r1', kind: 'run.reconciled' })).toHaveLength(1);
+ });
+
+ it('leaves a run that closed itself between the report and the write alone', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ // The run's own completion path landing mid-pass. It fires after the
+ // reconciler's FIRST read of the record (which still sees it open, so the
+ // finding is genuinely 'record-open' and repairable) and before the fresh
+ // read the repair loop takes — which is the read that has to notice.
+ let reads = 0;
+ hooks.afterRecordRead = (path) => {
+ if (!path.includes('r1')) return;
+ reads += 1;
+ if (reads === 1) writeRecord('r1', { endTime: LATER, success: true, duration: 1 });
+ };
+
+ const result = await repairRunRecords();
+ hooks.afterRecordRead = null;
+ expect(reads).toBeGreaterThan(1);
+ expect(result.repaired).toEqual([]);
+ expect(result.skipped).toBe(1);
+ expect(readRecord('r1')).toMatchObject({ success: true, duration: 1 });
+ expect(readRecord('r1').reconciledFromLedger).toBeUndefined();
+ });
+
+ it('does not repair a verdict mismatch — the record verdict stands', async () => {
+ writeRecord('r1', { endTime: LATER, success: false });
+ await spawn('r1');
+ await finalize('r1', true);
+
+ const result = await repairRunRecords();
+ expect(result.repaired).toEqual([]);
+ expect(result.findings[0].finding).toBe('verdict-mismatch');
+ expect(readRecord('r1').success).toBe(false);
+ });
+
+ it('does not invent a ledger event for a close the ledger missed', async () => {
+ writeRecord('r1', { endTime: LATER, success: true });
+ await spawn('r1');
+
+ const result = await repairRunRecords();
+ expect(result.findings[0].finding).toBe('ledger-open');
+ expect(result.repaired).toEqual([]);
+ expect(await readRunEvents({ runId: 'r1', kind: 'run.finalized' })).toEqual([]);
+ });
+
+ it('closes an orphaned run as a failure even with no verdict event', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await appendRunEvent({ kind: 'run.orphan-recovered', runId: 'r1', agentId: 'a1', at: LATER, data: { pid: 4242 } });
+
+ const result = await repairRunRecords();
+ expect(result.repaired[0]).toMatchObject({ runId: 'r1', from: 'orphaned', success: false });
+ const record = readRecord('r1');
+ expect(record.success).toBe(false);
+ expect(record.error).toContain('reconciliation');
+ });
+
+ it('runs one pass at a time', async () => {
+ writeRecord('r1', { endTime: null, success: null });
+ await spawn('r1');
+ await finalize('r1', false);
+
+ const [a, b] = await Promise.all([repairRunRecords(), repairRunRecords()]);
+ // The second call joins the first rather than planning the same repair from
+ // records the first has not written yet.
+ expect(b).toBe(a);
+ expect(a.repaired).toHaveLength(1);
+ });
+});