Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

feat(coding-agent): persist parent edges and derived depth for all sessions (#584)

Sebastian Müller44683372c3d7
diff --git a/packages/coding-agent/src/core/agent-session-runtime.ts b/packages/coding-agent/src/core/agent-session-runtime.ts
index c51108380e..c862753a54 100644
--- a/packages/coding-agent/src/core/agent-session-runtime.ts
+++ b/packages/coding-agent/src/core/agent-session-runtime.ts
@@ -344,7 +344,10 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
async createRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): Promise<RlmSubagentRuntime> {
const sessionManager = SessionManager.create(options.parentSession.sessionManager.getCwd(), options.sessionDir);
if (options.parentSession.sessionFile) {
- sessionManager.newSession({ parentSession: options.parentSession.sessionFile });
+ sessionManager.newSession({
+ parentSession: options.parentSession.sessionFile,
+ rlmDepth: options.rlmDepth,
+ });
}
const runtime = await this.scopedBuild(() =>
createAgentSessionRuntime(this.createRuntime, {
@@ -570,8 +573,12 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
}
const sessionDir = this.session.sessionManager.getSessionDir();
if (!targetLeafId) {
+ const sourceHeader = this.session.sessionManager.getHeader();
const sessionManager = SessionManager.create(this.cwd, sessionDir);
- sessionManager.newSession({ parentSession: currentSessionFile });
+ sessionManager.newSession({
+ parentSession: currentSessionFile,
+ rlmDepth: sourceHeader?.rlmDepth,
+ });
const lease = this.acquireReplacementLease(sessionManager.getSessionFile());
await this.teardownForReplacement("fork", sessionManager.getSessionFile(), lease);
await this.buildAndApplyReplacement(
@@ -618,7 +625,11 @@ export class AgentSessionRuntime implements SubagentRuntimeHost {
const sessionManager = this.session.sessionManager;
if (!targetLeafId) {
- sessionManager.newSession({ parentSession: this.session.sessionFile });
+ const sourceHeader = sessionManager.getHeader();
+ sessionManager.newSession({
+ parentSession: this.session.sessionFile,
+ rlmDepth: sourceHeader?.rlmDepth,
+ });
} else {
sessionManager.createBranchedSession(targetLeafId);
}
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index 8f2e8530ab..8ceb35940e 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -1231,7 +1231,10 @@ export class AgentSession {
this._mcpManager = config.mcpManager;
this._baseToolsOverride = config.baseToolsOverride;
this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
- this._rlmDepth = config.rlmDepth ?? parseDepth(process.env.RLM_DEPTH, 0, "RLM_DEPTH");
+ this._rlmDepth =
+ config.rlmDepth ??
+ this.sessionManager.getHeader()?.rlmDepth ??
+ parseDepth(process.env.RLM_DEPTH, 0, "RLM_DEPTH");
this._rlmMaxDepth = config.rlmMaxDepth ?? parseDepth(process.env.RLM_MAX_DEPTH, 1, "RLM_MAX_DEPTH");
this._prewarmIpythonKernel = (config.prewarmIpythonKernel ?? false) && this._rlmDepth === 0;
this._autoRefineReviewer = config.autoRefineReviewer;
@@ -3990,6 +3993,11 @@ export class AgentSession {
return this.sessionManager.getSessionId();
}
+ /** Current RLM spawn depth for this session. */
+ get rlmDepth(): number {
+ return this._rlmDepth;
+ }
+
/** Current session display name, if set */
get sessionName(): string | undefined {
return this.sessionManager.getSessionName();
@@ -8625,7 +8633,10 @@ export class AgentSession {
private _createInlineRlmSubagentRuntime(options: CreateRlmSubagentRuntimeOptions): RlmSubagentRuntime {
const childSessionManager = SessionManager.create(this._cwd, options.sessionDir);
if (options.parentSession.sessionFile) {
- childSessionManager.newSession({ parentSession: options.parentSession.sessionFile });
+ childSessionManager.newSession({
+ parentSession: options.parentSession.sessionFile,
+ rlmDepth: options.rlmDepth,
+ });
}
childSessionManager.appendModelChange(options.model.provider, options.model.id);
childSessionManager.appendThinkingLevelChange(options.thinkingLevel);
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 54215f3ea7..769b60a1b4 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -79,12 +79,16 @@ export interface SessionHeader {
timestamp: string;
cwd: string;
parentSession?: string;
+ /** RLM spawn depth. Optional for backward compatibility. Forks preserve the source depth. */
+ rlmDepth?: number;
git?: GitContext;
}
export interface NewSessionOptions {
id?: string;
parentSession?: string;
+ /** Explicit RLM spawn depth. An explicitly undefined value suppresses parent derivation. */
+ rlmDepth?: number;
}
export type SessionPersistListener = (sessionFile: string) => void;
@@ -291,6 +295,8 @@ export interface SessionInfo {
state?: SessionState;
/** Path to the parent session (if this session was forked). */
parentSessionPath?: string;
+ /** Resolved RLM spawn depth. */
+ rlmDepth: number;
created: Date;
modified: Date;
messageCount: number;
@@ -692,6 +698,82 @@ function readSessionHeader(filePath: string): Partial<SessionHeader> | undefined
return JSON.parse(firstLine) as Partial<SessionHeader>;
}
+function isValidRlmDepth(value: unknown): value is number {
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
+}
+
+export function resolveSessionRlmDepth(
+ header: { rlmDepth?: number; parentSession?: string },
+ sessionPath: string,
+): number {
+ return resolveLegacySessionRlmDepth(header, sessionPath, new Set()) ?? legacyChildDepthFromPath(sessionPath);
+}
+
+function resolveLegacySessionRlmDepth(
+ header: { rlmDepth?: number; parentSession?: string },
+ sessionPath: string,
+ visitedPaths: Set<string>,
+): number | undefined {
+ if (isValidRlmDepth(header.rlmDepth)) {
+ return header.rlmDepth;
+ }
+ if (!header.parentSession) {
+ return 0;
+ }
+
+ const resolvedSessionPath = resolve(sessionPath);
+ if (visitedPaths.has(resolvedSessionPath)) {
+ return undefined;
+ }
+ visitedPaths.add(resolvedSessionPath);
+
+ const pathDepth = legacyChildDepthFromPath(sessionPath);
+ const parentSessionPath = resolve(dirname(sessionPath), header.parentSession);
+ try {
+ const parentHeader = readSessionHeader(parentSessionPath);
+ if (parentHeader) {
+ const parentDepth = resolveLegacySessionRlmDepth(parentHeader, parentSessionPath, visitedPaths);
+ if (parentDepth !== undefined) {
+ return pathDepth > 0 ? parentDepth + 1 : parentDepth;
+ }
+ }
+ } catch {
+ // Fall back to artifact ancestry for unavailable or invalid legacy parents.
+ } finally {
+ visitedPaths.delete(resolvedSessionPath);
+ }
+ return pathDepth;
+}
+
+function legacyChildDepthFromPath(sessionPath: string): number {
+ let depth = 0;
+ for (const segment of dirname(sessionPath)
+ .split(/[\\/]+/)
+ .reverse()) {
+ if (!/^sub-[0-9a-f]{8}$/.test(segment)) {
+ break;
+ }
+ depth += 1;
+ }
+ return depth;
+}
+
+function deriveChildRlmDepth(parentHeader: Partial<SessionHeader> | undefined): number | undefined {
+ return isValidRlmDepth(parentHeader?.rlmDepth) ? parentHeader.rlmDepth + 1 : undefined;
+}
+
+function rootRlmDepthFromEnv(): number {
+ const value = process.env.RLM_DEPTH;
+ if (value === undefined || value === "") {
+ return 0;
+ }
+ const parsed = Number.parseInt(value, 10);
+ if (!Number.isFinite(parsed) || parsed < 0) {
+ throw new Error("RLM_DEPTH must be a non-negative integer");
+ }
+ return parsed;
+}
+
function isValidSessionFile(filePath: string): boolean {
try {
const header = readSessionHeader(filePath);
@@ -1021,6 +1103,7 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
if (!header) return null;
const cwd = typeof header.cwd === "string" ? header.cwd : "";
const parentSessionPath = header.parentSession;
+ const rlmDepth = resolveSessionRlmDepth(header, filePath);
const modified = getSessionModifiedDateFromLastActivity(lastActivityTime, header, stats.mtime);
return {
@@ -1030,6 +1113,7 @@ async function scanSessionInfo(filePath: string, stats: Awaited<ReturnType<typeo
name,
state,
parentSessionPath,
+ rlmDepth,
created: new Date(header.timestamp),
modified,
messageCount,
@@ -1161,7 +1245,12 @@ export class SessionManager {
const header = this.fileEntries.find((e) => e.type === "session") as SessionHeader | undefined;
this.sessionId = header?.id ?? createSessionId();
- if (migrateToCurrentVersion(this.fileEntries)) {
+ let shouldRewrite = migrateToCurrentVersion(this.fileEntries);
+ if (header?.parentSession && !isValidRlmDepth(header.rlmDepth)) {
+ header.rlmDepth = resolveSessionRlmDepth(header, this.sessionFile);
+ shouldRewrite = true;
+ }
+ if (shouldRewrite) {
this._rewriteFile();
}
@@ -1177,6 +1266,15 @@ export class SessionManager {
newSession(options?: NewSessionOptions): string | undefined {
let sessionId = options?.id ?? createSessionId();
let sessionFile: string | undefined;
+ const hasExplicitRlmDepth = options !== undefined && Object.hasOwn(options, "rlmDepth");
+ let parentHeader: Partial<SessionHeader> | undefined;
+ if (options?.parentSession && !hasExplicitRlmDepth) {
+ try {
+ parentHeader = readSessionHeader(options.parentSession);
+ } catch {
+ // Legacy-invalid or unavailable parents leave the child depth unknown.
+ }
+ }
if (this.persist) {
if (options?.id) {
sessionFile = getSessionFilePath(this.getSessionDir(), sessionId);
@@ -1193,6 +1291,11 @@ export class SessionManager {
this.sessionId = sessionId;
const timestamp = new Date().toISOString();
const git = this.persist ? (captureGitContext(this.cwd) ?? undefined) : undefined;
+ const rlmDepth = hasExplicitRlmDepth
+ ? options?.rlmDepth
+ : options?.parentSession
+ ? deriveChildRlmDepth(parentHeader)
+ : rootRlmDepthFromEnv();
const header: SessionHeader = {
type: "session",
version: CURRENT_SESSION_VERSION,
@@ -1200,6 +1303,7 @@ export class SessionManager {
timestamp,
cwd: this.cwd,
parentSession: options?.parentSession,
+ rlmDepth,
git,
};
this.fileEntries = [header];
@@ -1305,6 +1409,7 @@ export class SessionManager {
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
+ const previousHeader = this.getHeader();
const target = createUniqueSessionFileTarget(dir);
this.sessionDir = dir;
this.sessionId = target.sessionId;
@@ -1318,6 +1423,8 @@ export class SessionManager {
id: this.sessionId,
timestamp,
cwd: this.cwd,
+ parentSession: previousHeader?.parentSession,
+ rlmDepth: resolveSessionRlmDepth(previousHeader ?? {}, target.sessionFile),
git,
};
this.fileEntries = [header, ...this.getEntries()];
@@ -1941,6 +2048,7 @@ export class SessionManager {
timestamp,
cwd: this.cwd,
parentSession: this.persist ? previousSessionFile : undefined,
+ rlmDepth: resolveSessionRlmDepth(this.getHeader() ?? {}, previousSessionFile ?? newSessionFile ?? ""),
git: this.persist ? (captureGitContext(this.cwd) ?? undefined) : undefined,
};
@@ -2134,6 +2242,7 @@ export class SessionManager {
timestamp,
cwd: targetCwd,
parentSession: sourcePath,
+ rlmDepth: resolveSessionRlmDepth(sourceHeader, sourcePath),
git: captureGitContext(targetCwd) ?? undefined,
};
appendFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`);
diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.ts
index 118e04a94b..d1f6bc7c93 100644
--- a/packages/coding-agent/src/modes/agent-connection/types.ts
+++ b/packages/coding-agent/src/modes/agent-connection/types.ts
@@ -60,6 +60,7 @@ export interface AgentConnectionSessionHeader {
timestamp: string;
cwd: string;
parentSession?: string;
+ rlmDepth?: number;
git?: {
repoUrl?: string;
commit?: string;
@@ -122,6 +123,7 @@ export interface AgentConnectionSavedSessionInfo {
name?: string;
state?: AgentConnectionSavedSessionState;
parentSessionPath?: string;
+ rlmDepth?: number;
created: Date;
modified: Date;
messageCount: number;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
index 8b646923ce..91cc1389fa 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts
@@ -99,7 +99,12 @@ import type {
} from "../../core/rlm-runtime.js";
import { deleteSessionFile } from "../../core/session-file-actions.js";
import { acquireSessionLease, type SessionLease } from "../../core/session-lease.js";
-import { readSessionInfo, type SessionInfo, SessionManager } from "../../core/session-manager.js";
+import {
+ readSessionInfo,
+ resolveSessionRlmDepth,
+ type SessionInfo,
+ SessionManager,
+} from "../../core/session-manager.js";
import { resolveSessionPath } from "../../core/session-resolver.js";
import type { SessionStats } from "../../core/session-stats.js";
import { type SideQuestionRun, startSideQuestion } from "../../core/side-question.js";
@@ -141,7 +146,6 @@ import {
type DaemonCommand,
type DaemonOutbound,
type DaemonResponse,
- type DaemonSavedSessionInfo,
type DaemonSessionClosedReason,
type DaemonSessionSnapshot,
type DaemonUpdateRestartManifest,
@@ -186,6 +190,7 @@ import {
SESSION_LEASES_ENABLED_ENV,
} from "./daemon-worker-protocol.js";
import { MutationDrainLatch } from "./mutation-drain-latch.js";
+import { serializeSavedSessionInfo } from "./saved-session-info.js";
import {
createSnapshotTranscriptChunks,
SNAPSHOT_TARGET_CHUNK_BYTES,
@@ -1070,9 +1075,9 @@ export class AgentDaemon {
parentEntry?.sessionFile ??
passive.rootParentState?.runtime.session.sessionFile ??
passive.rootInfo?.path,
+ rlmDepth: passive.entry.rlmDepth ?? passive.info.rlmDepth,
rlmChildId: passive.entry.childId,
rlmParentNodeId: passive.entry.rlmParentNodeId ?? passive.entry.childId,
- ...(!passive.rootParentState ? { rlmDepth: passive.entry.rlmDepth } : {}),
spawnCode: passive.entry.spawnCode,
};
});
@@ -2146,7 +2151,10 @@ export class AgentDaemon {
): Promise<AgentSessionRuntime> {
const sessionManager = SessionManager.create(options.parentSession.sessionManager.getCwd(), options.sessionDir);
if (options.parentSession.sessionFile) {
- sessionManager.newSession({ parentSession: options.parentSession.sessionFile });
+ sessionManager.newSession({
+ parentSession: options.parentSession.sessionFile,
+ rlmDepth: options.rlmDepth,
+ });
}
let stateRef: ActiveSessionState | undefined;
// Subagents inherit the parent's client env (e.g. herdr pane identity).
@@ -2369,7 +2377,9 @@ export class AgentDaemon {
},
},
rlmSessionDir: entry.sessionDir,
- rlmDepth: entry.rlmDepth ?? 1,
+ rlmDepth: existsSync(entry.sessionFile)
+ ? resolveSessionRlmDepth(sessionManager.getHeader() ?? {}, entry.sessionFile)
+ : undefined,
rlmMaxDepth: entry.rlmMaxDepth ?? 1,
rlmParentNodeId: entry.rlmParentNodeId ?? entry.childId,
},
@@ -5585,23 +5595,6 @@ function hasDaemonOutboundActiveSessionId(
return "activeSessionId" in message && typeof message.activeSessionId === "string";
}
-function serializeSavedSessionInfo(session: SessionInfo): DaemonSavedSessionInfo {
- return {
- path: session.path,
- id: session.id,
- cwd: session.cwd,
- name: session.name,
- state: session.state,
- parentSessionPath: session.parentSessionPath,
- created: session.created.toISOString(),
- modified: session.modified.toISOString(),
- messageCount: session.messageCount,
- firstMessage: session.firstMessage,
- allMessagesText: session.allMessagesText,
- agentStatus: session.agentStatus,
- };
-}
-
export function getChildActiveSessionStates(
sessions: ReadonlyMap<string, ActiveSessionState>,
parentState: ActiveSessionState,
diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
index 37d1643d5a..7440e217fc 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts
@@ -52,8 +52,9 @@ export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";
export const DAEMON_PROTOCOL_VERSION = 7;
export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 7;
// Revision 9 publishes persisted RLM spawn depth on passive session rows.
-export const DAEMON_SCHEMA_REVISION = 9;
-export const DAEMON_SCHEMA_ID = "protocol-7-schema-9-b56e29842cfa";
+// Revision 10 publishes persisted RLM spawn depth on all session catalog rows.
+export const DAEMON_SCHEMA_REVISION = 10;
+export const DAEMON_SCHEMA_ID = "protocol-7-schema-10-37a654228732";
export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;
export type DaemonProtocolVersion = number;
@@ -779,6 +780,7 @@ export interface DaemonSavedSessionInfo {
name?: string;
state?: AgentConnectionSavedSessionState;
parentSessionPath?: string;
+ rlmDepth?: number;
created: string;
modified: string;
messageCount: number;
diff --git a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
index 7a2d2d37ed..f81d81d680 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-session-list.ts
@@ -32,7 +32,7 @@ export interface SessionSummary {
isSessionActive: boolean;
hasActiveHeartbeat?: boolean;
runtimeKind?: "top-level" | "subagent";
- /** RLM spawn depth for persisted passive subagent rows. */
+ /** RLM spawn depth (0 for roots); fork edges preserve the source depth. */
rlmDepth?: number;
activeSessionId?: string;
sessionId: string;
@@ -167,6 +167,7 @@ export function summaryForActiveSession(
isSessionActive: session.isSessionActive,
hasActiveHeartbeat: hasActiveHeartbeat || undefined,
runtimeKind: metadata.kind,
+ rlmDepth: session.rlmDepth,
activeSessionId: activeSession.activeSessionId,
sessionId: session.sessionId,
sessionFile: session.sessionFile,
@@ -238,6 +239,7 @@ export function summaryForInactiveSession(session: SessionInfo): SessionSummary
modified: session.modified.toISOString(),
firstMessage: session.firstMessage,
parentSessionPath: session.parentSessionPath,
+ rlmDepth: session.rlmDepth,
// Carry the persisted recap/verdict so an off-daemon session keeps its
// agents-view bucket (e.g. Completed) instead of defaulting to Needs Input.
// Gate on message-count currency like isSummaryCurrent does for resident
diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
index 43be339a1d..99557d8173 100644
--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts
@@ -56,7 +56,6 @@ import {
type DaemonCommand,
type DaemonOutbound,
type DaemonResponse,
- type DaemonSavedSessionInfo,
type DaemonUpdateRestartManifest,
failure,
isDaemonCommandEnvelope,
@@ -100,6 +99,7 @@ import {
SESSION_LEASES_ENABLED_ENV,
} from "./daemon-worker-protocol.js";
import { MutationDrainLatch } from "./mutation-drain-latch.js";
+import { serializeSavedSessionInfo } from "./saved-session-info.js";
import { SNAPSHOT_TARGET_CHUNK_BYTES, SnapshotTranscriptCache } from "./snapshot-transcript-cache.js";
import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";
@@ -456,23 +456,6 @@ function sortCronJobs(jobs: AgentCronJob[]): AgentCronJob[] {
});
}
-function serializeSavedSessionInfo(session: SessionInfo): DaemonSavedSessionInfo {
- return {
- path: session.path,
- id: session.id,
- cwd: session.cwd,
- name: session.name,
- state: session.state,
- parentSessionPath: session.parentSessionPath,
- created: session.created.toISOString(),
- modified: session.modified.toISOString(),
- messageCount: session.messageCount,
- firstMessage: session.firstMessage,
- allMessagesText: session.allMessagesText,
- agentStatus: session.agentStatus,
- };
-}
-
function descriptorKey(socketPath: string): string {
return createHash("sha256").update(socketPath).digest("hex").slice(0, 12);
}
diff --git a/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts b/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
index ccfea4bfa0..6b22b1143a 100644
--- a/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
+++ b/packages/coding-agent/src/modes/daemon/saved-session-catalog.ts
@@ -12,6 +12,9 @@ import type {
DaemonSavedSessionInfo,
DaemonSavedSessionListCommand,
} from "./daemon-protocol.js";
+import { deserializeSavedSessionInfo } from "./saved-session-info.js";
+
+export { deserializeSavedSessionInfo } from "./saved-session-info.js";
export type DaemonSavedSessionCatalogContext = { activeSessionId: string } | { cwd: string; sessionDir?: string };
@@ -72,20 +75,3 @@ export async function deleteDaemonSavedSession(
}
return response.data as DaemonDeleteSavedSessionResult;
}
-
-export function deserializeSavedSessionInfo(session: DaemonSavedSessionInfo): AgentConnectionSavedSessionInfo {
- return {
- path: session.path,
- id: session.id,
- cwd: session.cwd,
- name: session.name,
- state: session.state,
- parentSessionPath: session.parentSessionPath,
- created: new Date(session.created),
- modified: new Date(session.modified),
- messageCount: session.messageCount,
- firstMessage: session.firstMessage,
- allMessagesText: session.allMessagesText,
- agentStatus: session.agentStatus,
- };
-}
diff --git a/packages/coding-agent/src/modes/daemon/saved-session-info.ts b/packages/coding-agent/src/modes/daemon/saved-session-info.ts
new file mode 100644
index 0000000000..0eaa8d0727
--- /dev/null
+++ b/packages/coding-agent/src/modes/daemon/saved-session-info.ts
@@ -0,0 +1,39 @@
+import type { SessionInfo } from "../../core/session-manager.js";
+import type { AgentConnectionSavedSessionInfo } from "../agent-connection/types.js";
+import type { DaemonSavedSessionInfo } from "./daemon-protocol.js";
+
+export function serializeSavedSessionInfo(session: SessionInfo): DaemonSavedSessionInfo {
+ return {
+ path: session.path,
+ id: session.id,
+ cwd: session.cwd,
+ name: session.name,
+ state: session.state,
+ parentSessionPath: session.parentSessionPath,
+ rlmDepth: session.rlmDepth,
+ created: session.created.toISOString(),
+ modified: session.modified.toISOString(),
+ messageCount: session.messageCount,
+ firstMessage: session.firstMessage,
+ allMessagesText: session.allMessagesText,
+ agentStatus: session.agentStatus,
+ };
+}
+
+export function deserializeSavedSessionInfo(session: DaemonSavedSessionInfo): AgentConnectionSavedSessionInfo {
+ return {
+ path: session.path,
+ id: session.id,
+ cwd: session.cwd,
+ name: session.name,
+ state: session.state,
+ parentSessionPath: session.parentSessionPath,
+ rlmDepth: session.rlmDepth,
+ created: new Date(session.created),
+ modified: new Date(session.modified),
+ messageCount: session.messageCount,
+ firstMessage: session.firstMessage,
+ allMessagesText: session.allMessagesText,
+ agentStatus: session.agentStatus,
+ };
+}
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index 714ab0dad9..aa10efd206 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -231,11 +231,12 @@ describe("AgentSession rlm recursion", () => {
agentMessageController?: AgentSessionMessageController;
subagentRuntimeHost?: SubagentRuntimeHost;
rlmSessionDir?: string;
+ sessionManager?: SessionManager;
} = {},
): AgentSession {
const authStorage = AuthStorage.create(join(tempDir, "auth.json"));
authStorage.setRuntimeApiKey("anthropic", "test-key");
- const sessionManager = SessionManager.create(tempDir, join(tempDir, "sessions"));
+ const sessionManager = options.sessionManager ?? SessionManager.create(tempDir, join(tempDir, "sessions"));
const settingsManager = SettingsManager.create(tempDir, tempDir);
const agent = new Agent({
@@ -266,6 +267,50 @@ describe("AgentSession rlm recursion", () => {
return session;
}
+ it("persists RLM_DEPTH for a fresh session and reports the seeded depth", () => {
+ vi.stubEnv("RLM_DEPTH", "1");
+ try {
+ const fresh = createSession({ maxDepth: 2 });
+ fresh.sessionManager.flushNow();
+ if (!fresh.sessionFile) throw new Error("Missing fresh session file");
+
+ const header = JSON.parse(readFileSync(fresh.sessionFile, "utf8").split("\n")[0] ?? "{}");
+ expect(header.rlmDepth).toBe(1);
+ expect(fresh.rlmDepth).toBe(1);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it("prefers persisted depth over RLM_DEPTH when resuming a session", () => {
+ const persistedManager = SessionManager.create(tempDir, join(tempDir, "resumed-sessions"));
+ persistedManager.newSession({ rlmDepth: 2 });
+ persistedManager.flushNow();
+ vi.stubEnv("RLM_DEPTH", "1");
+ try {
+ const resumed = createSession({ maxDepth: 3, sessionManager: persistedManager });
+ expect(resumed.rlmDepth).toBe(2);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it("keeps a forked root at depth zero so recursion remains allowed", async () => {
+ const source = SessionManager.create(tempDir, join(tempDir, "source-sessions"));
+ source.newSession({ rlmDepth: 0 });
+ source.appendMessage({ role: "user", content: "source prompt", timestamp: 1 });
+ source.flushNow();
+ const sourceFile = source.getSessionFile();
+ if (!sourceFile) throw new Error("Missing source session file");
+ const forkedManager = SessionManager.forkFrom(sourceFile, tempDir, join(tempDir, "forked-sessions"));
+ const forked = createSession({ maxDepth: 1, sessionManager: forkedManager });
+
+ expect(forked.rlmDepth).toBe(0);
+ await expect(forked.runRlmChild("recursion remains available")).resolves.toMatchObject({
+ answer: "child answer: recursion remains available",
+ });
+ });
+
it("creates readable collision-resistant default subagent session names", () => {
expect(createDefaultRlmSubagentSessionName("Summarize the HTTP API!", "sub-a1b2c3d4")).toBe(
"subagent-summarize-the-http-api-a1b2c3d4",
@@ -279,6 +324,18 @@ describe("AgentSession rlm recursion", () => {
expect(createDefaultRlmSubagentSessionName("x".repeat(200), "sub-a1b2c3d4")).toHaveLength(64);
});
+ it("persists the spawned child's parent edge and derived runtime depth in its header", async () => {
+ const root = createSession({ depth: 2, maxDepth: 4 });
+ const result = await root.runRlmChild("persist my tree position");
+ if (!result.session_dir) throw new Error("Missing child session directory");
+ const child = root.getRlmChildSession(basename(result.session_dir));
+ if (!child?.sessionFile || !root.sessionFile) throw new Error("Missing persisted session paths");
+
+ const header = JSON.parse(readFileSync(child.sessionFile, "utf8").split("\n")[0] ?? "{}");
+ expect(header).toMatchObject({ parentSession: root.sessionFile, rlmDepth: 3 });
+ expect(child.rlmDepth).toBe(3);
+ });
+
it("lets the orchestrator choose a unique subagent session name", async () => {
const root = createSession();
const result = await root.runRlmChild("inspect the API", { name: " api-reviewer " });
diff --git a/packages/coding-agent/test/agents-view-state.test.ts b/packages/coding-agent/test/agents-view-state.test.ts
index 74ad3c9be7..cf033a88c6 100644
--- a/packages/coding-agent/test/agents-view-state.test.ts
+++ b/packages/coding-agent/test/agents-view-state.test.ts
@@ -1160,6 +1160,7 @@ function makeSessionInfo(overrides: Partial<SessionInfo> & { path: string; id: s
name: overrides.name,
state: overrides.state,
parentSessionPath: overrides.parentSessionPath,
+ rlmDepth: overrides.rlmDepth ?? 0,
created: overrides.created ?? new Date("2026-01-01T00:00:00Z"),
modified: overrides.modified ?? new Date("2026-01-01T00:00:00Z"),
messageCount: overrides.messageCount ?? 1,
diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.ts
index 90a685efdb..ff47a5e240 100644
--- a/packages/coding-agent/test/daemon-mode.test.ts
+++ b/packages/coding-agent/test/daemon-mode.test.ts
@@ -3597,6 +3597,15 @@ describe("daemon mode helpers", () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-list-"));
try {
const fixture = makePersistedRlmDaemonFixture(tempDir);
+ // Simulate children written before rlmDepth was added to the extensible header.
+ // Their persisted registry rows remain the compatibility source after restart.
+ for (const sessionFile of [fixture.childSessionFile, fixture.grandchildSessionFile]) {
+ const lines = readFileSync(sessionFile, "utf8").split("\n");
+ const header = JSON.parse(lines[0] ?? "{}") as Record<string, unknown>;
+ delete header.rlmDepth;
+ lines[0] = JSON.stringify(header);
+ writeFileSync(sessionFile, lines.join("\n"));
+ }
const internals = fixture.daemon as unknown as {
sessions: Map<string, ActiveSessionState>;
createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
@@ -3644,6 +3653,7 @@ describe("daemon mode helpers", () => {
parentActiveSessionId: parentState.activeSessionId,
rlmChildId: fixture.childId,
parentSessionPath: fixture.parentSessionFile,
+ rlmDepth: 1,
});
expect(passiveRow?.activeSessionId).toBeUndefined();
const nestedRow = listResponse.data.sessions.find(
@@ -3654,6 +3664,7 @@ describe("daemon mode helpers", () => {
runtimeKind: "subagent",
rlmChildId: fixture.grandchildId,
parentSessionPath: fixture.childSessionFile,
+ rlmDepth: 2,
});
const activeOnlyResponse = (await internals.handleCommand(
@@ -3719,6 +3730,40 @@ describe("daemon mode helpers", () => {
}
});
+ it("prefers registry depth when listing a passive legacy child", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-passive-legacy-depth-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const parentManager = SessionManager.open(fixture.parentSessionFile);
+ parentManager.appendMessage({ role: "user", content: "parent task", timestamp: 0 });
+ parentManager.flushNow();
+ const lines = readFileSync(fixture.childSessionFile, "utf8").split("\n");
+ const header = JSON.parse(lines[0] ?? "{}") as Record<string, unknown>;
+ delete header.rlmDepth;
+ lines[0] = JSON.stringify(header);
+ writeFileSync(fixture.childSessionFile, lines.join("\n"));
+ const registryFile = join(fixture.parentArtifactDir, "rlm-subagents.jsonl");
+ const registryEntry = JSON.parse(readFileSync(registryFile, "utf8")) as Record<string, unknown>;
+ registryEntry.rlmDepth = 5;
+ registryEntry.rlmMaxDepth = 8;
+ writeFileSync(registryFile, `${JSON.stringify(registryEntry)}\n`);
+ const parentInfo = await readSessionInfo(fixture.parentSessionFile);
+ if (!parentInfo) throw new Error("Missing parent session info");
+ const internals = fixture.daemon as unknown as {
+ buildSessionListWithPassiveRlmSubagents(
+ activeSessions: ActiveSessionState[],
+ savedSessions: SessionInfo[],
+ scheduledJobs: AgentCronJob[],
+ ): Promise<SessionSummary[]>;
+ };
+
+ const sessions = await internals.buildSessionListWithPassiveRlmSubagents([], [parentInfo], []);
+ expect(sessions.find((session) => session.sessionFile === fixture.childSessionFile)?.rlmDepth).toBe(5);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("ignores a crashed registry tail and protects a nested cycle back to the root", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-corrupt-registry-"));
try {
@@ -3807,6 +3852,33 @@ describe("daemon mode helpers", () => {
}
});
+ it("rehydrates a legacy child with depth inferred from its session file path", async () => {
+ const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-legacy-rlm-depth-"));
+ try {
+ const fixture = makePersistedRlmDaemonFixture(tempDir);
+ const lines = readFileSync(fixture.childSessionFile, "utf8").split("\n");
+ const header = JSON.parse(lines[0] ?? "{}") as Record<string, unknown>;
+ delete header.rlmDepth;
+ lines[0] = JSON.stringify(header);
+ writeFileSync(fixture.childSessionFile, lines.join("\n"));
+ const internals = fixture.daemon as unknown as {
+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;
+ createAgentMessageController(
+ getCurrentState: () => ActiveSessionState | undefined,
+ ): AgentSessionMessageController;
+ };
+ const parentState = await internals.createRuntime({ type: "create", sessionPath: fixture.parentSessionFile });
+
+ await internals
+ .createAgentMessageController(() => parentState)
+ .sendAgentMessage({ target: "renamed-worker", message: "report progress" });
+
+ expect(fixture.createRuntime.mock.calls[1]?.[0].sessionOptions?.rlmDepth).toBe(1);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
it("does not match a renamed passive child by its stale registry name", async () => {
const tempDir = mkdtempSync(join(tmpdir(), "prime-agent-daemon-lazy-rlm-renamed-"));
try {
@@ -6108,7 +6180,7 @@ function makePersistedRlmDaemonFixture(
}
const childId = "child-1";
- const childSessionDir = join(parentArtifactDir, childId);
+ const childSessionDir = join(parentArtifactDir, "sub-1234abcd");
const childManager = SessionManager.create(tempDir, childSessionDir);
childManager.newSession({ parentSession: parentSessionFile });
childManager.appendSessionInfo("spawn-worker");
@@ -6121,7 +6193,8 @@ function makePersistedRlmDaemonFixture(
throw new Error("Missing child session paths");
}
const grandchildId = "grandchild-1";
- const grandchildSessionDir = join(childArtifactDir, grandchildId);
+ mkdirSync(childArtifactDir, { recursive: true });
+ const grandchildSessionDir = join(childSessionDir, "sub-deadbeef");
const grandchildManager = SessionManager.create(tempDir, grandchildSessionDir);
grandchildManager.newSession({ parentSession: childSessionFile });
grandchildManager.appendSessionInfo("nested-worker");
diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.ts
index bc3f52715f..abbdec1bb8 100644
--- a/packages/coding-agent/test/daemon-protocol.test.ts
+++ b/packages/coding-agent/test/daemon-protocol.test.ts
@@ -28,11 +28,18 @@ describe("daemon protocol helpers", () => {
source.indexOf("export type DaemonCommand ="),
source.indexOf("type DaemonCommandName"),
);
+ const savedSessionSource = source.slice(
+ source.indexOf("export interface DaemonSavedSessionInfo"),
+ source.indexOf("export type DaemonDeleteSavedSessionResult"),
+ );
const outboundSource = source.slice(
source.indexOf("export type DaemonOutbound ="),
source.indexOf("export const DAEMON_OUTBOUND_COMPATIBILITY"),
);
- const digest = createHash("sha256").update(`${commandSource}\n${outboundSource}`).digest("hex").slice(0, 12);
+ const digest = createHash("sha256")
+ .update(`${commandSource}\n${savedSessionSource}\n${outboundSource}`)
+ .digest("hex")
+ .slice(0, 12);
expect(DAEMON_SCHEMA_ID).toBe(`protocol-${DAEMON_PROTOCOL_VERSION}-schema-${DAEMON_SCHEMA_REVISION}-${digest}`);
});
diff --git a/packages/coding-agent/test/daemon-session-list.test.ts b/packages/coding-agent/test/daemon-session-list.test.ts
index f3cd64d5af..835af38166 100644
--- a/packages/coding-agent/test/daemon-session-list.test.ts
+++ b/packages/coding-agent/test/daemon-session-list.test.ts
@@ -346,6 +346,21 @@ describe("buildSessionList", () => {
firstMessage: "Audit the retry logic for races",
});
});
+
+ it("uses runtime depth for live rows and catalog depth for saved-only rows", () => {
+ const livePath = resolve("/tmp/project/live-depth.jsonl");
+ const savedPath = resolve("/tmp/project/saved-depth.jsonl");
+ const entries = buildSessionList(
+ [makeState({ activeSessionId: "live", sessionFile: livePath, rlmDepth: 2 })],
+ [
+ makeSessionInfo({ path: livePath, id: "live", rlmDepth: 99 }),
+ makeSessionInfo({ path: savedPath, id: "saved", rlmDepth: 3 }),
+ ],
+ );
+
+ expect(entries.find((entry) => entry.activeSessionId === "live")?.rlmDepth).toBe(2);
+ expect(entries.find((entry) => entry.sessionFile === savedPath)?.rlmDepth).toBe(3);
+ });
});
describe("summaryForActiveSession recap currency", () => {
@@ -568,6 +583,7 @@ interface StateOptions {
unfinishedActionCount?: number;
contextTokens?: number;
streamingMessage?: AgentMessage;
+ rlmDepth?: number;
metadata?: {
kind: "top-level" | "subagent";
createdAt: number;
@@ -602,6 +618,7 @@ function makeState(options: StateOptions): ActiveSessionState {
isCompacting: false,
sessionFile: options.sessionFile,
sessionId: options.sessionId ?? `session-${options.activeSessionId}`,
+ rlmDepth: options.rlmDepth ?? 0,
sessionName: `session ${options.activeSessionId}`,
sessionManager: {
getCwd: () => "/tmp/project",
@@ -641,6 +658,8 @@ function makeSessionInfo(overrides: Pick<SessionInfo, "path" | "id"> & Partial<S
cwd: "/tmp/project",
name: overrides.name,
state: overrides.state,
+ parentSessionPath: overrides.parentSessionPath,
+ rlmDepth: overrides.rlmDepth ?? 0,
created: new Date("2026-05-01T00:00:00.000Z"),
modified: new Date("2026-05-02T00:00:00.000Z"),
messageCount: overrides.messageCount ?? 2,
diff --git a/packages/coding-agent/test/saved-session-catalog.test.ts b/packages/coding-agent/test/saved-session-catalog.test.ts
index a351bb4d4b..30a7f33ac4 100644
--- a/packages/coding-agent/test/saved-session-catalog.test.ts
+++ b/packages/coding-agent/test/saved-session-catalog.test.ts
@@ -30,6 +30,8 @@ class FakeDaemonClient {
path: "/tmp/sessions/one.jsonl",
id: "one",
cwd: "/tmp/project",
+ parentSessionPath: "/tmp/sessions/parent.jsonl",
+ rlmDepth: 1,
created: "2026-01-01T00:00:00.000Z",
modified: "2026-01-02T00:00:00.000Z",
messageCount: 1,
@@ -52,6 +54,8 @@ class FakeDaemonClient {
path: "/tmp/sessions/one.jsonl",
id: "one",
cwd: "/tmp/project",
+ parentSessionPath: "/tmp/sessions/parent.jsonl",
+ rlmDepth: 1,
created: "2026-01-01T00:00:00.000Z",
modified: "2026-01-02T00:00:00.000Z",
messageCount: 1,
@@ -112,6 +116,8 @@ describe("saved session catalog", () => {
path: "/tmp/sessions/one.jsonl",
id: "one",
cwd: "/tmp/project",
+ parentSessionPath: "/tmp/sessions/parent.jsonl",
+ rlmDepth: 1,
created: new Date("2026-01-01T00:00:00.000Z"),
modified: new Date("2026-01-02T00:00:00.000Z"),
messageCount: 1,
diff --git a/packages/coding-agent/test/session-manager/file-operations.test.ts b/packages/coding-agent/test/session-manager/file-operations.test.ts
index 28331ca758..20fcac326d 100644
--- a/packages/coding-agent/test/session-manager/file-operations.test.ts
+++ b/packages/coding-agent/test/session-manager/file-operations.test.ts
@@ -7,6 +7,7 @@ import {
loadEntriesFromFile,
loadEntriesFromFileAsync,
readSessionInfo,
+ resolveSessionRlmDepth,
SessionManager,
} from "../../src/core/session-manager.js";
@@ -156,6 +157,273 @@ describe("loadEntriesFromFile", () => {
});
});
+describe("session tree metadata", () => {
+ it("persists a derived depth and exposes parent linkage from the header", async () => {
+ const tempDir = join(tmpdir(), `session-tree-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const parent = SessionManager.create(tempDir, tempDir);
+ parent.newSession({ rlmDepth: 2 });
+ parent.flushNow();
+ const parentFile = parent.getSessionFile();
+ if (!parentFile) throw new Error("Missing parent session file");
+
+ const child = SessionManager.create(tempDir, tempDir);
+ child.newSession({ parentSession: parentFile });
+ child.flushNow();
+ const childFile = child.getSessionFile();
+ if (!childFile) throw new Error("Missing child session file");
+
+ const header = JSON.parse(readFileSync(childFile, "utf8").split("\n")[0] ?? "{}");
+ expect(header).toMatchObject({ parentSession: parentFile, rlmDepth: 3 });
+ expect(await readSessionInfo(childFile)).toMatchObject({
+ parentSessionPath: parentFile,
+ rlmDepth: 3,
+ });
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it.each([0, 2])("copies source depth %i across branch and fork reference edges", (depth) => {
+ const tempDir = join(tmpdir(), `session-reference-depth-test-${depth}-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const source = SessionManager.create(tempDir, tempDir);
+ source.newSession({ rlmDepth: depth });
+ const leafId = source.appendMessage({ role: "user", content: "fork here", timestamp: 1 });
+ source.flushNow();
+ const sourceFile = source.getSessionFile();
+ if (!sourceFile) throw new Error("Missing source session file");
+
+ const forked = SessionManager.forkFrom(sourceFile, tempDir, tempDir);
+ expect(forked.getHeader()?.rlmDepth).toBe(depth);
+
+ const branched = SessionManager.open(sourceFile, tempDir);
+ branched.createBranchedSession(leafId);
+ expect(branched.getHeader()?.rlmDepth).toBe(depth);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("resolves legacy root depth across branch and fork reference edges", () => {
+ const tempDir = join(tmpdir(), `legacy-session-reference-depth-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const source = SessionManager.create(tempDir, tempDir);
+ source.newSession({ rlmDepth: undefined });
+ const leafId = source.appendMessage({ role: "user", content: "fork here", timestamp: 1 });
+ source.flushNow();
+ const sourceFile = source.getSessionFile();
+ if (!sourceFile) throw new Error("Missing source session file");
+
+ expect(SessionManager.forkFrom(sourceFile, tempDir, tempDir).getHeader()?.rlmDepth).toBe(0);
+ const branched = SessionManager.open(sourceFile, tempDir);
+ branched.createBranchedSession(leafId);
+ expect(branched.getHeader()?.rlmDepth).toBe(0);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("leaves derived child depth unknown when a legacy parent has no depth", () => {
+ const tempDir = join(tmpdir(), `legacy-parent-depth-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const parentFile = join(tempDir, "legacy-parent.jsonl");
+ writeFileSync(
+ parentFile,
+ `${JSON.stringify({ type: "session", id: "parent", timestamp: "2025-01-01T00:00:00Z", cwd: tempDir })}\n`,
+ );
+ const child = SessionManager.create(tempDir, tempDir);
+ child.newSession({ parentSession: parentFile });
+ expect(child.getHeader()).toMatchObject({ parentSession: parentFile });
+ expect(child.getHeader()?.rlmDepth).toBeUndefined();
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("infers root depth when materializing a legacy fork", () => {
+ const tempDir = join(tmpdir(), `materialized-legacy-depth-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const parentFile = join(tempDir, "legacy-parent.jsonl");
+ const session = SessionManager.inMemory(tempDir);
+ session.newSession({ parentSession: parentFile, rlmDepth: undefined });
+
+ const sessionFile = session.materializeSessionFile(tempDir);
+ const header = JSON.parse(readFileSync(sessionFile, "utf8").split("\n")[0] ?? "{}");
+ expect(header).toMatchObject({ parentSession: parentFile });
+ expect(header.rlmDepth).toBe(0);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("infers and backfills legacy child depth from nested subagent directories on open", async () => {
+ const tempDir = join(tmpdir(), `legacy-session-tree-test-${Date.now()}-${Math.random()}`);
+ const parentFile = join(tempDir, "parent.jsonl");
+ const childDir = join(tempDir, "session-artifacts", "root", "sub-1234abcd", "sub-deadbeef");
+ const childFile = join(childDir, "child.jsonl");
+ mkdirSync(childDir, { recursive: true });
+ try {
+ const header = {
+ type: "session" as const,
+ id: "child",
+ timestamp: "2025-01-01T00:00:01Z",
+ cwd: tempDir,
+ parentSession: parentFile,
+ };
+ writeFileSync(childFile, `${JSON.stringify(header)}\n`);
+
+ expect(resolveSessionRlmDepth(header, childFile)).toBe(2);
+ expect((await readSessionInfo(childFile))?.rlmDepth).toBe(2);
+ expect(JSON.parse(readFileSync(childFile, "utf8").split("\n")[0] ?? "{}").rlmDepth).toBeUndefined();
+
+ expect(SessionManager.open(childFile).getHeader()?.rlmDepth).toBe(2);
+ expect(JSON.parse(readFileSync(childFile, "utf8").split("\n")[0] ?? "{}").rlmDepth).toBe(2);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("copies and backfills a readable source depth for a legacy fork", async () => {
+ const tempDir = join(tmpdir(), `legacy-fork-source-depth-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const sourceFile = join(tempDir, "source.jsonl");
+ const forkFile = join(tempDir, "fork.jsonl");
+ writeFileSync(
+ sourceFile,
+ `${JSON.stringify({
+ type: "session",
+ id: "source",
+ timestamp: "2025-01-01T00:00:00Z",
+ cwd: tempDir,
+ rlmDepth: 2,
+ })}
+`,
+ );
+ const forkHeader = {
+ type: "session" as const,
+ id: "fork",
+ timestamp: "2025-01-01T00:00:01Z",
+ cwd: tempDir,
+ parentSession: sourceFile,
+ };
+ writeFileSync(
+ forkFile,
+ `${JSON.stringify(forkHeader)}
+`,
+ );
+
+ expect(resolveSessionRlmDepth(forkHeader, forkFile)).toBe(2);
+ expect((await readSessionInfo(forkFile))?.rlmDepth).toBe(2);
+ expect(JSON.parse(readFileSync(forkFile, "utf8").split("\n")[0] ?? "{}").rlmDepth).toBeUndefined();
+
+ expect(SessionManager.open(forkFile).getHeader()?.rlmDepth).toBe(2);
+ expect(JSON.parse(readFileSync(forkFile, "utf8").split("\n")[0] ?? "{}").rlmDepth).toBe(2);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("treats a legacy fork in the sessions directory as a root", async () => {
+ const tempDir = join(tmpdir(), `legacy-fork-depth-test-${Date.now()}-${Math.random()}`);
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ const forkFile = join(tempDir, "fork.jsonl");
+ const header = {
+ type: "session" as const,
+ id: "fork",
+ timestamp: "2025-01-01T00:00:01Z",
+ cwd: tempDir,
+ parentSession: join(tempDir, "source.jsonl"),
+ };
+ writeFileSync(forkFile, `${JSON.stringify(header)}\n`);
+
+ expect(resolveSessionRlmDepth(header, forkFile)).toBe(0);
+ expect((await readSessionInfo(forkFile))?.rlmDepth).toBe(0);
+ expect(SessionManager.open(forkFile).getHeader()?.rlmDepth).toBe(0);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("does not count a matching segment outside the trailing subagent path", () => {
+ const sessionFile = join(tmpdir(), "sub-deadbeef", "sessions", "child.jsonl");
+ expect(resolveSessionRlmDepth({ parentSession: "/missing-parent.jsonl" }, sessionFile)).toBe(0);
+ });
+
+ it("prefers the parent header depth over path inference", () => {
+ const tempDir = join(tmpdir(), `parent-header-depth-test-${Date.now()}-${Math.random()}`);
+ const parentFile = join(tempDir, "parent.jsonl");
+ const childFile = join(tempDir, "sub-1234abcd", "sub-deadbeef", "child.jsonl");
+ mkdirSync(tempDir, { recursive: true });
+ try {
+ writeFileSync(
+ parentFile,
+ `${JSON.stringify({
+ type: "session",
+ id: "parent",
+ timestamp: "2025-01-01T00:00:00Z",
+ cwd: tempDir,
+ rlmDepth: 4,
+ })}
+`,
+ );
+
+ expect(resolveSessionRlmDepth({ parentSession: parentFile }, childFile)).toBe(5);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("resolves relative parent paths from each legacy session directory", () => {
+ const tempDir = join(tmpdir(), `relative-parent-depth-test-${Date.now()}-${Math.random()}`);
+ const grandparentFile = join(tempDir, "grandparent.jsonl");
+ const parentFile = join(tempDir, "parent.jsonl");
+ const childDir = join(tempDir, "sub-1234abcd");
+ const childFile = join(childDir, "child.jsonl");
+ mkdirSync(childDir, { recursive: true });
+ try {
+ writeFileSync(
+ grandparentFile,
+ `${JSON.stringify({
+ type: "session",
+ id: "grandparent",
+ timestamp: "2025-01-01T00:00:00Z",
+ cwd: tempDir,
+ rlmDepth: 4,
+ })}
+`,
+ );
+ writeFileSync(
+ parentFile,
+ `${JSON.stringify({
+ type: "session",
+ id: "parent",
+ timestamp: "2025-01-01T00:00:01Z",
+ cwd: tempDir,
+ parentSession: "grandparent.jsonl",
+ })}
+`,
+ );
+
+ expect(resolveSessionRlmDepth({ parentSession: "../parent.jsonl" }, childFile)).toBe(5);
+ } finally {
+ rmSync(tempDir, { recursive: true, force: true });
+ }
+ });
+
+ it("prefers a valid persisted depth over path inference", () => {
+ const sessionFile = join(tmpdir(), "sub-1234abcd", "sub-deadbeef", "session.jsonl");
+ expect(resolveSessionRlmDepth({ parentSession: "/parent.jsonl", rlmDepth: 7 }, sessionFile)).toBe(7);
+ });
+});
+
describe("findMostRecentSession", () => {
let tempDir: string;