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

fix: tighten the run-event boundaries after review (#4540)

[._.]/ Adam Eivy7804beb6b6ff
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.js
index 5d35a67ef6..5d98fa89ce 100644
--- a/server/lib/agentRunEvents.js
+++ b/server/lib/agentRunEvents.js
@@ -502,6 +502,11 @@ function applyKind(state, event) {
state.endedAt = event.at;
state.exitCode = Number.isFinite(data.exitCode) ? data.exitCode : null;
state.durationMs = Number.isFinite(data.durationMs) ? data.durationMs : null;
+ // The finalize event carries the run's TOTAL output size — the only place
+ // a real byte count exists. `run.output` marks the first byte, not the
+ // last, so without this the projection's `outputBytes` would be null for
+ // every completed run.
+ if (Number.isFinite(data.outputBytes)) state.outputBytes = data.outputBytes;
if (typeof data.errorCategory === 'string') state.errorCategory = data.errorCategory;
break;
}
diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.js
index cac78943de..5aa80b1c08 100644
--- a/server/lib/agentRunEvents.test.js
+++ b/server/lib/agentRunEvents.test.js
@@ -369,6 +369,18 @@ describe('projectRunStates — the second-slice boundaries (#4540)', () => {
expect(state).toMatchObject({ handoffCount: 1, owner: 'none' });
});
+ it('takes the run total output size from the finalize event, not the first-byte marker', () => {
+ // `run.output` marks the FIRST byte; only `run.finalized` knows how much
+ // there was in the end. Reading the size off the marker would leave every
+ // completed run reporting no output at all.
+ const [state] = projectRunStates([
+ buildRunEvent({ kind: 'run.output', runId: 'r1', at: at('10:02'), data: { source: 'cli-stdout', firstChunkChars: 40 } }),
+ buildRunEvent({ kind: 'run.finalized', runId: 'r1', at: at('11:00'), data: { success: true, exitCode: 0, outputBytes: 98304 } })
+ ]);
+ expect(state.outputBytes).toBe(98304);
+ expect(state.lastOutputAt).toBe(at('10:02'));
+ });
+
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' } })
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 86c7b7b091..9378f98fb9 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -668,18 +668,26 @@ export async function finalizeAgent({
// 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') {
+ //
+ // `forge-unreachable` is excluded for the same reason a throw is: the forge
+ // being down is not evidence about the PR. Recording it as `verified: false`
+ // would put "this run shipped no PR" on the record for a run that may well
+ // have shipped one.
+ if (!prCheckThrew && typeof prVerdict.branch === 'string' && prVerdict.category !== FORGE_UNREACHABLE_CATEGORY) {
+ const verified = prVerdict.ok === true;
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'}`,
+ // Keyed on the run AND the verdict. The run part collapses a retried
+ // finalize (the close handler and the orphan sweep can both reach this
+ // path) into one entry; the verdict part keeps a run whose SECOND check
+ // found the PR its first check missed from being silently suppressed by
+ // the miss — that transition is the whole reason to look at the ledger.
+ eventId: `pr-verify:${agentId}:${runId || 'no-run'}:${verified ? 'ok' : prVerdict.category || 'failed'}`,
data: {
- verified: prVerdict.ok === true,
+ verified,
branch: prVerdict.branch ?? null,
category: prVerdict.category ?? null,
noChangesToShip: prVerdict.noChangesToShip === true,
diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.js
index 6d6d53e9f5..a9ecfb5ba5 100644
--- a/server/services/agentFinalization.prVerification.test.js
+++ b/server/services/agentFinalization.prVerification.test.js
@@ -481,3 +481,47 @@ describe('finalizeAgent — records the PR verdict in the lifecycle ledger', ()
expect(prVerified()).toHaveLength(0);
});
});
+
+describe('finalizeAgent — the PR verdict is only recorded when one was reached', () => {
+ 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('writes NOTHING when the forge was unreachable', async () => {
+ // The forge being down is not evidence about the PR. Recording it as
+ // `verified: false` would put "this run shipped no PR" on the record for a
+ // run that may well have shipped one.
+ onBranch('claim/issue-1');
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'error', number: null, url: null, detail: 'gh: connection refused' });
+ await finalize();
+
+ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ completionReason: FORGE_UNREACHABLE_CATEGORY }));
+ expect(prVerified()).toHaveLength(0);
+ });
+
+ it('records a later verdict that CHANGED, rather than suppressing it as a duplicate', async () => {
+ // A retry that finally opens the PR is exactly the transition worth reading
+ // the ledger for; a run-scoped key alone would swallow it.
+ onBranch('claim/issue-1');
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });
+ await finalize();
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7' });
+ await finalize();
+
+ expect(prVerified().map((e) => e.data.verified)).toEqual([false, true]);
+ expect(new Set(prVerified().map((e) => e.eventId)).size).toBe(2);
+ });
+});
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index aacbea26d5..6f2ca7967d 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -931,15 +931,17 @@ export async function spawnViaRunner(agentId, task, opts) {
return null;
}
- // Store PID in persisted state for zombie detection
- await 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.
+ // has no recorded answer at all.
+ //
+ // Recorded the instant the runner accepts, BEFORE the pid persist below: the
+ // handoff has already happened by then, and a failed `updateAgent` would
+ // otherwise leave a live runner-owned process with no record of who owns it —
+ // precisely the orphan this ledger exists to explain. 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,
@@ -949,6 +951,9 @@ export async function spawnViaRunner(agentId, task, opts) {
data: { to: 'cos-runner', accepted: true, pid: result.pid ?? null, providerId: provider.id, laneName: laneName ?? null },
});
+ // Store PID in persisted state for zombie detection
+ await updateAgent(agentId, { pid: result.pid });
+
emitLog('info', `Agent ${agentId} spawned via runner (PID: ${result.pid})`, { agentId, pid: result.pid });
return agentId;
}
diff --git a/server/services/agentManagement.js b/server/services/agentManagement.js
index 47557337e0..6a0fa6803e 100644
--- a/server/services/agentManagement.js
+++ b/server/services/agentManagement.js
@@ -393,16 +393,21 @@ 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 },
- });
+ // A paused run was released back to the queue (#4540). Only the modes that
+ // actually CONTINUE the work qualify: 'already-active' and 'superseded' retire
+ // the paused record without queueing anything, so recording them as a resume
+ // would show a run going back to `running` that nothing is running. `mode` is
+ // the part the mutable record still loses — 'requeued' and 'new-task' both
+ // read as a completed paused agent afterwards, and only one left a fresh task.
+ if (mode === 'requeued' || mode === 'new-task') {
+ 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,
diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.js
index ea75ebfef9..58349e7f83 100644
--- a/server/services/agentManagement.test.js
+++ b/server/services/agentManagement.test.js
@@ -871,6 +871,22 @@ describe('resumeAgent — requeues the paused agent\'s own task', () => {
expect(markAgentComplete).toHaveBeenCalledWith('agent-paused-1', expect.objectContaining({ resumed: true }));
});
+ // The lifecycle ledger (#4540) records a RESUME, not a retirement. The two
+ // non-continuing modes retire the paused record without queueing anything, so
+ // recording them would show a run going back to `running` that nothing runs.
+ it('records run.resumed only for the modes that actually continued the work', async () => {
+ appendRunEvent.mockClear();
+ await resumeAgent('agent-paused-1');
+ expect(appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.resumed')).toEqual([
+ expect.objectContaining({ agentId: 'agent-paused-1', data: expect.objectContaining({ mode: 'requeued' }) })
+ ]);
+
+ appendRunEvent.mockClear();
+ getTaskById.mockResolvedValue({ ...PAUSED_TASK, status: 'in_progress', metadata: { context: 'original context' } });
+ await resumeAgent('agent-paused-1');
+ expect(appendRunEvent.mock.calls.map(([e]) => e).filter((e) => e.kind === 'run.resumed')).toHaveLength(0);
+ });
+
// A user asking to resume is an explicit dispatch, and reviveBlockedTask resets the
// spawn/orphan budgets — so a task that fell into a LATER failure block restarts in
// place rather than being duplicated onto a fresh task.
diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.js
index 5f65e86a8b..7470830954 100644
--- a/server/services/agentRunEventLog.js
+++ b/server/services/agentRunEventLog.js
@@ -96,9 +96,12 @@ const PRUNE_INTERVAL_MS = 60 * 60 * 1000;
export const DEFAULT_READ_LIMIT = RUN_EVENT_READ_LIMITS.default;
export const MAX_READ_LIMIT = RUN_EVENT_READ_LIMITS.max;
-// Lazily hydrated on first append/read. `null` (not an empty Set) is the
-// "never loaded" sentinel, so a genuinely empty ledger caches as empty instead
-// of re-reading both files on every single append.
+// Lazily hydrated on first append/read: Maps of eventId → the event's `at`.
+// `null` (not an empty Map) is the "never loaded" sentinel, so a genuinely
+// empty ledger caches as empty instead of re-reading both files on every single
+// append. The timestamp is carried so the duplicate check can apply the SAME age
+// cutoff the read path applies — otherwise, in the window between prunes, a
+// redelivery could be rejected as a duplicate of an event no reader can see.
let activeIds = null;
let archiveIds = null;
let activeCount = 0;
@@ -109,14 +112,35 @@ let lastPrunedAt = null;
// Serializes appends; also the handle callers await.
let appendQueue = Promise.resolve();
+/** eventId → `at`, for the duplicate check. Lines with no id are unindexable. */
+function indexById(events) {
+ return new Map(events.filter((e) => e?.eventId).map((e) => [e.eventId, e.at ?? null]));
+}
+
+/**
+ * Have we already stored this event, in a copy a reader can still see?
+ *
+ * An id whose only copy has aged past the cutoff does NOT count: the read path
+ * filters that event out, so treating a redelivery as a duplicate would leave
+ * the ledger with an event nothing can read and no way to re-observe it. Same
+ * reasoning as rotation — a duplicate we can no longer see is no longer a
+ * duplicate — applied continuously rather than only at the moment of a prune.
+ */
+function isStoredDuplicate(eventId, cutoff) {
+ const at = activeIds.has(eventId) ? activeIds.get(eventId)
+ : archiveIds.has(eventId) ? archiveIds.get(eventId)
+ : undefined;
+ return at !== undefined && typeof at === 'string' && at > cutoff;
+}
+
async function hydrate() {
if (activeIds) return;
const [active, archive] = await Promise.all([
readJSONLFile(ACTIVE_PATH),
readJSONLFile(ARCHIVE_PATH)
]);
- activeIds = new Set(active.map((e) => e?.eventId).filter(Boolean));
- archiveIds = new Set(archive.map((e) => e?.eventId).filter(Boolean));
+ activeIds = indexById(active);
+ archiveIds = indexById(archive);
activeCount = active.length;
}
@@ -131,7 +155,7 @@ async function rotateIfFull() {
if (await pathExists(ARCHIVE_PATH)) await unlink(ARCHIVE_PATH);
await rename(ACTIVE_PATH, ARCHIVE_PATH);
archiveIds = activeIds;
- activeIds = new Set();
+ activeIds = new Map();
activeCount = 0;
console.log(`🔁 Rotated CoS run event ledger at ${MAX_ACTIVE_EVENTS} events`);
}
@@ -190,8 +214,8 @@ async function pruneExpired({ now = Date.now(), force = false } = {}) {
}
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));
+ archiveIds = indexById(keptArchive);
+ activeIds = indexById(keptActive);
activeCount = keptActive.length;
console.log(`🧹 Pruned ${dropped} CoS run events older than ${MAX_EVENT_AGE_DAYS} days`);
}
@@ -202,12 +226,12 @@ async function appendNow(input) {
// 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)) {
+ if (isStoredDuplicate(event.eventId, expiryCutoff())) {
return { appended: false, duplicate: true, event };
}
await rotateIfFull();
await appendJSONLine(ACTIVE_PATH, event);
- activeIds.add(event.eventId);
+ activeIds.set(event.eventId, event.at);
activeCount += 1;
return { appended: true, duplicate: false, event };
}
@@ -362,7 +386,7 @@ export async function getRunEventLedgerStats() {
}
/**
- * Drop every cached seen-id set so the next call re-reads from disk.
+ * Drop every cached seen-id map so the next call re-reads from disk.
*
* Exported for tests, which write ledger files directly to simulate a restart —
* the in-process caches are exactly what a real restart discards.
diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.js
index c926afb43c..83c03daea8 100644
--- a/server/services/agentRunEventLog.test.js
+++ b/server/services/agentRunEventLog.test.js
@@ -360,3 +360,28 @@ describe('retention — age bound (#4540)', () => {
expect(countLines(ACTIVE)).toBe(1);
});
});
+
+describe('retention — dedupe and the age bound agree (#4540)', () => {
+ const MINUTE = 60 * 1000;
+ const AGE_MS = MAX_EVENT_AGE_DAYS * 24 * 60 * MINUTE;
+
+ it('re-admits an expired event even when the on-disk prune has not run yet', async () => {
+ // The prune is throttled to once an hour; the read filter is not. Without an
+ // age-aware duplicate check there is a window where a redelivery is rejected
+ // as a duplicate of an event no reader can see — the ledger would hold a
+ // fact it refuses to show and refuses to re-record.
+ //
+ // Pinned INSIDE that window on purpose: the event is 30 minutes short of
+ // expiry when first appended, and the clock then advances 40 minutes — past
+ // the event's age bound, but short of the prune interval that would
+ // otherwise have swept the id away and made this pass for the wrong reason.
+ const event = { kind: 'run.spawned', runId: 'r1', at: new Date(Date.parse(NOW) - AGE_MS + 30 * MINUTE).toISOString() };
+ expect(await appendRunEvent(event)).toMatchObject({ appended: true });
+
+ vi.setSystemTime(new Date(Date.parse(NOW) + 40 * MINUTE));
+ expect(countLines(ACTIVE)).toBe(1); // still on disk — the prune has NOT run
+ expect(await readRunEvents()).toHaveLength(0); // …but no reader can see it
+
+ expect(await appendRunEvent({ ...event })).toMatchObject({ appended: true, duplicate: false });
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 59e7270818..48522458b5 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -559,6 +559,34 @@ export async function spawnTuiAgent({
// read-at-most-once invariant at the helper.
let sentinelIngested = false;
let hasStartedWorking = false;
+ // Guards the once-per-run `run.output` boundary (#4540). Kept separate from
+ // `firstOutputAt` / `hasStartedWorking`: both of those are also set by paths
+ // with no real output behind them, and a run that never spoke is exactly the
+ // run this boundary must not vouch for.
+ let firstOutputRecorded = false;
+ /**
+ * Record the run's first observed output, once. Called from the live PTY
+ * stream and from the exit-tail fallback — a durable runner can deliver a
+ * short-lived agent's entire output as `outputTail` on `tui:exit`, and that
+ * output is no less real for having lost the race with process exit.
+ *
+ * Not awaited: the live caller is on the hot output path, and
+ * `appendRunEvent` is a serialized queue that never rejects — blocking a
+ * terminal repaint on a telemetry write would be the wrong trade. The
+ * explicit key makes the append idempotent however the two callers race.
+ */
+ const recordFirstOutput = (source) => {
+ if (firstOutputRecorded) return;
+ firstOutputRecorded = true;
+ appendRunEvent({
+ kind: 'run.output',
+ runId,
+ agentId,
+ taskId: task.id,
+ eventId: `output:${agentId}:${runId || 'no-run'}:first`,
+ data: { source },
+ });
+ };
let promptSentAt = null;
// When the submit-Enter is first written (NOT when the paste starts). Provider
// signal handling keys on this so a startup banner is not treated as a signal
@@ -1021,22 +1049,8 @@ export async function spawnTuiAgent({
if (isCodexSession && !promptSubmittedAt && stripped && !mcpBoot.active) mcpBoot.observe(stripped);
const now = Date.now();
lastOutputAt = now;
- 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 (firstOutputAt === null) firstOutputAt = lastOutputAt;
+ recordFirstOutput('tui-pty');
if (!hasStartedWorking) {
hasStartedWorking = true;
@@ -1104,6 +1118,7 @@ export async function spawnTuiAgent({
if (!receivedTuiOutput && typeof outputTail === 'string' && outputTail) {
receivedTuiOutput = true;
pushRaw(outputTail.slice(-16 * 1024));
+ recordFirstOutput('tui-exit-tail');
}
// A host restart reaches here as a plain PTY exit (pm2's TreeKill walks
// portos-server's descendants), which the `success` reading below would
@@ -1197,6 +1212,20 @@ export async function spawnTuiAgent({
return null;
}
sessionId = session.sessionId;
+ if (useDurableRunner) {
+ // A durable TUI's PTY lives in the CoS Runner, not this server — the same
+ // ownership transfer `spawnViaRunner` records for CLI agents (#4540).
+ // Without it, the longest-lived runs in the system are the only ones whose
+ // ledger never says who owns their process.
+ await appendRunEvent({
+ kind: 'run.handoff',
+ runId,
+ agentId,
+ taskId: task.id,
+ eventId: `handoff:${agentId}:${runId || 'no-run'}:cos-runner`,
+ data: { to: 'cos-runner', accepted: true, kind: 'tui', providerId: provider.id, sessionId: session.sessionId ?? null },
+ });
+ }
// A durable runner can emit tui:exit before its spawn POST response reaches
// this process. handleExit() then finalizes the run while createAgentTuiSession