Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): bound the local trace store (#1292)

Chad Hietala1e35a26b2969
diff --git a/.changeset/dull-pugs-smile.md b/.changeset/dull-pugs-smile.md
new file mode 100644
index 000000000..7efcb5743
--- /dev/null
+++ b/.changeset/dull-pugs-smile.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Bound the zero-config local trace store so `.eve/traces` no longer grows without limit. `eve dev` now sweeps it when a session finishes and at startup, keeping open sessions, the twenty newest traces, and anything from the last seven days before evicting oldest-first above 512 MB. Tune it with `EVE_TRACES_MAX_AGE_MS`, `EVE_TRACES_MAX_TOTAL_BYTES`, and `EVE_TRACES_RETAIN_COUNT`, or set `EVE_TRACES=off` to turn local tracing off entirely.
diff --git a/docs/guides/instrumentation.md b/docs/guides/instrumentation.md
index 0f2aef372..b6ab7e1ab 100644
--- a/docs/guides/instrumentation.md
+++ b/docs/guides/instrumentation.md
@@ -11,12 +11,38 @@ If you intend to export telemetry, review the exporter destination, data categor
When no authored `instrumentation.ts` exists, `eve dev` records agent, AI SDK, and user-created OpenTelemetry spans under `.eve/traces/v1`. Each session has one trace, rooted independently from Workflow telemetry, with turns, model steps, and tool actions represented explicitly. Spans created by application code while a model or tool is executing inherit that active agent context.
-The directory is an immutable OTLP/JSON spool and remains available after `eve dev` exits. Inspection tools may build a query index from these segments, but the index is derived and can be rebuilt without changing the captured trace data.
+The directory is an immutable OTLP/JSON spool and remains available after `eve dev` exits, subject to the [retention policy](#local-trace-retention) below. Inspection tools may build a query index from these segments, but the index is derived and can be rebuilt without changing the captured trace data.
Use `eve trace ls` to list captured traces and `eve trace <trace>` to inspect a session's span tree.
The local writer is an internal development default, not a second provider layered over authored instrumentation. When `instrumentation.ts` exists, its setup retains control and the zero-config writer is not installed.
+### Local trace retention
+
+The store is bounded, so it cannot grow without limit on a development machine. eve sweeps it when a session finishes and once when the dev server starts. A trace is kept when **any** of these holds:
+
+- its session is open in the running dev worker;
+- it received a span in the last five minutes;
+- it is one of the newest `EVE_TRACES_RETAIN_COUNT` traces;
+- it last received a span within `EVE_TRACES_MAX_AGE_MS`.
+
+Whatever survives is then evicted oldest-first while the store exceeds `EVE_TRACES_MAX_TOTAL_BYTES`. The keep-newest floor always wins: eve will exceed the size budget rather than drop below it, because a trace records something that happened and cannot be regenerated.
+
+Open sessions are tracked per dev worker, so a session waiting across a restart, or a trace a draining worker is still writing, is not covered by the first rule. The five-minute write-recency rule is what protects those, and it applies even when you set `EVE_TRACES_MAX_AGE_MS=0`.
+
+| Variable | Default | Effect |
+| ---------------------------- | -------------------- | --------------------------------------------- |
+| `EVE_TRACES` | on | `off` stops writing traces and stops sweeping |
+| `EVE_TRACES_MAX_AGE_MS` | `604800000` (7d) | Age after which a trace may be evicted |
+| `EVE_TRACES_MAX_TOTAL_BYTES` | `536870912` (512 MB) | Size budget for the whole store |
+| `EVE_TRACES_RETAIN_COUNT` | `20` | Newest traces kept regardless of age or size |
+
+Set these in `.env.local`, which `eve dev` loads automatically. Each bound accepts `off` to disable it individually — note that `EVE_TRACES_RETAIN_COUNT=off` removes the keep-newest guarantee rather than retaining everything.
+
+`EVE_TRACES=off` disables writing _and_ sweeping, so an existing store is left exactly as it is; eve will not reclaim it later.
+
+A sweep that deletes something records one line naming the count, the bytes reclaimed, and which bound triggered it. Read it with [`eve logs`](../reference/cli#eve-logs).
+
## Three observability surfaces
eve observes an agent through three distinct surfaces. They do not all live in this file, and they write to different places:
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index ef5ad57d7..56bd176f6 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -195,6 +195,8 @@ Local dev records the last ready URL per resolved app root in `.eve/dev-server-s
Local dev keeps immutable runtime source snapshots under `.eve/dev-runtime/snapshots/` so in-flight turns hold a consistent code revision while new turns pick up rebuilds. The terminal REPL keeps its logical session across successful rebuilds, so the next turn continues the conversation on the latest generation; `/new` terminally retires that session before clearing the transcript, and the next prompt starts a fresh session with a new session-scoped sandbox on first sandbox use. After a generation is superseded, `eve dev` retains it for at least 30 minutes and also retains the five most recently superseded generations, regardless of the configured Workflow World. The active generation is never pruned. Old runtime snapshots and local sandbox templates are pruned in the background. For manual cleanup, stop `eve dev` before deleting `.eve/dev-runtime/snapshots/` or `.eve/sandbox-cache/local/templates/`. A turn that remains unfinished beyond the automatic retention window can no longer resume after its generation is pruned.
+When no authored `agent/instrumentation.ts` exists, local dev also records traces under `.eve/traces/`, and bounds that store by age, size, and a keep-newest floor. Configure it with `EVE_TRACES*` in `.env.local`; see [local trace retention](../guides/instrumentation#local-trace-retention) for the rules and defaults.
+
## `eve logs`
```bash
diff --git a/packages/eve/src/harness/agent-trace-span-processor.test.ts b/packages/eve/src/harness/agent-trace-span-processor.test.ts
index ec830ab6e..3cbac6c22 100644
--- a/packages/eve/src/harness/agent-trace-span-processor.test.ts
+++ b/packages/eve/src/harness/agent-trace-span-processor.test.ts
@@ -30,6 +30,24 @@ describe("AgentTraceSpanProcessor", () => {
expect(child.onEnd).toHaveBeenCalledTimes(2);
});
+ it("reports open sessions so retention never evicts a live trace", () => {
+ const processor = new AgentTraceSpanProcessor([]);
+ expect([...processor.activeTraceIds()]).toEqual([]);
+
+ processor.onStart(span("trace-1", { "agent.session.id": "session-1" }), {});
+ processor.onStart(span("trace-2", { "agent.session.id": "session-2" }), {});
+ expect([...processor.activeTraceIds()].sort()).toEqual(["trace-1", "trace-2"]);
+
+ expect(processor.releaseSession("session-1")).toBe(true);
+ expect([...processor.activeTraceIds()]).toEqual(["trace-2"]);
+ });
+
+ it("reports no release for a session it never owned", () => {
+ const processor = new AgentTraceSpanProcessor([]);
+
+ expect(processor.releaseSession("session-unknown")).toBe(false);
+ });
+
it("excludes Workflow instrumentation from an agent trace", () => {
const child = {
forceFlush: vi.fn(async () => {}),
diff --git a/packages/eve/src/harness/agent-trace-span-processor.ts b/packages/eve/src/harness/agent-trace-span-processor.ts
index dd88a0892..39ea26ff3 100644
--- a/packages/eve/src/harness/agent-trace-span-processor.ts
+++ b/packages/eve/src/harness/agent-trace-span-processor.ts
@@ -43,11 +43,18 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
for (const child of this.#children) child.onEnd(span);
}
- releaseSession(sessionId: string): void {
+ /** Trace ids whose session is still open, so retention never evicts them. */
+ activeTraceIds(): ReadonlySet<string> {
+ return this.#ownedTraceIds;
+ }
+
+ /** Forgets one session's trace, reporting whether it owned one. */
+ releaseSession(sessionId: string): boolean {
const traceId = this.#sessionTraceIds.get(sessionId);
- if (traceId === undefined) return;
+ if (traceId === undefined) return false;
this.#ownedTraceIds.delete(traceId);
this.#sessionTraceIds.delete(sessionId);
+ return true;
}
async shutdown(): Promise<void> {
diff --git a/packages/eve/src/harness/local-instrumentation-runtime.ts b/packages/eve/src/harness/local-instrumentation-runtime.ts
index 4186ff10a..63d889e26 100644
--- a/packages/eve/src/harness/local-instrumentation-runtime.ts
+++ b/packages/eve/src/harness/local-instrumentation-runtime.ts
@@ -13,6 +13,10 @@ import {
registerInstrumentationRuntime,
type InstrumentationRuntime,
} from "#harness/instrumentation-runtime.js";
+import {
+ requestLocalTraceStorePrune,
+ resolveLocalTraceRetentionSettings,
+} from "#harness/local-trace-retention.js";
import { LocalTraceSpanProcessor } from "#harness/local-trace-span-processor.js";
/** Installs the zero-config local OTel runtime once in an `eve dev` worker. */
@@ -24,8 +28,12 @@ export function installLocalInstrumentationRuntime(input: {
const existing = getInstrumentationRuntime();
if (existing !== undefined) return existing;
- const persistence = new LocalTraceSpanProcessor(input.appRoot);
- const processor = new AgentTraceSpanProcessor([persistence]);
+ const retention = resolveLocalTraceRetentionSettings();
+ // `EVE_TRACES=off` removes the writer but keeps the runtime: agent context
+ // still has to propagate so AI SDK and user spans nest correctly.
+ const processor = new AgentTraceSpanProcessor(
+ retention.enabled ? [new LocalTraceSpanProcessor(input.appRoot)] : [],
+ );
registerOTel({
autoDetectResources: false,
instrumentations: [],
@@ -51,13 +59,33 @@ export function installLocalInstrumentationRuntime(input: {
"session.failed": releaseSessionTrace,
},
};
+ // Startup sweep: a store left oversized by a killed dev server is bounded
+ // before this worker adds to it.
+ requestPrune();
+
return registerInstrumentationRuntime({
forceFlush: () => processor.forceFlush(),
hooks: createInstrumentationHooks([agentOtel.hook, releaseTrace]),
runInContext: agentOtel.runInContext,
});
- function releaseSessionTrace(event: { readonly sessionId: string }): void {
- processor.releaseSession(event.sessionId);
+ async function releaseSessionTrace(event: { readonly sessionId: string }): Promise<void> {
+ // Settle pending segment writes before dropping liveness: a sweep already
+ // running reads the same live set, so releasing first would expose the
+ // trace to eviction while it is still being written.
+ await processor.forceFlush();
+ if (!processor.releaseSession(event.sessionId)) return;
+ requestPrune();
+ }
+
+ function requestPrune(): void {
+ if (!retention.enabled) return;
+ requestLocalTraceStorePrune({
+ activeTraceIds: processor.activeTraceIds(),
+ appRoot: input.appRoot,
+ maxAgeMs: retention.maxAgeMs,
+ maxTotalBytes: retention.maxTotalBytes,
+ retainCount: retention.retainCount,
+ });
}
}
diff --git a/packages/eve/src/harness/local-trace-retention.integration.test.ts b/packages/eve/src/harness/local-trace-retention.integration.test.ts
new file mode 100644
index 000000000..7efc963e5
--- /dev/null
+++ b/packages/eve/src/harness/local-trace-retention.integration.test.ts
@@ -0,0 +1,253 @@
+import { mkdir, readdir, stat, utimes, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+import { describe, expect, it } from "vitest";
+
+import { pruneLocalTraceStore } from "#harness/local-trace-retention.js";
+import {
+ resolveLocalTraceSchemaDirectory,
+ resolveLocalTraceSegmentsDirectory,
+} from "#harness/local-trace-span-processor.js";
+import { useTemporaryDirectories } from "#internal/testing/use-temporary-app-roots.js";
+
+const createScratchDirectory = useTemporaryDirectories();
+
+const NOW = 1_700_000_000_000;
+const DAY_MS = 24 * 60 * 60 * 1_000;
+const HOUR_MS = 60 * 60 * 1_000;
+
+/**
+ * Writes one trace whose segments directory carries `modifiedAtMs`, which is
+ * what the policy reads as "when this trace last received a span".
+ */
+async function writeTrace(input: {
+ readonly appRoot: string;
+ readonly modifiedAtMs: number;
+ readonly segmentBytes?: number;
+ readonly traceId: string;
+}): Promise<void> {
+ const segments = resolveLocalTraceSegmentsDirectory(input.appRoot, input.traceId);
+ await mkdir(segments, { recursive: true });
+ await writeFile(
+ join(segments, "aaaaaaaaaaaaaaaa.otlp.json"),
+ "x".repeat(input.segmentBytes ?? 8),
+ );
+ const modifiedAt = new Date(input.modifiedAtMs);
+ await utimes(segments, modifiedAt, modifiedAt);
+}
+
+async function listTraceIds(appRoot: string): Promise<string[]> {
+ return (await readdir(resolveLocalTraceSchemaDirectory(appRoot))).sort();
+}
+
+describe("pruneLocalTraceStore", () => {
+ it("treats a missing store as a no-op", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-missing-");
+
+ await expect(
+ pruneLocalTraceStore({ activeTraceIds: new Set(), appRoot, now: NOW }),
+ ).resolves.toMatchObject({ reclaimedBytes: 0, removedTraces: 0 });
+ });
+
+ it("evicts traces past the age bound", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-age-");
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 30 * DAY_MS, traceId: "old" });
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 1 * DAY_MS, traceId: "recent" });
+
+ const result = await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: 7 * DAY_MS,
+ now: NOW,
+ retainCount: 1,
+ });
+
+ expect(result.removedTraces).toBe(1);
+ expect(result.reasons).toContain("maxAgeMs");
+ await expect(listTraceIds(appRoot)).resolves.toEqual(["recent"]);
+ });
+
+ it("keeps the newest traces even when every one is past the age bound", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-floor-");
+ for (const index of [0, 1, 2, 3]) {
+ await writeTrace({
+ appRoot,
+ modifiedAtMs: NOW - (30 + index) * DAY_MS,
+ traceId: `trace-${index}`,
+ });
+ }
+
+ await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: 7 * DAY_MS,
+ now: NOW,
+ retainCount: 2,
+ });
+
+ await expect(listTraceIds(appRoot)).resolves.toEqual(["trace-0", "trace-1"]);
+ });
+
+ it("evicts oldest-first under the size budget without breaching the floor", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-size-");
+ for (const index of [0, 1, 2, 3]) {
+ await writeTrace({
+ appRoot,
+ modifiedAtMs: NOW - HOUR_MS - index * 1_000,
+ segmentBytes: 1_000,
+ traceId: `trace-${index}`,
+ });
+ }
+
+ const result = await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: false,
+ maxTotalBytes: 1_500,
+ now: NOW,
+ retainCount: 2,
+ });
+
+ expect(result.reasons).toContain("maxTotalBytes");
+ // The budget wants one trace; the floor guarantees two.
+ await expect(listTraceIds(appRoot)).resolves.toEqual(["trace-0", "trace-1"]);
+ });
+
+ it("never evicts a trace whose session is still open", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-active-");
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 90 * DAY_MS, traceId: "live" });
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 91 * DAY_MS, traceId: "finished" });
+
+ await pruneLocalTraceStore({
+ activeTraceIds: new Set(["live"]),
+ appRoot,
+ maxAgeMs: 0,
+ maxTotalBytes: 0,
+ now: NOW,
+ retainCount: 0,
+ });
+
+ await expect(listTraceIds(appRoot)).resolves.toEqual(["live"]);
+ });
+
+ it("reaps temp files abandoned by a killed writer", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-tmp-");
+ await writeTrace({ appRoot, modifiedAtMs: NOW, traceId: "current" });
+ const segments = resolveLocalTraceSegmentsDirectory(appRoot, "current");
+ const abandoned = join(segments, "bbbbbbbbbbbbbbbb.otlp.json.tmp-123-abc");
+ await writeFile(abandoned, "orphan");
+ const staleAt = new Date(NOW - 60 * 60 * 1_000);
+ await utimes(abandoned, staleAt, staleAt);
+
+ await pruneLocalTraceStore({ activeTraceIds: new Set(), appRoot, now: NOW });
+
+ await expect(readdir(segments)).resolves.toEqual(["aaaaaaaaaaaaaaaa.otlp.json"]);
+ });
+
+ it("leaves a temp file alone while its atomic write is still in flight", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-tmp-live-");
+ await writeTrace({ appRoot, modifiedAtMs: NOW, traceId: "current" });
+ const segments = resolveLocalTraceSegmentsDirectory(appRoot, "current");
+ const inFlight = join(segments, "cccccccccccccccc.otlp.json.tmp-123-abc");
+ await writeFile(inFlight, "half-written");
+ const justNow = new Date(NOW);
+ await utimes(inFlight, justNow, justNow);
+
+ await pruneLocalTraceStore({ activeTraceIds: new Set(["current"]), appRoot, now: NOW });
+
+ await expect(stat(inFlight)).resolves.toBeDefined();
+ });
+
+ it("bounds a trace directory that never grew a segments directory", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-partial-");
+ const partial = join(resolveLocalTraceSchemaDirectory(appRoot), "partial");
+ await mkdir(partial, { recursive: true });
+ const staleAt = new Date(NOW - 30 * DAY_MS);
+ await utimes(partial, staleAt, staleAt);
+
+ await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: 7 * DAY_MS,
+ now: NOW,
+ retainCount: 0,
+ });
+
+ await expect(stat(partial)).rejects.toThrow();
+ });
+
+ it("keeps sweeping when stray files sit where directories are expected", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-stray-");
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 30 * DAY_MS, traceId: "old" });
+ // Finder leaves these behind in any browsed directory, and a sweep that
+ // throws on one would stop bounding the store forever.
+ await writeFile(join(resolveLocalTraceSchemaDirectory(appRoot), ".DS_Store"), "junk");
+ const occupied = join(resolveLocalTraceSchemaDirectory(appRoot), "occupied");
+ await mkdir(occupied, { recursive: true });
+ const strayPath = join(occupied, "segments");
+ await writeFile(strayPath, "not a directory");
+ const staleAt = new Date(NOW - 30 * DAY_MS);
+ await utimes(strayPath, staleAt, staleAt);
+ await utimes(occupied, staleAt, staleAt);
+
+ const result = await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: 7 * DAY_MS,
+ now: NOW,
+ retainCount: 0,
+ });
+
+ // Both aged-out entries go, and the stray file is simply not a trace.
+ expect(result.removedTraces).toBe(2);
+ await expect(listTraceIds(appRoot)).resolves.toEqual([".DS_Store"]);
+ });
+
+ it("never evicts a trace written inside the quiescence window", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-quiescent-");
+ // Another dev worker could still be writing this one: liveness is tracked
+ // per process, so recency is the only cross-process signal.
+ await writeTrace({ appRoot, modifiedAtMs: NOW - 1_000, traceId: "draining" });
+ await writeTrace({ appRoot, modifiedAtMs: NOW - HOUR_MS, traceId: "settled" });
+
+ await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: 0,
+ maxTotalBytes: 0,
+ now: NOW,
+ retainCount: 0,
+ });
+
+ await expect(listTraceIds(appRoot)).resolves.toEqual(["draining"]);
+ });
+
+ it("counts temp files left behind toward the size budget", async () => {
+ const appRoot = await createScratchDirectory("eve-trace-retention-tmp-budget-");
+ await writeTrace({
+ appRoot,
+ modifiedAtMs: NOW - HOUR_MS,
+ segmentBytes: 10,
+ traceId: "bloated",
+ });
+ const segments = resolveLocalTraceSegmentsDirectory(appRoot, "bloated");
+ // Recent enough to survive reaping, so its bytes must still be counted.
+ await writeFile(join(segments, "dddddddddddddddd.otlp.json.tmp-1-a"), "x".repeat(5_000));
+ // Writing into the directory bumped its mtime; restore the settled age.
+ const settledAt = new Date(NOW - HOUR_MS);
+ await utimes(segments, settledAt, settledAt);
+
+ const result = await pruneLocalTraceStore({
+ activeTraceIds: new Set(),
+ appRoot,
+ maxAgeMs: false,
+ maxTotalBytes: 1_000,
+ now: NOW,
+ retainCount: 0,
+ });
+
+ expect(result.reasons).toEqual(["maxTotalBytes"]);
+ expect(result.reclaimedBytes).toBeGreaterThan(5_000);
+ await expect(listTraceIds(appRoot)).resolves.toEqual([]);
+ });
+});
diff --git a/packages/eve/src/harness/local-trace-retention.test.ts b/packages/eve/src/harness/local-trace-retention.test.ts
new file mode 100644
index 000000000..691befa26
--- /dev/null
+++ b/packages/eve/src/harness/local-trace-retention.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import { resolveLocalTraceRetentionSettings } from "#harness/local-trace-retention.js";
+
+const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1_000;
+const FIVE_HUNDRED_TWELVE_MIB = 512 * 1024 * 1024;
+
+describe("resolveLocalTraceRetentionSettings", () => {
+ it("bounds the store by age, size, and a keep-newest floor by default", () => {
+ expect(resolveLocalTraceRetentionSettings({})).toEqual({
+ enabled: true,
+ maxAgeMs: SEVEN_DAYS_MS,
+ maxTotalBytes: FIVE_HUNDRED_TWELVE_MIB,
+ retainCount: 20,
+ });
+ });
+
+ it("reads each bound from the environment", () => {
+ expect(
+ resolveLocalTraceRetentionSettings({
+ EVE_TRACES_MAX_AGE_MS: "1000",
+ EVE_TRACES_MAX_TOTAL_BYTES: "2048",
+ EVE_TRACES_RETAIN_COUNT: "3",
+ }),
+ ).toEqual({ enabled: true, maxAgeMs: 1000, maxTotalBytes: 2048, retainCount: 3 });
+ });
+
+ it("disables one bound at a time with `off`", () => {
+ const settings = resolveLocalTraceRetentionSettings({
+ EVE_TRACES_MAX_AGE_MS: "off",
+ EVE_TRACES_MAX_TOTAL_BYTES: "OFF",
+ EVE_TRACES_RETAIN_COUNT: "false",
+ });
+
+ expect(settings).toEqual({
+ enabled: true,
+ maxAgeMs: false,
+ maxTotalBytes: false,
+ retainCount: false,
+ });
+ });
+
+ it("treats EVE_TRACES=off as disabling the whole subsystem", () => {
+ for (const value of ["off", "OFF", " false ", "0"]) {
+ expect(resolveLocalTraceRetentionSettings({ EVE_TRACES: value }).enabled).toBe(false);
+ }
+ });
+
+ it("keeps tracing enabled for any other EVE_TRACES value", () => {
+ expect(resolveLocalTraceRetentionSettings({ EVE_TRACES: "on" }).enabled).toBe(true);
+ });
+
+ it("falls back to the default rather than throwing on an unparseable value", () => {
+ const settings = resolveLocalTraceRetentionSettings({
+ EVE_TRACES_MAX_AGE_MS: "sometimes",
+ EVE_TRACES_RETAIN_COUNT: "-4",
+ });
+
+ expect(settings.maxAgeMs).toBe(SEVEN_DAYS_MS);
+ expect(settings.retainCount).toBe(20);
+ });
+});
diff --git a/packages/eve/src/harness/local-trace-retention.ts b/packages/eve/src/harness/local-trace-retention.ts
new file mode 100644
index 000000000..21ccbe6f3
--- /dev/null
+++ b/packages/eve/src/harness/local-trace-retention.ts
@@ -0,0 +1,343 @@
+import type { Dirent } from "node:fs";
+import { readdir, rm, stat } from "node:fs/promises";
+import { join } from "node:path";
+
+import {
+ resolveLocalTraceSchemaDirectory,
+ resolveLocalTraceSegmentsDirectory,
+} from "#harness/local-trace-span-processor.js";
+import { createLogger, formatError } from "#internal/logging.js";
+
+const log = createLogger("harness.local-trace-retention");
+
+/**
+ * How long a trace must sit untouched before a sweep may act on it.
+ *
+ * Liveness is tracked per dev worker, so a draining worker's writes and a
+ * waiting session restored into a replacement worker are both invisible to the
+ * open-session set. Recent writes are the one liveness signal that crosses
+ * processes, so nothing written this recently is evicted, and an
+ * `atomicWriteFile` temp file is only reaped once this stale — a real write
+ * renames within milliseconds.
+ */
+const LOCAL_TRACE_QUIESCENCE_MS = 5 * 60 * 1_000;
+
+const LOCAL_TRACE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
+const LOCAL_TRACE_MAX_TOTAL_BYTES = 512 * 1024 * 1024;
+const LOCAL_TRACE_RETAIN_COUNT = 20;
+
+/**
+ * A bound that may be switched off individually, mirroring the `number | false`
+ * idiom used by authored agent limits.
+ */
+type RetentionBound = number | false;
+
+/** Resolved retention policy for one dev worker. */
+export interface LocalTraceRetentionSettings {
+ readonly enabled: boolean;
+ readonly maxAgeMs: RetentionBound;
+ readonly maxTotalBytes: RetentionBound;
+ readonly retainCount: RetentionBound;
+}
+
+/** Which bound removed traces, reported for a single diagnostics line. */
+export type LocalTracePruneReason = "maxAgeMs" | "maxTotalBytes";
+
+/** Outcome of one sweep. `removedTraces` counts trace directories, not spans. */
+export interface LocalTracePruneResult {
+ readonly reasons: readonly LocalTracePruneReason[];
+ readonly reclaimedBytes: number;
+ readonly removedTraces: number;
+ readonly retainedTraces: number;
+}
+
+export interface PruneLocalTraceStoreInput {
+ readonly appRoot: string;
+ /** Traces whose session is open in this worker; never evicted. */
+ readonly activeTraceIds: ReadonlySet<string>;
+ readonly maxAgeMs?: RetentionBound;
+ readonly maxTotalBytes?: RetentionBound;
+ readonly now?: number;
+ readonly retainCount?: RetentionBound;
+}
+
+interface StoredTrace {
+ readonly byteSize: number;
+ readonly modifiedAtMs: number;
+ readonly path: string;
+ readonly traceId: string;
+}
+
+/**
+ * Reads the retention policy from the environment.
+ *
+ * `eve dev` loads `.env.local` into `process.env` before the tracing runtime
+ * installs, so these are authored there rather than in `agent.ts`: the store is
+ * a property of one developer's machine, not of the deployed agent.
+ *
+ * Every bound accepts `off` to disable that axis alone. Unparseable values warn
+ * and fall back to the default instead of throwing, because a typo in a dev env
+ * file should not prevent the agent from booting.
+ */
+export function resolveLocalTraceRetentionSettings(
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): LocalTraceRetentionSettings {
+ return {
+ enabled: !isDisabled(env.EVE_TRACES),
+ maxAgeMs: readBound(env, "EVE_TRACES_MAX_AGE_MS", LOCAL_TRACE_MAX_AGE_MS),
+ maxTotalBytes: readBound(env, "EVE_TRACES_MAX_TOTAL_BYTES", LOCAL_TRACE_MAX_TOTAL_BYTES),
+ retainCount: readBound(env, "EVE_TRACES_RETAIN_COUNT", LOCAL_TRACE_RETAIN_COUNT),
+ };
+}
+
+/**
+ * Bounds the local trace store.
+ *
+ * A trace survives while its session is open, while it was written within the
+ * quiescence window, while it is among the newest `retainCount`, and while it
+ * is younger than `maxAgeMs`. Everything else is evicted oldest-first, taking
+ * the age bound first and then whatever the `maxTotalBytes` budget still
+ * demands.
+ *
+ * The count floor outranks both other bounds deliberately: a trace records
+ * something that happened and cannot be regenerated, so returning to a quiet
+ * project should not mean returning to an empty store.
+ */
+export async function pruneLocalTraceStore(
+ input: PruneLocalTraceStoreInput,
+): Promise<LocalTracePruneResult> {
+ const now = input.now ?? Date.now();
+ const maxAgeMs = clampBound(input.maxAgeMs ?? LOCAL_TRACE_MAX_AGE_MS);
+ const maxTotalBytes = clampBound(input.maxTotalBytes ?? LOCAL_TRACE_MAX_TOTAL_BYTES);
+ const retainCount = clampCount(input.retainCount ?? LOCAL_TRACE_RETAIN_COUNT);
+
+ const traces = await readStoredTraces(input.appRoot, now);
+ const newestFirst = [...traces].sort((left, right) => right.modifiedAtMs - left.modifiedAtMs);
+ // `off` disables the bound, and this bound is a floor: disabling it removes
+ // the keep-newest guarantee rather than granting unlimited retention.
+ const floor = new Set(newestFirst.slice(0, retainCount === false ? 0 : retainCount));
+
+ const reasons = new Set<LocalTracePruneReason>();
+ let totalBytes = traces.reduce((sum, trace) => sum + trace.byteSize, 0);
+ let reclaimedBytes = 0;
+ let removedTraces = 0;
+ let retainedTraces = 0;
+
+ for (const trace of newestFirst.toReversed()) {
+ const idle = now - trace.modifiedAtMs;
+ const protectedTrace =
+ input.activeTraceIds.has(trace.traceId) ||
+ floor.has(trace) ||
+ idle <= LOCAL_TRACE_QUIESCENCE_MS;
+ const reason: LocalTracePruneReason | undefined = protectedTrace
+ ? undefined
+ : maxAgeMs !== false && idle > maxAgeMs
+ ? "maxAgeMs"
+ : maxTotalBytes !== false && totalBytes > maxTotalBytes
+ ? "maxTotalBytes"
+ : undefined;
+
+ if (reason === undefined) {
+ retainedTraces += 1;
+ continue;
+ }
+ await rm(trace.path, { force: true, recursive: true });
+ totalBytes -= trace.byteSize;
+ reclaimedBytes += trace.byteSize;
+ removedTraces += 1;
+ reasons.add(reason);
+ }
+
+ return { reasons: [...reasons], reclaimedBytes, removedTraces, retainedTraces };
+}
+
+interface PruneRequestState {
+ input: PruneLocalTraceStoreInput;
+ requested: boolean;
+ running: Promise<void> | undefined;
+}
+
+const pruneRequest: PruneRequestState = {
+ input: { activeTraceIds: new Set(), appRoot: "" },
+ requested: false,
+ running: undefined,
+};
+
+/**
+ * Requests a sweep without blocking the caller.
+ *
+ * One pending request is coalesced rather than dropped, so a session that
+ * finishes while a sweep is already running still gets swept — the same
+ * guarantee `requestDevelopmentGenerationPrune` gives dev runtime generations.
+ * Failures are reported and otherwise swallowed: an unbounded store is
+ * preferable to a broken dev server.
+ */
+export function requestLocalTraceStorePrune(input: PruneLocalTraceStoreInput): void {
+ pruneRequest.input = input;
+ pruneRequest.requested = true;
+ if (pruneRequest.running === undefined) startPruning();
+}
+
+function startPruning(): void {
+ pruneRequest.running = (async () => {
+ while (pruneRequest.requested) {
+ pruneRequest.requested = false;
+ report(await pruneLocalTraceStore(pruneRequest.input));
+ }
+ })()
+ .catch((error: unknown) => {
+ log.warn("local trace retention failed", { error: formatError(error) });
+ })
+ .finally(() => {
+ pruneRequest.running = undefined;
+ if (pruneRequest.requested) startPruning();
+ });
+}
+
+/**
+ * Reports at `info` so it survives the default log threshold: a trace cannot be
+ * regenerated, and there is no trace browser yet, so a silent deletion is
+ * indistinguishable from a span that was never captured.
+ */
+function report(result: LocalTracePruneResult): void {
+ if (result.removedTraces === 0) return;
+ log.info("pruned local traces", {
+ reasons: result.reasons.join(","),
+ reclaimedBytes: result.reclaimedBytes,
+ removedTraces: result.removedTraces,
+ retainedTraces: result.retainedTraces,
+ });
+}
+
+async function readStoredTraces(appRoot: string, now: number): Promise<StoredTrace[]> {
+ const schemaDirectory = resolveLocalTraceSchemaDirectory(appRoot);
+ const entries = await readDirectoryEntries(schemaDirectory);
+ if (entries === undefined) return [];
+
+ const traces = await Promise.all(
+ entries
+ .filter((entry) => entry.isDirectory())
+ .map(async (entry) => {
+ const path = join(schemaDirectory, entry.name);
+ const segments = resolveLocalTraceSegmentsDirectory(appRoot, entry.name);
+ await reapAbandonedTemporaryFiles(segments, now);
+ // Segments are added and never rewritten, so that directory's mtime is
+ // when the trace last received a span. A trace directory without one
+ // falls back to its own mtime so it is still bounded rather than
+ // invisible to the policy.
+ const modifiedAtMs = (await directoryMtime(segments)) ?? (await directoryMtime(path));
+ if (modifiedAtMs === undefined) return undefined;
+ return {
+ // Measured across the whole trace directory, so anything the writer
+ // leaves behind counts against the budget.
+ byteSize: await directorySize(path),
+ modifiedAtMs,
+ path,
+ traceId: entry.name,
+ };
+ }),
+ );
+ return traces.filter((trace): trace is StoredTrace => trace !== undefined);
+}
+
+/**
+ * Removes `atomicWriteFile` temp files left by a killed process. It clears its
+ * own on a failed rename, but a process killed between write and rename leaves
+ * one behind and nothing else would ever reclaim those bytes.
+ */
+async function reapAbandonedTemporaryFiles(segmentsDirectory: string, now: number): Promise<void> {
+ const entries = await readDirectoryEntries(segmentsDirectory);
+ if (entries === undefined) return;
+ for (const entry of entries) {
+ if (!entry.isFile() || !entry.name.includes(".tmp-")) continue;
+ const path = join(segmentsDirectory, entry.name);
+ try {
+ if (now - (await stat(path)).mtimeMs <= LOCAL_TRACE_QUIESCENCE_MS) continue;
+ await rm(path, { force: true });
+ } catch {
+ // Raced with the writer that owns it; the next sweep sees the outcome.
+ }
+ }
+}
+
+async function directoryMtime(path: string): Promise<number | undefined> {
+ try {
+ return (await stat(path)).mtimeMs;
+ } catch {
+ return undefined;
+ }
+}
+
+async function directorySize(path: string): Promise<number> {
+ const entries = await readDirectoryEntries(path);
+ if (entries === undefined) return 0;
+ let total = 0;
+ for (const entry of entries) {
+ const child = join(path, entry.name);
+ if (entry.isDirectory()) {
+ total += await directorySize(child);
+ continue;
+ }
+ try {
+ total += (await stat(child)).size;
+ } catch {
+ // Disappeared mid-sweep; it contributes nothing to the measured size.
+ }
+ }
+ return total;
+}
+
+/**
+ * Reads a directory, reporting "no directory here" for both a missing path and
+ * a path occupied by a file.
+ *
+ * A stray inode where the layout expects a directory must not disable the
+ * sweep: the store would then grow forever, which is the failure this module
+ * exists to prevent. Whatever occupies the path is measured as ordinary bytes
+ * and aged out with the trace that holds it.
+ */
+async function readDirectoryEntries(path: string): Promise<Dirent<string>[] | undefined> {
+ try {
+ return await readdir(path, { withFileTypes: true });
+ } catch (error) {
+ if (
+ error instanceof Error &&
+ "code" in error &&
+ (error.code === "ENOENT" || error.code === "ENOTDIR")
+ ) {
+ return undefined;
+ }
+ throw error;
+ }
+}
+
+function isDisabled(value: string | undefined): boolean {
+ if (value === undefined) return false;
+ const normalized = value.trim().toLowerCase();
+ return normalized === "off" || normalized === "false" || normalized === "0";
+}
+
+function readBound(
+ env: Readonly<Record<string, string | undefined>>,
+ name: string,
+ fallback: number,
+): RetentionBound {
+ const raw = env[name];
+ if (raw === undefined) return fallback;
+ const normalized = raw.trim().toLowerCase();
+ if (normalized === "off" || normalized === "false") return false;
+ const parsed = Number(normalized);
+ if (!Number.isFinite(parsed) || parsed < 0) {
+ log.warn("ignoring invalid local trace retention value", { fallback, name, value: raw });
+ return fallback;
+ }
+ return parsed;
+}
+
+function clampBound(value: RetentionBound): RetentionBound {
+ return value === false ? false : Math.max(0, value);
+}
+
+function clampCount(value: RetentionBound): RetentionBound {
+ return value === false ? false : Math.max(0, Math.trunc(value));
+}
diff --git a/packages/eve/src/harness/local-trace-span-processor.ts b/packages/eve/src/harness/local-trace-span-processor.ts
index bcbf460d7..a992871b4 100644
--- a/packages/eve/src/harness/local-trace-span-processor.ts
+++ b/packages/eve/src/harness/local-trace-span-processor.ts
@@ -13,6 +13,28 @@ interface ReadableSpanLike {
const log = createLogger("harness.local-trace-span-processor");
+const LOCAL_TRACE_SCHEMA_DIRECTORY = "v1";
+const LOCAL_TRACE_SEGMENTS_DIRECTORY = "segments";
+
+function resolveLocalTraceStoreDirectory(appRoot: string): string {
+ return join(appRoot, ".eve", "traces");
+}
+
+/** Resolves the directory holding one trace per subdirectory. */
+export function resolveLocalTraceSchemaDirectory(appRoot: string): string {
+ return join(resolveLocalTraceStoreDirectory(appRoot), LOCAL_TRACE_SCHEMA_DIRECTORY);
+}
+
+/**
+ * Resolves the directory holding one trace's span segments.
+ *
+ * Segments are added, never rewritten, so this directory's mtime is the instant
+ * the trace last received a span.
+ */
+export function resolveLocalTraceSegmentsDirectory(appRoot: string, traceId: string): string {
+ return join(resolveLocalTraceSchemaDirectory(appRoot), traceId, LOCAL_TRACE_SEGMENTS_DIRECTORY);
+}
+
/** Persists spans from agent-owned traces as immutable OTLP/JSON segments. */
export class LocalTraceSpanProcessor implements SpanProcessor {
readonly #appRoot: string;
@@ -38,7 +60,7 @@ export class LocalTraceSpanProcessor implements SpanProcessor {
this.#queue = this.#queue
.then(async () => {
- const directory = join(this.#appRoot, ".eve", "traces", "v1", traceId, "segments");
+ const directory = resolveLocalTraceSegmentsDirectory(this.#appRoot, traceId);
await mkdir(directory, { recursive: true });
await atomicWriteFile(join(directory, `${spanId}.otlp.json`), payload);
})