A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix(daemon): drop deleted rlm children's kernel state and dedupe artifact paths (#1450)
Sebastian Müllera9a8655037b0
diff --git a/packages/ai/test/stream.test.ts b/packages/ai/test/stream.test.tsindex 7686ac6ede..74bc938c7a 100644--- a/packages/ai/test/stream.test.ts+++ b/packages/ai/test/stream.test.ts@@ -5,7 +5,7 @@ import { Type } from "typebox";import { fileURLToPath } from "url";import { afterAll, beforeAll, describe, expect, it } from "vitest";import { getEnvApiKey } from "../src/env-api-keys.js";-import { getModel } from "../src/models.js";+import { getModel, getModels } from "../src/models.js";import { complete, stream } from "../src/stream.js";import type { Api, Context, ImageContent, Model, StreamOptions, Tool, ToolResultMessage } from "../src/types.js";import { getKimiCodingTestModel } from "./kimi-test-model.js";@@ -727,9 +727,10 @@ describe("Generate E2E Tests", () => {);describe.skipIf(!hasCloudflareAiGatewayCredentials() || !process.env.ANTHROPIC_API_KEY)(- "Cloudflare AI Gateway → Anthropic BYOK (claude-sonnet-4-5 via /anthropic messages)",+ "Cloudflare AI Gateway → Anthropic BYOK (Claude Sonnet 4.6 via /anthropic messages)",() => {- const llm = getModel("cloudflare-ai-gateway", "claude-sonnet-4-5");+ const llm = getModels("cloudflare-ai-gateway").find((model) => model.name === "Claude Sonnet 4.6");+ if (!llm) throw new Error("Cloudflare AI Gateway is missing Claude Sonnet 4.6");const options = { headers: { Authorization: `Bearer ${process.env.ANTHROPIC_API_KEY}` } };const thinkingOptions = {...options,diff --git a/packages/coding-agent/src/core/agent-traces.ts b/packages/coding-agent/src/core/agent-traces.tsindex fb00b8aca8..86479d2039 100644--- a/packages/coding-agent/src/core/agent-traces.ts+++ b/packages/coding-agent/src/core/agent-traces.ts@@ -11,7 +11,7 @@ import {PRIME_INFERENCE_PROVIDER_ID,resolvePrimeAgentTracesBaseUrl,} from "./prime-inference-auth.js";-import type { SessionHeader, SessionManager } from "./session-manager.js";+import { getSessionArtifactsRoot, type SessionHeader, type SessionManager } from "./session-manager.js";import type { SettingsManager } from "./settings-manager.js";const MAX_TRACE_BYTES = 20 * 1024 * 1024;@@ -541,7 +541,7 @@ async function findSessionFilesUnder(root: string, files: Set<string>): Promise<export async function findAgentTraceFiles(sessionDir: string = getSessionsDir()): Promise<string[]> {const files = new Set<string>();- const roots = new Set([resolve(sessionDir), resolve(dirname(sessionDir), "session-artifacts")]);+ const roots = new Set([resolve(sessionDir), resolve(getSessionArtifactsRoot(sessionDir))]);await Promise.all([...roots].map((root) => findSessionFilesUnder(root, files)));return [...files].sort();}diff --git a/packages/coding-agent/src/core/cron-jobs.ts b/packages/coding-agent/src/core/cron-jobs.tsindex 999e68659d..3c26ed275c 100644--- a/packages/coding-agent/src/core/cron-jobs.ts+++ b/packages/coding-agent/src/core/cron-jobs.ts@@ -11,6 +11,7 @@ import {} from "node:fs";import { dirname, join, resolve } from "node:path";import { lockSync } from "proper-lockfile";+import { getSessionArtifactPathForFile } from "./session-manager.js";export type AgentCronJobStatus = "active" | "paused" | "completed" | "cancelled";export type AgentCronScheduleKind = "once" | "cron" | "interval";@@ -914,9 +915,7 @@ export function migrateLegacyCronJobsToSessionArtifacts(const jobsByArtifact = new Map<string, AgentCronJob[]>();for (const job of jobs) {const artifactPath = join(- dirname(dirname(resolve(job.sessionFile))),- "session-artifacts",- job.sessionId,+ getSessionArtifactPathForFile(resolve(job.sessionFile), job.sessionId),SESSION_SCHEDULED_JOBS_FILENAME,);const grouped = jobsByArtifact.get(artifactPath) ?? [];diff --git a/packages/coding-agent/src/core/session-file-actions.ts b/packages/coding-agent/src/core/session-file-actions.tsindex adcec4c012..6002263704 100644--- a/packages/coding-agent/src/core/session-file-actions.ts+++ b/packages/coding-agent/src/core/session-file-actions.ts@@ -1,7 +1,8 @@import { spawnSync } from "node:child_process";import { existsSync } from "node:fs";import { rm, unlink } from "node:fs/promises";-import { basename, dirname, join } from "node:path";+import { basename } from "node:path";+import { getSessionArtifactPathForFile } from "./session-manager.js";export type DeleteSessionFileResult = { ok: true; method: "trash" | "unlink" } | { ok: false; error: string };@@ -15,11 +16,10 @@ export interface DeleteSessionFileOptions {* `<dirname(sessionDir)>/session-artifacts/<id>`.* Only invoked on delete, never on deactivation.*/-async function deleteSessionArtifacts(sessionPath: string): Promise<void> {- const sessionId = basename(sessionPath).replace(/\.jsonl$/, "");- if (!sessionId) return;- const artifactDir = join(dirname(dirname(sessionPath)), "session-artifacts", sessionId);- await rm(artifactDir, { recursive: true, force: true });+export async function deleteSessionArtifacts(sessionPath: string): Promise<void> {+ // A degenerate name (".jsonl") would resolve to the artifacts root itself.+ if (!basename(sessionPath).replace(/\.jsonl$/, "")) return;+ await rm(getSessionArtifactPathForFile(sessionPath), { recursive: true, force: true });}/** Remove the session `.jsonl`, trying the `trash` CLI first, then falling back to unlink. */diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex f9161168e5..edc5aff0f0 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -343,8 +343,19 @@ function createUniqueSessionFileTarget(sessionDir: string): { sessionId: string;throw new Error("Unable to create a unique session file");}-function getSessionArtifactPath(sessionDir: string, sessionId: string): string {- return join(dirname(sessionDir), "session-artifacts", sessionId);+/** Root of the artifact tree next to a sessions dir: `<dirname(sessionDir)>/session-artifacts`. */+export function getSessionArtifactsRoot(sessionDir: string): string {+ return join(dirname(sessionDir), "session-artifacts");+}++/** A session's artifact directory: `<dirname(sessionDir)>/session-artifacts/<sessionId>`. */+export function getSessionArtifactPath(sessionDir: string, sessionId: string): string {+ return join(getSessionArtifactsRoot(sessionDir), sessionId);+}++/** {@link getSessionArtifactPath} from a session file; the id defaults to basename minus `.jsonl`. */+export function getSessionArtifactPathForFile(sessionFile: string, sessionId?: string): string {+ return getSessionArtifactPath(dirname(sessionFile), sessionId ?? basename(sessionFile).replace(/\.jsonl$/, ""));}/** Generate a unique short ID (8 hex chars, collision-checked) */diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 841160ecb0..d7f5c099cd 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -96,9 +96,10 @@ import {type IdleEvictionMinutes,type SessionPassivationSnapshot,} from "../../core/session-action-store.js";-import { deleteSessionFile } from "../../core/session-file-actions.js";+import { deleteSessionArtifacts, deleteSessionFile } from "../../core/session-file-actions.js";import { acquireSessionLease, canonicalSessionPath, type SessionLease } from "../../core/session-lease.js";import {+ getSessionArtifactPathForFile,readSessionInfo,resolveSessionRlmDepth,type SessionInfo,@@ -953,12 +954,7 @@ export class AgentDaemon {* ledger seed source has its own equivalent reader).*/private legacyRlmSubagentRegistryPath(parentSessionFile: string, parentSessionId: string): string {- return join(- dirname(dirname(parentSessionFile)),- "session-artifacts",- parentSessionId,- RLM_SUBAGENT_REGISTRY_FILE,- );+ return join(getSessionArtifactPathForFile(parentSessionFile, parentSessionId), RLM_SUBAGENT_REGISTRY_FILE);}private async readLegacyRlmSubagentRegistry(@@ -1091,8 +1087,12 @@ export class AgentDaemon {sessionFile: parentFile,});} else if (edges.length > 0) {- // Only a tombstoned edge: the topology tombstone is already durable- // (the display tombstone was written before it), nothing to re-append.+ // Only tombstoned edges: the tombstones are already durable, nothing+ // to re-append. A prior deletion may have crashed before its artifact+ // sweep, so retry it here.+ for (const tombstoned of edges) {+ await this.deleteRlmSubagentArtifacts(childId, tombstoned.child);+ }return;} else {// No edge at all. A pre-ledger child the seed missed may still exist@@ -1148,6 +1148,20 @@ export class AgentDaemon {// dual-write era it has no other writer to fall back on, so a failed// append is a failed deletion.await this.rlmSpawnLedger().appendDelete({ childId, child: entry.sessionFile, reason });+ // Deletion boundary: transcript + display tombstone are the durable+ // record and stay; the nested artifact dir is a runtime cache and goes.+ await this.deleteRlmSubagentArtifacts(childId, entry.sessionFile);+ }++ /** Best-effort artifact-dir removal: cache cleanup must never fail a deletion. */+ private async deleteRlmSubagentArtifacts(childId: string, childSessionFile: string): Promise<void> {+ try {+ await deleteSessionArtifacts(childSessionFile);+ } catch (error) {+ this.log(+ `failed to remove artifact dir for deleted RLM subagent ${childId}: ${error instanceof Error ? error.message : String(error)}`,+ );+ }}/**@@ -2451,10 +2465,21 @@ export class AgentDaemon {candidate.runtime.metadata.rlmChildId === options.id &&candidate.runtime.session === runtime.session,);- if (state) {- await this.closeSession(state, status === "cancelled" ? "killed" : "completed");- } else {- await runtime.session.disposeAsync();+ try {+ if (state) {+ await this.closeSession(state, status === "cancelled" ? "killed" : "completed");+ } else {+ await runtime.session.disposeAsync();+ }+ } finally {+ // Sweep even when teardown throws (see deleteRlmSubagentRuntime);+ // never throws, so it cannot mask a teardown error.+ if (status === "cancelled" && deletionError === undefined) {+ const childSessionFile = runtime.session?.sessionFile;+ if (childSessionFile) {+ await this.deleteRlmSubagentArtifacts(options.id, childSessionFile);+ }+ }}if (deletionError !== undefined) throw deletionError;},@@ -2495,22 +2520,36 @@ export class AgentDaemon {: undefined;const childSessionFile =persisted?.sessionFile ?? state?.runtime.session.sessionFile ?? legacyFallback?.sessionFile;- // Persist the deletion boundary before tearing down the runtime. As with a- // resident child, deletion keeps its transcript and artifact tree on disk.+ // Persist the deletion boundary before tearing down the runtime.await this.recordRlmSubagentDeletion(parentState, childId);const staleSession = state && session && state.runtime.session !== session ? session : undefined;try {- if (state) {- await this.closeSession(state, "killed", false);- } else {- await session?.disposeAsync();+ try {+ if (state) {+ await this.closeSession(state, "killed", false);+ } else {+ await session?.disposeAsync();+ }+ } finally {+ await staleSession?.disposeAsync();}} finally {- await staleSession?.disposeAsync();- }- // A killed close can join a passivation close that already skipped killed cleanup.- if (childSessionFile) {- this.cancelScheduledJobsForSessionFile(childSessionFile);+ // Runs even when teardown throws: the jobs-cancel rewrite and the+ // kernel dispose's final snapshot flush may have already happened,+ // resurrecting the artifact dir swept in recordRlmSubagentDeletion.+ // A killed close can join a passivation close that already skipped+ // killed cleanup. Neither step may throw here: a jobs-store error+ // would mask the teardown error and skip the sweep.+ if (childSessionFile) {+ try {+ this.cancelScheduledJobsForSessionFile(childSessionFile);+ } catch (error) {+ this.log(+ `failed to cancel scheduled jobs for deleted RLM subagent ${childId}: ${error instanceof Error ? error.message : String(error)}`,+ );+ }+ await this.deleteRlmSubagentArtifacts(childId, childSessionFile);+ }}},disposeRlmSubagentRuntimes: async () => {diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex abffaf0490..56874b8812 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -42,7 +42,7 @@ import {type WorkerEvictionSnapshot,} from "../../core/session-action-store.js";import { canonicalSessionPath, getProcessStartId, SessionAlreadyActiveError } from "../../core/session-lease.js";-import { readSessionInfo, type SessionInfo } from "../../core/session-manager.js";+import { getSessionArtifactPathForFile, readSessionInfo, type SessionInfo } from "../../core/session-manager.js";import { SettingsManager } from "../../core/settings-manager.js";import { isProcessAlive, processIdExists, signalProcessGroupOrProcess } from "../../utils/child-process.js";import type { AgentConnectionHeartbeat } from "../agent-connection/types.js";@@ -4997,7 +4997,7 @@ export class DaemonSupervisor {}return {sessionFile,- artifactDir: join(dirname(dirname(sessionFile)), "session-artifacts", worker.descriptor.rootSessionId),+ artifactDir: getSessionArtifactPathForFile(sessionFile, worker.descriptor.rootSessionId),};}diff --git a/packages/coding-agent/src/modes/daemon/rlm-ledger.ts b/packages/coding-agent/src/modes/daemon/rlm-ledger.tsindex 0f8e6a4d1b..0ab9ee9e28 100644--- a/packages/coding-agent/src/modes/daemon/rlm-ledger.ts+++ b/packages/coding-agent/src/modes/daemon/rlm-ledger.ts@@ -18,7 +18,7 @@ import {import { readdir, readFile, stat } from "node:fs/promises";import { basename, dirname, join, resolve } from "node:path";import { canonicalSessionPath } from "../../core/session-lease.js";-import { readSessionInfo, type SessionInfo } from "../../core/session-manager.js";+import { getSessionArtifactPathForFile, readSessionInfo, type SessionInfo } from "../../core/session-manager.js";import { readFirstLineSync } from "../../utils/file-lines.js";/**@@ -133,7 +133,7 @@ export function createRlmLedgerRegistrySeedSource(): RlmLedgerSeedSource {return [];}if (!headerId) return [];- const registryPath = join(dirname(dirname(sessionFile)), "session-artifacts", headerId, "rlm-subagents.jsonl");+ const registryPath = join(getSessionArtifactPathForFile(sessionFile, headerId), "rlm-subagents.jsonl");let contents: string;try {contents = await readFile(registryPath, "utf8");diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex c921a24786..000443c740 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -1,5 +1,6 @@import { EventEmitter } from "node:events";import {+ chmodSync,existsSync,mkdirSync,mkdtempSync,@@ -7396,6 +7397,136 @@ describe("daemon mode helpers", () => {}});+ it("removes a deleted child's nested artifact dir but keeps its transcript and display tombstone", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-artifact-cleanup-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ writeFileSync(join(fixture.childArtifactDir, "kernel-state.dill"), "payload");+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ const host = internals.createSubagentRuntimeHost(parentState);+ await host.deleteRlmSubagentRuntime(fixture.childId);++ // Runtime cache gone; transcript + display tombstone (durable record) stay.+ expect(existsSync(fixture.childArtifactDir)).toBe(false);+ expect(existsSync(fixture.childSessionFile)).toBe(true);+ // Depth-2 boundary: deleting a child never touches descendant transcripts.+ expect(existsSync(fixture.grandchildSessionFile)).toBe(true);+ const display = JSON.parse(readFileSync(join(fixture.childSessionDir, "rlm-subagent.json"), "utf8")) as {+ status: string;+ };+ expect(display).toMatchObject({ status: "deleted" });++ // Retry heal: a crash between the tombstone writes and the sweep (or a+ // pre-cleanup build) leaves the dir behind; a retried delete of the+ // tombstoned child sweeps it again.+ mkdirSync(fixture.childArtifactDir, { recursive: true });+ writeFileSync(join(fixture.childArtifactDir, "kernel-state.dill"), "leftover");+ await host.deleteRlmSubagentRuntime(fixture.childId);+ expect(existsSync(fixture.childArtifactDir)).toBe(false);+ expect(existsSync(fixture.childSessionFile)).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ // chmod-based read-only dirs don't block root, so skip when running as uid 0.+ it.skipIf(process.getuid?.() === 0)("does not fail a deletion when the artifact dir cannot be removed", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-artifact-rm-failure-"));+ let lockedRoot: string | undefined;+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const nestedArtifactsRoot = resolve(fixture.childArtifactDir, "..");+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ chmodSync(nestedArtifactsRoot, 0o555);+ lockedRoot = nestedArtifactsRoot;++ // Cache cleanup is best-effort: the rm failure must not surface.+ await internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId);++ expect(existsSync(fixture.childArtifactDir)).toBe(true);+ // Both tombstones are still durable.+ const display = JSON.parse(readFileSync(join(fixture.childSessionDir, "rlm-subagent.json"), "utf8")) as {+ status: string;+ };+ expect(display).toMatchObject({ status: "deleted" });+ const ledgerFile = readdirSync(join(tempDir, "rlm-ledger")).find((name) => name.endsWith(".jsonl"));+ if (!ledgerFile) throw new Error("Missing RLM ledger file");+ const ledgerOps = readFileSync(join(tempDir, "rlm-ledger", ledgerFile), "utf8")+ .trim()+ .split(/\r?\n/)+ .map((line) => JSON.parse(line) as { op: string; childId?: string });+ expect(ledgerOps.some((record) => record.op === "delete" && record.childId === fixture.childId)).toBe(true);+ } finally {+ if (lockedRoot) chmodSync(lockedRoot, 0o755);+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("still sweeps and resolves when scheduled-job cancellation throws", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-artifact-cancel-throw-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ writeFileSync(join(fixture.childArtifactDir, "kernel-state.dill"), "payload");+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ cancelScheduledJobsForSessionFile(sessionFile: string): void;+ };+ internals.cancelScheduledJobsForSessionFile = vi.fn(() => {+ throw new Error("corrupt scheduled-jobs.json");+ });+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });++ // Jobs-store bookkeeping must not fail the deletion or skip the sweep.+ await internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId);++ expect(internals.cancelScheduledJobsForSessionFile).toHaveBeenCalledOnce();+ expect(existsSync(fixture.childArtifactDir)).toBe(false);+ expect(existsSync(fixture.childSessionFile)).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });++ it("sweeps the artifact dir even when child teardown throws", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-artifact-teardown-throw-"));+ try {+ const fixture = makePersistedRlmDaemonFixture(tempDir);+ const internals = fixture.daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ createSubagentRuntimeHost(parent: ActiveSessionState): SubagentRuntimeHost;+ };+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });+ // A dispose that flushes a fresh kernel snapshot (recreating the+ // artifact dir) and then fails.+ const throwingSession = {+ disposeAsync: vi.fn(async () => {+ mkdirSync(fixture.childArtifactDir, { recursive: true });+ writeFileSync(join(fixture.childArtifactDir, "kernel-state.dill"), "flushed");+ throw new Error("dispose failed");+ }),+ } as unknown as ActiveSessionState["runtime"]["session"];++ await expect(+ internals.createSubagentRuntimeHost(parentState).deleteRlmSubagentRuntime(fixture.childId, throwingSession),+ ).rejects.toThrow("dispose failed");++ expect(throwingSession.disposeAsync).toHaveBeenCalledOnce();+ expect(existsSync(fixture.childArtifactDir)).toBe(false);+ expect(existsSync(fixture.childSessionFile)).toBe(true);+ } finally {+ rmSync(tempDir, { recursive: true, force: true });+ }+ });+it("cancels scheduled jobs when deleting a pre-ledger legacy child without hydrating it", async () => {const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-delete-jobs-"));try {@@ -10001,6 +10132,7 @@ function makePersistedRlmDaemonFixture(childId,childSessionFile,childSessionDir,+ childArtifactDir,grandchildId,grandchildSessionFile,};diff --git a/packages/coding-agent/test/session-artifacts-delete.test.ts b/packages/coding-agent/test/session-artifacts-delete.test.tsindex 2f2a370c50..d16be25d3f 100644--- a/packages/coding-agent/test/session-artifacts-delete.test.ts+++ b/packages/coding-agent/test/session-artifacts-delete.test.ts@@ -2,7 +2,7 @@ import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { deleteSessionFile } from "../src/core/session-file-actions.js";+import { deleteSessionArtifacts, deleteSessionFile } from "../src/core/session-file-actions.js";let root = "";@@ -62,6 +62,18 @@ describe("deleteSessionFile removes the session artifact directory", () => {expect(existsSync(artifactDir)).toBe(false);});+ it("never removes the artifacts root for a degenerate session file name", async () => {+ const sessionsDir = join(root, "sessions");+ mkdirSync(sessionsDir, { recursive: true });+ const artifactsRoot = join(root, "session-artifacts");+ mkdirSync(join(artifactsRoot, "live-session"), { recursive: true });++ // Basename ".jsonl" strips to an empty id, which would resolve to the root.+ await deleteSessionArtifacts(join(sessionsDir, ".jsonl"));++ expect(existsSync(join(artifactsRoot, "live-session"))).toBe(true);+ });+it("succeeds when the session has no artifact directory", async () => {const sessionsDir = join(root, "sessions");mkdirSync(sessionsDir, { recursive: true });diff --git a/packages/coding-agent/test/session-manager/artifact-paths.test.ts b/packages/coding-agent/test/session-manager/artifact-paths.test.tsnew file mode 100644index 0000000000..877aaeb08b--- /dev/null+++ b/packages/coding-agent/test/session-manager/artifact-paths.test.ts@@ -0,0 +1,28 @@+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import {+ getSessionArtifactPath,+ getSessionArtifactPathForFile,+ getSessionArtifactsRoot,+} from "../../src/core/session-manager.js";++describe("session artifact path helpers", () => {+ const sessionDir = join("/agent", "sessions");++ it("derives the same artifact dir from a sessionDir and from a sessionFile", () => {+ const fromDir = getSessionArtifactPath(sessionDir, "abc-123");+ const fromFile = getSessionArtifactPathForFile(join(sessionDir, "abc-123.jsonl"));+ expect(fromFile).toBe(fromDir);+ expect(fromDir).toBe(join("/agent", "session-artifacts", "abc-123"));+ });++ it("honors an explicit id that differs from the file basename", () => {+ const fromFile = getSessionArtifactPathForFile(join(sessionDir, "renamed.jsonl"), "header-id");+ expect(fromFile).toBe(getSessionArtifactPath(sessionDir, "header-id"));+ });++ it("anchors the artifacts root next to the sessions dir", () => {+ expect(getSessionArtifactsRoot(sessionDir)).toBe(join("/agent", "session-artifacts"));+ expect(getSessionArtifactPath(sessionDir, "x")).toBe(join(getSessionArtifactsRoot(sessionDir), "x"));+ });+});