A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): /rlm-max-depth session command (#585)
Sebastian Müller5929ebee6004
diff --git a/packages/agent/src/agent-loop.ts b/packages/agent/src/agent-loop.tsindex aadffc8d7e..0d3d7376dd 100644--- a/packages/agent/src/agent-loop.ts+++ b/packages/agent/src/agent-loop.ts@@ -496,13 +496,6 @@ async function streamAssistantResponse(// Convert to LLM-compatible messages (AgentMessage[] → Message[])const llmMessages = await maybePromiseWithAbort(config.convertToLlm(messages), signal);- // Build LLM context- const llmContext: Context = {- systemPrompt: context.systemPrompt,- messages: llmMessages,- tools: context.tools,- };-const streamFunction = streamFn || streamSimple;// Resolve API key (important for expiring tokens)@@ -511,6 +504,13 @@ async function streamAssistantResponse(? await maybePromiseWithAbort(config.getApiKey(config.model.provider), signal): undefined) || config.apiKey;+ // Build LLM context immediately before starting the provider call.+ const llmContext: Context = {+ systemPrompt: config.getSystemPrompt?.() ?? context.systemPrompt,+ messages: llmMessages,+ tools: context.tools,+ };+const response = await maybePromiseWithAbort(streamFunction(config.model, llmContext, {...config,diff --git a/packages/agent/src/agent.ts b/packages/agent/src/agent.tsindex 56609d38ac..49156e001a 100644--- a/packages/agent/src/agent.ts+++ b/packages/agent/src/agent.ts@@ -487,6 +487,7 @@ export class Agent {shouldStopBeforeTurn: () => this.shouldStopBeforeTurn?.() ?? false,convertToLlm: this.convertToLlm,transformContext: this.transformContext,+ getSystemPrompt: () => this._state.systemPrompt,getApiKey: this.getApiKey,getSteeringMessages: async () => {if (skipInitialSteeringPoll) {diff --git a/packages/agent/src/types.ts b/packages/agent/src/types.tsindex a6788e6574..92f68a6570 100644--- a/packages/agent/src/types.ts+++ b/packages/agent/src/types.ts@@ -169,6 +169,9 @@ export interface AgentLoopConfig extends SimpleStreamOptions {*/transformContext?: (messages: AgentMessage[], signal?: AbortSignal) => Promise<AgentMessage[]>;+ /** Resolves the system prompt immediately before each LLM call. */+ getSystemPrompt?: () => string;+/*** Resolves an API key dynamically for each LLM call.*diff --git a/packages/agent/test/agent-loop.test.ts b/packages/agent/test/agent-loop.test.tsindex 1b3ca26377..f8745d0a08 100644--- a/packages/agent/test/agent-loop.test.ts+++ b/packages/agent/test/agent-loop.test.ts@@ -596,6 +596,59 @@ describe("agentLoop with AgentMessage", () => {expect(convertedMessages[0].role).toBe("user");});+ it("should resolve the system prompt after asynchronous API key lookup", async () => {+ let systemPrompt = "before lookup";+ let resolveApiKey: ((apiKey: string) => void) | undefined;+ const apiKey = new Promise<string>((resolve) => {+ resolveApiKey = resolve;+ });+ let markLookupStarted: (() => void) | undefined;+ const lookupStarted = new Promise<void>((resolve) => {+ markLookupStarted = resolve;+ });+ let providerSystemPrompt: string | undefined;+ const config: AgentLoopConfig = {+ model: createModel(),+ convertToLlm: identityConverter,+ getApiKey: async () => {+ markLookupStarted?.();+ return apiKey;+ },+ getSystemPrompt: () => systemPrompt,+ };+ const stream = agentLoop(+ [createUserMessage("Hello")],+ { systemPrompt: "fallback", messages: [], tools: [] },+ config,+ undefined,+ (_model, context, options) => {+ providerSystemPrompt = context.systemPrompt;+ expect(options?.apiKey).toBe("resolved key");+ const mockStream = new MockAssistantStream();+ queueMicrotask(() => {+ mockStream.push({+ type: "done",+ reason: "stop",+ message: createAssistantMessage([{ type: "text", text: "Response" }]),+ });+ });+ return mockStream;+ },+ );+ const consume = (async () => {+ for await (const _event of stream) {+ // consume+ }+ })();++ await lookupStarted;+ systemPrompt = "after lookup";+ resolveApiKey?.("resolved key");+ await consume;++ expect(providerSystemPrompt).toBe("after lookup");+ });+it("should apply transformContext before convertToLlm", async () => {const context: AgentContext = {systemPrompt: "You are helpful.",diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 8ceb35940e..71cd9e600a 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -872,6 +872,14 @@ type GoalSlashCommand =type AutonomousSlashCommand = { kind: "status" } | { kind: "on" } | { kind: "off" };+import type { RlmMaxDepthSource, RlmMaxDepthStatus, SetRlmMaxDepthResult } from "./rlm-max-depth.js";++export type { RlmMaxDepthSource, RlmMaxDepthStatus, SetRlmMaxDepthResult } from "./rlm-max-depth.js";++interface PersistedRlmMaxDepthState {+ maxDepth: number;+}+type AutonomousRuntimeSnapshot = Pick<AutonomousRuntimeState,"continuationsUsed" | "gateAttempts" | "lastGateFailure" | "lastGateFailureSnapshot"@@ -914,6 +922,7 @@ const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "hi/** Cap on the post-compaction kernel namespace probe so a wedged kernel can't stall recovery. */const KERNEL_STATE_LISTING_TIMEOUT_MS = 5000;+const RLM_MAX_DEPTH_STATE_CUSTOM_TYPE = "rlm_max_depth_state";function noopRlmChildAbort(): void {}@@ -929,17 +938,30 @@ Reviewer instructions: ${review.instructions}`return `Automatic refine review triggered by ${reason}. Only create/update/delete local harness entries if there is clear evidence that should help this session continue. Prefer an empty edits array over speculative or one-off memories. Do not promote anything global unless explicitly requested. Reviewer rationale: ${review.rationale}${detail}`;}+function isNonNegativeInteger(value: unknown): value is number {+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;+}+function parseDepth(value: string | undefined, fallback: number, name: string): number {if (value === undefined || value === "") {return fallback;}- const parsed = Number.parseInt(value, 10);- if (!Number.isFinite(parsed) || parsed < 0) {+ if (!/^\d+$/.test(value)) {+ throw new Error(`${name} must be a non-negative integer`);+ }+ const parsed = Number(value);+ if (!isNonNegativeInteger(parsed)) {throw new Error(`${name} must be a non-negative integer`);}return parsed;}+function isPersistedRlmMaxDepthState(value: unknown): value is PersistedRlmMaxDepthState {+ return (+ typeof value === "object" && value !== null && isNonNegativeInteger((value as PersistedRlmMaxDepthState).maxDepth)+ );+}+function parseGoalBudgetValue(value: string): number {if (!/^[1-9]\d*$/.test(value)) {throw new Error("Goal token budget must be a positive integer.");@@ -1142,7 +1164,9 @@ export class AgentSession {private _ipythonRuntimeBuilt = false;private readonly _prewarmIpythonKernel: boolean;private _rlmDepth: number;+ private readonly _configuredRlmMaxDepth: number | undefined;private _rlmMaxDepth: number;+ private _rlmMaxDepthSource: RlmMaxDepthSource;private _rlmSessionDir?: string;private _rlmParentNodeId?: string;private _subagentRuntimeHost?: SubagentRuntimeHost;@@ -1235,7 +1259,13 @@ export class AgentSession {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._configuredRlmMaxDepth = config.rlmMaxDepth;+ if (this._configuredRlmMaxDepth !== undefined && !isNonNegativeInteger(this._configuredRlmMaxDepth)) {+ throw new Error("rlmMaxDepth must be a non-negative integer");+ }+ const resolvedRlmMaxDepth = this._resolveRlmMaxDepth();+ this._rlmMaxDepth = resolvedRlmMaxDepth.maxDepth;+ this._rlmMaxDepthSource = resolvedRlmMaxDepth.source;this._prewarmIpythonKernel = (config.prewarmIpythonKernel ?? false) && this._rlmDepth === 0;this._autoRefineReviewer = config.autoRefineReviewer;this._serializedRefine = config.serializedRefine ?? false;@@ -1467,6 +1497,43 @@ export class AgentSession {this._emit({ type: "goal_update", goal: this.goalState });}+ private _loadPersistedRlmMaxDepthState(): PersistedRlmMaxDepthState | undefined {+ const branch = this.sessionManager.getBranch();+ for (let i = branch.length - 1; i >= 0; i--) {+ const entry = branch[i];+ if (+ entry.type === "custom" &&+ entry.customType === RLM_MAX_DEPTH_STATE_CUSTOM_TYPE &&+ isPersistedRlmMaxDepthState(entry.data)+ ) {+ return entry.data;+ }+ }+ return undefined;+ }++ private _resolveRlmMaxDepth(): { maxDepth: number; source: RlmMaxDepthSource } {+ const persisted = this._loadPersistedRlmMaxDepthState();+ if (persisted) {+ return { maxDepth: persisted.maxDepth, source: "chat" };+ }+ if (this._configuredRlmMaxDepth !== undefined) {+ return { maxDepth: this._configuredRlmMaxDepth, source: "inherited" };+ }+ const global = this.settingsManager.getRlmMaxDepth();+ if (global !== undefined) {+ if (!isNonNegativeInteger(global)) {+ throw new Error("The rlmMaxDepth setting must be a non-negative integer");+ }+ return { maxDepth: global, source: "global" };+ }+ const env = process.env.RLM_MAX_DEPTH;+ if (env !== undefined && env !== "") {+ return { maxDepth: parseDepth(env, 1, "RLM_MAX_DEPTH"), source: "env" };+ }+ return { maxDepth: 1, source: "default" };+ }+private _loadPersistedGoalState(): GoalState {const branch = this.sessionManager.getBranch();for (let i = branch.length - 1; i >= 0; i--) {@@ -1516,6 +1583,17 @@ export class AgentSession {this._emitGoalUpdate();}+ private _reloadRlmMaxDepthFromBranch(): void {+ const previousMaxDepth = this._rlmMaxDepth;+ const resolved = this._resolveRlmMaxDepth();+ this._rlmMaxDepth = resolved.maxDepth;+ this._rlmMaxDepthSource = resolved.source;+ if (resolved.maxDepth !== previousMaxDepth) {+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());+ this.agent.state.systemPrompt = this._baseSystemPrompt;+ }+ }+private _persistGoalState(goal: GoalState): void {this.sessionManager.appendCustomEntry(GOAL_STATE_CUSTOM_TYPE, goal);// Force flush so the goal state is durable on disk immediately,@@ -3998,6 +4076,11 @@ export class AgentSession {return this._rlmDepth;}+ /** Current absolute RLM spawn-depth cap. */+ get rlmMaxDepth(): number {+ return this._rlmMaxDepth;+ }+/** Current session display name, if set */get sessionName(): string | undefined {return this.sessionManager.getSessionName();@@ -8422,6 +8505,8 @@ export class AgentSession {}private _rlmKernelEnv(): Record<string, string> {+ // Kernel env is provisioning-time only: RLM_MAX_DEPTH may be stale in an already-running kernel;+ // the TypeScript-side spawn check remains authoritative.const env: Record<string, string> = {RLM_DEPTH: String(this._rlmDepth),RLM_MAX_DEPTH: String(this._rlmMaxDepth),@@ -10072,9 +10157,40 @@ export class AgentSession {// Session Management// =========================================================================- /**- * Set a display name for the current session.- */+ /** Current RLM max-depth value and the source that supplied it. */+ getRlmMaxDepthStatus(): RlmMaxDepthStatus {+ return { maxDepth: this._rlmMaxDepth, source: this._rlmMaxDepthSource };+ }++ /** Persist and immediately apply a per-chat RLM max-depth override. */+ async setRlmMaxDepth(maxDepth: number, options: { global?: boolean } = {}): Promise<SetRlmMaxDepthResult> {+ if (!isNonNegativeInteger(maxDepth)) {+ throw new Error("RLM max depth must be a non-negative integer.");+ }++ this.sessionManager.appendCustomEntryWithRollback(RLM_MAX_DEPTH_STATE_CUSTOM_TYPE, { maxDepth });+ this._rlmMaxDepth = maxDepth;+ this._rlmMaxDepthSource = "chat";+ const oldBase = this._baseSystemPrompt;+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());+ this.agent.state.systemPrompt = this._refreshExtensionSystemPrompt(this.agent.state.systemPrompt, oldBase);++ let globalError: string | undefined;+ if (options.global) {+ this.settingsManager.setRlmMaxDepth(maxDepth);+ await this.settingsManager.flush();+ const errors = this.settingsManager.drainErrors().filter(({ scope }) => scope === "global");+ globalError = errors.map(({ error }) => error.message).join("; ") || undefined;+ }++ return {+ ...this.getRlmMaxDepthStatus(),+ globalSaved: options.global === true && globalError === undefined,+ ...(globalError ? { globalError } : {}),+ };+ }++ /** Set a display name for the current session. */setSessionName(name: string): void {this.sessionManager.appendSessionInfo(name);this._emit({ type: "session_info_changed", name: this.sessionManager.getSessionName() });@@ -10315,6 +10431,7 @@ export class AgentSession {this._mergeUnpersistedCompactionOutcomes(this.agent.state.messages);this._restoreLateIpythonSentAgentMessages();this._reloadGoalStateFromBranch();+ this._reloadRlmMaxDepthFromBranch();this._invalidateQueuedPromptPreparation();// Emit session_tree eventdiff --git a/packages/coding-agent/src/core/rlm-max-depth.ts b/packages/coding-agent/src/core/rlm-max-depth.tsnew file mode 100644index 0000000000..e51e6f65b9--- /dev/null+++ b/packages/coding-agent/src/core/rlm-max-depth.ts@@ -0,0 +1,13 @@+/** Wire-safe types for the immediate /rlm-max-depth state APIs. */++export type RlmMaxDepthSource = "default" | "env" | "global" | "inherited" | "chat";++export interface RlmMaxDepthStatus {+ maxDepth: number;+ source: RlmMaxDepthSource;+}++export interface SetRlmMaxDepthResult extends RlmMaxDepthStatus {+ globalSaved: boolean;+ globalError?: string;+}diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex 769b60a1b4..cfbfaa1660 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -1576,6 +1576,11 @@ export class SessionManager {return entry.id;}+ /** Append a custom entry and undo its in-memory index if persistence fails. */+ appendCustomEntryWithRollback(customType: string, data?: unknown): string {+ return this._appendEntryWithRollback(() => this.appendCustomEntry(customType, data));+ }+/** Append an RLM child usage attribution and update the parent assistant aggregate in memory. */appendChildUsageAttribution(targetId: string, childUsage: Usage, aggregateUsage: Usage): string {const target = this.byId.get(targetId);@@ -1780,9 +1785,13 @@ export class SessionManager {display: boolean,details?: T,): string {+ return this._appendEntryWithRollback(() => this.appendCustomMessageEntry(customType, content, display, details));+ }++ private _appendEntryWithRollback(append: () => string): string {const previousLeafId = this.leafId;try {- const entryId = this.appendCustomMessageEntry(customType, content, display, details);+ const entryId = append();this.flushNow();return entryId;} catch (error) {diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.tsindex 5230b109c1..a6458508af 100644--- a/packages/coding-agent/src/core/settings-manager.ts+++ b/packages/coding-agent/src/core/settings-manager.ts@@ -126,6 +126,7 @@ export interface Settings {recentModels?: string[]; // "provider/id" keys, most-recently-used firstdefaultThinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";defaultServiceTier?: ServiceTier;+ rlmMaxDepth?: number; // default for new sessions; unset falls through to RLM_MAX_DEPTH, then 1transport?: TransportSetting; // default: "auto"steeringMode?: "all" | "one-at-a-time";followUpMode?: "all" | "one-at-a-time";@@ -579,6 +580,12 @@ export class SettingsManager {this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);if (this.globalSettingsLoadError) {+ this.recordError(+ "global",+ new Error(+ `Global settings not saved: settings file failed to parse: ${this.globalSettingsLoadError.message}`,+ ),+ );return;}@@ -596,6 +603,12 @@ export class SettingsManager {this.settings = deepMergeSettings(this.globalSettings, this.projectSettings);if (this.projectSettingsLoadError) {+ this.recordError(+ "project",+ new Error(+ `Project settings not saved: settings file failed to parse: ${this.projectSettingsLoadError.message}`,+ ),+ );return;}@@ -731,6 +744,16 @@ export class SettingsManager {this.save();}+ getRlmMaxDepth(): number | undefined {+ return this.globalSettings.rlmMaxDepth;+ }++ setRlmMaxDepth(maxDepth: number): void {+ this.globalSettings.rlmMaxDepth = maxDepth;+ this.markModified("rlmMaxDepth");+ this.save();+ }+getTransport(): TransportSetting {return this.settings.transport ?? "auto";}diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.tsindex 3e96827997..a3478361b3 100644--- a/packages/coding-agent/src/core/slash-commands.ts+++ b/packages/coding-agent/src/core/slash-commands.ts@@ -171,6 +171,13 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [argumentHint: "[status|on|off]",takesArgument: true,},+ {+ name: "rlm-max-depth",+ description:+ "Set/view the per-chat persistent RLM max depth immediately; never interrupts or queues the running turn",+ argumentHint: "[<int> [--global]]",+ takesArgument: true,+ },{name: "heartbeat",description:diff --git a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.tsindex a739407c47..a1a20e995f 100644--- a/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/daemon-agent-connection.ts@@ -1246,6 +1246,27 @@ export class DaemonAgentConnection implements AgentConnection {await this.requestOk({ type: "set_session_name", activeSessionId: this.activeSessionId, name });}+ async getRlmMaxDepthStatus() {+ return this.requestData<{ maxDepth: number; source: "default" | "env" | "global" | "inherited" | "chat" }>({+ type: "get_rlm_max_depth_status",+ activeSessionId: this.activeSessionId,+ });+ }++ async setRlmMaxDepth(maxDepth: number, options?: { global?: boolean }) {+ return this.requestData<{+ maxDepth: number;+ source: "default" | "env" | "global" | "inherited" | "chat";+ globalSaved: boolean;+ globalError?: string;+ }>({+ type: "set_rlm_max_depth",+ activeSessionId: this.activeSessionId,+ maxDepth,+ global: options?.global,+ });+ }+async renameSavedSession(sessionPath: string, name: string): Promise<void> {await renameDaemonSavedSession(this.client, { activeSessionId: this.activeSessionId }, sessionPath, name);}diff --git a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.tsindex 8b566b1726..4170bf082a 100644--- a/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts+++ b/packages/coding-agent/src/modes/agent-connection/in-process-agent-connection.ts@@ -529,6 +529,14 @@ export class InProcessAgentConnection implements AgentConnection {this.session.setSessionName(trimmedName);}+ async getRlmMaxDepthStatus() {+ return this.session.getRlmMaxDepthStatus();+ }++ async setRlmMaxDepth(maxDepth: number, options?: { global?: boolean }) {+ return this.session.setRlmMaxDepth(maxDepth, options);+ }+async renameSavedSession(sessionPath: string, name: string): Promise<void> {const trimmedName = name.trim();if (!trimmedName) {diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex d1f6bc7c93..ed3899a40f 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -21,6 +21,7 @@ import type { InputSource } from "../../core/extensions/types.js";import type { GoalState } from "../../core/goals.js";import type { KernelSentAgentMessage } from "../../core/kernel/index.js";import type { RefinementResult } from "../../core/refinement/index.js";+import type { RlmMaxDepthStatus, SetRlmMaxDepthResult } from "../../core/rlm-max-depth.js";import type { SessionActionSnapshot } from "../../core/session-action-store.js";import type { DeleteSessionFileResult } from "../../core/session-file-actions.js";import type { SessionStats } from "../../core/session-stats.js";@@ -730,6 +731,8 @@ export interface AgentConnection {exportToHtml(outputPath?: string): Promise<string>;exportToJsonl(outputPath?: string): Promise<string>;setSessionName(name: string): Promise<void>;+ getRlmMaxDepthStatus(): Promise<RlmMaxDepthStatus>;+ setRlmMaxDepth(maxDepth: number, options?: { global?: boolean }): Promise<SetRlmMaxDepthResult>;renameSavedSession(sessionPath: string, name: string): Promise<void>;deleteSavedSession(sessionPath: string): Promise<DeleteSessionFileResult>;diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 91cc1389fa..d2f54c385d 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -294,6 +294,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["export_html","export_jsonl","set_session_name",+ "get_rlm_max_depth_status",+ "set_rlm_max_depth","rename_saved_session","delete_saved_session","get_session_context",@@ -2380,7 +2382,7 @@ export class AgentDaemon {rlmDepth: existsSync(entry.sessionFile)? resolveSessionRlmDepth(sessionManager.getHeader() ?? {}, entry.sessionFile): undefined,- rlmMaxDepth: entry.rlmMaxDepth ?? 1,+ rlmMaxDepth: entry.rlmMaxDepth,rlmParentNodeId: entry.rlmParentNodeId ?? entry.childId,},runtimeMetadata: {@@ -3924,6 +3926,17 @@ export class AgentDaemon {return success(command.id, "set_session_name");}+ case "get_rlm_max_depth_status": {+ const state = this.getSessionState(command.activeSessionId);+ return success(command.id, "get_rlm_max_depth_status", state.runtime.session.getRlmMaxDepthStatus());+ }++ case "set_rlm_max_depth": {+ const state = this.getSessionState(command.activeSessionId);+ const result = await state.runtime.session.setRlmMaxDepth(command.maxDepth, { global: command.global });+ return success(command.id, "set_rlm_max_depth", result);+ }+case "get_session_context": {const state = this.getSessionState(command.activeSessionId);return success(command.id, "get_session_context", {diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 7440e217fc..9c5a73ca89 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -53,8 +53,9 @@ 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.// 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";+// Revision 11 adds immediate get/set commands for active-session RLM max depth.+export const DAEMON_SCHEMA_REVISION = 11;+export const DAEMON_SCHEMA_ID = "protocol-7-schema-11-5bd6b0b12204";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;@@ -570,6 +571,8 @@ export type DaemonCommand =| { id?: string; type: "export_html"; activeSessionId: string; outputPath?: string }| { id?: string; type: "export_jsonl"; activeSessionId: string; outputPath?: string }| { id?: string; type: "set_session_name"; activeSessionId: string; name: string }+ | { id?: string; type: "get_rlm_max_depth_status"; activeSessionId: string }+ | { id?: string; type: "set_rlm_max_depth"; activeSessionId: string; maxDepth: number; global?: boolean }| { id?: string; type: "rename_saved_session"; activeSessionId?: string; sessionPath: string; name: string }| { id?: string; type: "delete_saved_session"; activeSessionId?: string; sessionPath: string }| { id?: string; type: "get_session_context"; activeSessionId: string }@@ -602,6 +605,7 @@ export interface DaemonCommandCompatibility {const LEGACY_DAEMON_COMMAND = { minProtocol: 7 } as const;const CURRENT_DAEMON_COMMAND = { minProtocol: 7 } as const;+const RLM_MAX_DEPTH_COMMAND = { minProtocol: 7, minSchemaRevision: 11 } as const;const SESSION_INPUT_ADMISSION_COMMAND = {minProtocol: 7,capability: "session_input_admission",@@ -698,6 +702,8 @@ export const DAEMON_COMMAND_COMPATIBILITY = {export_html: LEGACY_DAEMON_COMMAND,export_jsonl: LEGACY_DAEMON_COMMAND,set_session_name: LEGACY_DAEMON_COMMAND,+ get_rlm_max_depth_status: RLM_MAX_DEPTH_COMMAND,+ set_rlm_max_depth: RLM_MAX_DEPTH_COMMAND,rename_saved_session: LEGACY_DAEMON_COMMAND,delete_saved_session: LEGACY_DAEMON_COMMAND,get_session_context: LEGACY_DAEMON_COMMAND,@@ -1012,6 +1018,7 @@ const READ_ONLY_DAEMON_COMMANDS: ReadonlySet<DaemonCommand["type"]> = new Set(["get_user_messages_for_forking","get_last_assistant_text","get_system_prompt",+ "get_rlm_max_depth_status","get_tool_definition",]);diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex 99557d8173..54581b4274 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -202,6 +202,8 @@ const DAEMON_COMMAND_TYPES: ReadonlySet<string> = new Set(["export_html","export_jsonl","set_session_name",+ "get_rlm_max_depth_status",+ "set_rlm_max_depth","rename_saved_session","delete_saved_session","get_session_context",diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 1cd07b516e..c1ca3decb3 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -4737,6 +4737,11 @@ export class InteractiveMode {this.editor.setText("");return;}+ if (commandName === "rlm-max-depth") {+ this.editor.setText("");+ await this.handleRlmMaxDepthCommand(commandArgs);+ return;+ }if (commandName === "session" && !commandArgs) {this.echoLocalCommand(text);await this.handleSessionCommand();@@ -9128,6 +9133,57 @@ export class InteractiveMode {this.ui.requestRender();}+ private async handleRlmMaxDepthCommand(args: string): Promise<void> {+ const tokens = args ? args.split(/\s+/) : [];+ if (tokens.length === 0) {+ try {+ const status = await this.agentConnection.getRlmMaxDepthStatus();+ this.chatContainer.addChild(new Spacer(1));+ this.chatContainer.addChild(+ new Text(theme.fg("dim", `RLM max depth: ${status.maxDepth} (${status.source})`), 1, 0),+ );+ this.ui.requestRender();+ } catch (error) {+ this.showError(error instanceof Error ? error.message : String(error));+ }+ return;+ }++ const global = tokens[1] === "--global";+ if (tokens.length > (global ? 2 : 1) || !/^\d+$/.test(tokens[0] ?? "")) {+ this.showWarning("Usage: /rlm-max-depth [<non-negative integer> [--global]]");+ return;+ }+ const maxDepth = Number(tokens[0]);+ if (!Number.isSafeInteger(maxDepth)) {+ this.showWarning("RLM max depth must be a non-negative integer.");+ return;+ }++ try {+ const result = await this.agentConnection.setRlmMaxDepth(maxDepth, { global });+ this.chatContainer.addChild(new Spacer(1));+ this.chatContainer.addChild(+ new Text(+ theme.fg(+ "dim",+ `RLM max depth set: ${result.maxDepth}${result.globalSaved ? " and saved as global default" : ""}`,+ ),+ 1,+ 0,+ ),+ );+ this.ui.requestRender();+ if (result.globalError) {+ this.showError(+ `RLM max depth set for this chat, but the global default was not saved: ${result.globalError}`,+ );+ }+ } catch (error) {+ this.showError(error instanceof Error ? error.message : String(error));+ }+ }+private async handleSessionCommand(): Promise<void> {const stats = await this.agentConnection.getSessionStats();const sessionName = this.getCurrentSessionName();diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex aa10efd206..c89673ea29 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -232,12 +232,13 @@ describe("AgentSession rlm recursion", () => {subagentRuntimeHost?: SubagentRuntimeHost;rlmSessionDir?: string;sessionManager?: SessionManager;+ settingsManager?: SettingsManager;} = {},): AgentSession {const authStorage = AuthStorage.create(join(tempDir, "auth.json"));authStorage.setRuntimeApiKey("anthropic", "test-key");const sessionManager = options.sessionManager ?? SessionManager.create(tempDir, join(tempDir, "sessions"));- const settingsManager = SettingsManager.create(tempDir, tempDir);+ const settingsManager = options.settingsManager ?? SettingsManager.create(tempDir, tempDir);const agent = new Agent({convertToLlm,@@ -832,6 +833,177 @@ describe("AgentSession rlm recursion", () => {expect(reloadedParentEntry.message.usage.cost.total).toBe(10);});+ it("gets and persists per-chat max-depth changes without transcript messages", async () => {+ const root = createSession();+ const originalMessages = [...root.messages];++ expect(root.getRlmMaxDepthStatus()).toEqual({ maxDepth: 1, source: "default" });+ await expect(root.setRlmMaxDepth(-1)).rejects.toThrow("non-negative integer");+ await root.setRlmMaxDepth(3);++ expect(root.getRlmMaxDepthStatus()).toEqual({ maxDepth: 3, source: "chat" });+ expect(root.messages).toEqual(originalMessages);+ const stateEntries = root.sessionManager+ .getBranch()+ .filter((entry) => entry.type === "custom" && entry.customType === "rlm_max_depth_state");+ expect(stateEntries.at(-1)).toMatchObject({ data: { maxDepth: 3 } });+ });++ it("applies max-depth immediately while a turn streams without aborting or entering the transcript", async () => {+ let releaseTurn!: () => void;+ const release = new Promise<void>((resolve) => {+ releaseTurn = resolve;+ });+ let turnStarted = false;+ const root = createSession({+ streamFn: () => {+ const stream = createAssistantMessageEventStream();+ turnStarted = true;+ void release.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("finished normally") });+ });+ return stream;+ },+ });++ const promptPromise = root.prompt("keep streaming");+ await waitFor(() => turnStarted);+ const messagesBeforeSet = [...root.messages];+ await root.setRlmMaxDepth(2);+ expect(root.rlmMaxDepth).toBe(2);+ expect(root.messages).toEqual(messagesBeforeSet);+ expect(root.isStreaming).toBe(true);++ releaseTurn();+ await promptPromise;+ await root.agent.waitForIdle();+ expect(root.messages.at(-1)).toMatchObject({ role: "assistant", stopReason: "stop" });+ });++ it("uses a max-depth prompt update on the next turn of the active run", async () => {+ let releaseFirstTurn = () => {};+ const firstTurnPending = new Promise<void>((resolve) => {+ releaseFirstTurn = resolve;+ });+ const seenSystemPrompts: string[] = [];+ const root = createSession({+ streamFn: (_model, context) => {+ seenSystemPrompts.push(context.systemPrompt ?? "");+ if (seenSystemPrompts.length === 1) {+ const stream = createAssistantMessageEventStream();+ void firstTurnPending.then(() => {+ stream.push({ type: "done", reason: "stop", message: assistantMessage("first turn") });+ });+ return stream;+ }+ return streamAnswer("second turn");+ },+ });++ const promptPromise = root.prompt("start");+ await waitFor(() => seenSystemPrompts.length === 1);+ expect(seenSystemPrompts[0]!).toContain("A callable `rlm`");++ await root.setRlmMaxDepth(0);+ await root.steer("continue after max-depth update");+ releaseFirstTurn();+ await promptPromise;++ expect(seenSystemPrompts).toHaveLength(2);+ expect(seenSystemPrompts[1]!).not.toContain("A callable `rlm`");+ });++ it("rehydrates chat max depth ahead of reconstruction config", async () => {+ const root = createSession();+ await root.setRlmMaxDepth(3);+ if (!root.sessionFile) throw new Error("Missing persisted session file");+ const sessionFile = root.sessionFile;+ root.dispose();++ const resumedManager = SessionManager.open(sessionFile, join(tempDir, "sessions"));+ const resumed = createSession({ sessionManager: resumedManager, maxDepth: 4 });+ expect(resumed.getRlmMaxDepthStatus()).toEqual({ maxDepth: 3, source: "chat" });+ });++ it("reloads max depth and its source when navigating to a branch without an override", async () => {+ vi.stubEnv("RLM_MAX_DEPTH", "0");+ try {+ const root = createSession();+ await root.prompt("baseline branch");+ await root.agent.waitForIdle();+ const baselineLeafId = root.sessionManager.getLeafId();+ if (!baselineLeafId) throw new Error("Missing baseline branch leaf");++ await root.setRlmMaxDepth(2);+ expect(root.systemPrompt).toContain("A callable `rlm`");+ await root.navigateTree(baselineLeafId, { summarize: false });+ expect(root.getRlmMaxDepthStatus()).toEqual({ maxDepth: 0, source: "env" });+ expect(root.systemPrompt).not.toContain("A callable `rlm`");+ } finally {+ vi.unstubAllEnvs();+ }+ });++ it("applies --global to this chat and new sessions without changing existing sessions", async () => {+ const current = createSession();+ const existingSettings = SettingsManager.create(tempDir, tempDir);+ const existing = createSession({ settingsManager: existingSettings });++ await expect(current.setRlmMaxDepth(4, { global: true })).resolves.toMatchObject({+ maxDepth: 4,+ source: "chat",+ globalSaved: true,+ });+ expect(existing.rlmMaxDepth).toBe(1);+ const freshSettings = SettingsManager.create(tempDir, tempDir);+ const fresh = createSession({ settingsManager: freshSettings });+ expect(fresh.getRlmMaxDepthStatus()).toEqual({ maxDepth: 4, source: "global" });+ current.dispose();+ existing.dispose();+ });++ it("keeps a spawned child's chat override when reconstructed with its inherited config", async () => {+ const root = createSession({ maxDepth: 2 });+ const childResult = await root.runRlmChild("child with a durable override");+ if (!childResult.session_dir) throw new Error("Missing child session directory");+ const child = root.getRlmChildSession(basename(childResult.session_dir));+ if (!child?.sessionFile) throw new Error("Missing persisted child session");++ expect(child.getRlmMaxDepthStatus()).toEqual({ maxDepth: 2, source: "inherited" });+ await child.setRlmMaxDepth(3);+ const childSessionFile = child.sessionFile;+ root.dispose();++ const rehydratedManager = SessionManager.open(childSessionFile, join(tempDir, "sessions"));+ const rehydratedChild = createSession({ sessionManager: rehydratedManager, depth: 1, maxDepth: 2 });+ expect(rehydratedChild.getRlmMaxDepthStatus()).toEqual({ maxDepth: 3, source: "chat" });+ });++ it("copies live max depth at spawn, keeps child overrides independent, and lets zero disable root spawning", async () => {+ const root = createSession();+ await root.setRlmMaxDepth(2);+ const childResult = await root.runRlmChild("first child");+ if (!childResult.session_dir) throw new Error("Missing child session directory");+ const child = root.getRlmChildSession(basename(childResult.session_dir));+ if (!child) throw new Error("Missing retained child session");+ expect(child.rlmMaxDepth).toBe(2);++ await child.setRlmMaxDepth(3);+ expect((child as unknown as InspectableRlmDirSession)._rlmKernelEnv().RLM_MAX_DEPTH).toBe("3");+ expect(root.rlmMaxDepth).toBe(2);+ const grandchildResult = await child.runRlmChild("grandchild after override");+ if (!grandchildResult.session_dir) throw new Error("Missing grandchild session directory");+ const grandchild = child.getRlmChildSession(basename(grandchildResult.session_dir));+ expect(grandchild?.rlmMaxDepth).toBe(3);++ await root.setRlmMaxDepth(0);+ expect(root.systemPrompt).not.toContain("A callable `rlm`");+ await expect(root.runRlmChild("blocked at root")).rejects.toThrow(+ "RLM recursion depth limit reached (RLM_DEPTH=0, RLM_MAX_DEPTH=0)",+ );+ expect(child.rlmMaxDepth).toBe(3);+ });+it("rejects child creation at the configured recursion depth cap", async () => {const root = createSession({ depth: 1, maxDepth: 1 });diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex ff47a5e240..4b9435becc 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -4868,6 +4868,45 @@ describe("daemon mode helpers", () => {});});+ it("gets and sets RLM max depth directly on the active session", async () => {+ const daemon = new AgentDaemon("/tmp/prime-agent-test.sock", {+ defaultSessionConfig: { agentDir: "/tmp/prime-agent-test-agent", cwd: "/tmp" },+ createRuntime: async () => {+ throw new Error("unexpected runtime creation");+ },+ });+ const getRlmMaxDepthStatus = vi.fn(() => ({ maxDepth: 2, source: "chat" as const }));+ const setRlmMaxDepth = vi.fn(async () => ({+ maxDepth: 3,+ source: "chat" as const,+ globalSaved: true,+ }));+ const state = makeState("active-1") as ActiveSessionState;+ (state.runtime as { session: unknown }).session = { getRlmMaxDepthStatus, setRlmMaxDepth };+ const internals = daemon as unknown as {+ sessions: Map<string, ActiveSessionState>;+ handleCommand(client: DaemonSocketClient, command: DaemonCommand): Promise<unknown>;+ };+ internals.sessions.set(state.activeSessionId, state);+ const client = makeClient("client-1", state.activeSessionId);++ await expect(+ internals.handleCommand(client, {+ type: "get_rlm_max_depth_status",+ activeSessionId: state.activeSessionId,+ }),+ ).resolves.toMatchObject({ success: true, data: { maxDepth: 2, source: "chat" } });+ await expect(+ internals.handleCommand(client, {+ type: "set_rlm_max_depth",+ activeSessionId: state.activeSessionId,+ maxDepth: 3,+ global: true,+ }),+ ).resolves.toMatchObject({ success: true, data: { maxDepth: 3, globalSaved: true } });+ expect(setRlmMaxDepth).toHaveBeenCalledWith(3, { global: true });+ });+it.each([{name: "defers busy heartbeat cron jobs instead of queueing a follow-up",diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.tsindex abbdec1bb8..870e226234 100644--- a/packages/coding-agent/test/daemon-protocol.test.ts+++ b/packages/coding-agent/test/daemon-protocol.test.ts@@ -75,6 +75,11 @@ describe("daemon protocol helpers", () => {expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");});+ it("schema-gates the RLM max depth commands at their introducing revision", () => {+ expect(DAEMON_COMMAND_COMPATIBILITY.get_rlm_max_depth_status).toEqual({ minProtocol: 7, minSchemaRevision: 11 });+ expect(DAEMON_COMMAND_COMPATIBILITY.set_rlm_max_depth).toEqual({ minProtocol: 7, minSchemaRevision: 11 });+ });+it("version- and capability-gates prompt admission cancellation", () => {expect(DAEMON_COMMAND_COMPATIBILITY.cancel_prompt_admission).toEqual({minProtocol: 7,diff --git a/packages/coding-agent/test/interactive-mode-rlm-max-depth-command.test.ts b/packages/coding-agent/test/interactive-mode-rlm-max-depth-command.test.tsnew file mode 100644index 0000000000..d5350b5e0d--- /dev/null+++ b/packages/coding-agent/test/interactive-mode-rlm-max-depth-command.test.ts@@ -0,0 +1,125 @@+import { Container } from "@earendil-works/pi-tui";+import { beforeAll, describe, expect, it, vi } from "vitest";+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";+import { initTheme } from "../src/modes/interactive/theme/theme.js";++type Context = {+ agentConnection: {+ getRlmMaxDepthStatus: () => Promise<{ maxDepth: number; source: "chat" }>;+ setRlmMaxDepth: (+ maxDepth: number,+ options?: { global?: boolean },+ ) => Promise<{ maxDepth: number; source: "chat"; globalSaved: boolean; globalError?: string }>;+ };+ chatContainer: Container;+ ui: { requestRender: () => void };+ showWarning: (message: string) => void;+ showError: (message: string) => void;+};++type SubmitContext = {+ defaultEditor: { onSubmit?: (text: string) => Promise<void> };+ editor: { getText: () => string; setText: (text: string) => void };+ handleRlmMaxDepthCommand: (args: string) => Promise<void>;+ [key: string]: unknown;+};++type Prototype = {+ handleRlmMaxDepthCommand(this: Context, args: string): Promise<void>;+ setupEditorSubmitHandler(this: SubmitContext): void;+};++const prototype = InteractiveMode.prototype as unknown as Prototype;++function renderAll(container: Container, width = 120): string {+ return container.children+ .flatMap((child) => child.render(width))+ .join("\n")+ .replace(/\u001b\[[0-9;]*m/g, "");+}++function makeContext(overrides: Partial<Context["agentConnection"]> = {}): Context {+ return {+ agentConnection: {+ getRlmMaxDepthStatus: vi.fn(async () => ({ maxDepth: 2, source: "chat" as const })),+ setRlmMaxDepth: vi.fn(async (maxDepth, options) => ({+ maxDepth,+ source: "chat" as const,+ globalSaved: options?.global === true,+ })),+ ...overrides,+ },+ chatContainer: new Container(),+ ui: { requestRender: vi.fn() },+ showWarning: vi.fn(),+ showError: vi.fn(),+ };+}++describe("InteractiveMode /rlm-max-depth", () => {+ beforeAll(() => initTheme("dark"));++ it("does not erase input typed while the command RPC is pending", async () => {+ let editorText = "";+ let resolveCommand = () => {};+ const commandPending = new Promise<void>((resolve) => {+ resolveCommand = resolve;+ });+ const submitContext = {+ defaultEditor: {},+ editor: {+ getText: () => editorText,+ setText: (text: string) => {+ editorText = text;+ },+ },+ handleRlmMaxDepthCommand: vi.fn(() => commandPending),+ submittedInputBehavior: "steer",+ inputSubmissionGeneration: 0,+ inputSubmissionsPending: 0,+ pendingPromptStashReleases: [],+ promptStashState: {},+ clearShortcutGuide: vi.fn(),+ } as unknown as SubmitContext;+ prototype.setupEditorSubmitHandler.call(submitContext);++ const submission = submitContext.defaultEditor.onSubmit?.("/rlm-max-depth 3");+ await vi.waitFor(() => expect(submitContext.handleRlmMaxDepthCommand).toHaveBeenCalledWith("3"));+ editorText = "new draft";+ resolveCommand();+ await submission;++ expect(editorText).toBe("new draft");+ });++ it("shows current state as a dim one-liner through the immediate connection API", async () => {+ const context = makeContext();+ await prototype.handleRlmMaxDepthCommand.call(context, "");+ expect(context.agentConnection.getRlmMaxDepthStatus).toHaveBeenCalledOnce();+ expect(context.agentConnection.setRlmMaxDepth).not.toHaveBeenCalled();+ expect(renderAll(context.chatContainer)).toContain("RLM max depth: 2 (chat)");+ });++ it("sets the value globally and shows a dim one-liner", async () => {+ const context = makeContext();+ await prototype.handleRlmMaxDepthCommand.call(context, "3 --global");+ expect(context.agentConnection.setRlmMaxDepth).toHaveBeenCalledWith(3, { global: true });+ expect(renderAll(context.chatContainer)).toContain("RLM max depth set: 3 and saved as global default");+ });++ it("surfaces a global-save error without losing the successful chat update", async () => {+ const context = makeContext({+ setRlmMaxDepth: vi.fn(async () => ({+ maxDepth: 4,+ source: "chat" as const,+ globalSaved: false,+ globalError: "disk full",+ })),+ });+ await prototype.handleRlmMaxDepthCommand.call(context, "4 --global");+ expect(renderAll(context.chatContainer)).toContain("RLM max depth set: 4");+ expect(context.showError).toHaveBeenCalledWith(+ "RLM max depth set for this chat, but the global default was not saved: disk full",+ );+ });+});diff --git a/packages/coding-agent/test/session-manager-flush.test.ts b/packages/coding-agent/test/session-manager-flush.test.tsindex 0feb728369..418b52b2e4 100644--- a/packages/coding-agent/test/session-manager-flush.test.ts+++ b/packages/coding-agent/test/session-manager-flush.test.ts@@ -356,6 +356,17 @@ const failAfterPartialTempWrite: WriteFileSync = (path, data, options) => {};describe("SessionManager.appendCustomMessageEntryWithRollback", () => {+ it("flushes rollback-aware value entries immediately", () => {+ const dir = createTempDir();+ const mgr = SessionManager.create(dir, join(dir, "sessions"));++ mgr.appendCustomEntryWithRollback("rlm_max_depth_state", { maxDepth: 2 });++ expect(readFileSync(mgr.getSessionFile()!, "utf8")).toContain(+ '"customType":"rlm_max_depth_state","data":{"maxDepth":2}',+ );+ });+it("flushes rollback-aware custom messages before the first assistant response", () => {const dir = createTempDir();const sessionDir = join(dir, "sessions");diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.tsindex 451d2241ea..5e5b6c3d06 100644--- a/packages/coding-agent/test/settings-manager.test.ts+++ b/packages/coding-agent/test/settings-manager.test.ts@@ -316,6 +316,42 @@ describe("SettingsManager", () => {expect(errors.map((e) => e.scope).sort()).toEqual(["global", "project"]);expect(manager.drainErrors()).toEqual([]);});++ it("should report a new global error when saving after the load error was drained", async () => {+ const settingsPath = join(agentDir, "settings.json");+ const invalidSettings = "{ invalid global json";+ writeFileSync(settingsPath, invalidSettings);++ const manager = SettingsManager.create(projectDir, agentDir);+ expect(manager.drainErrors()).toHaveLength(1);++ manager.setRlmMaxDepth(3);+ await manager.flush();++ const errors = manager.drainErrors();+ expect(errors).toHaveLength(1);+ expect(errors[0]?.scope).toBe("global");+ expect(errors[0]?.error.message).toContain("Global settings not saved: settings file failed to parse:");+ expect(readFileSync(settingsPath, "utf-8")).toBe(invalidSettings);+ });++ it("should report a new project error when saving after the load error was drained", async () => {+ const settingsPath = join(projectDir, ".prime", "agent", "settings.json");+ const invalidSettings = "{ invalid project json";+ writeFileSync(settingsPath, invalidSettings);++ const manager = SettingsManager.create(projectDir, agentDir);+ expect(manager.drainErrors()).toHaveLength(1);++ manager.setProjectPackages(["npm:test-pkg"]);+ await manager.flush();++ const errors = manager.drainErrors();+ expect(errors).toHaveLength(1);+ expect(errors[0]?.scope).toBe("project");+ expect(errors[0]?.error.message).toContain("Project settings not saved: settings file failed to parse:");+ expect(readFileSync(settingsPath, "utf-8")).toBe(invalidSettings);+ });});describe("project settings directory creation", () => {diff --git a/packages/coding-agent/test/slash-commands.test.ts b/packages/coding-agent/test/slash-commands.test.tsindex 5db91f124c..d406439553 100644--- a/packages/coding-agent/test/slash-commands.test.ts+++ b/packages/coding-agent/test/slash-commands.test.ts@@ -21,6 +21,15 @@ describe("built-in slash commands", () => {expect(commandNames).not.toContain("cron");});+ test("describes the fine-grained /rlm-max-depth semantics", () => {+ expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "rlm-max-depth")).toMatchObject({+ description:+ "Set/view the per-chat persistent RLM max depth immediately; never interrupts or queues the running turn",+ argumentHint: "[<int> [--global]]",+ takesArgument: true,+ });+ });+test("exposes heartbeat syntax guidance", () => {expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "heartbeat")).toMatchObject({description:@@ -248,6 +257,7 @@ describe("session slash commands", () => {args: "status",text: "/autonomous status",});+ expect(parseSessionSlashCommand("/rlm-max-depth 3 --global")).toBeUndefined();expect(parseSessionSlashCommand("Explain /compact")).toBeUndefined();expect(parseSessionSlashCommand(" /compact")).toBeUndefined();expect(parseSessionSlashCommand("/compaction")).toBeUndefined();diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.tsindex 0d173d494f..8cec019947 100644--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts@@ -458,6 +458,43 @@ describe("AgentSession prompt characterization", () => {await promptPromise;});+ it("preserves the active extension system prompt when max depth changes mid-run", async () => {+ const responseStarted = createDeferred();+ const responseGate = createDeferred();+ const harness = await createHarness({+ rlmDepth: 1,+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async (event) => ({+ systemPrompt: `${event.systemPrompt}++active extension doctrine`,+ }));+ },+ ],+ });+ harnesses.push(harness);+ harness.setResponses([+ async () => {+ responseStarted.resolve();+ await responseGate.promise;+ return fauxAssistantMessage("done");+ },+ ]);++ const promptPromise = harness.session.prompt("start");+ await responseStarted.promise;+ expect(harness.session.agent.state.systemPrompt).toContain("active extension doctrine");+ expect(harness.session.agent.state.systemPrompt).not.toContain("A callable `rlm`");++ await harness.session.setRlmMaxDepth(2);++ expect(harness.session.agent.state.systemPrompt).toContain("A callable `rlm`");+ expect(harness.session.agent.state.systemPrompt).toContain("active extension doctrine");+ responseGate.resolve();+ await promptPromise;+ });+it("resets stale extension system prompt for accepted agent messages", async () => {const harness = await createHarness({systemPrompt: "base prompt",