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
address review (codex): don't drop unknown event kinds on read, and key the orphan reap on the agent life (#4540)
[._.]/ Adam Eivy170afd19af4a
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.jsindex 88b490fc4b..a4513ef9b3 100644--- a/server/lib/agentRunEvents.js+++ b/server/lib/agentRunEvents.js@@ -100,6 +100,19 @@ export const RUN_EVENT_LIMITS = Object.freeze({maxDepth: 3});+/**+ * Read-page bounds, here in the pure module rather than in the ledger service+ * because BOTH the service and the route's Zod schema must agree on them. A+ * route capped below the service's ceiling would 400 a request the service+ * would happily serve; a route capped above it would silently clamp instead.+ * `lib/cosValidation.js` imports these — a lib module must not reach into+ * `services/`, so the constants live on this side of that edge.+ */+export const RUN_EVENT_READ_LIMITS = Object.freeze({+ default: 200,+ max: 1000+});+const isDroppedKey = (key) => DROPPED_KEY_PATTERNS.some((re) => re.test(key));/**@@ -212,6 +225,27 @@ export const agentRunEventSchema = z.object({data: z.record(z.unknown())}).strict();+/**+ * Structural envelope check for the READ path.+ *+ * Identical to `agentRunEventSchema` except `kind` is any bounded string rather+ * than the closed enum. A ledger file can outlive the build that wrote it — a+ * peer install, or this install before a downgrade, may have written kinds this+ * build has never heard of. Validating reads against the closed enum would drop+ * those lines, which both loses the trace and silently renumbers `eventCount`,+ * contradicting the forward-compatibility the projection already provides (it+ * folds unknown kinds as no-ops). Writes stay strict — a typo at a call site is+ * still a bug, and `buildRunEvent` is where it gets caught.+ */+export const storedRunEventSchema = agentRunEventSchema.extend({+ kind: z.string().min(1).max(64)+});++/** Is this parsed line a structurally sound ledger line? Used by the read path. */+export function isStoredRunEvent(value) {+ return storedRunEventSchema.safeParse(value).success;+}+const nullableId = (value) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, 128) : null);/**@@ -220,8 +254,15 @@ const nullableId = (value) => (typeof value === 'string' && value.trim() ? value* `eventId` is content-derived by default: the sha256 of the canonicalized* envelope (kind + ids + timestamp + redacted data), truncated to 32 hex chars.* Two deliveries of the same logical transition therefore collide by design and- * the ledger keeps one. Pass an explicit `eventId` only when a call site has a- * better natural key than its own content.+ * the ledger keeps one.+ *+ * **The timestamp is part of that hash**, so the content-derived id only dedupes+ * a redelivery when the caller passes the SAME `at` — which is the normal case,+ * because the stable lifecycle boundaries read theirs off the run record+ * (`metadata.startTime` / `metadata.endTime`). A caller that lets `at` default+ * to the wall clock is asserting that each occurrence is a distinct fact. When+ * it isn't — a sweep that can re-observe the same dead agent — pass an explicit+ * `eventId` naming the natural key instead.** Throws on an invalid envelope — a malformed event is a bug at the call site,* and the append path (which owns the "never break a run for telemetry" rule)diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.jsindex 7522c2768d..49f6ad7ab4 100644--- a/server/lib/agentRunEvents.test.js+++ b/server/lib/agentRunEvents.test.js@@ -11,6 +11,7 @@ import {projectRunState,projectRunStates,redactRunEventData,+ isStoredRunEvent,runEventKey,scrubHomePath} from './agentRunEvents.js';@@ -46,6 +47,22 @@ describe('buildRunEvent — envelope schema', () => {expect(isValidRunEvent(buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }))).toBe(true);});+ it('admits an UNKNOWN kind on the read path while refusing it on the write path', () => {+ // A ledger file outlives the build that wrote it. Validating reads against+ // the closed enum would drop a newer install's lines, losing the trace AND+ // renumbering eventCount — the projection already folds unknown kinds as+ // no-ops, so the read check only has to be structural.+ const future = { ...buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }), kind: 'run.from-the-future' };+ expect(isStoredRunEvent(future)).toBe(true);+ expect(isValidRunEvent(future)).toBe(false);+ });++ it('still refuses a structurally broken line on the read path', () => {+ expect(isStoredRunEvent({ kind: 'run.spawned' })).toBe(false);+ expect(isStoredRunEvent({ ...buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }), at: 'not-a-date' })).toBe(false);+ expect(isStoredRunEvent({ ...buildRunEvent({ kind: 'run.spawned', runId: 'r1', at: AT }), extra: 1 })).toBe(false);+ });+it('isKnownRunEventKind tracks the exported vocabulary', () => {for (const kind of AGENT_RUN_EVENT_KINDS) expect(isKnownRunEventKind(kind)).toBe(true);expect(isKnownRunEventKind('run.nope')).toBe(false);diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex a7e9cd735c..25af2e6126 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -15,7 +15,7 @@ import { EFFORT_LEVELS, effortLevelsForProvider, buildEffortArgs, splitAntigraviimport { ANTIGRAVITY_COMMAND } from './antigravity.js';import { isValidSlashdoCommand } from './slashdoInvocation.js';import { PR_COMPLETION_VALUES } from './prDisposition.js';-import { AGENT_RUN_EVENT_KINDS } from './agentRunEvents.js';+import { AGENT_RUN_EVENT_KINDS, RUN_EVENT_READ_LIMITS } from './agentRunEvents.js';// =============================================================================// COS TASK SCHEMAS@@ -1643,22 +1643,22 @@ export function sanitizeTaskMetadata(raw) {// Query bounds for the read-only run-event diagnostics under// `/api/agents/activity/run-events`. `z.coerce` because these arrive as query-// strings; the `limit` ceiling mirrors MAX_READ_LIMIT in-// `services/agentRunEventLog.js` so a caller cannot ask the route to load and-// serialize an unbounded slice of the ledger.+// strings; the `limit` ceiling IS the ledger's own `RUN_EVENT_READ_LIMITS.max`+// (imported, not copied — a literal here would drift into 400-ing requests the+// service would happily serve, or clamping ones it would refuse).export const runEventsQuerySchema = z.object({runId: z.string().min(1).max(128).optional(),agentId: z.string().min(1).max(128).optional(),taskId: z.string().min(1).max(128).optional(),kind: z.enum(AGENT_RUN_EVENT_KINDS).optional(),since: z.string().datetime().optional(),- limit: z.coerce.number().int().min(1).max(1000).optional()+ limit: z.coerce.number().int().min(1).max(RUN_EVENT_READ_LIMITS.max).optional()}).strict();export const runEventProjectionsQuerySchema = z.object({runId: z.string().min(1).max(128).optional(),agentId: z.string().min(1).max(128).optional(),- limit: z.coerce.number().int().min(1).max(1000).optional()+ limit: z.coerce.number().int().min(1).max(RUN_EVENT_READ_LIMITS.max).optional()}).strict();// A projection id is either a run id or the `agent:<agentId>` fallback key adiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 61f08339de..8e616b0b6a 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -954,6 +954,13 @@ export async function cleanupOrphanedAgents() {// so it keys off the agent instead of disappearing.await appendRunEvent({kind: 'run.orphan-recovered',+ // Explicit natural key rather than the content-derived default: this+ // sweep runs every 15 minutes and can re-observe the same dead agent+ // if the `completeAgent` write below ever fails to land, and the+ // content hash covers the wall-clock `at`, so a retry would otherwise+ // mint a second "this agent died" fact. An agent dies once per life,+ // and `id + startedAt` names exactly that.+ eventId: `orphan:${agent.id}:${agent.startedAt || 'unknown'}`,runId: agent.metadata?.runId,agentId: agent.id,taskId: agent.taskId,diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex ec31dba2b5..540119d1e2 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -1152,6 +1152,22 @@ describe('orphan retries resume what the dead run left behind', () => {}));});+ // The sweep re-runs every 15 minutes and can re-observe the same dead agent if+ // the completeAgent write never landed. The ledger's default id covers the+ // wall-clock timestamp, so without an explicit natural key a retry would file+ // a second "this agent died" fact for one death.+ it('keys the reap on the agent life, so a repeated sweep dedupes', async () => {+ await cleanupOrphanedAgents();+ await cleanupOrphanedAgents();++ const ids = appendRunEvent.mock.calls+ .filter(([e]) => e.kind === 'run.orphan-recovered')+ .map(([e]) => e.eventId);+ expect(ids).toHaveLength(2);+ expect(new Set(ids).size).toBe(1);+ expect(ids[0]).toContain('agent-dead');+ });+it('hands the dead agent’s worktree metadata from the sweep to the retry handler', async () => {await cleanupOrphanedAgents();diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex 62c5efc583..8ea4cdec04 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -39,9 +39,10 @@ import {} from '../lib/fileUtils.js';import {buildRunEvent,- isValidRunEvent,+ isStoredRunEvent,projectRunStates,- AGENT_RUN_EVENT_KINDS+ AGENT_RUN_EVENT_KINDS,+ RUN_EVENT_READ_LIMITS} from '../lib/agentRunEvents.js';const ACTIVE_PATH = join(PATHS.cos, 'run-events.jsonl');@@ -53,9 +54,11 @@ const ARCHIVE_PATH = join(PATHS.cos, 'run-events.1.jsonl');*/export const MAX_ACTIVE_EVENTS = 5000;-/** Default page size for the read API, and the ceiling a caller can request. */-export const DEFAULT_READ_LIMIT = 200;-export const MAX_READ_LIMIT = 1000;+// 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).+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@@ -155,9 +158,11 @@ export async function readRunEvents({ runId, agentId, taskId, kind, since, limitreadJSONLFile(ARCHIVE_PATH),readJSONLFile(ACTIVE_PATH)]);- // A line that fails validation is a corrupt/truncated write, not data —- // dropping it keeps one bad line from poisoning the whole projection.- let events = [...archive, ...active].filter(isValidRunEvent);+ // 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);if (runId) events = events.filter((e) => e.runId === runId);if (agentId) events = events.filter((e) => e.agentId === agentId);diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex b5cff1c54b..b1eff4360d 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -199,6 +199,21 @@ describe('readRunEvents', () => {expect((await readRunEvents()).map((e) => e.eventId)).toEqual(all.map((e) => e.eventId));});+ it('keeps a line whose KIND this build does not know', async () => {+ // A newer install's ledger (or this one's, before a downgrade) must still+ // read here — dropping unknown kinds would lose the trace and renumber+ // eventCount, which the projection's unknown-kind tolerance already avoids.+ const known = await readRunEvents({ runId: 'r1' });+ const future = { ...known[0], eventId: 'future-1', kind: 'run.from-the-future', at: '2026-08-18T10:20:00.000Z' };+ writeFileSync(ACTIVE, `${readFileSync(ACTIVE, 'utf8')}${JSON.stringify(future)}\n`);+ restartServer();++ expect((await readRunEvents()).map((e) => e.kind)).toContain('run.from-the-future');+ const [state] = await getRunProjections({ runId: 'r1' });+ expect(state.eventCount).toBe(3);+ expect(state.status).toBe('completed'); // unknown kind counted, not interpreted+ });+it('drops a corrupt line instead of poisoning the whole read', async () => {writeFileSync(ACTIVE, `${readFileSync(ACTIVE, 'utf8')}{"eventId":"x","kind":"nope"}\nnot json at all\n`);restartServer();diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex 7bc99fad90..8fcd6298e2 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -93,9 +93,14 @@ export async function syncRunnerAgents() {if (!recoveredRunId) {console.warn(`⚠️ Recovered agent ${agent.id} has no run id on record — its run stays open and unbilled`);}- // Record the re-adoption in the lifecycle ledger (#4540). `recoveryCount`- // in the projection is what turns "this run has been running for nine- // hours" into "this run has survived three restarts", and `hasRunId:false`+ // Record the re-adoption in the lifecycle ledger (#4540). No explicit+ // idempotency key here, unlike the orphan sweep: `runnerAgents.set` above+ // has already made this agent locally owned, so the `isAgentOwnedLocally`+ // guard stops this branch re-firing within the process. A SECOND+ // re-adoption therefore means a second server lifetime — a genuinely+ // distinct recovery, which `recoveryCount` is supposed to count — and that+ // count is what turns "this run has been running for nine+ // hours" into "this run has survived three restarts". `hasRunId:false`// is the durable trace of the unbilled-run warning above — today that// warning only exists in a console line nothing retains.await appendRunEvent({