A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
feat(coding-agent): agent-callable refine skill (#504)
Seth Karten42ea9046ab9f
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.mdindex 80f8e0f087..5885a89527 100644--- a/packages/coding-agent/CHANGELOG.md+++ b/packages/coding-agent/CHANGELOG.md@@ -10,8 +10,10 @@- Changed slash-command autocomplete to separate argument hints and resource provenance, show only the selected command description, and summarize hidden results directionally.- Fixed cancelled extension commands remaining alive when spawned processes ignored SIGTERM ([#458](https://github.com/PrimeIntellect-ai/prime-agent/pull/458) by [@snimu](https://github.com/snimu)).- Fixed OAuth browser launch URLs being interpreted by the system shell.+- Added agent-callable `refine` skill so the model can schedule continual harness refinement from IPython via `await refine.run()` without blocking the current turn ([#504](https://github.com/PrimeIntellect-ai/prime-agent/pull/504) by [@sethkarten](https://github.com/sethkarten)).- Changed long live session opens to render a bounded recent transcript tail while preserving full prompt history ([#343](https://github.com/PrimeIntellect-ai/prime-agent/pull/343) by [@sethkarten](https://github.com/sethkarten)).-- Changed `/refine` to run planning in the background so the conversation is not blocked during the LLM pass.+- Changed `/refine` to run planning in the background so the conversation is not blocked during the LLM pass ([#497](https://github.com/PrimeIntellect-ai/prime-agent/pull/497) by [@sethkarten](https://github.com/sethkarten)).+- Added serialized headless refinement and `--goal` / `--goal-token-budget` for seeding durable session goals ([#514](https://github.com/PrimeIntellect-ai/prime-agent/pull/514) by [@sethkarten](https://github.com/sethkarten)).## [0.3.2] - 2026-07-20diff --git a/packages/coding-agent/docs/usage.md b/packages/coding-agent/docs/usage.mdindex ace7cd6a0a..6d5c276107 100644--- a/packages/coding-agent/docs/usage.md+++ b/packages/coding-agent/docs/usage.md@@ -259,6 +259,8 @@ prime-agent --no-extensions -e ./my-extension.ts| `--autonomous-max-turns <n>` | Maximum assistant turns; default is 12 || `--autonomous-max-tokens <n>` | Maximum tokens; default is 80000 || `--autonomous-timeout-ms <n>` | Maximum wall-clock duration; default is 1800000 milliseconds |+| `--goal <objective>` | Start the session with an active persistent goal; only seeds new top-level sessions (rlmDepth 0) with no existing goal state |+| `--goal-token-budget <n>` | Positive integer token budget for the initial goal; requires `--goal` |### Other Optionsdiff --git a/packages/coding-agent/skills/refine/SKILL.md b/packages/coding-agent/skills/refine/SKILL.mdnew file mode 100644index 0000000000..3d5c83f4e6--- /dev/null+++ b/packages/coding-agent/skills/refine/SKILL.md@@ -0,0 +1,42 @@+---+name: refine+description: Trigger continual harness refinement from IPython. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.+---++# Refine++Refinement analyzes the conversation trajectory and applies small, evidence-backed+updates to the continual harness (prompts, memories, skills, subagent specs).+The implementation lives in the host (the same one behind the user's `/refine`+command); this skill is the kernel-side interface to it. Call it directly from+IPython:++```python+await refine.status()+await refine.run()+await refine.run("create a memory about always checking git status before committing")+await refine.run("promote the error-handling pattern to a global skill", global_=True)+```++## API++- `await refine.status()` — current refine state as a dict: `pending` (whether a+ requested refine is already queued for this turn) and `in_flight` (whether a+ refine is currently planning or applying).+- `await refine.run(instructions=None, global_=False)` — schedule refinement.+ Returns `{"scheduled": True}` immediately, or `{"scheduled": False, "reason": ...}`+ when refinement cannot start. Optional `instructions` focus the refinement on a+ specific observation. Set `global_=True` to target the global harness store+ (cross-session); omit for local (session-scoped) refinement.++## Rules++- Refinement never runs mid-cell. A scheduled refinement runs when the current+ turn ends; the harness applies changes and rebuilds the system prompt, then+ resumes you automatically. Continue working normally after calling it.+- One request per turn is enough; calling `run` again before the turn ends only+ updates the instructions.+- Use refinement after observing a repeated failure, a reusable tactic, a+ repeated delegation role, or a behavior policy worth persisting. Do not+ rewrite the whole harness when a focused memory, skill, prompt note, or+ subagent spec is enough.diff --git a/packages/coding-agent/skills/refine/pyproject.toml b/packages/coding-agent/skills/refine/pyproject.tomlnew file mode 100644index 0000000000..9f9e9f3064--- /dev/null+++ b/packages/coding-agent/skills/refine/pyproject.toml@@ -0,0 +1,17 @@+# Kernel-side package for the bundled refine skill. It only talks to the host+# through rlm.host_request; prime-agent-runtime is always installed in the+# kernel venv before skills, so it is intentionally not declared as a+# dependency (it is not published on PyPI).+[project]+name = "refine"+version = "0.1.0"+description = "Prime Agent refine skill: continual harness refinement over the host bridge"+requires-python = ">=3.10"+dependencies = []++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/refine"]diff --git a/packages/coding-agent/skills/refine/src/refine/__init__.py b/packages/coding-agent/skills/refine/src/refine/__init__.pynew file mode 100644index 0000000000..5c50a37c54--- /dev/null+++ b/packages/coding-agent/skills/refine/src/refine/__init__.py@@ -0,0 +1,50 @@+"""Prime Agent refine skill: continual harness refinement from the kernel.++Refinement runs host-side (the same implementation as /refine); these+functions are thin typed wrappers over the generic host bridge+(`rlm.host_request`). They only work inside the Prime Agent IPython kernel.+"""++from __future__ import annotations++from typing import Any++from rlm import host_request+++async def status() -> dict[str, Any]:+ """Read current refine state.++ Returns a dict with `pending` (whether a requested refine is already+ queued for this turn) and `in_flight` (whether a refine is currently+ planning or applying).+ """+ return await host_request("refine.status")+++async def run(+ instructions: str | None = None,+ global_: bool = False,+) -> dict[str, Any]:+ """Schedule continual harness refinement.++ Refinement never runs mid-cell: it runs when the current turn ends and+ the harness applies changes and rebuilds the system prompt, then resumes+ you automatically. Returns `{"scheduled": True}`, or+ `{"scheduled": False, "reason": ...}` when refinement cannot start.+ Optional `instructions` focus the refinement on a specific observation.+ Set `global_=True` to target the global (cross-session) harness store;+ omit for local (session-scoped) refinement.+ """+ if instructions is not None and not isinstance(instructions, str):+ raise TypeError(+ f"instructions must be str or None, got {type(instructions).__name__}"+ )+ if not isinstance(global_, bool):+ raise TypeError(f"global_ must be bool, got {type(global_).__name__}")+ payload: dict[str, Any] = {}+ if instructions is not None:+ payload["instructions"] = instructions+ if global_:+ payload["global"] = True+ return await host_request("refine.run", payload)diff --git a/packages/coding-agent/src/cli/args.ts b/packages/coding-agent/src/cli/args.tsindex 12915027e8..9b66483932 100644--- a/packages/coding-agent/src/cli/args.ts+++ b/packages/coding-agent/src/cli/args.ts@@ -47,6 +47,8 @@ export interface Args {autonomousMaxTurns?: number;autonomousMaxTokens?: number;autonomousTimeoutMs?: number;+ goal?: string;+ goalTokenBudget?: number;listModels?: string | true;offline?: boolean;verbose?: boolean;@@ -257,6 +259,19 @@ export function parseArgs(args: string[]): Args {if (hasRequiredOptionValue(args, i, arg, result)) {result.autonomousTimeoutMs = parsePositiveInt(args[++i], "--autonomous-timeout-ms", result);}+ } else if (arg === "--goal") {+ if (hasRequiredOptionValue(args, i, arg, result)) {+ const value = args[++i];+ if (!value.trim()) {+ result.diagnostics.push({ type: "error", message: "--goal requires a non-empty objective" });+ } else {+ result.goal = value;+ }+ }+ } else if (arg === "--goal-token-budget") {+ if (hasRequiredOptionValue(args, i, arg, result)) {+ result.goalTokenBudget = parsePositiveInt(args[++i], "--goal-token-budget", result);+ }} else if (arg === "--list-models") {const hasSearch = i + 1 < args.length && !args[i + 1].startsWith("-") && !args[i + 1].startsWith("@");if (!internalRuntimeCommand) {@@ -302,6 +317,13 @@ export function parseArgs(args: string[]): Args {}}+ if (result.goalTokenBudget !== undefined && !result.goal) {+ result.diagnostics.push({+ type: "error",+ message: "--goal-token-budget requires --goal",+ });+ }+return result;}diff --git a/packages/coding-agent/src/cli/daemon-command.ts b/packages/coding-agent/src/cli/daemon-command.tsindex 357bddf50c..2fb10d5bd2 100644--- a/packages/coding-agent/src/cli/daemon-command.ts+++ b/packages/coding-agent/src/cli/daemon-command.ts@@ -381,6 +381,10 @@ function parseSessionArgs(args: string[]): ParsedSessionArgs {}const name = nameParts.join(" ").trim();+ // Validate: --goal-token-budget without --goal is an error.+ if (config.initialGoal?.tokenBudget !== undefined && !config.initialGoal.objective) {+ throw new Error("--goal-token-budget requires --goal");+ }return {daemonArgs,name: name || undefined,@@ -528,6 +532,30 @@ function parseSessionOption(case "-nc":config.noContextFiles = true;return boolean(arg);+ case "--goal": {+ const value = readValue(arg);+ if (!value.trim()) {+ throw new Error("--goal requires a non-empty objective");+ }+ config.initialGoal = { objective: value, tokenBudget: config.initialGoal?.tokenBudget };+ // Session-specific flag: do NOT propagate to daemon startup args.+ // The goal is sent per-create via the config in the daemon request,+ // so a later no-goal create is not contaminated.+ return { consumed: 1 };+ }+ case "--goal-token-budget": {+ const value = readValue(arg);+ const budget = Number(value);+ if (!Number.isInteger(budget) || budget <= 0) {+ throw new Error("--goal-token-budget must be a positive integer");+ }+ config.initialGoal = {+ objective: config.initialGoal?.objective ?? "",+ tokenBudget: budget,+ };+ // Session-specific flag: do NOT propagate to daemon startup args.+ return { consumed: 1 };+ }case "--foreground":case "--no-detach":case "--background":@@ -1355,7 +1383,9 @@ class DaemonAttachTerminal {this.rl?.prompt();return;case "session_event":- this.handleSessionEvent(message.event);+ if (message.event.type !== "refine_complete") {+ this.handleSessionEvent(message.event);+ }return;case "session_replaced":this.isStreaming = message.state.isStreaming;@@ -1452,6 +1482,11 @@ class DaemonAttachTerminal {case "goal_update":this.writeLine(chalk.dim(`Goal: ${event.goal.status}`));return;+ case "refine_failed":+ this.writeLine(chalk.red(`Refinement failed: ${event.error}`));+ return;+ case "refine_complete":+ return;case "turn_start":case "turn_end":case "message_start":diff --git a/packages/coding-agent/src/cli/daemon-launch.ts b/packages/coding-agent/src/cli/daemon-launch.tsindex 96a824336a..0083582997 100644--- a/packages/coding-agent/src/cli/daemon-launch.ts+++ b/packages/coding-agent/src/cli/daemon-launch.ts@@ -9,12 +9,20 @@ import { spawn } from "node:child_process";import { existsSync } from "node:fs";import { resolve } from "node:path";import { appendRotatingLog, expandTildePath, getClientErrorLogPath, VERSION } from "../config.js";-import { getProcessStartId } from "../core/session-lease.js";+import { ORPHAN_PROCESS_JOURNAL_ENV } from "../core/orphan-process-journal.js";+import { getProcessStartId, SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../core/session-lease.js";import { DaemonClient, type DaemonHello } from "../modes/daemon/daemon-client.js";import { DAEMON_PROTOCOL_VERSION, DAEMON_SCHEMA_ID } from "../modes/daemon/daemon-protocol.js";import { getDaemonRuntimeIdentity } from "../modes/daemon/daemon-runtime-identity.js";import { isSessionSummaryBusy, type SessionSummary } from "../modes/daemon/daemon-session-list.js";import { defaultDaemonSocketPath } from "../modes/daemon/daemon-socket.js";+import {+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,+ DAEMON_WORKER_RECOVERY_JOURNAL_ENV,+ DAEMON_WORKER_ROLE_ENV,+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,+ DAEMON_WORKER_TOKEN_ENV,+} from "../modes/daemon/daemon-worker-protocol.js";import { isHelpCommandRequest, PUBLIC_COMMAND_NAMES, REMOVED_COMMAND_NAMES } from "./command-registry.js";import { createCliSubprocessEnv, formatCurrentCliCommand } from "./subprocess-launch.js";@@ -374,13 +382,28 @@ async function ensureDaemonRunning(socketPath: string, spawnCwd?: string): Promithrow new Error("Cannot determine current CLI entrypoint for daemon launch");}+ // Strip inherited daemon worker/supervisor role env vars so the spawned+ // daemon supervisor does not inherit worker-mode behavior. Without this,+ // a CLI running inside a daemon worker (e.g. a test spawned by the Prime+ // Agent daemon) would launch the supervisor in worker mode, which listens+ // on the socket but never sends the daemon_hello handshake.+ const env = createCliSubprocessEnv();+ delete env[DAEMON_WORKER_ROLE_ENV];+ delete env[DAEMON_WORKER_TOKEN_ENV];+ delete env[DAEMON_WORKER_ACTIVE_SESSION_ID_ENV];+ delete env[DAEMON_WORKER_RECOVERY_JOURNAL_ENV];+ delete env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];+ delete env[ORPHAN_PROCESS_JOURNAL_ENV];+ delete env[SESSION_LEASES_ENABLED_ENV];+ delete env[SESSION_LEASE_OWNER_ID_ENV];+const child = spawn(process.execPath,[...process.execArgv, entrypoint, "--mode", "daemon", "--daemon-socket", socketPath],{cwd: spawnCwd ?? process.cwd(),detached: true,- env: createCliSubprocessEnv(),+ env,// The daemon writes its own rotating log (see daemon-mode); nothing here// needs its stdout/stderr, so leave them detached.stdio: "ignore",@@ -451,6 +474,8 @@ const EARLY_LAUNCH_VALUE_FLAGS = new Set(["--autonomous-max-turns","--autonomous-max-tokens","--autonomous-timeout-ms",+ "--goal",+ "--goal-token-budget",]);function findFirstEarlyLaunchPositional(args: readonly string[]): { index: number; value: string } | undefined {diff --git a/packages/coding-agent/src/core/agent-session-config.ts b/packages/coding-agent/src/core/agent-session-config.tsindex 16dd239388..8cf90917b1 100644--- a/packages/coding-agent/src/core/agent-session-config.ts+++ b/packages/coding-agent/src/core/agent-session-config.ts@@ -26,6 +26,19 @@ export interface AgentSessionRuntimeConfig {noContextFiles?: boolean;autonomous?: AgentAutonomousConfig;extensionFlagValues?: Record<string, boolean | string>;+ /**+ * When true, auto-refine runs synchronously between turns at the+ * shouldStopAfterTurn boundary instead of in the background after+ * agent_end. Passed from the JSON/print client to the daemon worker+ * so it survives the appMode="daemon" context switch.+ */+ serializedRefine?: boolean;+ /**+ * Initial goal to seed when creating a new top-level session (rlmDepth 0).+ * Ignored for subagent sessions and when the branch already has a persisted+ * thread_goal_state entry (idempotent restart/rehydration).+ */+ initialGoal?: { objective: string; tokenBudget?: number };}export function mergeAgentSessionRuntimeConfig(@@ -63,6 +76,8 @@ export function mergeAgentSessionRuntimeConfig(base.extensionFlagValues || override.extensionFlagValues? { ...(base.extensionFlagValues ?? {}), ...(override.extensionFlagValues ?? {}) }: undefined,+ serializedRefine: override.serializedRefine ?? base.serializedRefine,+ initialGoal: override.initialGoal ?? base.initialGoal,};}@@ -78,6 +93,8 @@ function cloneAgentSessionRuntimeConfig(config: AgentSessionRuntimeConfig): Agenthemes: cloneArray(config.themes),autonomous: mergeAutonomousConfig(undefined, config.autonomous),extensionFlagValues: config.extensionFlagValues ? { ...config.extensionFlagValues } : undefined,+ serializedRefine: config.serializedRefine,+ initialGoal: config.initialGoal ? { ...config.initialGoal } : undefined,};}diff --git a/packages/coding-agent/src/core/agent-session-services.ts b/packages/coding-agent/src/core/agent-session-services.tsindex 15e99241d6..172945c4c5 100644--- a/packages/coding-agent/src/core/agent-session-services.ts+++ b/packages/coding-agent/src/core/agent-session-services.ts@@ -77,6 +77,10 @@ export interface AgentSessionCreationOptions {rlmHeartbeatController?: AgentRlmHeartbeatController;prewarmIpythonKernel?: boolean;autonomous?: AgentAutonomousConfig;+ /** Serialized refine mode for print/headless autonomous runs. */+ serializedRefine?: boolean;+ /** Initial goal to seed at session creation (rlmDepth 0 only, idempotent). */+ initialGoal?: { objective: string; tokenBudget?: number };}/**@@ -274,5 +278,7 @@ export async function createAgentSessionFromServices(sessionStartEvent: options.sessionStartEvent,prewarmIpythonKernel: options.prewarmIpythonKernel,autonomous: options.autonomous,+ serializedRefine: options.serializedRefine,+ initialGoal: options.initialGoal,});}diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 5ceb5fddba..6ef741659a 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -187,11 +187,13 @@ import {getLocalHarnessStateDir,getRefinementHistory,type HarnessState,+ inferRefinementResultScope,loadGlobalRefinementHistory,loadHarnessState,mergeHarnessStates,mergeRefinementHistory,planRefinement,+ REFINE_SKILL_NAME,type RefinementPlan,type RefinementResult,reviewAutoRefine,@@ -317,7 +319,9 @@ export type AgentSessionEvent =fullOutputPath?: string;/** Set when execution failed before producing a result (e.g. spawn failure) */errorMessage?: string;- };+ }+ | { type: "refine_complete"; result: RefinementResult }+ | { type: "refine_failed"; error: string };/** Listener function for agent session events */export type AgentSessionEventListener = (event: AgentSessionEvent) => void;@@ -415,6 +419,18 @@ export interface AgentSessionConfig {prewarmIpythonKernel?: boolean;/** Test/extension hook for automatic refine review decisions. Defaults to the model-backed review gate. */autoRefineReviewer?: AutoRefineReviewer;+ /**+ * When true, auto-refine runs synchronously between turns at the+ * shouldStopAfterTurn boundary instead of in the background after+ * agent_end. Used for print/headless autonomous runs so refinement+ * never overlaps the primary model request. Default: false.+ */+ serializedRefine?: boolean;+ /**+ * Initial goal to seed at session creation. Only applied when rlmDepth+ * is 0 and no persisted thread_goal_state entry exists in the branch.+ */+ initialGoal?: { objective: string; tokenBudget?: number };}export interface ExtensionBindings {@@ -429,6 +445,33 @@ export interface AutoRefineReviewRequest {turnsSinceLastReview: number;}+/**+ * Discriminated result from a serialized-mode background planning pass.+ * - "plan": review approved and planning succeeded; carry the exact plan,+ * options, and abort controller so the boundary can apply directly+ * without a second planning request.+ * - "skip": reviewer declined; no refine needed.+ * - "failure": review or planning threw; boundary should not retry.+ */+export type SerializedBackgroundPlanResult =+ | {+ status: "plan";+ plan: RefinementPlan;+ options: { instructions?: string; rollbackId?: string; global?: boolean };+ abort: AbortController;+ branchVersion: number;+ }+ | { status: "skip" }+ | { status: "invalidated"; branchVersion: number }+ | {+ status: "failure";+ /** True when the background plan was for an explicit refine.run (skipReview). */+ explicit: boolean;+ /** Original options for the failed plan, to allow re-queue on explicit failure. */+ options: { instructions?: string; rollbackId?: string; global?: boolean };+ branchVersion: number;+ };+export type AutoRefineReviewer = (request: AutoRefineReviewRequest, signal?: AbortSignal) => Promise<AutoRefineReview>;/** Options for AgentSession.prompt() */@@ -831,6 +874,7 @@ export class AgentSession {private _overflowRecoveryAttempted = false;private _continueAfterThresholdCompaction = false;private _pendingRequestedCompaction: { customInstructions?: string } | undefined;+ private _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;// Branch summarization stateprivate _branchSummaryAbortController: AbortController | undefined = undefined;@@ -933,6 +977,8 @@ export class AgentSession {private _assistantTurnsSinceAutoRefine = 0;private _lastAutoRefineReviewAt = 0;private _autoRefineInProgress = false;+ private readonly _autoRefineOperations = new Set<Promise<void>>();+ private readonly _scheduledAutoRefineTimers = new Set<ReturnType<typeof setTimeout>>();private _compactAutoRefinePending = false;private _turnIntervalAutoRefinePending = false;private _postCompactionContinuationScheduled = false;@@ -946,10 +992,20 @@ export class AgentSession {private _autoRefineReviewAbort?: AbortController;private _refineAbortController?: AbortController;private readonly _autoRefineReviewer?: AutoRefineReviewer;+ /** When true, auto-refine runs synchronously between turns (serialized mode). */+ private readonly _serializedRefine: boolean;/** Settles (never rejects) after a planned refine waits for idle and finishes applying. */private _refineInFlight?: Promise<void>;/** Settles when the background planning LLM pass completes. Planning does not block turn entry points. */private _refinePlanInFlight?: Promise<void>;+ /**+ * Settles when a serialized-mode background planning pass completes.+ * Planning starts at assistant message_end (overlapping tool execution)+ * and is awaited at shouldStopAfterTurn before applying.+ */+ private _serializedPlanInFlight?: Promise<SerializedBackgroundPlanResult | undefined>;+ private _serializedPlanClaim?: Promise<void>;+ private _serializedExplicitRefineOptions?: { instructions?: string; global?: boolean };constructor(config: AgentSessionConfig) {this.agent = config.agent;@@ -977,11 +1033,20 @@ export class AgentSession {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;+ this._serializedRefine = config.serializedRefine ?? false;this._rlmSessionDir = config.rlmSessionDir;this._rlmParentNodeId = config.rlmParentNodeId;this._subagentRuntimeHost = config.subagentRuntimeHost;this._autonomousState = createAutonomousRuntimeState(config.autonomous, { cwd: this._cwd });this._goalState = this._loadPersistedGoalState();+ // Seed initial goal from CLI --goal flag, but only for top-level sessions+ // and only when the branch contains only bootstrap entry types (model_change,+ // thinking_level_change, service_tier_change) and no persisted+ // thread_goal_state. This prevents reseeding after clear/complete/error+ // or restart/rehydration of a session that already has messages or a goal.+ if (this._rlmDepth === 0 && config.initialGoal && this._isBranchSeedable()) {+ this._goalState = this._startGoal(config.initialGoal.objective, config.initialGoal.tokenBudget);+ }this._restoreLateIpythonSentAgentMessages();if (this._goalState.status === "active") {this._goalAccountingStartedAt = Date.now();@@ -1000,6 +1065,24 @@ export class AgentSession {});}+ /**+ * Set the RLM heartbeat controller after construction. Used by+ * print/headless mode to attach an in-process heartbeat scheduler+ * when the session is created outside the daemon.+ */+ setRlmHeartbeatController(controller: AgentRlmHeartbeatController): void {+ if (this._rlmHeartbeatController === controller) {+ return;+ }+ this._rlmHeartbeatController = controller;+ this._buildRuntime({+ activeToolNames: this.getActiveToolNames(),+ includeAllExtensionTools: true,+ });+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());+ this.agent.state.systemPrompt = this._baseSystemPrompt;+ }+/** Model registry for API key resolution and model discovery */get modelRegistry(): ModelRegistry {return this._modelRegistry;@@ -1106,7 +1189,12 @@ export class AgentSession {/** Emit an event to all listeners */private _emit(event: AgentSessionEvent): void {for (const l of this._eventListeners) {- l(event);+ try {+ l(event);+ } catch {+ // A failing observer must not prevent other subscribers from+ // receiving lifecycle and persistence events.+ }}}@@ -1189,6 +1277,34 @@ export class AgentSession {return emptyGoalState();}+ /**+ * Whether the session branch is seedable for an initial goal. Returns true+ * only when the branch contains exclusively bootstrap entry types+ * (model_change, thinking_level_change, service_tier_change) and no+ * thread_goal_state custom entry. Any message, custom entry, or persisted+ * goal (including cleared/complete/error) means the session has been used+ * and should not be reseeded.+ */+ private _isBranchSeedable(): boolean {+ const branch = this.sessionManager.getBranch();+ for (const entry of branch) {+ switch (entry.type) {+ case "model_change":+ case "thinking_level_change":+ case "service_tier_change":+ continue;+ case "custom":+ if (entry.customType === GOAL_STATE_CUSTOM_TYPE) {+ return false;+ }+ return false;+ default:+ return false;+ }+ }+ return true;+ }+private _reloadGoalStateFromBranch(): void {this._goalState = this._loadPersistedGoalState();this._goalAccountingStartedAt = this._goalState.status === "active" ? Date.now() : undefined;@@ -1197,6 +1313,10 @@ export class AgentSession {private _persistGoalState(goal: GoalState): void {this.sessionManager.appendCustomEntry(GOAL_STATE_CUSTOM_TYPE, goal);+ // Force flush so the goal state is durable on disk immediately,+ // even before the first assistant response. This ensures idempotent+ // restart/rehydration can detect the persisted goal.+ this.sessionManager.flushNow();}private _setGoalState(next: GoalState, options: { persist?: boolean } = {}): void {@@ -1617,6 +1737,18 @@ export class AgentSession {} catch {// Goal accounting must not interrupt the core agent loop.}+ // Serialized refine checkpoint: in print/headless mode, run refinement+ // planning+apply synchronously here — the quiescent boundary between+ // turns — so it never overlaps the primary model request.+ // This MUST run BEFORE threshold compaction to prevent the+ // compaction model call from overlapping an in-flight refine+ // plan/apply that was started at message_end.+ if (this._serializedRefine) {+ // Ensure the preceding message_end processing (counter increment,+ // background plan kickoff) has completed before the checkpoint.+ await this._agentEventQueue;+ await this._runSerializedRefineCheckpoint();+ }if (await this._shouldStopForThresholdCompaction(context)) {return true;}@@ -1634,6 +1766,461 @@ export class AgentSession {return true;}+ /**+ * Serialized-mode auto-refine checkpoint called from _shouldStopAfterTurn.+ * Runs the review, planning, and application phases inline between turns+ * at the quiescent shouldStopAfterTurn boundary. This path NEVER calls+ * _maybeAutoRefine, _runApprovedRefine, public refine(), agent.abort(),+ * or agent.waitForIdle — all of which would deadlock or defer because+ * the agent loop still owns activeRun at this point. Instead it calls+ * _reviewAutoRefine, _planRefine, and _applyRefine directly with proper+ * in-flight guards and counter resets.+ */+ private async _runSerializedRefineCheckpoint(): Promise<void> {+ if (this._disposed || this._disposing) {+ return;+ }++ // 1. Await any background plan that was started at message_end+ // (either for a pending refine.run or for interval-triggered+ // auto-refine). This must be checked BEFORE the pending and+ // interval checks because background planning may have consumed+ // the pending request at message_end.+ const branchVersion = this._autoRefineBranchVersion;+ const bgConsumption = await this._consumeSerializedBackgroundPlan(async (bgResult) => {+ if (this._disposed || this._disposing) {+ return true;+ }++ if (bgResult?.status === "plan") {+ // Fix 4: Validate branchVersion before applying the plan.+ if (bgResult.branchVersion !== this._autoRefineBranchVersion) {+ if (!this._pendingRequestedRefine) {+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ return true;+ }+ } else {+ // Apply the EXACT background plan directly via _applyRefine+ // (no second _planRefine call).+ try {+ await this._applySerializedPlan(bgResult);+ } catch (error) {+ this._emitRefineFailed(error);+ }+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ if (!this._pendingRequestedRefine) {+ return true;+ }+ }+ }++ if (bgResult?.status === "skip") {+ // Reviewer declined during background planning.+ // Reset exactly once. Never retry the interval review; only fall through for a separate pending refine.run.+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ if (!this._pendingRequestedRefine) {+ return true;+ }+ }++ if (bgResult?.status === "failure") {+ // Fix 3: Background review or planning failed. Stamp cooldown+ // without a synchronous retry (the discriminated contract says no duplicate boundary+ // model call). A separately queued refine.run may still be serviced below.+ if (branchVersion === this._autoRefineBranchVersion) {+ this._lastAutoRefineReviewAt = Date.now();+ }+ // Re-queue an explicit refine.run whose background plan failed,+ // but only when branchVersion is still current and no newer+ // pending request has arrived since the background plan consumed+ // the original one. A newer request retains priority; interval+ // failures keep existing no-retry cooldown semantics.+ if (+ bgResult.explicit &&+ bgResult.branchVersion === this._autoRefineBranchVersion &&+ !this._pendingRequestedRefine+ ) {+ this._pendingRequestedRefine = bgResult.options;+ }+ if (!this._pendingRequestedRefine) {+ return true;+ }+ }++ if (bgResult?.status === "invalidated" && !this._pendingRequestedRefine) {+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ return true;+ }++ await this._runSerializedRefineCheckpointAfterBackground(branchVersion);+ return true;+ });+ if (this._disposed || this._disposing || bgConsumption !== "none") {+ return;+ }+ await this._runSerializedRefineCheckpointAfterBackground(branchVersion);+ }++ private async _runSerializedRefineCheckpointAfterBackground(branchVersion: number): Promise<void> {+ // No background result, or a refine.run arrived while the background result was+ // in flight. Fall through so an explicit pending request is serviced at this boundary.++ // 2. Agent-callable refine.run requests that were NOT consumed by+ // background planning (e.g. interval not reached at message_end,+ // or cooldown was active). Service them synchronously.+ const pending = this._pendingRequestedRefine;+ if (pending) {+ this._pendingRequestedRefine = undefined;+ try {+ await this._runSerializedRefine(pending);+ } catch (error) {+ this._emitRefineFailed(error);+ }+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ return;+ }++ // 3. Post-compaction auto-refine. Serialized sessions defer the+ // compaction trigger to this boundary instead of entering the interactive+ // path, which waits for agent idle and can never run inside a tool loop.+ if (!this._autoRefineAllowedForSession()) {+ this._compactAutoRefinePending = false;+ return;+ }+ const settings = this.settingsManager.getAutoRefineSettings();+ if (!settings.enabled) {+ this._compactAutoRefinePending = false;+ return;+ }+ if (this._compactAutoRefinePending) {+ if (!settings.compact) {+ this._compactAutoRefinePending = false;+ } else {+ const nowMs = Date.now();+ const underCooldown =+ this._lastAutoRefineReviewAt > 0 && nowMs - this._lastAutoRefineReviewAt < settings.cooldownMs;+ if (underCooldown) {+ // Preserve the compact trigger for a later boundary, matching the+ // interactive path's pending behavior while the cooldown is active.+ return;+ }+ this._compactAutoRefinePending = false;+ await this._runSerializedAutoRefineReview("compact", branchVersion);+ return;+ }+ }++ // 4. Interval-triggered auto-refine (no background plan was started).+ if (this._assistantTurnsSinceAutoRefine < settings.turnInterval) {+ return;+ }+ const nowMs = Date.now();+ const underCooldown =+ this._lastAutoRefineReviewAt > 0 && nowMs - this._lastAutoRefineReviewAt < settings.cooldownMs;+ if (underCooldown) {+ return;+ }+ await this._runSerializedAutoRefineReview("turn_interval", branchVersion);+ }++ /** Run automatic review and, when approved, refinement at a serialized turn boundary. */+ private async _runSerializedAutoRefineReview(+ reason: "compact" | "turn_interval",+ branchVersion: number,+ ): Promise<void> {+ const reviewAbort = new AbortController();+ this._autoRefineReviewAbort = reviewAbort;+ this._autoRefineInProgress = true;+ try {+ const review = await this._reviewAutoRefine(+ { reason, turnsSinceLastReview: this._assistantTurnsSinceAutoRefine },+ reviewAbort.signal,+ );+ if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {+ return;+ }+ if (!review.shouldRefine) {+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ return;+ }+ await this._runSerializedRefine({+ instructions: autoRefineInstructions(reason, review),+ });+ if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {+ return;+ }+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ } catch (error) {+ if (branchVersion === this._autoRefineBranchVersion) {+ this._lastAutoRefineReviewAt = Date.now();+ this._emitRefineFailed(error);+ }+ } finally {+ if (this._autoRefineReviewAbort === reviewAbort) {+ this._autoRefineReviewAbort = undefined;+ }+ this._autoRefineInProgress = false;+ }+ }++ /**+ * Claim and process the serialized background plan if one is in flight.+ * A concurrent caller waits for the claim holder's full processing callback+ * instead of resuming as soon as planning settles.+ */+ private async _consumeSerializedBackgroundPlan(+ consume: (result: SerializedBackgroundPlanResult | undefined) => Promise<boolean>,+ ): Promise<"none" | "waited" | "continue" | "stop"> {+ if (this._serializedPlanClaim) {+ await this._serializedPlanClaim.catch(() => undefined);+ return "waited";+ }+ const planInFlight = this._serializedPlanInFlight;+ if (!planInFlight) {+ return "none";+ }++ let releaseClaim: () => void = () => {};+ const claim = new Promise<void>((resolve) => {+ releaseClaim = resolve;+ });+ this._serializedPlanClaim = claim;+ try {+ const result = await planInFlight.catch(() => undefined);+ if (this._serializedPlanInFlight === planInFlight) {+ this._serializedPlanInFlight = undefined;+ this._serializedExplicitRefineOptions = undefined;+ }+ return (await consume(result)) ? "stop" : "continue";+ } finally {+ releaseClaim();+ if (this._serializedPlanClaim === claim) {+ this._serializedPlanClaim = undefined;+ }+ }+ }++ /**+ * Apply an exact background plan directly via _applyRefine without+ * calling _planRefine again. Sets _refineInFlight for safety.+ */+ private async _applySerializedPlan(+ bgResult: Extract<SerializedBackgroundPlanResult, { status: "plan" }>,+ ): Promise<void> {+ let resolveApplySettled: () => void = () => {};+ const applySettled = new Promise<void>((resolve) => {+ resolveApplySettled = resolve;+ });+ this._refineInFlight = applySettled;+ try {+ await this._applyRefine(bgResult.plan, bgResult.options, bgResult.abort);+ } finally {+ resolveApplySettled();+ if (this._refineInFlight === applySettled) {+ this._refineInFlight = undefined;+ }+ this._schedulePendingMessageResume();+ }+ }++ /**+ * Start background refinement planning at assistant message_end, while+ * tools are still executing. The plan (if any) is awaited at the+ * shouldStopAfterTurn boundary before applying. Planning overlaps tool+ * execution only — never another model request.+ */+ private _maybeStartSerializedBackgroundPlan(): void {+ if (!this._serializedRefine || this._disposed || this._disposing) {+ return;+ }+ // Don't start if a plan is already in flight.+ if (this._serializedPlanInFlight || this._refineInFlight || this._refinePlanInFlight) {+ return;+ }++ // Bug 4 fix: Also start background planning for a pending agent-callable+ // refine.run request, so its plan is ready at the shouldStopAfterTurn+ // boundary. The pending request is consumed (cleared) here so the+ // boundary doesn't re-plan it. Explicit refine.run skips the review gate.+ const pending = this._pendingRequestedRefine;+ if (pending) {+ this._pendingRequestedRefine = undefined;+ this._serializedExplicitRefineOptions = pending;+ const refineAbort = new AbortController();+ this._refineAbortController = refineAbort;+ const branchVersion = this._autoRefineBranchVersion;+ this._serializedPlanInFlight = this._runBackgroundPlan(pending, refineAbort, branchVersion, true);+ return;+ }++ // Interval-triggered auto-refine background planning.+ if (!this._autoRefineAllowedForSession()) {+ return;+ }+ const settings = this.settingsManager.getAutoRefineSettings();+ if (!settings.enabled) {+ return;+ }+ if (this._assistantTurnsSinceAutoRefine < settings.turnInterval) {+ return;+ }+ const nowMs = Date.now();+ const underCooldown =+ this._lastAutoRefineReviewAt > 0 && nowMs - this._lastAutoRefineReviewAt < settings.cooldownMs;+ if (underCooldown) {+ return;+ }++ const refineAbort = new AbortController();+ this._refineAbortController = refineAbort;+ const branchVersion = this._autoRefineBranchVersion;+ // Pass empty options — _runBackgroundPlan derives instructions from+ // the review result for interval-triggered auto-refine.+ this._serializedPlanInFlight = this._runBackgroundPlan({}, refineAbort, branchVersion);+ }++ /**+ * Shared background planning coroutine. Runs review + planRefine and+ * returns a discriminated result so the boundary can distinguish+ * reviewer-declined ("skip") from failure ("failure") from a ready+ * plan ("plan") and apply that exact plan without re-planning.+ */+ private async _runBackgroundPlan(+ options: { instructions?: string; rollbackId?: string; global?: boolean },+ refineAbort: AbortController,+ branchVersion: number,+ skipReview = false,+ ): Promise<SerializedBackgroundPlanResult | undefined> {+ try {+ let planOptions = options;+ if (!skipReview) {+ // Interval-triggered: run the review gate first, then derive+ // instructions from the review result (not prepopulated).+ const review = await this._reviewAutoRefine(+ { reason: "turn_interval", turnsSinceLastReview: this._assistantTurnsSinceAutoRefine },+ refineAbort.signal,+ );+ if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {+ return { status: "invalidated", branchVersion };+ }+ if (!review.shouldRefine) {+ return { status: "skip" };+ }+ planOptions = { instructions: autoRefineInstructions("turn_interval", review) };+ }+ // For explicit refine.run (skipReview=true), plan directly with+ // the user-provided options — no auto-review gate.+ const plan = await this._planRefine(planOptions, refineAbort.signal);+ if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {+ return { status: "invalidated", branchVersion };+ }+ return { status: "plan", plan, options: planOptions, abort: refineAbort, branchVersion };+ } catch {+ if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {+ return { status: "invalidated", branchVersion };+ }+ return {+ status: "failure",+ explicit: skipReview,+ options,+ branchVersion,+ };+ } finally {+ if (this._refineAbortController === refineAbort) {+ this._refineAbortController = undefined;+ }+ }+ }++ /**+ * Direct serialized plan+apply. Calls _planRefine and _applyRefine with+ * proper in-flight guards but NEVER agent.waitForIdle or agent.abort.+ * The caller (shouldStopAfterTurn) is already at the quiescent boundary,+ * so the agent is between turns and _applyRefine's disconnect/reconnect+ * is safe.+ */+ private async _runSerializedRefine(options: {+ instructions?: string;+ rollbackId?: string;+ global?: boolean;+ }): Promise<void> {+ if (this._disposed || this._disposing) {+ return;+ }+ // Guard: serialize against concurrent _runSerializedRefine calls.+ // _serializedPlanInFlight covers background planning; _refineInFlight+ // covers the apply phase. Both must be settled before starting a new+ // plan+apply cycle.+ while (this._serializedPlanInFlight || this._refineInFlight || this._refinePlanInFlight) {+ if (this._serializedPlanInFlight) {+ await this._consumeSerializedBackgroundPlan(async () => false);+ } else if (this._refineInFlight) {+ await this._refineInFlight;+ } else {+ await this._refinePlanInFlight;+ }+ }+ if (this._disposed || this._disposing) {+ return;+ }++ const refineAbort = new AbortController();+ this._refineAbortController = refineAbort;++ const planRun = this._planRefine(options, refineAbort.signal);+ const planSettled = planRun.then(+ () => undefined,+ () => undefined,+ );+ this._refinePlanInFlight = planSettled;+ let plan: RefinementPlan;+ try {+ plan = await planRun;+ } catch (error) {+ if (this._refineAbortController === refineAbort) {+ this._refineAbortController = undefined;+ }+ this._schedulePendingMessageResume();+ throw error;+ } finally {+ if (this._refinePlanInFlight === planSettled) {+ this._refinePlanInFlight = undefined;+ }+ }++ if (this._disposed || refineAbort.signal.aborted) {+ if (this._refineAbortController === refineAbort) {+ this._refineAbortController = undefined;+ }+ this._schedulePendingMessageResume();+ return;+ }++ // Do NOT call agent.waitForIdle() — we are at the quiescent boundary+ // already (shouldStopAfterTurn). _applyRefine handles disconnect/reconnect internally.+ let resolveApplySettled: () => void = () => {};+ const applySettled = new Promise<void>((resolve) => {+ resolveApplySettled = resolve;+ });+ this._refineInFlight = applySettled;+ try {+ await this._applyRefine(plan, options, refineAbort);+ } finally {+ resolveApplySettled();+ if (this._refineInFlight === applySettled) {+ this._refineInFlight = undefined;+ }+ this._schedulePendingMessageResume();+ }+ }+private async _thresholdCompactionNeeded(context: ShouldStopAfterTurnContext): Promise<boolean> {const settings = this.settingsManager.getCompactionSettings();if (!settings.enabled) return false;@@ -1830,6 +2417,73 @@ export class AgentSession {}}+ /**+ * Handle a refine.* request from the kernel host bridge. Like compact,+ * refinement waits for the current turn to become idle before applying+ * changes, so refine.run only schedules it; _consumePendingRequestedRefine+ * fires it at the turn boundary. This prevents a deadlock that would occur+ * if refine() awaited agent idle from within the active tool call.+ */+ handleRefineHostRequest(type: string, payload: Record<string, unknown> = {}): Record<string, unknown> {+ switch (type) {+ case "refine.status": {+ return {+ pending: this._pendingRequestedRefine !== undefined,+ in_flight:+ this._refineInFlight !== undefined ||+ this._refinePlanInFlight !== undefined ||+ this._serializedPlanInFlight !== undefined,+ };+ }+ case "refine.run": {+ const instructions = payload.instructions;+ if (instructions !== undefined && typeof instructions !== "string") {+ throw new Error("refine.run instructions must be a string when provided");+ }+ const globalFlag = payload.global;+ if (globalFlag !== undefined && typeof globalFlag !== "boolean") {+ throw new Error("refine.run global must be a boolean when provided");+ }+ if (!this.isStreaming) {+ return {+ scheduled: false,+ reason: "no active turn; refine can only be requested while a turn is running",+ };+ }+ const previous = this._pendingRequestedRefine ?? this._serializedExplicitRefineOptions;+ this._pendingRequestedRefine = {+ instructions: instructions ?? previous?.instructions,+ global: globalFlag ?? previous?.global,+ };+ // In serialized mode, kick off background planning immediately+ // (the primary response ended at message_end, tools are active).+ // This lets planning overlap tool execution rather than waiting+ // for the shouldStopAfterTurn boundary.+ if (this._serializedRefine) {+ if (this._serializedPlanInFlight) {+ this._autoRefineBranchVersion++;+ if (this._refineAbortController) {+ this._refineAbortController.abort();+ } else {+ this._serializedPlanInFlight = Promise.resolve({+ status: "invalidated",+ branchVersion: this._autoRefineBranchVersion,+ });+ }+ } else {+ this._maybeStartSerializedBackgroundPlan();+ }+ }+ return {+ scheduled: true,+ note: "Refinement runs when the current turn ends; the harness rebuilds the system prompt and resumes you automatically. Continue working normally.",+ };+ }+ default:+ throw new Error(`unknown refine request type "${type}"`);+ }+ }+/*** Handle an rlm_heartbeat.* request from the bundled rlm-heartbeat skill.* These heartbeats are internal to this active session and never read or@@ -2320,6 +2974,12 @@ export class AgentSession {}if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "aborted") {this._assistantTurnsSinceAutoRefine++;+ // In serialized mode, kick off background refinement planning+ // immediately after the primary stream finishes, while tools+ // are still executing. The plan is awaited at shouldStopAfterTurn+ // before applying, so planning overlaps tools only — never another+ // model request.+ this._maybeStartSerializedBackgroundPlan();}if (assistantMsg.stopReason !== "error") {this._overflowRecoveryAttempted = false;@@ -2383,7 +3043,14 @@ export class AgentSession {this._resolveRetry();if (!compactionWillRetry) {this._finishGoalForTerminalAssistantMessage(msg);- this._scheduleAutoRefineAfterAgentEnd();+ // In serialized mode, agent-callable refine.run is serviced+ // at the shouldStopAfterTurn boundary, not here at agent_end.+ if (!this._serializedRefine) {+ const consumedRequestedRefine = this._consumePendingRequestedRefine();+ if (!consumedRequestedRefine) {+ this._scheduleAutoRefineAfterAgentEnd();+ }+ }}}}@@ -2567,11 +3234,150 @@ export class AgentSession {if (this._disposeAsyncPromise) {return this._disposeAsyncPromise;}- this._disposing = true;- this._disposeAsyncPromise = this._disposeAsyncOnce();+ this._disposeAsyncPromise = (async () => {+ // Drain before marking _disposing so a refine triggered at the final+ // agent_end completes instead of being aborted by dispose().+ await this._drainPendingRefinementForDisposal();+ if (this._disposed) {+ return;+ }+ this._disposing = true;+ await this._disposeAsyncOnce();+ })();return this._disposeAsyncPromise;}+ /**+ * Await any in-flight refinement (planning or application) and run a+ * pending auto-refine that was scheduled but not yet started. Called+ * from disposeAsync before _disposing is set so refinement completes+ * before disposal.+ */+ private async _drainPendingRefinementForDisposal(): Promise<void> {+ for (const timer of this._scheduledAutoRefineTimers) {+ clearTimeout(timer);+ }+ this._scheduledAutoRefineTimers.clear();+ await Promise.allSettled([...this._autoRefineOperations]);+ for (const timer of this._scheduledAutoRefineTimers) {+ clearTimeout(timer);+ }+ this._scheduledAutoRefineTimers.clear();+ // Wait for in-flight refinement (including serialized background plan) to settle.+ while (this._refineInFlight || this._refinePlanInFlight || this._serializedPlanInFlight) {+ if (this._refineInFlight) {+ await this._refineInFlight;+ } else if (this._refinePlanInFlight) {+ await this._refinePlanInFlight;+ } else if (this._serializedPlanInFlight) {+ // Fix 5: Await the background plan and apply a ready "plan"+ // result before teardown so the refinement is persisted.+ // Do NOT discard a ready plan.+ await this._consumeSerializedBackgroundPlan(async (bgResult) => {+ if (bgResult?.status === "plan" && bgResult.branchVersion === this._autoRefineBranchVersion) {+ try {+ await this._applySerializedPlan(bgResult);+ } catch (error) {+ this._emitRefineFailed(error);+ }+ // Stamp cooldown and reset counter so the interval+ // check below does not trigger a duplicate refine.+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ }+ // Preserve a consumed explicit request when its background plan failed,+ // matching the turn-boundary recovery path. The pending drain below+ // retries it once before disposal.+ if (+ bgResult?.status === "failure" &&+ bgResult.explicit &&+ bgResult.branchVersion === this._autoRefineBranchVersion &&+ !this._pendingRequestedRefine+ ) {+ this._pendingRequestedRefine = bgResult.options;+ }+ // For "skip" or "failure", stamp cooldown and reset counter+ // so the interval check below does not trigger a duplicate+ // terminal retry.+ if (+ bgResult?.status === "skip" ||+ bgResult?.status === "failure" ||+ bgResult?.status === "invalidated"+ ) {+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ }+ return false;+ });+ } else {+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ }+ }+ // Drain an agent-callable refine.run request that was scheduled but+ // not yet consumed. Use the direct serialized path (no waitForIdle)+ // since the agent may still own activeRun at the final agent_end.+ if (this._pendingRequestedRefine) {+ const pending = this._pendingRequestedRefine;+ this._pendingRequestedRefine = undefined;+ try {+ await this._runSerializedRefine(pending);+ } catch {+ // Best-effort drain; refinement errors must not block disposal.+ }+ // Stamp cooldown and reset counter so the interval check below+ // does not trigger a duplicate refine after the explicit drain.+ this._lastAutoRefineReviewAt = Date.now();+ this._assistantTurnsSinceAutoRefine = 0;+ }+ // A serialized compaction can finish without another model turn. Drain its+ // pending review here so disposal does not silently lose the trigger.+ if (this._serializedRefine && this._compactAutoRefinePending && this._autoRefineAllowedForSession()) {+ const compactSettings = this.settingsManager.getAutoRefineSettings();+ if (!compactSettings.enabled || !compactSettings.compact) {+ this._compactAutoRefinePending = false;+ } else {+ const nowMs = Date.now();+ const underCooldown =+ this._lastAutoRefineReviewAt > 0 && nowMs - this._lastAutoRefineReviewAt < compactSettings.cooldownMs;+ this._compactAutoRefinePending = false;+ if (!underCooldown) {+ try {+ await this._runSerializedAutoRefineReview("compact", this._autoRefineBranchVersion);+ } catch {+ // Best-effort drain; refinement errors must not block disposal.+ }+ return;+ }+ }+ }++ // If auto-refine is due but has not started yet, run it now so the+ // refinement is persisted before disposal. Use the direct serialized+ // path in serialized mode, or _maybeAutoRefine in interactive mode+ // (where the agent is idle at this point).+ if (this._disposed || !this._autoRefineAllowedForSession()) {+ return;+ }+ const settings = this.settingsManager.getAutoRefineSettings();+ if (!settings.enabled) {+ return;+ }+ if (this._assistantTurnsSinceAutoRefine < settings.turnInterval) {+ return;+ }+ const nowMs = Date.now();+ const underCooldown =+ this._lastAutoRefineReviewAt > 0 && nowMs - this._lastAutoRefineReviewAt < settings.cooldownMs;+ if (underCooldown) {+ return;+ }+ if (this._serializedRefine) {+ await this._runSerializedRefineCheckpoint();+ } else {+ await this._maybeAutoRefine("turn_interval");+ }+ }+private async _disposeAsyncOnce(): Promise<void> {// Flush kernels/traces for both still-running and retained children; the sync// dispose() below only tears them down synchronously.@@ -2608,6 +3414,13 @@ export class AgentSession {// resolution cannot write harness state or re-subscribe handlers.this._autoRefineReviewAbort?.abort();this._refineAbortController?.abort();+ for (const timer of this._scheduledAutoRefineTimers) {+ clearTimeout(timer);+ }+ this._scheduledAutoRefineTimers.clear();+ this._serializedPlanInFlight = undefined;+ this._serializedExplicitRefineOptions = undefined;+ this._pendingRequestedRefine = undefined;this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });this._autoRefineBranchVersion++;this._cancelActiveRlmChildRuns("Parent session disposed");@@ -2900,6 +3713,16 @@ export class AgentSession {// Prompting// =========================================================================+ private _refreshExtensionSystemPrompt(extensionPrompt: string, baseSnapshot: string): string {+ if (this._baseSystemPrompt === baseSnapshot) {+ return extensionPrompt;+ }+ if (!extensionPrompt.includes(baseSnapshot)) {+ return extensionPrompt;+ }+ return extensionPrompt.replace(baseSnapshot, () => this._baseSystemPrompt);+ }+/*** Send a prompt to the agent.* - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming@@ -2967,6 +3790,7 @@ export class AgentSession {let drainedNextTurnMessages: CustomMessage[] = [];const previewLabel = injectedMessagePreviewLabel(message);let extensionResult: Awaited<ReturnType<typeof this._extensionRunner.emitBeforeAgentStart>> | undefined;+ let basePromptSnapshot: string | undefined;try {const shouldQueueForStreaming = this.isStreaming;const shouldQueueForPendingWork =@@ -3031,10 +3855,11 @@ export class AgentSession {this._pendingNextTurnMessages = [];messages = [...drainedNextTurnMessages, message];+ basePromptSnapshot = this._baseSystemPrompt;extensionResult = await this._extensionRunner.emitBeforeAgentStart(text,undefined,- this._baseSystemPrompt,+ basePromptSnapshot,this._baseSystemPromptOptions,);if (extensionResult?.messages) {@@ -3049,7 +3874,10 @@ export class AgentSession {});}}- this.agent.state.systemPrompt = extensionResult?.systemPrompt ?? this._baseSystemPrompt;+ this.agent.state.systemPrompt =+ extensionResult?.systemPrompt !== undefined+ ? this._refreshExtensionSystemPrompt(extensionResult.systemPrompt, basePromptSnapshot)+ : this._baseSystemPrompt;} catch (error) {reportPreflight(false);throw error;@@ -3061,10 +3889,14 @@ export class AgentSession {if (this._refineInFlight) {await this._waitForRefineIdle();- // A refine may have completed during the wait and rewritten- // _baseSystemPrompt. Re-apply the extension-modified prompt if- // the extension provided one, otherwise use the refreshed base.- this.agent.state.systemPrompt = extensionResult?.systemPrompt ?? this._baseSystemPrompt;+ if (extensionResult?.systemPrompt !== undefined && basePromptSnapshot !== undefined) {+ this.agent.state.systemPrompt = this._refreshExtensionSystemPrompt(+ extensionResult.systemPrompt,+ basePromptSnapshot,+ );+ } else {+ this.agent.state.systemPrompt = this._baseSystemPrompt;+ }}const shouldQueueAtHandoff =options?.queueIfBusy === true &&@@ -3135,6 +3967,7 @@ export class AgentSession {let expandedText = text;let currentImages = options?.images;let extensionResult: Awaited<ReturnType<typeof this._extensionRunner.emitBeforeAgentStart>> | undefined;+ let basePromptSnapshot: string | undefined;try {let currentText = text;@@ -3346,10 +4179,11 @@ export class AgentSession {}// Emit before_agent_start extension event+ basePromptSnapshot = this._baseSystemPrompt;extensionResult = await this._extensionRunner.emitBeforeAgentStart(expandedText,currentImages,- this._baseSystemPrompt,+ basePromptSnapshot,this._baseSystemPromptOptions,);// Add all custom messages from extensions@@ -3365,13 +4199,9 @@ export class AgentSession {});}}- // Apply extension-modified system prompt, or reset to base- if (extensionResult?.systemPrompt) {- this.agent.state.systemPrompt = extensionResult.systemPrompt;- } else {- // Ensure we're using the base prompt (in case previous turn had modifications)- this.agent.state.systemPrompt = this._baseSystemPrompt;- }+ this.agent.state.systemPrompt = extensionResult?.systemPrompt+ ? this._refreshExtensionSystemPrompt(extensionResult.systemPrompt, basePromptSnapshot)+ : this._baseSystemPrompt;}} catch (error) {reportPreflight(false);@@ -3389,10 +4219,14 @@ export class AgentSession {// above may have suspended this turn long enough for a refine to start.if (this._refineInFlight) {await this._waitForRefineIdle();- // A refine may have completed during the wait and rewritten- // _baseSystemPrompt. Re-apply the extension-modified prompt if- // the extension provided one, otherwise use the refreshed base.- this.agent.state.systemPrompt = extensionResult?.systemPrompt ?? this._baseSystemPrompt;+ if (extensionResult?.systemPrompt && basePromptSnapshot !== undefined) {+ this.agent.state.systemPrompt = this._refreshExtensionSystemPrompt(+ extensionResult.systemPrompt,+ basePromptSnapshot,+ );+ } else {+ this.agent.state.systemPrompt = this._baseSystemPrompt;+ }}if (acceptedAgentMessagePrompt?.cleared) {reportPreflight(false);@@ -4221,6 +5055,10 @@ export class AgentSession {this.abortCompaction();this.abortBranchSummary();this.abortBash();+ this._pendingRequestedRefine = undefined;+ this._autoRefineBranchVersion++;+ this._autoRefineReviewAbort?.abort();+ this._refineAbortController?.abort();this._pendingMessageResumeRequested = false;this._pendingMessageResumeEpoch++;this.agent.abort();@@ -4749,7 +5587,7 @@ export class AgentSession {if (hadPostCompactionContinue) {this._schedulePostCompactionContinue();}- this._scheduleAutoRefine("compact");+ this._scheduleAutoRefineAfterCompaction(hadPostCompactionContinue);}}}@@ -4877,13 +5715,47 @@ export class AgentSession {this._autoRefineReviewAbort?.abort();this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });this._assistantTurnsSinceAutoRefine = 0;+ // Increment branch version BEFORE aborting/awaiting the serialized plan.+ // This invalidates the plan's branchVersion check at the boundary+ // so even if the plan completes, the boundary will reject it+ // (bgResult.branchVersion !== this._autoRefineBranchVersion).this._autoRefineBranchVersion++;+ // Abort the in-flight refine/bplan controller so any pending+ // _planRefine or _reviewAutoRefine call settles via signal abort+ // rather than hanging forever.+ this._refineAbortController?.abort();+ // Await and clear serialized background plan if in flight.+ if (this._serializedPlanInFlight) {+ await this._consumeSerializedBackgroundPlan(async () => false);+ }while (this._refinePlanInFlight) {await this._refinePlanInFlight;}await this._waitForRefineIdle();}+ /**+ * Consume a refine request that was scheduled by the agent-callable refine+ * skill (refine.run). Fire-and-forget: the refine() method handles its own+ * background planning, idle wait, application, and error recovery. Called+ * at the turn boundary after compaction checks and before auto-refine+ * scheduling so the manual request takes priority.+ */+ private _emitRefineFailed(error: unknown): void {+ this._emit({+ type: "refine_failed",+ error: error instanceof Error ? error.message : String(error),+ });+ }++ private _consumePendingRequestedRefine(): boolean {+ const pending = this._pendingRequestedRefine;+ if (!pending) return false;+ this._pendingRequestedRefine = undefined;+ void this.refine(pending).catch((error) => this._emitRefineFailed(error));+ return true;+ }+private _scheduleAutoRefineAfterAgentEnd(): void {if (!this._autoRefineAllowedForSession()) {return;@@ -4907,6 +5779,12 @@ export class AgentSession {if (!this._autoRefineAllowedForSession()) {return;}+ if (this._serializedRefine) {+ // Serialized sessions must service compaction-triggered refinement at+ // shouldStopAfterTurn (or disposal), never through the interactive path.+ this._compactAutoRefinePending = true;+ return;+ }if (willContinueAfterCompaction) {this._compactAutoRefinePending = true;return;@@ -4984,12 +5862,16 @@ export class AgentSession {}private _scheduleAutoRefine(reason: AutoRefineReason, branchVersion = this._autoRefineBranchVersion): void {- setTimeout(() => {+ const timer = setTimeout(() => {+ this._scheduledAutoRefineTimers.delete(timer);if (branchVersion !== this._autoRefineBranchVersion) {return;}- void this._maybeAutoRefine(reason);+ const operation = this._maybeAutoRefine(reason);+ this._autoRefineOperations.add(operation);+ void operation.finally(() => this._autoRefineOperations.delete(operation)).catch(() => undefined);}, 0);+ this._scheduledAutoRefineTimers.add(timer);}private async _maybeAutoRefine(reason: AutoRefineReason): Promise<void> {@@ -5180,14 +6062,34 @@ export class AgentSession {// starting a new run. This serializes concurrent /refine calls so two// planning phases cannot race into concurrent _applyRefine calls that// overwrite harness state.- while (this._refineInFlight || this._refinePlanInFlight) {- await (this._refineInFlight ?? this._refinePlanInFlight);+ while (this._refineInFlight || this._refinePlanInFlight || this._serializedPlanInFlight) {+ if (this._refineInFlight) {+ await this._refineInFlight;+ } else if (this._refinePlanInFlight) {+ await this._refinePlanInFlight;+ } else {+ // A serialized background plan is in flight (started during an+ // active turn at message_end). Wait for planning and for the active+ // turn to settle so its normal checkpoint can consume the plan.+ const serializedPlanInFlight = this._serializedPlanInFlight;+ await serializedPlanInFlight;+ if (this._refineInFlight || this._refinePlanInFlight) {+ continue;+ }+ await this.agent.waitForIdle();+ // Aborted turns skip shouldStopAfterTurn. Drop their settled plan+ // after idle so a later public refine cannot spin on it forever.+ if (this._serializedPlanInFlight === serializedPlanInFlight) {+ this._serializedPlanInFlight = undefined;+ this._serializedExplicitRefineOptions = undefined;+ }+ }}const refineAbort = new AbortController();this._refineAbortController = refineAbort;- // Background planning phase — does NOT block turn entry points.+ // Background planning phase — does NOT block turn entry pointsconst planRun = this._planRefine(options, refineAbort.signal);const planSettled = planRun.then(() => undefined,@@ -5217,9 +6119,27 @@ export class AgentSession {});this._refineInFlight = applySettled;try {- // Wait for any agent turn that started during background planning- // to finish before entering the application critical section.+ // Wait for the session to become quiescent before applying. Planning is+ // allowed to overlap active user work, but application must not disconnect+ // event handling until that work and its queued events have completed.await this.agent.waitForIdle();+ while (true) {+ const eventQueue = this._agentEventQueue;+ const compactionOp = this._compactionOperation;+ const branchSummaryOp = this._branchSummaryOperation;+ await Promise.allSettled([+ eventQueue,+ ...(compactionOp ? [compactionOp] : []),+ ...(branchSummaryOp ? [branchSummaryOp] : []),+ ]);+ if (+ eventQueue === this._agentEventQueue &&+ compactionOp === this._compactionOperation &&+ branchSummaryOp === this._branchSummaryOperation+ ) {+ break;+ }+ }if (this._disposed || refineAbort.signal.aborted) {throw new Error("Refinement cancelled because the session was disposed.");}@@ -5229,7 +6149,7 @@ export class AgentSession {if (this._refineInFlight === applySettled) {this._refineInFlight = undefined;}- this._schedulePendingMessageResume();+ this._schedulePendingMessageResume(true);}}@@ -5250,8 +6170,8 @@ export class AgentSession {/*** Background planning phase: runs the LLM planning call via `planRefinement`.- * Does NOT call `_disconnectFromAgent` or `this.abort` — those happen in- * `_applyRefine`. Returns the plan without applying anything.+ * Does not disconnect from or abort the agent. Returns the plan without+ * applying anything.*/private async _planRefine(options: { instructions?: string; rollbackId?: string; global?: boolean },@@ -5273,13 +6193,17 @@ export class AgentSession {if (!options.rollbackId && requestedScope === "local" && !localHarnessStateDir) {throw new Error("Local harness refinement requires a persisted session; use global refinement instead.");}+ const globalPlanningState = loadHarnessState(globalHarnessStateDir, "global");+ const localPlanningState = localHarnessStateDir ? loadHarnessState(localHarnessStateDir, "local") : undefined;const planningState =requestedScope === "global"- ? loadHarnessState(globalHarnessStateDir, "global")- : this._loadMergedHarnessState();+ ? globalPlanningState+ : mergeHarnessStates(globalPlanningState, localPlanningState);const history = this._loadRefinementHistory();const rollbackTarget = options.rollbackId ? history.find((item) => item.id === options.rollbackId) : undefined;- let baselineScope = rollbackTarget?.scope ?? requestedScope;+ let baselineScope = rollbackTarget+ ? (inferRefinementResultScope(rollbackTarget) ?? requestedScope)+ : requestedScope;let baselineHarnessStateDir = baselineScope === "global" ? globalHarnessStateDir : localHarnessStateDir;if (rollbackTarget?.harnessStatePath) {baselineHarnessStateDir = dirname(rollbackTarget.harnessStatePath);@@ -5288,7 +6212,11 @@ export class AgentSession {if (!baselineHarnessStateDir) {throw new Error("Local harness refinement requires a persisted session; use global refinement instead.");}- const baselineState = loadHarnessState(baselineHarnessStateDir, baselineScope);+ const baselineState = rollbackTarget+ ? loadHarnessState(baselineHarnessStateDir, baselineScope)+ : baselineScope === "global"+ ? globalPlanningState+ : localPlanningState!;const plan = await planRefinement(this.agent.state.messages,planningState,@@ -5381,6 +6309,24 @@ export class AgentSession {this.sessionManager.appendCustomEntry("prime-agent.refinement", result);this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());this.agent.state.systemPrompt = this._baseSystemPrompt;+ try {+ this._emit({ type: "refine_complete", result });+ } catch {+ // Listener failures must not flip a successful refinement into+ // a reported failure — the refinement is already persisted.+ }+ try {+ await this._extensionRunner.emit({+ type: "refine_complete",+ id: result.id,+ summary: result.summary,+ appliedEdits: result.appliedEdits.filter((edit) => edit.applied).length,+ scope: result.scope ?? "local",+ });+ } catch {+ // Extension emit failures must not flip a successful refinement+ // into a reported failure — the refinement is already persisted.+ }return result;} finally {if (this._refineAbortController === refineAbort) {@@ -5443,6 +6389,22 @@ export class AgentSession {// pre-prompt path (skipAbortedCheck=false) which continues to threshold checks.if (assistantMessage.stopReason === "aborted") {this._pendingRequestedCompaction = undefined;+ // An abort also drops any pending explicit refine.run request: the+ // turn that would service it (non-serialized: _consumePendingRequestedRefine+ // at agent_end; serialized: the shouldStopAfterTurn checkpoint) never+ // runs for an aborted turn, so a stale request would leak into the+ // next turn or checkpoint.+ this._pendingRequestedRefine = undefined;+ if (this._serializedPlanInFlight) {+ const serializedPlanInFlight = this._serializedPlanInFlight;+ this._autoRefineBranchVersion++;+ this._refineAbortController?.abort();+ await serializedPlanInFlight.catch(() => undefined);+ if (this._serializedPlanInFlight === serializedPlanInFlight) {+ this._serializedPlanInFlight = undefined;+ this._serializedExplicitRefineOptions = undefined;+ }+ }if (skipAbortedCheck) return false;}@@ -6104,6 +7066,9 @@ export class AgentSession {if (!this._includeCompactSkill) {skills = skills.filter((skill) => skill.name !== COMPACT_SKILL_NAME);}+ if (!this._autoRefineAllowedForSession()) {+ skills = skills.filter((skill) => skill.name !== REFINE_SKILL_NAME);+ }if (!this._agentMessageController) {skills = skills.filter((skill) => skill.name !== AGENT_MESSAGE_SKILL_NAME);}@@ -6141,6 +7106,11 @@ export class AgentSession {handlers[type] = async (payload) => this.handleCompactHostRequest(type, payload);}}+ if (this._autoRefineAllowedForSession()) {+ for (const type of ["refine.run", "refine.status"]) {+ handlers[type] = async (payload) => this.handleRefineHostRequest(type, payload);+ }+ }if (this._rlmHeartbeatController) {for (const type of ["rlm_heartbeat.list",diff --git a/packages/coding-agent/src/core/extensions/index.ts b/packages/coding-agent/src/core/extensions/index.tsindex 820b6b47d9..0ddadf4a1d 100644--- a/packages/coding-agent/src/core/extensions/index.ts+++ b/packages/coding-agent/src/core/extensions/index.ts@@ -102,6 +102,7 @@ export type {// Provider RegistrationProviderConfig,ProviderModelConfig,+ RefineCompleteEvent,// CommandsRegisteredCommand,RegisteredTool,diff --git a/packages/coding-agent/src/core/extensions/types.ts b/packages/coding-agent/src/core/extensions/types.tsindex b0dfecb1f7..99b86a5b78 100644--- a/packages/coding-agent/src/core/extensions/types.ts+++ b/packages/coding-agent/src/core/extensions/types.ts@@ -645,6 +645,19 @@ export interface AgentEndEvent {messages: AgentMessage[];}+/** Fired when a continual-harness refinement completes (auto-refine or explicit /refine). */+export interface RefineCompleteEvent {+ type: "refine_complete";+ /** Unique refinement id. */+ id: string;+ /** Human-readable summary of the refinement. */+ summary: string;+ /** Number of edits applied. */+ appliedEdits: number;+ /** Whether the refinement was applied to the global or local harness. */+ scope: "global" | "local";+}+/** Fired at the start of each turn */export interface TurnStartEvent {type: "turn_start";@@ -902,7 +915,8 @@ export type ExtensionEvent =| UserBashEvent| InputEvent| ToolCallEvent- | ToolResultEvent;+ | ToolResultEvent+ | RefineCompleteEvent;// ============================================================================// Event Results@@ -1057,6 +1071,7 @@ export interface ExtensionAPI {on(event: "tool_result", handler: ExtensionHandler<ToolResultEvent, ToolResultEventResult>): void;on(event: "user_bash", handler: ExtensionHandler<UserBashEvent, UserBashEventResult>): void;on(event: "input", handler: ExtensionHandler<InputEvent, InputEventResult>): void;+ on(event: "refine_complete", handler: ExtensionHandler<RefineCompleteEvent>): void;// =========================================================================// Tool Registrationdiff --git a/packages/coding-agent/src/core/prompts/rlm.ts b/packages/coding-agent/src/core/prompts/rlm.tsindex 4bfd21331a..abcd6bed8b 100644--- a/packages/coding-agent/src/core/prompts/rlm.ts+++ b/packages/coding-agent/src/core/prompts/rlm.ts@@ -29,8 +29,6 @@ const IPYTHON_CONTROL_PROMPT = ["Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, IPython kernel, and native call interface exposed to the model.","","RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.",- "",- "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",].join("\n");export function buildRlmPrompt(options: RlmPromptOptions): string {@@ -97,6 +95,12 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {if (hasIpython) {parts.push("", IPYTHON_CONTROL_PROMPT);+ if (installedSkills.includes("refine")) {+ parts.push(+ "",+ "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",+ );+ }}return parts.join("\n");@@ -110,8 +114,8 @@ export function buildRlmPrompt(options: RlmPromptOptions): string {* uses. The subagent-spec menu itself renders just after this, inside the* harness-state block.*/-export function buildSubagentGuidance(): string {- return [+export function buildSubagentGuidance(options: { includeRefineExamples?: boolean } = {}): string {+ const lines = ["# Delegating to sub-agents","","You already have `rlm` in scope. This is about *when* to spawn one — which matters as much as how.",@@ -153,6 +157,11 @@ export function buildSubagentGuidance(): string {"```","","These are illustrations, not a fixed menu: delegate any self-contained sub-task that fits the cases above.",- "When you notice a delegation role, procedure, fact, preference, or behavior policy that should be reused, use `/refine` to create or update the smallest relevant subagent spec, skill, memory, or prompt addendum.",- ].join("\n");+ ];+ if (options.includeRefineExamples ?? true) {+ lines.push(+ "When you notice a delegation role, procedure, fact, preference, or behavior policy that should be reused, use `await refine.run()` to create or update the smallest relevant subagent spec, skill, memory, or prompt addendum.",+ );+ }+ return lines.join("\n");}diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.tsindex 112cbefc87..589d5259c8 100644--- a/packages/coding-agent/src/core/refinement/refinement.ts+++ b/packages/coding-agent/src/core/refinement/refinement.ts@@ -1,4 +1,14 @@-import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { randomUUID } from "node:crypto";+import {+ appendFileSync,+ existsSync,+ mkdirSync,+ readFileSync,+ renameSync,+ statSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";import { join } from "node:path";import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";import type { Model } from "@earendil-works/pi-ai";@@ -9,6 +19,8 @@ import { convertToLlm } from "../messages.js";import type { CustomEntry } from "../session-manager.js";export const REFINEMENT_CUSTOM_TYPE = "prime-agent.refinement";++export const REFINE_SKILL_NAME = "refine";const HARNESS_STATE_DIR_NAME = "harness";const REFINEMENT_HISTORY_FILE_NAME = "refinements.jsonl";const DEFAULT_OVERVIEW_ENTRY_LIMIT = 6;@@ -214,7 +226,7 @@ function normalizeHarnessScope(value: unknown, fallback: HarnessScope): HarnessSreturn value === "global" || value === "local" ? value : fallback;}-function inferRefinementResultScope(result: RefinementResult): HarnessScope | undefined {+export function inferRefinementResultScope(result: RefinementResult): HarnessScope | undefined {if (result.scope) {return result.scope;}@@ -312,8 +324,17 @@ export function mergeHarnessStates(globalState: HarnessState, localState?: Harneexport function saveHarnessState(harnessStateDir: string, state: HarnessState): string {const statePath = getHarnessStatePath(harnessStateDir);+ const tempPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;mkdirSync(harnessStateDir, { recursive: true });- writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");+ try {+ const mode = existsSync(statePath) ? statSync(statePath).mode & 0o777 : 0o600;+ writeFileSync(tempPath, `${JSON.stringify(state, null, 2)}\n`, { encoding: "utf8", mode });+ renameSync(tempPath, statePath);+ } finally {+ if (existsSync(tempPath)) {+ unlinkSync(tempPath);+ }+ }return statePath;}@@ -393,12 +414,14 @@ export function formatHarnessStateForPrompt(maxContentLength?: number;includeIpythonExamples?: boolean;includeShellExamples?: boolean;+ includeRefineExamples?: boolean;} = {},): string {const maxEntriesPerKind = options.maxEntriesPerKind ?? DEFAULT_OVERVIEW_ENTRY_LIMIT;const maxRefinements = options.maxRefinements ?? DEFAULT_OVERVIEW_REFINEMENT_LIMIT;const maxContentLength = options.maxContentLength ?? DEFAULT_OVERVIEW_CONTENT_LIMIT;const includeIpythonExamples = options.includeIpythonExamples ?? true;+ const includeRefineExamples = options.includeRefineExamples ?? includeIpythonExamples;const lines = ["# Continual Harness State","",@@ -407,7 +430,9 @@ export function formatHarnessStateForPrompt("Default to local continual harness refinement for current task progress, temporary blockers, and session coordination. Use global continual harness refinement only for stable cross-session lessons, durable user preferences, reusable skills/subagents, or explicitly project-qualified facts.","Use these continual harness prompt notes, memories, skills, and subagent specs when they are relevant. The base system prompt is immutable; prompt entries below are supplemental notes only.","",- "When to call `/refine`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `/refine` continual harness edits small and evidence-backed.",+ includeRefineExamples+ ? "When to call `await refine.run()`: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep `await refine.run()` continual harness edits small and evidence-backed."+ : "When to refine the continual harness: after a repeated failure, a reusable tactic emerges, a repeated delegation role should become a subagent spec, a repeated procedure should become a skill, a durable fact/preference should become a memory, a narrow behavioral policy should become a prompt addendum, a user corrects behavior that should persist locally or globally, validation shows a continual harness entry is wrong, or a skill/subagent/memory/prompt note should be created, updated, deleted, or rolled back. Keep continual harness edits small and evidence-backed.","",includeIpythonExamples? "Call contract: read each installed Python skill's SKILL.md and call its documented module function in IPython; do not assume a `.run` entrypoint. Use `<skill_import> ...` in shell when a CLI exists. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are invoked by composing a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then awaiting only when the result is needed; use `await asyncio.gather(rlm('task1'), rlm('task2'))` for independent parallel subagents. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries."@@ -613,6 +638,7 @@ export function applyRefinementProposal(options: { id: string; rollbackOf?: string; scope?: HarnessScope; baselineState?: HarnessState },): RefinementResult {const appliedEdits: AppliedRefinementEdit[] = [];+ const proposalModifiedKeys = new Set<string>();for (const edit of proposal.edits) {const computedId = edit.id ?? (edit.action === "create" ? slug(edit.title ?? edit.kind, edit.kind) : undefined);const id = computedId ?? "";@@ -624,8 +650,13 @@ export function applyRefinementProposal(const records = state.entries[edit.kind];const before = cloneEntry(records[id]);+ const entryKey = `${edit.kind}:${id}`;const baseline = cloneEntry(options.baselineState?.entries[edit.kind][id]);- if (options.baselineState && JSON.stringify(before) !== JSON.stringify(baseline)) {+ if (+ options.baselineState &&+ !proposalModifiedKeys.has(entryKey) &&+ JSON.stringify(before) !== JSON.stringify(baseline)+ ) {appliedEdits.push({...edit,id,@@ -641,6 +672,7 @@ export function applyRefinementProposal(continue;}delete records[id];+ proposalModifiedKeys.add(entryKey);appliedEdits.push({ ...edit, id, before, applied: true });continue;}@@ -671,6 +703,7 @@ export function applyRefinementProposal(version,};records[id] = after;+ proposalModifiedKeys.add(entryKey);appliedEdits.push({ ...edit, id, before, after: cloneEntry(after), applied: true });}diff --git a/packages/coding-agent/src/core/sdk.ts b/packages/coding-agent/src/core/sdk.tsindex 0d73925bde..f4055b005b 100644--- a/packages/coding-agent/src/core/sdk.ts+++ b/packages/coding-agent/src/core/sdk.ts@@ -395,6 +395,8 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}sessionStartEvent: options.sessionStartEvent,prewarmIpythonKernel: options.prewarmIpythonKernel,autonomous: options.autonomous,+ serializedRefine: options.serializedRefine,+ initialGoal: options.initialGoal,});const extensionsResult = resourceLoader.getExtensions();diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex 00cafa8101..1840af57dd 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -1273,6 +1273,20 @@ export class SessionManager {return this.persist ? getSessionArtifactPath(this.sessionDir, this.sessionId) : undefined;}+ /**+ * Force-write all in-memory entries to the session file immediately.+ * This bypasses the no-assistant guard in {@link _persist} so that+ * pre-model entries (session header, goal state, settings changes)+ * are durable on disk before the first assistant response.+ * No-op for in-memory (non-persisted) sessions.+ */+ flushNow(): void {+ if (!this.persist || !this.sessionFile) return;+ if (this.flushed && existsSync(this.sessionFile)) return;+ this._rewriteFile();+ this.flushed = true;+ }+_persist(entry: SessionEntry): void {if (!this.persist || !this.sessionFile) return;diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.tsindex 7a9154fd96..5f84502995 100644--- a/packages/coding-agent/src/core/system-prompt.ts+++ b/packages/coding-agent/src/core/system-prompt.ts@@ -3,7 +3,7 @@*/import { buildRlmPrompt, buildSubagentGuidance } from "./prompts/index.js";-import { formatHarnessStateForPrompt, type HarnessState } from "./refinement/index.js";+import { formatHarnessStateForPrompt, type HarnessState, REFINE_SKILL_NAME } from "./refinement/index.js";import { formatSkillsForPrompt, getPythonSkillRuntimeInfo, type Skill } from "./skills.js";export interface BuildSystemPromptOptions {@@ -62,6 +62,7 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {const hasIpython = tools.includes("ipython");const hasBash = tools.includes("bash");const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);+ const hasRefineSkill = visibleSkills.some((skill) => skill.name === REFINE_SKILL_NAME);if (customPrompt) {let prompt = customPrompt;@@ -87,7 +88,7 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {prompt += `\nCurrent working directory: ${promptCwd}`;if (harnessState) {- prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash })}`;+ prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash, includeRefineExamples: hasIpython && hasRefineSkill })}`;}if (appendSection) {@@ -109,11 +110,11 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {// menu, so the model reads when/why to delegate and then sees the concrete subagent// specs it can match against — the same ordering as Claude Code's Agent tool.if ((allowRecursion ?? true) && hasIpython) {- prompt += `\n\n${buildSubagentGuidance()}`;+ prompt += `\n\n${buildSubagentGuidance({ includeRefineExamples: hasRefineSkill })}`;}if (harnessState) {- prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash })}`;+ prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash, includeRefineExamples: hasIpython && hasRefineSkill })}`;}const guidelines = formatPromptGuidelines(promptGuidelines);diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.tsindex b76eaf3a61..3b7c135716 100644--- a/packages/coding-agent/src/index.ts+++ b/packages/coding-agent/src/index.ts@@ -93,6 +93,7 @@ export type {MessageRenderOptions,ProviderConfig,ProviderModelConfig,+ RefineCompleteEvent,RegisteredCommand,RegisteredTool,ResolvedCommand,diff --git a/packages/coding-agent/src/main.ts b/packages/coding-agent/src/main.tsindex 76b7f4de74..803dd660f9 100644--- a/packages/coding-agent/src/main.ts+++ b/packages/coding-agent/src/main.ts@@ -643,6 +643,7 @@ function runtimeConfigFromArgs(cwd: string,agentDir: string,sessionDir: string | undefined,+ appMode: AppMode,): AgentSessionRuntimeConfig {return {cwd,@@ -669,6 +670,12 @@ function runtimeConfigFromArgs(noContextFiles: parsed.noContextFiles,autonomous: runtimeAutonomousConfigFromArgs(parsed),extensionFlagValues: parsed.unknownFlags.size > 0 ? Object.fromEntries(parsed.unknownFlags.entries()) : undefined,+ // Serialized refine for print/json/rpc: the client's appMode is NOT+ // "daemon" here — it's "print", "json", or "rpc". The daemon worker+ // receives this flag via AgentSessionRuntimeConfig and uses it+ // instead of its own appMode="daemon".+ serializedRefine: appMode !== "interactive" && appMode !== "daemon",+ initialGoal: parsed.goal ? { objective: parsed.goal, tokenBudget: parsed.goalTokenBudget } : undefined,};}@@ -680,6 +687,10 @@ interface PreparedRuntimeServices {diagnostics: AgentSessionRuntimeDiagnostic[];}+export function daemonServerDefaultSessionConfig(config: AgentSessionRuntimeConfig): AgentSessionRuntimeConfig {+ return { ...config, initialGoal: undefined };+}+export function resolveRuntimeSessionOptions(sessionOptions: CreateAgentSessionOptions,runtimeSessionOptions?: CreateAgentSessionOptions,@@ -1065,6 +1076,7 @@ export async function main(args: string[], options?: MainOptions) {}time("parseArgs");let appMode = resolveAppMode(parsed, process.stdin.isTTY);+if (shouldRejectNonInteractiveAttach(publicCommand.attachAgent, appMode)) {console.error(chalk.red("Error: attach requires an interactive terminal"));process.exit(1);@@ -1228,7 +1240,11 @@ export async function main(args: string[], options?: MainOptions) {}time("createSessionManager");- const defaultSessionConfig = runtimeConfigFromArgs(parsed, sessionManager.getCwd(), agentDir, sessionDir);+ const defaultSessionConfig = runtimeConfigFromArgs(parsed, sessionManager.getCwd(), agentDir, sessionDir, appMode);+ // Verifier/headless clients pass initialGoal in each create request. The long-lived+ // daemon fallback must not seed that goal into unrelated future sessions.+ const daemonDefaultSessionConfig = daemonServerDefaultSessionConfig(defaultSessionConfig);+ const runtimeDefaultSessionConfig = appMode === "daemon" ? daemonDefaultSessionConfig : defaultSessionConfig;const createRuntime: CreateAgentSessionRuntimeFactory = async ({cwd,agentDir,@@ -1237,7 +1253,7 @@ export async function main(args: string[], options?: MainOptions) {sessionConfig,sessionOptions: runtimeSessionOptions,}) => {- const config = mergeAgentSessionRuntimeConfig(defaultSessionConfig, sessionConfig);+ const config = mergeAgentSessionRuntimeConfig(runtimeDefaultSessionConfig, sessionConfig);const prepared = await prepareRuntimeServices({config,cwd,@@ -1257,6 +1273,12 @@ export async function main(args: string[], options?: MainOptions) {// Main agents boot their kernel in the background at session creation;// subagent sessions (rlmDepth > 0) keep the lazy first-call start.prewarmIpythonKernel: true,+ // Read serializedRefine from the merged runtime config (passed+ // from the JSON/print client through AgentSessionRuntimeConfig)+ // so it survives the daemon worker's appMode="daemon" context.+ serializedRefine: config.serializedRefine ?? false,+ // Only seed initial goal for top-level sessions (rlmDepth 0).+ initialGoal: (runtimeSessionOptions?.rlmDepth ?? 0) === 0 ? config.initialGoal : undefined,});const cliThinkingOverride = config.thinking !== undefined || prepared.cliThinkingFromModel;if (created.session.model && cliThinkingOverride) {@@ -1279,7 +1301,7 @@ export async function main(args: string[], options?: MainOptions) {if (isDaemonWorkerProcess()) {await runDaemonMode({socketPath: parsed.daemonSocket,- defaultSessionConfig,+ defaultSessionConfig: daemonDefaultSessionConfig,createRuntime,worker: {authenticationToken: requireDaemonWorkerAuthenticationToken(),@@ -1289,7 +1311,7 @@ export async function main(args: string[], options?: MainOptions) {} else {await runDaemonSupervisorMode({socketPath: parsed.daemonSocket,- defaultSessionConfig,+ defaultSessionConfig: daemonDefaultSessionConfig,});}return;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 661810c111..f9b831f2a3 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@@ -1336,7 +1336,9 @@ export class DaemonAgentConnection implements AgentConnection {this.observeDaemonEventSequence(message);if (message.type === "session_event") {- this.observeStreamingMessage(message.event);+ if (message.event.type !== "refine_complete" && message.event.type !== "refine_failed") {+ this.observeStreamingMessage(message.event);+ }this.latestSnapshotIsFresh = false;await this.emit({ type: "session_event", event: message.event });return;diff --git a/packages/coding-agent/src/modes/agent-connection/types.ts b/packages/coding-agent/src/modes/agent-connection/types.tsindex 817e376924..6c32824610 100644--- a/packages/coding-agent/src/modes/agent-connection/types.ts+++ b/packages/coding-agent/src/modes/agent-connection/types.ts@@ -567,7 +567,9 @@ export type AgentConnectionSessionEvent =fullOutputPath?: string;/** Set when execution failed before producing a result (e.g. spawn failure) */errorMessage?: string;- };+ }+ | { type: "refine_complete"; result: RefinementResult }+ | { type: "refine_failed"; error: string };export type AgentConnectionEvent =| { type: "session_event"; event: AgentConnectionSessionEvent }diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex a5b3802fe8..0aef897a9d 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -22,7 +22,7 @@ import {} from "node:fs";import { createConnection, createServer, type Server, type Socket } from "node:net";import { dirname, join, resolve } from "node:path";-import { getLogger } from "@earendil-works/pi-ai";+import { type Api, getLogger, type Model } from "@earendil-works/pi-ai";import { createCliSubprocessEnv, createCliSubprocessLaunchSpec } from "../../cli/subprocess-launch.js";import {appendRotatingLog,@@ -345,6 +345,7 @@ interface PersistedRlmSubagentRegistryEntry {rlmParentNodeId?: string;prompt?: string;spawnCode?: string;+ model?: { provider: string; modelId: string };status: "running" | "completed" | "deleted";createdAt: number;updatedAt: string;@@ -806,6 +807,7 @@ export class AgentDaemon {rlmParentNodeId?: string;prompt?: string;spawnCode?: string;+ model?: { provider: string; modelId: string };status: PersistedRlmSubagentRegistryEntry["status"];createdAt?: number;},@@ -824,6 +826,7 @@ export class AgentDaemon {...(input.rlmParentNodeId ? { rlmParentNodeId: input.rlmParentNodeId } : {}),...(input.prompt ? { prompt: input.prompt } : {}),...(input.spawnCode ? { spawnCode: input.spawnCode } : {}),+ ...(input.model ? { model: input.model } : {}),status: input.status,createdAt: input.createdAt ?? Date.now(),updatedAt: new Date().toISOString(),@@ -1809,6 +1812,7 @@ export class AgentDaemon {// a late completion cannot overwrite a durable deletion tombstone.if (options.parentSession.retainFinishedRlmChildSession(options.id, runtime.session)) {if (runtime.session.sessionFile) {+ const retainedModel = runtime.session.model ?? options.model;this.recordRlmSubagentRegistryEntry(parentState, {childId: options.id,sessionName: runtime.session.sessionName ?? options.sessionName,@@ -1819,6 +1823,9 @@ export class AgentDaemon {rlmParentNodeId: options.rlmParentNodeId,prompt: options.prompt.length <= 4096 ? options.prompt : undefined,spawnCode: options.spawnCode,+ ...(retainedModel+ ? { model: { provider: retainedModel.provider, modelId: retainedModel.id } }+ : {}),status: "completed",createdAt: state.runtime.metadata.createdAt,});@@ -1936,6 +1943,7 @@ export class AgentDaemon {rlmParentNodeId: options.rlmParentNodeId,prompt: options.prompt.length <= 4096 ? options.prompt : undefined,spawnCode: options.spawnCode,+ model: { provider: options.model.provider, modelId: options.model.id },status: "running",createdAt: runtime.metadata.createdAt,});@@ -1984,6 +1992,14 @@ export class AgentDaemon {let runtime: AgentSessionRuntime | undefined;try {const sessionManager = await SessionManager.openAsync(entry.sessionFile, entry.sessionDir);+ const modelRegistry = parentState.runtime.services.modelRegistry;+ let rehydratedModel: Model<Api> | undefined;+ if (entry.model) {+ const resolved = modelRegistry.find(entry.model.provider, entry.model.modelId);+ if (resolved && (await modelRegistry.canUseModel(resolved))) {+ rehydratedModel = resolved;+ }+ }runtime = await withClientEnv(parentState.clientEnv, () =>createAgentSessionRuntime(this.options.createRuntime, {cwd: sessionManager.getCwd(),@@ -1992,6 +2008,7 @@ export class AgentDaemon {sessionStartEvent: { type: "session_start", reason: "startup" },sessionConfig: parentState.runtime.runtimeConfig,sessionOptions: {+ ...(rehydratedModel ? { model: rehydratedModel } : {}),agentMessageController: this.createAgentMessageController(() => stateRef),agentObserveController: this.createAgentObserveController(() => stateRef),rlmHeartbeatController: {diff --git a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts b/packages/coding-agent/src/modes/daemon/daemon-protocol.tsindex 559135c5fe..7ad382c46b 100644--- a/packages/coding-agent/src/modes/daemon/daemon-protocol.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-protocol.ts@@ -49,8 +49,8 @@ import type { SessionSummary } from "./daemon-session-list.js";export const DAEMON_PROTOCOL_NAME = "prime-agent.daemon";export const DAEMON_PROTOCOL_VERSION = 4;export const DAEMON_COMMAND_ENVELOPE_MIN_PROTOCOL_VERSION = 2;-export const DAEMON_SCHEMA_REVISION = 2;-export const DAEMON_SCHEMA_ID = "protocol-4-schema-2-cbdbe20e7ce4";+export const DAEMON_SCHEMA_REVISION = 3;+export const DAEMON_SCHEMA_ID = "protocol-4-schema-3-cbdbe20e7ce4";export type DaemonProtocolName = typeof DAEMON_PROTOCOL_NAME;export type DaemonProtocolVersion = number;diff --git a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts b/packages/coding-agent/src/modes/daemon/daemon-supervisor.tsindex b85b89949a..9f4c23beba 100644--- a/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-supervisor.ts@@ -3044,10 +3044,18 @@ export class DaemonSupervisor {);return;}+ // Snapshot summaries/state include live fields (for example activity and attached client+ // counts) that can change without advancing the transcript sequence. Treat the stable+ // transfer envelope as identity; duplicate chunks and end metadata are still byte-checked.const duplicate =generation?.transcript.complete === true &&generation.end !== undefined &&- generation.begin?.equals(frame.payload) === true;+ generation.result.snapshotStream?.messageCount === begin.messageCount &&+ generation.result.snapshotStream?.targetChunkBytes === begin.targetChunkBytes &&+ generation.result.lastEventSequence === result.lastEventSequence &&+ generation.result.snapshot.lastEventSequence === result.snapshot.lastEventSequence &&+ generation.result.snapshot.lastEventCursor?.generation === result.snapshot.lastEventCursor?.generation &&+ generation.result.snapshot.lastEventCursor?.sequence === result.snapshot.lastEventCursor?.sequence;if (generation?.transcript.complete && !duplicate) {this.failWorkerSnapshotCache(worker,diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex 63779382cf..47e9b48361 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -5146,6 +5146,13 @@ export class InteractiveMode {case "goal_update":this.handleGoalUpdate(event.goal);break;++ case "refine_failed":+ this.showError(`Refinement failed: ${event.error}`);+ break;++ case "refine_complete":+ break;}}diff --git a/packages/coding-agent/test/agent-session-config.test.ts b/packages/coding-agent/test/agent-session-config.test.tsindex f9b330a467..5825482411 100644--- a/packages/coding-agent/test/agent-session-config.test.ts+++ b/packages/coding-agent/test/agent-session-config.test.ts@@ -115,4 +115,40 @@ describe("mergeAgentSessionRuntimeConfig", () => {noTools: false,});});++ it("merges initialGoal from override over base", () => {+ const defaults: AgentSessionRuntimeConfig = {+ cwd: "/repo",+ agentDir: "/agent",+ initialGoal: { objective: "base goal", tokenBudget: 50000 },+ };+ const merged = mergeAgentSessionRuntimeConfig(defaults, {+ cwd: "/override",+ initialGoal: { objective: "override goal" },+ });+ expect(merged.initialGoal).toEqual({ objective: "override goal" });+ });++ it("preserves base initialGoal when override omits it", () => {+ const defaults: AgentSessionRuntimeConfig = {+ cwd: "/repo",+ agentDir: "/agent",+ initialGoal: { objective: "base goal", tokenBudget: 50000 },+ };+ const merged = mergeAgentSessionRuntimeConfig(defaults, { model: "openai/gpt-4o" });+ expect(merged.initialGoal).toEqual({ objective: "base goal", tokenBudget: 50000 });+ });++ it("clones initialGoal so mutating the original does not affect the merged config", () => {+ const base: AgentSessionRuntimeConfig = {+ cwd: "/repo",+ agentDir: "/agent",+ initialGoal: { objective: "base goal", tokenBudget: 50000 },+ };+ const merged = mergeAgentSessionRuntimeConfig(base);+ expect(merged.initialGoal).toEqual({ objective: "base goal", tokenBudget: 50000 });+ // Mutating the original should not affect the clone+ base.initialGoal!.objective = "mutated";+ expect(merged.initialGoal?.objective).toBe("base goal");+ });});diff --git a/packages/coding-agent/test/args.test.ts b/packages/coding-agent/test/args.test.tsindex e2899f0bb3..b1674d2f46 100644--- a/packages/coding-agent/test/args.test.ts+++ b/packages/coding-agent/test/args.test.ts@@ -432,6 +432,13 @@ describe("parseArgs", () => {});});+ test("accepts a gate command that starts with an unknown short flag", () => {+ const result = parseArgs(["--autonomous-gate", "-x npm test"]);++ expect(result.autonomousGates).toEqual(["-x npm test"]);+ expect(result.diagnostics).toEqual([]);+ });+test.each(["--autonomous-gate","--autonomous-gate-retries",@@ -593,5 +600,74 @@ describe("parseArgs", () => {expect(result.diagnostics).toEqual([]);expect(result.unknownFlags.size).toBe(0);});++ test("parses --goal as a string", () => {+ const result = parseArgs(["--goal", "Write a paper"]);+ expect(result.goal).toBe("Write a paper");+ expect(result.diagnostics).toEqual([]);+ });++ test("parses --goal-token-budget as a positive integer with --goal", () => {+ const result = parseArgs(["--goal", "test goal", "--goal-token-budget", "50000"]);+ expect(result.goalTokenBudget).toBe(50000);+ expect(result.diagnostics).toEqual([]);+ });++ test("rejects non-positive --goal-token-budget", () => {+ const result = parseArgs(["--goal-token-budget", "0"]);+ expect(result.goalTokenBudget).toBeUndefined();+ expect(result.diagnostics).toEqual([+ { type: "error", message: "--goal-token-budget must be a positive integer" },+ ]);+ });++ test("parses --goal and --goal-token-budget together", () => {+ const result = parseArgs(["--goal", "Fix all bugs", "--goal-token-budget", "100000"]);+ expect(result.goal).toBe("Fix all bugs");+ expect(result.goalTokenBudget).toBe(100000);+ });++ test("trailing --goal without value produces an error", () => {+ const result = parseArgs(["--goal"]);+ expect(result.goal).toBeUndefined();+ expect(result.diagnostics).toEqual([{ type: "error", message: "--goal requires a value" }]);+ });++ test("trailing --goal-token-budget without value produces an error", () => {+ const result = parseArgs(["--goal-token-budget"]);+ expect(result.goalTokenBudget).toBeUndefined();+ expect(result.diagnostics).toEqual([{ type: "error", message: "--goal-token-budget requires a value" }]);+ });++ test("--goal followed by --other flag produces an error for --goal", () => {+ const result = parseArgs(["--goal", "--verbose"]);+ expect(result.goal).toBeUndefined();+ expect(result.diagnostics).toEqual([{ type: "error", message: "--goal requires a value" }]);+ });++ test("--goal accepts a dash-prefixed objective", () => {+ const result = parseArgs(["--goal", "-p"]);++ expect(result.goal).toBe("-p");+ expect(result.print).toBeUndefined();+ expect(result.diagnostics).toEqual([]);+ });++ test("--goal-token-budget without --goal produces an error", () => {+ const result = parseArgs(["--goal-token-budget", "50000"]);+ expect(result.diagnostics).toContainEqual({+ type: "error",+ message: "--goal-token-budget requires --goal",+ });+ });++ test("empty --goal value produces an error", () => {+ const result = parseArgs(["--goal", " "]);+ expect(result.goal).toBeUndefined();+ expect(result.diagnostics).toContainEqual({+ type: "error",+ message: "--goal requires a non-empty objective",+ });+ });});});diff --git a/packages/coding-agent/test/daemon-command.test.ts b/packages/coding-agent/test/daemon-command.test.tsindex cd298873bd..71777eda3f 100644--- a/packages/coding-agent/test/daemon-command.test.ts+++ b/packages/coding-agent/test/daemon-command.test.ts@@ -15,7 +15,10 @@ const daemonClientMock = vi.hoisted(() => {prompt?: string;includeInactive?: boolean;sessionPath?: string;- config?: { extensionFlagValues?: Record<string, boolean | string> };+ config?: {+ extensionFlagValues?: Record<string, boolean | string>;+ initialGoal?: { objective: string; tokenBudget?: number };+ };};type Response =| { type: "response"; command: string; success: true; data?: unknown }@@ -25,6 +28,7 @@ const daemonClientMock = vi.hoisted(() => {const behavior = {promptSucceeds: false,emitStaleAgentEndOnAttach: false,+ connectFails: false,sessions: [] as Array<Record<string, unknown>>,};@@ -39,7 +43,9 @@ const daemonClientMock = vi.hoisted(() => {instances.push(this);}- async connect(): Promise<void> {}+ async connect(): Promise<void> {+ if (behavior.connectFails) throw new Error("mock connect failed");+ }async request(command: Command): Promise<Response> {this.requests.push(command);@@ -94,6 +100,31 @@ vi.mock("../src/modes/daemon/daemon-client.js", () => ({DaemonClient: daemonClientMock.MockDaemonClient,}));+const spawnMock = vi.hoisted(() => {+ const calls: string[][] = [];+ return {+ calls,+ mockSpawn: (...args: unknown[]) => {+ calls.push(args[1] as string[]);+ return {+ unref: () => {},+ kill: () => {},+ pid: 99999,+ stdout: null,+ stderr: null,+ stdin: null,+ on: () => {},+ once: () => {},+ };+ },+ };+});++vi.mock("node:child_process", async (importOriginal) => {+ const original = (await importOriginal()) as Record<string, unknown>;+ return { ...original, spawn: spawnMock.mockSpawn as never };+});+import { handleDaemonCommand } from "../src/cli/daemon-command.js";describe("daemon command", () => {@@ -104,6 +135,7 @@ describe("daemon command", () => {daemonClientMock.instances.length = 0;daemonClientMock.behavior.promptSucceeds = false;daemonClientMock.behavior.emitStaleAgentEndOnAttach = false;+ daemonClientMock.behavior.connectFails = false;daemonClientMock.behavior.sessions = [];consoleErrorMessages = [];vi.spyOn(process, "exit").mockImplementation(((code?: string | number | null | undefined) => {@@ -419,6 +451,114 @@ describe("daemon command", () => {{ type: "cron_list", activeSessionId: "active-1", includeInactive: false },]);});++ it("passes --goal and --goal-token-budget to the create config", async () => {+ await expect(+ handleDaemonCommand([+ "daemon",+ "--socket",+ "/tmp/prime-agent.sock",+ "create",+ "--goal",+ "Write tests",+ "--goal-token-budget",+ "50000",+ "my-session",+ ]),+ ).resolves.toBe(true);++ expect(daemonClientMock.instances[0]?.requests[0]).toMatchObject({+ type: "create",+ name: "my-session",+ config: {+ initialGoal: { objective: "Write tests", tokenBudget: 50000 },+ },+ });+ });++ it("rejects empty --goal in daemon create", async () => {+ await handleDaemonCommand([+ "daemon",+ "--socket",+ "/tmp/prime-agent.sock",+ "create",+ "--goal",+ " ",+ "my-session",+ ]);+ expect(process.exitCode).toBe(1);+ expect(+ consoleErrorMessages.some((m) => typeof m === "string" && m.includes("--goal requires a non-empty objective")),+ ).toBe(true);+ });++ it("rejects --goal-token-budget without --goal in daemon create", async () => {+ await handleDaemonCommand([+ "daemon",+ "--socket",+ "/tmp/prime-agent.sock",+ "create",+ "--goal-token-budget",+ "50000",+ "my-session",+ ]);+ expect(process.exitCode).toBe(1);+ expect(+ consoleErrorMessages.some((m) => typeof m === "string" && m.includes("--goal-token-budget requires --goal")),+ ).toBe(true);+ // DaemonClient is constructed before runCreate parses session args+ expect(daemonClientMock.instances.length).toBe(1);+ expect(daemonClientMock.instances[0]?.requests.length).toBe(0);+ });++ it("does not leak --goal/--goal-token-budget into daemon startup args", async () => {+ // Force canConnectToDaemon to fail so runStart is exercised.+ daemonClientMock.behavior.connectFails = true;+ spawnMock.calls.length = 0;++ await handleDaemonCommand([+ "daemon",+ "--socket",+ "/tmp/prime-agent-goal-leak-test.sock",+ "start",+ "--goal",+ "Leak test goal",+ "--goal-token-budget",+ "100",+ ]);++ expect(spawnMock.calls.length).toBe(1);+ const spawnArgs = spawnMock.calls[0]!;+ // The goal flags must NOT appear in the daemon startup args.+ expect(spawnArgs).not.toContain("--goal");+ expect(spawnArgs).not.toContain("Leak test goal");+ expect(spawnArgs).not.toContain("--goal-token-budget");+ expect(spawnArgs).not.toContain("100");+ });++ it("does not leak goal into default config for a subsequent no-goal create", async () => {+ // First create with goal — config has initialGoal.+ await handleDaemonCommand([+ "daemon",+ "--socket",+ "/tmp/prime-agent.sock",+ "create",+ "--goal",+ "Write tests",+ "--goal-token-budget",+ "50000",+ "first",+ ]);+ expect(daemonClientMock.instances.at(-1)?.requests[0]).toMatchObject({+ type: "create",+ config: { initialGoal: { objective: "Write tests", tokenBudget: 50000 } },+ });++ // Second create without goal — config must NOT have initialGoal.+ await handleDaemonCommand(["daemon", "--socket", "/tmp/prime-agent.sock", "create", "second"]);+ const secondConfig = daemonClientMock.instances.at(-1)?.requests[0]?.config;+ expect(secondConfig?.initialGoal).toBeUndefined();+ });});function makeSessionSummary(activeSessionId: string, sessionId: string, sessionName: string): Record<string, unknown> {diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex 868a870870..d9ac916a16 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -291,6 +291,7 @@ describe("daemon mode helpers", () => {hasAcceptedPromptInFlight: false,pendingMessageCount: 0,promptHeartbeat,+ model: { provider: "current-provider", id: "current-model" },});childState.runtime = {...childState.runtime,@@ -342,6 +343,7 @@ describe("daemon mode helpers", () => {rlmDepth: 1,rlmMaxDepth: 4,rlmParentNodeId: "child-1",+ model: { provider: "spawn-provider", id: "spawn-model" },} as unknown as CreateRlmSubagentRuntimeOptions;internals.sessions.set(childState.activeSessionId, childState);@@ -354,6 +356,11 @@ describe("daemon mode helpers", () => {runCount: 0,});expect(parentSession.retainFinishedRlmChildSession).toHaveBeenCalledWith("child-1", childSession);+ const registryLines = readFileSync(join(parentArtifactDir, "rlm-subagents.jsonl"), "utf8")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { model?: { provider: string; modelId: string } });+ expect(registryLines.at(-1)?.model).toEqual({ provider: "current-provider", modelId: "current-model" });const dueRuns = await internals.cronScheduler.runDue(new Date("2026-07-16T00:00:00.000Z"));expect(dueRuns).toBe(1);expect(promptHeartbeat).toHaveBeenCalledOnce();diff --git a/packages/coding-agent/test/daemon-protocol.test.ts b/packages/coding-agent/test/daemon-protocol.test.tsindex 48e732ad8d..cf4b5f0b5d 100644--- a/packages/coding-agent/test/daemon-protocol.test.ts+++ b/packages/coding-agent/test/daemon-protocol.test.ts@@ -66,6 +66,18 @@ describe("daemon protocol helpers", () => {expect(DAEMON_DEFAULT_SERVER_CAPABILITIES).toContain("model_catalog");});+ it("keeps refine failure events backward-compatible on the existing session event channel", () => {+ const event: DaemonOutbound = {+ type: "session_event",+ activeSessionId: "active-1",+ event: { type: "refine_failed", error: "disk full" },+ };++ expect(DAEMON_SCHEMA_REVISION).toBe(3);+ expect(DAEMON_OUTBOUND_COMPATIBILITY.session_event).toEqual({ minProtocol: 1 });+ expect(event).toMatchObject({ event: { type: "refine_failed", error: "disk full" } });+ });+it("creates versioned command and event envelopes", () => {const command = { id: "cmd-1", type: "attach", activeSessionId: "active-1" } as const;const commandEnvelope = createDaemonCommandEnvelope(command, "cmd-1", "client-1");diff --git a/packages/coding-agent/test/fixtures/eng-4685-event-order-extension.ts b/packages/coding-agent/test/fixtures/eng-4685-event-order-extension.tsnew file mode 100644index 0000000000..dc1561fe8a--- /dev/null+++ b/packages/coding-agent/test/fixtures/eng-4685-event-order-extension.ts@@ -0,0 +1,62 @@+import { appendFileSync, writeFileSync } from "node:fs";+import type { ExtensionAPI } from "../../src/index.js";++/**+ * ENG-4685 event-order recording extension.+ *+ * Runs inside the real daemon worker and records the order in which+ * `refine_complete` and `agent_end` fire, proving the serialized+ * checkpoint applies before the agent loop terminates.+ *+ * Each event is appended to a JSONL file (one JSON object per line).+ * The test reads the file after the CLI exits and checks the sequence.+ */+export default function registerEng4685EventOrder(pi: ExtensionAPI): void {+ const eventLogPath = process.env.PRIME_AGENT_TEST_EVENT_LOG;+ if (!eventLogPath) return;++ let seq = 0;+ // Write an empty array so the test can detect the file exists even+ // if no events fired (e.g. interactive mode without refine).+ writeFileSync(eventLogPath, "");++ pi.on("agent_start", (_event, ctx) => {+ appendFileSync(+ eventLogPath,+ `${JSON.stringify({+ seq: seq++,+ type: "agent_start",+ modelId: ctx.model?.id,+ modelProvider: ctx.model?.provider,+ hasUI: ctx.hasUI,+ ts: Date.now(),+ })}\n`,+ );+ });++ pi.on("refine_complete", (event) => {+ appendFileSync(+ eventLogPath,+ `${JSON.stringify({+ seq: seq++,+ type: "refine_complete",+ id: event.id,+ summary: event.summary,+ appliedEdits: event.appliedEdits,+ scope: event.scope,+ ts: Date.now(),+ })}\n`,+ );+ });++ pi.on("agent_end", () => {+ appendFileSync(+ eventLogPath,+ `${JSON.stringify({+ seq: seq++,+ type: "agent_end",+ ts: Date.now(),+ })}\n`,+ );+ });+}diff --git a/packages/coding-agent/test/fixtures/eng-4685-faux-refine-extension.ts b/packages/coding-agent/test/fixtures/eng-4685-faux-refine-extension.tsnew file mode 100644index 0000000000..1f287c600f--- /dev/null+++ b/packages/coding-agent/test/fixtures/eng-4685-faux-refine-extension.ts@@ -0,0 +1,61 @@+import { fauxAssistantMessage, getApiProvider, registerFauxProvider } from "../../../ai/src/index.js";+import type { ExtensionAPI } from "../../src/index.js";++/**+ * ENG-4685 faux provider extension for process-backed serialized-refine proof.+ *+ * Queues exactly three responses so the real daemon worker, model, and+ * auto-refine machinery all exercise the real code paths:+ *+ * 1. Parent assistant response for the user prompt.+ * 2. Valid auto-refine review JSON (shouldRefine: true).+ * 3. Valid empty refinement-proposal JSON (edits: []).+ *+ * The auto-refine review and plan both call completeSimple on the same+ * faux provider, so they consume responses 2 and 3 from the same queue.+ */+export default function registerEng4685FauxRefineProvider(pi: ExtensionAPI): void {+ const faux = registerFauxProvider({+ provider: "faux",+ models: [{ id: "faux", reasoning: false }],+ });++ faux.setResponses([+ // 1 — parent response for "Say hello"+ fauxAssistantMessage("Hello from the faux provider."),+ // 2 — auto-refine review JSON (parsed by parseAutoRefineReview)+ fauxAssistantMessage(JSON.stringify({ shouldRefine: true, rationale: "process-proof review" })),+ // 3 — empty refinement proposal JSON (parsed by parseProposal)+ fauxAssistantMessage(+ JSON.stringify({+ summary: "No edits needed",+ rationale: "process-proof empty proposal",+ edits: [],+ expectedOutcome: "No changes",+ }),+ ),+ ]);++ const apiProvider = getApiProvider(faux.api);+ if (!apiProvider) {+ throw new Error("Faux API provider was not registered");+ }++ pi.registerProvider(faux.getModel().provider, {+ api: faux.api,+ apiKey: "faux-key",+ baseUrl: faux.getModel().baseUrl,+ streamSimple: apiProvider.streamSimple,+ models: faux.models.map((model) => ({+ api: model.api,+ baseUrl: model.baseUrl,+ contextWindow: model.contextWindow,+ cost: model.cost,+ id: model.id,+ input: model.input,+ maxTokens: model.maxTokens,+ name: model.name,+ reasoning: model.reasoning,+ })),+ });+}diff --git a/packages/coding-agent/test/fixtures/serialized-refine-marker-extension.ts b/packages/coding-agent/test/fixtures/serialized-refine-marker-extension.tsnew file mode 100644index 0000000000..0d1f7ad43b--- /dev/null+++ b/packages/coding-agent/test/fixtures/serialized-refine-marker-extension.ts@@ -0,0 +1,36 @@+import { writeFileSync } from "node:fs";+import type { ExtensionAPI } from "../../src/index.js";++/**+ * Test fixture extension that writes a marker file when the first agent_start+ * fires. The marker includes the model id from the extension context, proving+ * the extension ran in the real daemon worker with a valid model (#503).+ *+ * Also listens for refine_complete events to detect serialized refine activity.+ */+export default function registerSerializedRefineMarker(pi: ExtensionAPI): void {+ let markerWritten = false;++ pi.on("agent_start", (_event, ctx) => {+ if (markerWritten) return;+ markerWritten = true;+ const markerPath = process.env.PRIME_AGENT_TEST_SERIALIZED_REFINE_MARKER;+ if (!markerPath) return;+ writeFileSync(+ markerPath,+ JSON.stringify({+ modelId: ctx.model?.id,+ modelProvider: ctx.model?.provider,+ hasUI: ctx.hasUI,+ }),+ );+ });++ pi.on("agent_end", () => {+ const refineMarkerPath = process.env.PRIME_AGENT_TEST_REFINE_COMPLETE_MARKER;+ if (!refineMarkerPath) return;+ // Write a marker when agent_end fires. If serializedRefine caused+ // a deadlock, this would never be written.+ writeFileSync(refineMarkerPath, "agent_end");+ });+}diff --git a/packages/coding-agent/test/main-interactive-routing.test.ts b/packages/coding-agent/test/main-interactive-routing.test.tsindex c1bf12f6b0..79cb483488 100644--- a/packages/coding-agent/test/main-interactive-routing.test.ts+++ b/packages/coding-agent/test/main-interactive-routing.test.ts@@ -2,10 +2,12 @@ import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, test } from "vitest";+import { mergeAgentSessionRuntimeConfig } from "../src/core/agent-session-config.js";import type { CreateAgentSessionOptions } from "../src/core/sdk.js";import {type AppMode,type DaemonInteractiveSessionManagerDecision,+ daemonServerDefaultSessionConfig,findActiveDaemonSessionSummaryForInteractiveStartup,findActiveDaemonSessionSummaryForSessionFile,type InteractiveDaemonStartupDecision,@@ -331,6 +333,30 @@ describe("agents view command parsing", () => {});describe("runtime session option resolution", () => {+ test("keeps verifier goals per session instead of in the daemon fallback", () => {+ const headlessCreateConfig = {+ cwd: "/repo",+ serializedRefine: true,+ initialGoal: { objective: "solve the verifier task", tokenBudget: 100_000 },+ };++ expect(headlessCreateConfig.initialGoal).toEqual({+ objective: "solve the verifier task",+ tokenBudget: 100_000,+ });+ const daemonFallback = daemonServerDefaultSessionConfig(headlessCreateConfig);+ expect(daemonFallback).toEqual({+ cwd: "/repo",+ serializedRefine: true,+ initialGoal: undefined,+ });+ expect(+ mergeAgentSessionRuntimeConfig(daemonFallback, {+ initialGoal: headlessCreateConfig.initialGoal,+ }),+ ).toMatchObject({ initialGoal: headlessCreateConfig.initialGoal });+ });+test("preserves daemon-provided RLM heartbeat controller when creating sessions", () => {const preparedModel = { id: "prepared-model" } as unknown as CreateAgentSessionOptions["model"];const runtimeModel = { id: "runtime-model" } as unknown as CreateAgentSessionOptions["model"];diff --git a/packages/coding-agent/test/refinement.test.ts b/packages/coding-agent/test/refinement.test.tsindex d29caca63e..79966a475c 100644--- a/packages/coding-agent/test/refinement.test.ts+++ b/packages/coding-agent/test/refinement.test.ts@@ -1,4 +1,4 @@-import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { appendFileSync, chmodSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import type { AgentMessage } from "@earendil-works/pi-agent-core";@@ -15,6 +15,7 @@ import {getRefinementHistory,getRefinementHistoryPath,type HarnessState,+ inferRefinementResultScope,loadGlobalRefinementHistory,loadHarnessState,mergeHarnessStates,@@ -167,6 +168,61 @@ describe("harness refinement", () => {expect(currentState.entries.memory.memory_entry.content).toBe("concurrent kernel content");});+ it("allows sequential edits to the same entry after the baseline matches once", () => {+ const state = loadHarnessState(makeTempDir(), "local");+ seedEntry(state, "memory");+ const baselineState = structuredClone(state);++ const result = applyRefinementProposal(+ state,+ proposal("Update memory twice", [+ { action: "update", kind: "memory", id: "memory_entry", title: "First", content: "first" },+ { action: "update", kind: "memory", id: "memory_entry", title: "Second", content: "second" },+ ]),+ { id: "refine_same_entry", baselineState, scope: "local" },+ );++ expect(result.appliedEdits.map((edit) => edit.applied)).toEqual([true, true]);+ expect(state.entries.memory.memory_entry.content).toBe("second");+ expect(state.entries.memory.memory_entry.version).toBe(3);+ });++ it("infers legacy refinement scope from applied edit snapshots", () => {+ const state = loadHarnessState(makeTempDir(), "global");+ seedEntry(state, "memory", "global_memory");+ const after = { ...state.entries.memory.global_memory, scope: "global" as const };+ const result: RefinementResult = {+ ...proposal("Legacy global edit", []),+ id: "legacy",+ appliedEdits: [+ {+ action: "create",+ kind: "memory",+ id: "global_memory",+ applied: true,+ after,+ },+ ],+ harnessStatePath: "",+ };++ expect(inferRefinementResultScope(result)).toBe("global");+ });++ it("atomically replaces harness state without leaving temporary files", () => {+ const harnessStateDir = makeTempDir();+ const state = loadHarnessState(harnessStateDir);+ seedEntry(state, "memory");++ const statePath = saveHarnessState(harnessStateDir, state);++ expect(loadHarnessState(harnessStateDir).entries.memory.memory_entry).toBeDefined();+ expect(readdirSync(harnessStateDir)).toEqual([statePath.split("/").at(-1)]);+ chmodSync(statePath, 0o600);+ saveHarnessState(harnessStateDir, state);+ expect(statSync(statePath).mode & 0o777).toBe(0o600);+ });+it("applies create, update, and delete for every editable harness kind", () => {const state = loadHarnessState(makeTempDir());diff --git a/packages/coding-agent/test/session-manager-flush.test.ts b/packages/coding-agent/test/session-manager-flush.test.tsnew file mode 100644index 0000000000..33b7cd22f9--- /dev/null+++ b/packages/coding-agent/test/session-manager-flush.test.ts@@ -0,0 +1,164 @@+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import { SessionManager } from "../src/core/session-manager.js";++const tempDirs: string[] = [];++afterEach(() => {+ while (tempDirs.length > 0) {+ const dir = tempDirs.pop()!;+ rmSync(dir, { recursive: true, force: true });+ }+});++function createTempDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "pi-flush-test-"));+ tempDirs.push(dir);+ return dir;+}++describe("SessionManager.flushNow", () => {+ it("writes the session file with all in-memory entries before any assistant message", () => {+ const dir = createTempDir();+ const sessionDir = join(dir, "sessions");+ const mgr = SessionManager.create(dir, sessionDir);++ // Append a custom entry (goal state) — normally suppressed by _persist+ // because no assistant message exists yet.+ mgr.appendCustomEntry("thread_goal_state", { active: true, status: "active" });++ const file = mgr.getSessionFile()!;+ expect(existsSync(file)).toBe(false);++ // flushNow forces a write despite the no-assistant guard+ mgr.flushNow();+ expect(existsSync(file)).toBe(true);++ const content = readFileSync(file, "utf8");+ const lines = content.trim().split("\n");+ expect(lines.length).toBe(2); // header + custom entry++ const header = JSON.parse(lines[0]!);+ expect(header.type).toBe("session");++ const custom = JSON.parse(lines[1]!);+ expect(custom.type).toBe("custom");+ expect(custom.customType).toBe("thread_goal_state");+ expect(custom.data).toEqual({ active: true, status: "active" });+ });++ it("is a no-op for in-memory (non-persisted) sessions", () => {+ const mgr = SessionManager.inMemory("/tmp");+ mgr.appendCustomEntry("thread_goal_state", { active: true });+ // Should not throw+ mgr.flushNow();+ expect(mgr.getSessionFile()).toBeUndefined();+ });++ it("preserves subsequent rewrite behavior after flush with user then assistant", () => {+ const dir = createTempDir();+ const sessionDir = join(dir, "sessions");+ const mgr = SessionManager.create(dir, sessionDir);++ mgr.appendCustomEntry("thread_goal_state", { active: true, status: "active" });+ mgr.flushNow();++ const file = mgr.getSessionFile()!;+ expect(existsSync(file)).toBe(true);++ // Append a USER message first — this sets flushed=false because+ // no assistant exists yet, exercising the pending full-rewrite path.+ mgr.appendMessage({+ role: "user",+ content: [{ type: "text", text: "hello" }],+ timestamp: Date.now(),+ });++ // Then append an ASSISTANT message — this triggers the full rewrite+ // (not appendFileSync) because flushed is false.+ mgr.appendMessage({+ role: "assistant",+ content: [{ type: "text", text: "hi" }],+ api: "openai-completions",+ provider: "openai",+ model: "test",+ usage: {+ input: 1,+ output: 1,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: "stop",+ timestamp: Date.now(),+ });++ // File should contain exactly: header, custom(goal), user, assistant+ const content = readFileSync(file, "utf8");+ const lines = content.trim().split("\n");+ expect(lines.length).toBe(4);++ const header = JSON.parse(lines[0]!);+ expect(header.type).toBe("session");++ const custom = JSON.parse(lines[1]!);+ expect(custom.type).toBe("custom");+ expect(custom.customType).toBe("thread_goal_state");++ const userMsg = JSON.parse(lines[2]!);+ expect(userMsg.type).toBe("message");+ expect(userMsg.message.role).toBe("user");++ const assistantMsg = JSON.parse(lines[3]!);+ expect(assistantMsg.type).toBe("message");+ expect(assistantMsg.message.role).toBe("assistant");++ // Verify valid parent chain: custom(null) -> user(custom) -> assistant(user)+ // (session header is not part of the entry parent chain)+ expect(custom.parentId).toBeNull();+ expect(userMsg.parentId).toBe(custom.id);+ expect(assistantMsg.parentId).toBe(userMsg.id);+ });++ it("does not rewrite an already-flushed session after an appended entry", () => {+ const dir = createTempDir();+ const sessionDir = join(dir, "sessions");+ const mgr = SessionManager.create(dir, sessionDir);++ mgr.appendMessage({+ role: "assistant",+ content: [{ type: "text", text: "ready" }],+ api: "openai-completions",+ provider: "openai",+ model: "test",+ usage: {+ input: 1,+ output: 1,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: "stop",+ timestamp: Date.now(),+ });+ const rewriteFile = vi.spyOn(mgr as unknown as { _rewriteFile(): void }, "_rewriteFile");++ mgr.appendCustomEntry("thread_goal_state", { active: true, status: "active" });+ mgr.flushNow();++ expect(rewriteFile).not.toHaveBeenCalled();+ const entries = readFileSync(mgr.getSessionFile()!, "utf8")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line));+ expect(entries.at(-1)).toMatchObject({+ type: "custom",+ customType: "thread_goal_state",+ data: { active: true, status: "active" },+ });+ });+});diff --git a/packages/coding-agent/test/suite/agent-session-goal.test.ts b/packages/coding-agent/test/suite/agent-session-goal.test.tsindex adb6973aaf..79c16c22b6 100644--- a/packages/coding-agent/test/suite/agent-session-goal.test.ts+++ b/packages/coding-agent/test/suite/agent-session-goal.test.ts@@ -1,10 +1,17 @@+import { existsSync } from "node:fs";import type { AgentContext, AgentTool } from "@earendil-works/pi-agent-core";+import { Agent } from "@earendil-works/pi-agent-core";import { type AssistantMessage, fauxAssistantMessage, fauxToolCall, type Usage } from "@earendil-works/pi-ai";import { Type } from "typebox";import { afterEach, describe, expect, it, vi } from "vitest";-import type { AgentSession } from "../../src/core/agent-session.js";+import { AgentSession } from "../../src/core/agent-session.js";+import { AuthStorage } from "../../src/core/auth-storage.js";import type { ExtensionFactory } from "../../src/core/extensions/types.js";import type { GoalHostResponse } from "../../src/core/goals.js";+import { ModelRegistry } from "../../src/core/model-registry.js";+import { SessionManager } from "../../src/core/session-manager.js";+import { SettingsManager } from "../../src/core/settings-manager.js";+import { createTestResourceLoader } from "../utilities.js";import { createHarness, getAssistantTexts, getMessageText, type Harness } from "./harness.js";function assistantWithUsage(message: string | AssistantMessage, usage: Partial<Usage>): AssistantMessage {@@ -832,3 +839,175 @@ describe("AgentSession goals", () => {expect(harness.getPendingResponseCount()).toBe(1);});});++describe("initial goal seeding from config", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("seeds an active goal from initialGoal config on a fresh top-level session", async () => {+ const harness = await createHarness({+ persistSession: true,+ initialGoal: { objective: "Write tests", tokenBudget: 50000 },+ });+ harnesses.push(harness);++ expect(harness.session.goalState).toMatchObject({+ active: true,+ status: "active",+ objective: "Write tests",+ tokenBudget: 50000,+ });++ // Goal is persisted before first prompt+ const { GOAL_STATE_CUSTOM_TYPE } = await import("../../src/core/goals.js");+ const branch = harness.sessionManager.getBranch();+ const goalEntry = branch.find((e) => e.type === "custom" && e.customType === GOAL_STATE_CUSTOM_TYPE);+ expect(goalEntry).toBeDefined();+ });++ it("does not seed initialGoal for subagent sessions (rlmDepth > 0)", async () => {+ const harness = await createHarness({+ persistSession: true,+ rlmDepth: 1,+ initialGoal: { objective: "Subagent goal" },+ });+ harnesses.push(harness);++ expect(harness.session.goalState.status).toBe("idle");+ expect(harness.session.goalState.active).toBe(false);+ });++ function createRestartSession(harness: Harness): AgentSession {+ const sessionFile = harness.sessionManager.getSessionFile()!;+ expect(existsSync(sessionFile)).toBe(true);+ const newSessionManager = SessionManager.open(sessionFile);++ // Assert the reopened branch contains a thread_goal_state custom entry+ // before constructing the new AgentSession. This proves the goal was+ // persisted to disk.+ const reopenedBranch = newSessionManager.getBranch();+ const goalEntries = reopenedBranch.filter(+ (e: { type: string; customType?: string }) => e.type === "custom" && e.customType === "thread_goal_state",+ );+ expect(goalEntries.length).toBeGreaterThan(0);++ const model = harness.getModel();+ const newAuth = AuthStorage.inMemory();+ newAuth.setRuntimeApiKey(model.provider, "faux-key");+ const newRegistry = ModelRegistry.inMemory(newAuth);+ const newSettings = SettingsManager.inMemory();++ const newAgent = new Agent({+ getApiKey: () => "faux-key",+ initialState: {+ model,+ systemPrompt: "You are a test assistant.",+ tools: [],+ },+ });++ return new AgentSession({+ agent: newAgent,+ sessionManager: newSessionManager,+ settingsManager: newSettings,+ cwd: harness.tempDir,+ modelRegistry: newRegistry,+ resourceLoader: createTestResourceLoader(),+ rlmDepth: 0,+ initialGoal: { objective: "Should not reseed" },+ });+ }++ it("does not reseed after goal is cleared (idempotent restart)", async () => {+ const harness = await createHarness({+ persistSession: true,+ initialGoal: { objective: "Initial goal" },+ });+ harnesses.push(harness);++ expect(harness.session.goalState.status).toBe("active");++ // Clear the goal via /goal clear (slash command)+ harness.setResponses([fauxAssistantMessage("unused")]);+ await harness.session.prompt("/goal clear");+ expect(harness.session.goalState.status).toBe("idle");++ // Simulate restart: reopen the same session file+ const newSession = createRestartSession(harness);++ // Goal should remain idle (cleared), not reseeded+ expect(newSession.goalState.status).toBe("idle");+ expect(newSession.goalState.objective).toBeUndefined();+ newSession.dispose();+ });++ it("does not reseed after goal is completed (idempotent restart)", async () => {+ const harness = await createHarness({+ persistSession: true,+ initialGoal: { objective: "Complete me" },+ });+ harnesses.push(harness);++ expect(harness.session.goalState.status).toBe("active");++ // Complete the goal via host request+ harness.session.handleGoalHostRequest("goal.complete");+ expect(harness.session.goalState.status).toBe("complete");++ // Simulate restart on the same session file+ const newSession = createRestartSession(harness);++ // Goal should remain complete, not reseeded+ expect(newSession.goalState.status).toBe("complete");+ expect(newSession.goalState.objective).toBe("Complete me");+ newSession.dispose();+ });++ it("does not reseed when branch has messages (idempotent restart after use)", async () => {+ const harness = await createHarness({+ persistSession: true,+ initialGoal: { objective: "Initial goal" },+ });+ harnesses.push(harness);++ expect(harness.session.goalState.status).toBe("active");++ // Append user and assistant messages directly via sessionManager+ // to avoid triggering autonomous goal continuation loop.+ harness.sessionManager.appendMessage({+ role: "user",+ content: [{ type: "text", text: "do something" }],+ timestamp: Date.now(),+ });+ harness.sessionManager.appendMessage({+ role: "assistant",+ content: [{ type: "text", text: "done" }],+ api: "openai-completions",+ provider: "openai",+ model: "test",+ usage: {+ input: 1,+ output: 1,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 2,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ },+ stopReason: "stop",+ timestamp: Date.now(),+ });++ // Simulate restart on the same session file+ const newSession = createRestartSession(harness);++ // Goal should be the persisted active goal, not the new initialGoal+ expect(newSession.goalState.status).toBe("active");+ expect(newSession.goalState.objective).toBe("Initial goal");+ newSession.dispose();+ });+});diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.tsindex 05e9dc1ba8..f61a127676 100644--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts@@ -4,7 +4,7 @@ import { join } from "node:path";import type { AgentTool } from "@earendil-works/pi-agent-core";import { fauxAssistantMessage, fauxToolCall, type Model } from "@earendil-works/pi-ai";import { Type } from "typebox";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import type { BashResult } from "../../src/core/bash-executor.js";import type { PromptTemplate } from "../../src/core/prompt-templates.js";import { createSyntheticSourceInfo } from "../../src/core/source-info.js";@@ -342,6 +342,287 @@ stale extension instructions`,expect(providerSystemPrompts[1]).not.toContain("stale extension instructions");});+ it("discards a stale extension prompt when refine completes during a normal prompt hook", async () => {+ let signalHookStarted: () => void = () => {};+ const hookStarted = new Promise<void>((resolve) => {+ signalHookStarted = resolve;+ });+ let releaseHook: () => void = () => {};+ const hookRelease = new Promise<void>((resolve) => {+ releaseHook = resolve;+ });+ const harness = await createHarness({+ persistSession: true,+ systemPrompt: "pre-refine base",+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async (event) => {+ signalHookStarted();+ await hookRelease;+ return {+ message: {+ customType: "refine-race-proof",+ content: "extension message preserved",+ display: false,+ },+ systemPrompt: `${event.systemPrompt}++stale extension instructions`,+ };+ });+ },+ ],+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as {+ _baseSystemPrompt: string;+ _refineInFlight?: Promise<void>;+ _refineAbortController?: AbortController;+ _planRefine(options: unknown, signal: AbortSignal): Promise<unknown>;+ _applyRefine(plan: unknown, options: unknown, abort: AbortController): Promise<unknown>;+ };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "race-plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ internals._baseSystemPrompt = "refined $& base";+ harness.session.agent.state.systemPrompt = "refined $& base";+ internals._refineAbortController = undefined;+ return {+ id: "refine_race",+ summary: "refined",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ };+ });+ let providerSystemPrompt = "";+ let providerMessages = "";+ harness.setResponses([+ (context) => {+ providerSystemPrompt = context.systemPrompt ?? "";+ providerMessages = JSON.stringify(context.messages);+ return fauxAssistantMessage("done");+ },+ ]);++ const promptPromise = harness.session.prompt("normal prompt");+ await hookStarted;+ await harness.session.refine({ instructions: "complete while the extension hook is suspended" });+ expect(internals._refineInFlight).toBeUndefined();+ releaseHook();+ await promptPromise;++ expect(providerSystemPrompt).toContain("refined $& base");+ expect(providerSystemPrompt).toContain("stale extension instructions");+ expect(providerMessages).toContain("extension message preserved");+ });++ it("preserves an independent extension prompt when refine completes during its hook", async () => {+ let releaseHook: () => void = () => {};+ const hookRelease = new Promise<void>((resolve) => {+ releaseHook = resolve;+ });+ let signalHookStarted: () => void = () => {};+ const hookStarted = new Promise<void>((resolve) => {+ signalHookStarted = resolve;+ });+ const harness = await createHarness({+ persistSession: true,+ systemPrompt: "pre-refine base",+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async () => {+ signalHookStarted();+ await hookRelease;+ return { systemPrompt: "independent extension replacement" };+ });+ },+ ],+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as {+ _baseSystemPrompt: string;+ _refineAbortController?: AbortController;+ _planRefine(options: unknown, signal: AbortSignal): Promise<unknown>;+ _applyRefine(plan: unknown, options: unknown, abort: AbortController): Promise<unknown>;+ };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "race-plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ internals._baseSystemPrompt = "refined base";+ harness.session.agent.state.systemPrompt = "refined base";+ internals._refineAbortController = undefined;+ return {+ id: "refine_independent",+ summary: "refined",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ harnessStatePath: "",+ };+ });+ let providerSystemPrompt = "";+ harness.setResponses([+ (context) => {+ providerSystemPrompt = context.systemPrompt ?? "";+ return fauxAssistantMessage("done");+ },+ ]);++ const promptPromise = harness.session.prompt("normal prompt");+ await hookStarted;+ await harness.session.refine({ instructions: "refresh the base" });+ releaseHook();+ await promptPromise;++ expect(providerSystemPrompt).toBe("independent extension replacement");+ });++ it("refreshes an extension system prompt when refine completes during an injected prompt hook", async () => {+ let signalHookStarted: () => void = () => {};+ const hookStarted = new Promise<void>((resolve) => {+ signalHookStarted = resolve;+ });+ let releaseHook: () => void = () => {};+ const hookRelease = new Promise<void>((resolve) => {+ releaseHook = resolve;+ });+ const harness = await createHarness({+ persistSession: true,+ systemPrompt: "pre-refine base",+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async (event) => {+ signalHookStarted();+ await hookRelease;+ return {+ message: {+ customType: "refine-race-proof",+ content: "injected extension message preserved",+ display: false,+ },+ systemPrompt: `${event.systemPrompt}++stale injected extension instructions`,+ };+ });+ },+ ],+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as {+ _baseSystemPrompt: string;+ _refineInFlight?: Promise<void>;+ _refineAbortController?: AbortController;+ _planRefine(options: unknown, signal: AbortSignal): Promise<unknown>;+ _applyRefine(plan: unknown, options: unknown, abort: AbortController): Promise<unknown>;+ _promptInjectedMessage(+ text: string,+ message: {+ role: "custom";+ customType: string;+ content: string;+ display: boolean;+ details: Record<string, never>;+ timestamp: number;+ },+ ): Promise<void>;+ };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "race-plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ internals._baseSystemPrompt = "refined injected base";+ harness.session.agent.state.systemPrompt = "refined injected base";+ internals._refineAbortController = undefined;+ return {+ id: "refine_race",+ summary: "refined",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ };+ });+ let providerSystemPrompt = "";+ let providerMessages = "";+ harness.setResponses([+ (context) => {+ providerSystemPrompt = context.systemPrompt ?? "";+ providerMessages = JSON.stringify(context.messages);+ return fauxAssistantMessage("done");+ },+ ]);++ const injectedPrompt = internals._promptInjectedMessage("injected prompt", {+ role: "custom",+ customType: "injected-test",+ content: "injected prompt",+ display: true,+ details: {},+ timestamp: Date.now(),+ });+ await hookStarted;+ await harness.session.refine({ instructions: "complete while the injected hook is suspended" });+ expect(internals._refineInFlight).toBeUndefined();+ releaseHook();+ await injectedPrompt;++ expect(providerSystemPrompt).toContain("refined injected base");+ expect(providerSystemPrompt).toContain("stale injected extension instructions");+ expect(providerMessages).toContain("injected extension message preserved");+ });++ it("preserves an empty extension system prompt across an injected refine handoff wait", async () => {+ let sessionInternals: {+ _refineInFlight?: Promise<void>;+ _promptInjectedMessage(+ text: string,+ message: {+ role: "custom";+ customType: string;+ content: string;+ display: boolean;+ details: Record<string, never>;+ timestamp: number;+ },+ ): Promise<void>;+ };+ const harness = await createHarness({+ systemPrompt: "base prompt",+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async () => {+ let releaseRefine: (() => void) | undefined;+ sessionInternals._refineInFlight = new Promise<void>((resolve) => {+ releaseRefine = resolve;+ });+ setTimeout(() => {+ sessionInternals._refineInFlight = undefined;+ releaseRefine?.();+ }, 0);+ return { systemPrompt: "" };+ });+ },+ ],+ });+ harnesses.push(harness);+ sessionInternals = harness.session as unknown as typeof sessionInternals;+ let providerSystemPrompt = "not observed";+ harness.setResponses([+ (context) => {+ providerSystemPrompt = context.systemPrompt ?? "";+ return fauxAssistantMessage("done");+ },+ ]);++ await sessionInternals._promptInjectedMessage("injected prompt", {+ role: "custom",+ customType: "injected-test",+ content: "injected prompt",+ display: true,+ details: {},+ timestamp: Date.now(),+ });++ expect(providerSystemPrompt).toBe("");+ });+it("preserves an extension system prompt across a refine handoff wait", async () => {let sessionInternals: { _refineInFlight?: Promise<void> };const harness = await createHarness({@@ -357,7 +638,11 @@ stale extension instructions`,sessionInternals._refineInFlight = undefined;releaseRefine?.();}, 0);- return { systemPrompt: `${event.systemPrompt}\n\nextension instructions` };+ return {+ systemPrompt: `${event.systemPrompt}++extension instructions`,+ };});},],@@ -377,6 +662,79 @@ stale extension instructions`,expect(providerSystemPrompt).toContain("extension instructions");});+ it("discards stale extension prompt when refine completes during post-hook _waitForRefineIdle", async () => {+ // Test C: the extension hook returns an extension prompt while+ // _refineInFlight is still active. During _waitForRefineIdle after+ // the hook, the refine completes and rewrites _baseSystemPrompt.+ // The post-wait guard must detect the base change and discard the+ // stale extension prompt, using the refined base instead.+ let sessionInternals: {+ _baseSystemPrompt: string;+ _refineInFlight?: Promise<void>;+ _refineAbortController?: AbortController;+ _planRefine(options: unknown, signal: AbortSignal): Promise<unknown>;+ _applyRefine(plan: unknown, options: unknown, abort: AbortController): Promise<unknown>;+ };+ let releaseRefine: (() => void) | undefined;+ const harness = await createHarness({+ persistSession: true,+ systemPrompt: "pre-refine base",+ extensionFactories: [+ (pi) => {+ pi.on("before_agent_start", async (event) => {+ // Set up _refineInFlight so the post-hook wait triggers.+ sessionInternals._refineInFlight = new Promise<void>((resolve) => {+ releaseRefine = resolve;+ });+ return {+ systemPrompt: `${event.systemPrompt}++stale post-hook extension instructions`,+ };+ });+ },+ ],+ });+ harnesses.push(harness);+ sessionInternals = harness.session as unknown as typeof sessionInternals;+ vi.spyOn(sessionInternals, "_planRefine").mockResolvedValue({ id: "race-plan", proposal: { edits: [] } });+ vi.spyOn(sessionInternals, "_applyRefine").mockImplementation(async () => {+ sessionInternals._baseSystemPrompt = "refined post-hook base";+ harness.session.agent.state.systemPrompt = "refined post-hook base";+ sessionInternals._refineAbortController = undefined;+ return {+ id: "refine_post_hook",+ summary: "refined",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ };+ });+ let providerSystemPrompt = "";+ harness.setResponses([+ (context) => {+ providerSystemPrompt = context.systemPrompt ?? "";+ return fauxAssistantMessage("done");+ },+ ]);++ const promptPromise = harness.session.prompt("normal prompt");+ // The extension hook fires, sets _refineInFlight, and returns a stale+ // extension prompt. The prompt path enters _waitForRefineIdle.+ // Wait for the hook to fire and set _refineInFlight.+ await vi.waitFor(() => {+ expect(sessionInternals._refineInFlight).toBeDefined();+ });+ // Complete the refine during the wait: change the base and resolve.+ sessionInternals._baseSystemPrompt = "refined post-hook base";+ releaseRefine?.();+ sessionInternals._refineInFlight = undefined;+ await promptPromise;++ expect(providerSystemPrompt).toContain("refined post-hook base");+ expect(providerSystemPrompt).toContain("stale post-hook extension instructions");+ });+it("queues accepted agent messages while compacting", async () => {const harness = await createHarness();harnesses.push(harness);diff --git a/packages/coding-agent/test/suite/agent-session-queue.test.ts b/packages/coding-agent/test/suite/agent-session-queue.test.tsindex ed98401c65..3ecdb4dd46 100644--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts@@ -1178,6 +1178,15 @@ describe("AgentSession queue characterization", () => {const planStartedPromise = new Promise<void>((resolve) => {planStarted = resolve;});+ let releasePrompt: (() => void) | undefined;+ const promptGate = new Promise<void>((resolve) => {+ releasePrompt = resolve;+ });+ let promptStarted: (() => void) | undefined;+ const promptStartedPromise = new Promise<void>((resolve) => {+ promptStarted = resolve;+ });+ let promptSignal: AbortSignal | undefined;harness.setResponses([async () => {planStarted?.();@@ -1191,14 +1200,19 @@ describe("AgentSession queue characterization", () => {}),);},- fauxAssistantMessage("prompt reply"),+ async (_context, options) => {+ promptSignal = options?.signal;+ promptStarted?.();+ await promptGate;+ return fauxAssistantMessage("prompt reply");+ },]);const refinePromise = harness.session.refine({ instructions: "background refine" });await planStartedPromise;const promptPromise = harness.session.prompt("hello during refine");- await new Promise((resolve) => setTimeout(resolve, 10));+ await promptStartedPromise;// With backgrounded refine planning, the prompt does NOT wait for the// planning LLM pass. It starts immediately and streams its response// while planning is still in flight. The application phase waits for@@ -1206,6 +1220,17 @@ describe("AgentSession queue characterization", () => {expect(harness.getPendingResponseCount()).toBe(0);releasePlan?.();+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(promptSignal?.aborted).toBe(false);++ let refineSettled = false;+ void refinePromise.finally(() => {+ refineSettled = true;+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(refineSettled).toBe(false);++ releasePrompt?.();await refinePromise;await promptPromise;diff --git a/packages/coding-agent/test/suite/agent-session-refine-skill.test.ts b/packages/coding-agent/test/suite/agent-session-refine-skill.test.tsnew file mode 100644index 0000000000..109e824b12--- /dev/null+++ b/packages/coding-agent/test/suite/agent-session-refine-skill.test.ts@@ -0,0 +1,299 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { createHarness, type Harness } from "./harness.js";++type SessionInternals = {+ _consumePendingRequestedRefine: () => boolean;+ _emitRefineFailed: (error: unknown) => void;+ _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;+ _serializedPlanInFlight?: Promise<unknown>;+ _serializedExplicitRefineOptions?: { instructions?: string; global?: boolean };+ _refineAbortController?: AbortController;+ _createKernelHostHandlers: () => Record<string, unknown>;+ refine: (options: { instructions?: string; global?: boolean }) => Promise<unknown>;+};++function setStreaming(harness: Harness, streaming: boolean) {+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = streaming;+}++describe("AgentSession refine skill host requests", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("schedules via refine.run and reports pending via refine.status", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ const runResult = harness.session.handleRefineHostRequest("refine.run", { instructions: "test instructions" });+ setStreaming(harness, false);+ expect(runResult.scheduled).toBe(true);+ expect(runResult.note).toBeDefined();++ const status = harness.session.handleRefineHostRequest("refine.status");+ expect(status.pending).toBe(true);+ });++ it("stores global flag from refine.run", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { global: true });+ setStreaming(harness, false);++ const internals = harness.session as unknown as SessionInternals;+ expect(internals._pendingRequestedRefine?.global).toBe(true);+ });++ it("defaults to local scope when global is not provided", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run");+ setStreaming(harness, false);++ const internals = harness.session as unknown as SessionInternals;+ expect(internals._pendingRequestedRefine?.global).toBeUndefined();+ expect(internals._pendingRequestedRefine?.instructions).toBeUndefined();+ });++ it("updates pending request when called again", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "first", global: true });+ harness.session.handleRefineHostRequest("refine.run", { instructions: "second" });+ setStreaming(harness, false);++ const internals = harness.session as unknown as SessionInternals;+ expect(internals._pendingRequestedRefine?.instructions).toBe("second");+ expect(internals._pendingRequestedRefine?.global).toBe(true);+ });++ it("replaces an in-flight serialized plan instead of applying both requests", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SessionInternals;+ const abort = new AbortController();+ internals._serializedPlanInFlight = new Promise(() => {});+ internals._serializedExplicitRefineOptions = { instructions: "first", global: true };+ internals._refineAbortController = abort;++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "replacement" });+ setStreaming(harness, false);++ expect(abort.signal.aborted).toBe(true);+ expect(internals._pendingRequestedRefine).toEqual({ instructions: "replacement", global: true });+ });++ it("discards a settled serialized plan when a replacement request arrives", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SessionInternals;+ internals._serializedPlanInFlight = Promise.resolve({ status: "plan" });+ internals._serializedExplicitRefineOptions = { instructions: "first", global: true };++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "replacement" });+ setStreaming(harness, false);++ await expect(internals._serializedPlanInFlight).resolves.toEqual({+ status: "invalidated",+ branchVersion: expect.any(Number),+ });+ expect(internals._pendingRequestedRefine).toEqual({ instructions: "replacement", global: true });+ });++ it("rejects refine.run while no turn is active", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ const result = harness.session.handleRefineHostRequest("refine.run");+ expect(result.scheduled).toBe(false);+ expect(result.reason).toContain("no active turn");+ expect(harness.session.handleRefineHostRequest("refine.status").pending).toBe(false);+ });++ it("validates instructions type in refine.run", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ setStreaming(harness, true);+ expect(() =>+ harness.session.handleRefineHostRequest("refine.run", { instructions: 123 as unknown as string }),+ ).toThrow("instructions must be a string");+ setStreaming(harness, false);+ });++ it("validates global flag type in refine.run", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ setStreaming(harness, true);+ expect(() =>+ harness.session.handleRefineHostRequest("refine.run", { global: "yes" as unknown as boolean }),+ ).toThrow("global must be a boolean");+ setStreaming(harness, false);+ });++ it("reports in_flight as false when no refine is active", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ const status = harness.session.handleRefineHostRequest("refine.status");+ expect(status.in_flight).toBe(false);+ expect(status.pending).toBe(false);+ });++ it("consumes pending refine request at turn boundary", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ setStreaming(harness, false);++ const internals = harness.session as unknown as SessionInternals;+ const refineSpy = vi.spyOn(internals, "refine").mockResolvedValue({});+ internals._consumePendingRequestedRefine();+ expect(refineSpy).toHaveBeenCalledWith({ instructions: "test", global: undefined });+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("does nothing when no pending refine at turn boundary", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ const internals = harness.session as unknown as SessionInternals;+ const refineSpy = vi.spyOn(internals, "refine").mockResolvedValue({});+ expect(internals._consumePendingRequestedRefine()).toBe(false);+ expect(refineSpy).not.toHaveBeenCalled();+ });++ it("catches errors from refine at turn boundary without throwing", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ setStreaming(harness, false);++ const internals = harness.session as unknown as SessionInternals;+ vi.spyOn(internals, "refine").mockRejectedValue(new Error("refine failed"));+ const failed = new Promise<string>((resolve) => {+ const unsubscribe = harness.session.subscribe((event) => {+ if (event.type === "refine_failed") {+ unsubscribe();+ resolve(event.error);+ }+ });+ });++ expect(internals._consumePendingRequestedRefine()).toBe(true);+ expect(await failed).toBe("refine failed");+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("continues notifying refine listeners after one throws", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SessionInternals;+ const observed: string[] = [];+ harness.session.subscribe(() => {+ throw new Error("broken listener");+ });+ harness.session.subscribe((event) => {+ if (event.type === "refine_failed") {+ observed.push(event.error);+ }+ });++ expect(() => internals._emitRefineFailed(new Error("planning failed"))).not.toThrow();+ expect(observed).toEqual(["planning failed"]);+ });++ it("registers refine.run and refine.status handlers when auto-refine is allowed", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ const internals = harness.session as unknown as SessionInternals;+ const handlerKeys = Object.keys(internals._createKernelHostHandlers());+ expect(handlerKeys).toEqual(expect.arrayContaining(["refine.run", "refine.status"]));+ });++ it("does not register refine handlers when auto-refine is not allowed (rlmDepth > 0)", async () => {+ const harness = await createHarness({ persistSession: true, rlmDepth: 1 });+ harnesses.push(harness);+ await harness.session.prompt("one");++ const internals = harness.session as unknown as SessionInternals;+ const handlerKeys = Object.keys(internals._createKernelHostHandlers());+ expect(handlerKeys).not.toContain("refine.run");+ expect(handlerKeys).not.toContain("refine.status");+ });++ it("does not register refine handlers without a persisted session", async () => {+ const harness = await createHarness();+ harnesses.push(harness);+ await harness.session.prompt("one");++ const internals = harness.session as unknown as SessionInternals;+ const handlerKeys = Object.keys(internals._createKernelHostHandlers());+ expect(handlerKeys).not.toContain("refine.run");+ expect(handlerKeys).not.toContain("refine.status");+ });++ it("clears pending refine on dispose", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");+ await harness.session.prompt("two");++ setStreaming(harness, true);+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ setStreaming(harness, false);++ expect(harness.session.handleRefineHostRequest("refine.status").pending).toBe(true);+ harness.session.dispose();+ expect(harness.session.handleRefineHostRequest("refine.status").pending).toBe(false);+ });++ it("rejects unknown refine request type", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ await harness.session.prompt("one");++ expect(() => harness.session.handleRefineHostRequest("refine.unknown")).toThrow(+ 'unknown refine request type "refine.unknown"',+ );+ });+});diff --git a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.tsnew file mode 100644index 0000000000..d2318889f5--- /dev/null+++ b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts@@ -0,0 +1,2572 @@+import type { AgentTool } from "@earendil-works/pi-agent-core";+import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";+import { Type } from "typebox";+import { afterEach, describe, expect, it, vi } from "vitest";+import { createHarness, type Harness } from "./harness.js";++type SerializedInternals = {+ _shouldStopAfterTurn(context: {+ message: { stopReason?: string; content: unknown[]; role: string; usage?: unknown; timestamp?: number };+ toolResults: unknown[];+ context: unknown;+ newMessages: unknown[];+ }): Promise<boolean>;+ _runSerializedRefineCheckpoint(): Promise<void>;+ _runSerializedRefine(options: { instructions?: string; global?: boolean }): Promise<void>;+ _consumeSerializedBackgroundPlan(consume: (result: unknown) => Promise<boolean>): Promise<string>;+ _runSerializedAutoRefineReview(reason: "turn_interval" | "compact", branchVersion: number): Promise<void>;+ _consumePendingRequestedRefine(): boolean;+ _maybeAutoRefine(reason: string): Promise<void>;+ _reviewAutoRefine(context: { reason: string; turnsSinceLastReview: number }, signal?: AbortSignal): Promise<unknown>;+ _planRefine(options: { instructions?: string; global?: boolean }, signal: AbortSignal): Promise<unknown>;+ _applyRefine(+ plan: unknown,+ options: { instructions?: string; global?: boolean },+ abort: AbortController,+ ): Promise<unknown>;+ _serializedRefine: boolean;+ _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;+ _assistantTurnsSinceAutoRefine: number;+ _lastAutoRefineReviewAt: number;+ _autoRefineInProgress: boolean;+ _autoRefineBranchVersion: number;+ _refineInFlight?: Promise<void>;+ _refinePlanInFlight?: Promise<void>;+ _serializedPlanInFlight?: Promise<unknown>;+ _disposing: boolean;+ _disposed: boolean;+ _scheduleAutoRefineAfterAgentEnd(): void;+ _checkCompaction(message: unknown): Promise<boolean>;+ _lastAssistantMessage: unknown;+ _handleAgentEvent(event: { type: string; messages?: unknown[] }): void;+ _agentEventQueue: Promise<void>;+ _autoRefineReviewAbort?: AbortController | undefined;+ _refineAbortController?: AbortController | undefined;+ _compactionOperation?: Promise<void> | undefined;+ _branchSummaryOperation?: Promise<void> | undefined;+ requestAbort(): void;+ abortCompaction(): void;+ abortBranchSummary(): void;+ _pendingMessageResumeRequested: boolean;+ _pendingMessageResumeEpoch: number;+ _pendingMessageResumeQueue: Promise<void>;+ _schedulePendingMessageResume(request?: boolean): void;+ _maybeStartSerializedBackgroundPlan: () => void;+ _compactAutoRefinePending: boolean;+ _scheduleAutoRefine(reason: "turn_interval" | "compact"): void;+ _scheduleAutoRefineAfterCompaction(willContinueAfterCompaction: boolean): void;+ _getRequiredRequestAuth(model: unknown): Promise<{ apiKey: string; headers?: Record<string, string> }>;+ _performCompaction(options: unknown): Promise<{+ summary: string;+ firstKeptEntryId: string;+ tokensBefore: number;+ }>;+ _drainPendingRefinementForDisposal(): Promise<void>;+ _autoRefineOperations: Set<Promise<void>>;+};++function emptyRefinementResult() {+ return {+ id: "refine_test",+ summary: "test refinement",+ rationale: "test rationale",+ expectedOutcome: "test outcome",+ appliedEdits: [],+ harnessStatePath: "/tmp/harness_state.json",+ };+}++function makeCtx(text: string) {+ return {+ message: {+ stopReason: "stop",+ content: [{ type: "text" as const, text }],+ role: "assistant",+ usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, totalTokens: 15 },+ timestamp: Date.now(),+ },+ toolResults: [],+ context: {},+ newMessages: [],+ };+}++/** Mock _planRefine and _applyRefine so _runSerializedRefine completes without real LLM calls. */+function mockSerializedRefine(harness: Harness) {+ const internals = harness.session as unknown as SerializedInternals;+ const plan = { id: "test-plan", proposal: { edits: [] } };+ vi.spyOn(internals, "_planRefine").mockResolvedValue(plan);+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ return { plan, applyRefine: internals._applyRefine };+}++describe("Serialized auto-refine checkpoint", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("refines exactly once when >25 tool turns run in one loop", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "durable lesson",+ instructions: "capture the lesson",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);+ const internals = harness.session as unknown as SerializedInternals;++ for (let turn = 1; turn <= 26; turn++) {+ internals._assistantTurnsSinceAutoRefine++; // simulate message_end increment+ await internals._shouldStopAfterTurn(makeCtx(`turn ${turn}`));+ }++ // _applyRefine called exactly once (at turn 25).+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(reviewer).toHaveBeenCalledTimes(1);+ });++ it("max concurrent primary/refinement model requests is one in serialized mode", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;++ let applyInFlight = false;+ let resolveApply: () => void = () => {};+ const applyPromise = new Promise<void>((resolve) => {+ resolveApply = resolve;+ });+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ applyInFlight = true;+ await applyPromise;+ applyInFlight = false;+ return emptyRefinementResult();+ });++ // Start _shouldStopAfterTurn — it will await the serialized refine+ const checkpointPromise = internals._shouldStopAfterTurn(makeCtx("test"));++ // The checkpoint is running and apply is in flight.+ // _shouldStopAfterTurn has not returned yet, so the agent loop+ // cannot start the next model request.+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ expect(applyInFlight).toBe(true);++ // Release the apply+ resolveApply();+ await checkpointPromise;++ expect(applyInFlight).toBe(false);+ });++ it("prompt/state update visible on resumed turn after serialized refine", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "add memory",+ instructions: "add a memory entry",+ })),+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;++ await internals._runSerializedRefineCheckpoint();++ // _applyRefine was called (which rebuilds system prompt).+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });++ it("final agent_end pending refine completes before dispose", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;++ await harness.session.disposeAsync();++ // The drain path ran the serialized checkpoint which called _applyRefine.+ expect(applyRefine).toHaveBeenCalled();+ expect(internals._disposed).toBe(true);+ });++ it("interactive background refine behavior preserved when serializedRefine is false", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: false,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals;+ expect(internals._serializedRefine).toBe(false);++ let checkpointCalled = false;+ vi.spyOn(internals, "_runSerializedRefineCheckpoint").mockImplementation(async () => {+ checkpointCalled = true;+ });++ internals._assistantTurnsSinceAutoRefine = 1;+ await internals._shouldStopAfterTurn(makeCtx("test"));++ expect(checkpointCalled).toBe(false);+ });++ it("never deadlocks: serialized checkpoint does not call waitForIdle or _maybeAutoRefine", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ // Simulate "active" agent state (as during a tool loop)+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;++ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;++ // Must resolve within 5 seconds — if _maybeAutoRefine were called,+ // _shouldSkipAutoRefineForActiveAgent would defer, and if waitForIdle+ // were called, it would deadlock waiting for activeRun to finish.+ const timeout = new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error("Serialized checkpoint deadlocked")), 5000),+ );++ await Promise.race([internals._runSerializedRefineCheckpoint(), timeout]);++ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });+});++describe("Serialized agent-callable refine", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("agent-callable refine.run starts background planning immediately in serialized mode", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "capture a lesson" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // In serialized mode, handleRefineHostRequest immediately kicks off+ // background planning, consuming the pending request.+ expect(internals._pendingRequestedRefine).toBeUndefined();+ expect(internals._serializedPlanInFlight).toBeDefined();++ // Wait for background planning to complete+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // At the boundary, the plan should be applied+ await internals._runSerializedRefineCheckpoint();+ expect(applyRefine).toHaveBeenCalledTimes(1);+ });++ it("agent-callable request takes priority over interval-triggered auto-refine", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "interval",+ instructions: "interval lesson",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "callable lesson" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ await internals._runSerializedRefineCheckpoint();++ // _applyRefine called once (for the callable request only).+ // The explicit refine satisfied the interval and reset the counter,+ // so no interval-triggered auto-refine follows.+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ // The reviewer was NOT called because the explicit refine+ // satisfied the interval check.+ expect(reviewer).not.toHaveBeenCalled();+ });++ it("agent-callable refine.run background plan started immediately, NOT fire-and-forget at agent_end", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals;++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // In serialized mode, the pending request is consumed immediately+ // by background planning, NOT left for fire-and-forget at agent_end.+ expect(internals._pendingRequestedRefine).toBeUndefined();+ expect(internals._serializedPlanInFlight).toBeDefined();+ });++ it("pending agent-callable refine drained before disposal", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "drain test" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ await harness.session.disposeAsync();++ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._disposed).toBe(true);+ });+});++describe("Serialized autonomous continuation", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("autonomous tool loop continues past serialized refinement boundary with no deadlock", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "checkpoint",+ instructions: "capture lesson",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 3, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;++ // Simulate shouldStopAfterTurn calls for turns 1-5.+ const turnResults: boolean[] = [];+ for (let turn = 1; turn <= 5; turn++) {+ internals._assistantTurnsSinceAutoRefine++; // simulate message_end increment+ const stopResult = await Promise.race([+ internals._shouldStopAfterTurn(makeCtx(`autonomous turn ${turn}`)),+ new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`Deadlock at turn ${turn}`)), 5000)),+ ]);+ turnResults.push(stopResult);+ }++ // All turns return false (continue) — checkpoint ran but didn't stop.+ expect(turnResults).toEqual([false, false, false, false, false]);++ // _applyRefine called exactly once (at turn 3).+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(reviewer).toHaveBeenCalledTimes(1);++ // After the refine at turn 3, counter was reset to 0.+ // Turns 4 and 5 set it to 1 and 2, both < 3.+ expect(internals._assistantTurnsSinceAutoRefine).toBe(2);+ });+});++describe("Serialized background planning during tools", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("planning overlaps a deferred tool but next model turn waits for plan+apply", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let resolvePlan: () => void = () => {};+ const planPromise = new Promise<void>((resolve) => {+ resolvePlan = resolve;+ });+ let planStarted = false;+ let planFinished = false;++ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planStarted = true;+ await planPromise;+ planFinished = true;+ return { id: "bg-plan", proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Step 1: simulate message_end — this should kick off background planning.+ internals._assistantTurnsSinceAutoRefine++;+ // Call the private method that starts background planning+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait a tick for the async plan to start+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ expect(planStarted).toBe(true);+ expect(planFinished).toBe(false); // still planning while "tools execute"++ // Step 2: shouldStopAfterTurn should WAIT for the plan to finish.+ const checkpointPromise = internals._shouldStopAfterTurn(makeCtx("turn with tools"));++ // The checkpoint should be waiting for the plan (not yet resolved).+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ // _applyRefine has NOT been called yet because planning is still in flight.+ expect(internals._applyRefine).not.toHaveBeenCalled();++ // Release the plan — the checkpoint should proceed to apply.+ resolvePlan();+ await checkpointPromise;++ // Now apply has been called.+ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ expect(planFinished).toBe(true);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });++ it("lets refine.run supersede an interval plan that ignores abort", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "interval review",+ instructions: "interval plan",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let resolveIntervalPlan: () => void = () => {};+ const intervalPlanReady = new Promise<void>((resolve) => {+ resolveIntervalPlan = resolve;+ });+ let planCalls = 0;+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planCalls++;+ if (planCalls === 1) {+ await intervalPlanReady;+ }+ return { id: `plan-${planCalls}`, proposal: { edits: [] } };+ });+ const apply = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ internals._assistantTurnsSinceAutoRefine = 1;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ expect(planCalls).toBe(1);++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "explicit plan" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;+ expect(internals._pendingRequestedRefine?.instructions).toBe("explicit plan");++ const checkpoint = internals._runSerializedRefineCheckpoint();+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ resolveIntervalPlan();+ await checkpoint;++ expect(reviewer).toHaveBeenCalledTimes(1);+ expect(internals._planRefine).toHaveBeenCalledTimes(2);+ expect(apply).toHaveBeenCalledTimes(1);+ expect(apply.mock.calls[0]?.[0]).toMatchObject({ id: "plan-2" });+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("max concurrent model calls is one: planning does not start another model request", async () => {+ // The background plan uses _reviewAutoRefine which calls the LLM via+ // completeSimple (an independent non-streaming call). In serialized mode,+ // the review is part of the background plan, not a second model request+ // overlapping the primary stream. The primary stream is already done+ // (message_end fired) when planning starts.+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Simulate message_end+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for planning to complete (reviewer is async)+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // The reviewer was called (background planning started at message_end)+ expect(reviewer).toHaveBeenCalledTimes(1);++ // Now call shouldStopAfterTurn — it should await the background plan+ // and apply it without starting a new model request.+ await internals._shouldStopAfterTurn(makeCtx("boundary"));++ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });+});++describe("PR #503 model persistence regression", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("persisted subagent model is restored on session rehydration", async () => {+ // PR #503 commit 47c4b28f8 persists and restores the subagent model+ // on rehydration. This test verifies the model is not lost when a+ // session is created with a specific model.+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ });+ harnesses.push(harness);++ // The session should have a model set.+ expect(harness.session.model).toBeDefined();+ expect(harness.session.model?.id).toBe(harness.getModel().id);+ });++ it("model is preserved after serialized refine checkpoint", async () => {+ // PR #503 commit 742a85b99 preserves the extension system prompt+ // after the refine wait. This test verifies the model survives a+ // serialized refine checkpoint.+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const { applyRefine } = mockSerializedRefine(harness);++ const internals = harness.session as unknown as SerializedInternals;+ const modelBefore = harness.session.model;++ internals._assistantTurnsSinceAutoRefine = 1;+ await internals._runSerializedRefineCheckpoint();++ // Model is preserved after the checkpoint.+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(harness.session.model).toBe(modelBefore);+ });+});++describe("Serialized refine review-fix regressions", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("explicit refine.run does NOT call the auto-review gate", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "should not be called",+ instructions: "should not be called",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Queue a refine.run request — in serialized mode, this immediately+ // kicks off background planning (skipping the review gate).+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "explicit lesson" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // Background planning was started automatically by handleRefineHostRequest.+ expect(internals._serializedPlanInFlight).toBeDefined();++ // Wait for background planning to complete+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Reviewer was NOT called — explicit refine.run skips the review gate.+ expect(reviewer).not.toHaveBeenCalled();++ // At the boundary, the plan should be applied+ await internals._runSerializedRefineCheckpoint();+ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });++ it("failure result stamps cooldown and does NOT retry synchronously", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Make background planning fail+ vi.spyOn(internals, "_planRefine").mockRejectedValue(new Error("plan failed"));+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Start background planning+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for background planning to fail+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // At the boundary, the failure result should stamp cooldown and return.+ // It should NOT fall through to synchronous review+plan (no duplicate model call).+ await internals._runSerializedRefineCheckpoint();++ // Reviewer was called exactly once (during background planning).+ // It should NOT be called again at the boundary (failure -> no retry).+ expect(reviewer).toHaveBeenCalledTimes(1);+ // _applyRefine was NOT called (planning failed).+ expect(internals._applyRefine).not.toHaveBeenCalled();+ // Cooldown was stamped.+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);+ });++ it("non-serialized explicit refine suppresses interval auto-refine for that turn", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ refine(options: { instructions?: string }): Promise<unknown>;+ };+ internals._pendingRequestedRefine = { instructions: "explicit" };+ const refine = vi.spyOn(internals, "refine").mockResolvedValue(emptyRefinementResult());+ const schedule = vi.spyOn(internals, "_scheduleAutoRefineAfterAgentEnd");+ const assistant = fauxAssistantMessage("done");+ internals._lastAssistantMessage = assistant;++ internals._handleAgentEvent({ type: "agent_end", messages: [assistant] });+ await internals._agentEventQueue;+ await vi.waitFor(() => expect(refine).toHaveBeenCalledOnce());++ expect(schedule).not.toHaveBeenCalled();+ });++ it("serialized failure does not schedule interactive auto-refine at agent_end", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Make background planning fail+ vi.spyOn(internals, "_planRefine").mockRejectedValue(new Error("plan failed"));+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Start background planning and let it fail+ internals._assistantTurnsSinceAutoRefine = 1;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // At the boundary, the failure result should stamp cooldown and return.+ await internals._runSerializedRefineCheckpoint();++ // Reviewer was called exactly once (during background planning).+ expect(reviewer).toHaveBeenCalledTimes(1);+ // _applyRefine was NOT called (planning failed).+ expect(internals._applyRefine).not.toHaveBeenCalled();+ // Cooldown was stamped.+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);++ // Now simulate the actual agent_end event path.+ // Set _lastAssistantMessage so agent_end has a non-error assistant to process.+ const fauxAssistant = fauxAssistantMessage("done");+ internals._lastAssistantMessage = fauxAssistant;++ // Spy on _scheduleAutoRefineAfterAgentEnd — it should NOT be called in serialized mode.+ const scheduleSpy = vi.spyOn(internals, "_scheduleAutoRefineAfterAgentEnd");+ // Mock _checkCompaction so agent_end reaches the scheduling guard.+ vi.spyOn(internals, "_checkCompaction").mockResolvedValue(false);++ // Drive the real agent_end event through _handleAgentEvent → _processAgentEvent.+ internals._handleAgentEvent({ type: "agent_end", messages: [fauxAssistant] });+ await internals._agentEventQueue;+ // Flush any setTimeout(0) that _scheduleAutoRefine would have used.+ await new Promise<void>((resolve) => setTimeout(resolve, 20));++ // _scheduleAutoRefineAfterAgentEnd must NEVER be called in serialized mode.+ expect(scheduleSpy).not.toHaveBeenCalled();+ });++ it("explicit refine.run bg plan fails then boundary replan/apply succeeds", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let planCalls = 0;+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planCalls++;+ if (planCalls === 1) throw new Error("bg plan failed");+ return { id: "replan", proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Queue an explicit refine.run — this starts background planning at message_end.+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "explicit" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // Let the background plan fail.+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ expect(internals._pendingRequestedRefine).toBeUndefined();++ // At the boundary, the failure re-queues the explicit options and the+ // synchronous pending path replans + applies.+ await internals._runSerializedRefineCheckpoint();++ expect(planCalls).toBe(2); // bg plan (failed) + synchronous replan+ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("interval bg plan failure does not retry synchronously", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Interval background planning fails (not explicit refine.run).+ vi.spyOn(internals, "_planRefine").mockRejectedValue(new Error("plan failed"));+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ internals._assistantTurnsSinceAutoRefine = 1;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ await internals._runSerializedRefineCheckpoint();++ // Reviewer called once (interval bg plan), NOT retried at boundary.+ expect(reviewer).toHaveBeenCalledTimes(1);+ expect(internals._applyRefine).not.toHaveBeenCalled();+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("classifies an aborted stale background plan as invalidated", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ _runBackgroundPlan(+ options: { instructions?: string },+ abort: AbortController,+ branchVersion: number,+ skipReview?: boolean,+ ): Promise<unknown>;+ };+ const branchVersion = internals._autoRefineBranchVersion;+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ internals._autoRefineBranchVersion++;+ throw new Error("branch changed");+ });++ await expect(+ internals._runBackgroundPlan({ instructions: "stale" }, new AbortController(), branchVersion, true),+ ).resolves.toEqual({ status: "invalidated", branchVersion });+ });++ it("stale branch failure does not requeue explicit refine.run", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ vi.spyOn(internals, "_planRefine").mockRejectedValue(new Error("plan failed"));+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Queue explicit refine.run — starts background planning.+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "explicit" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Invalidate the branch (simulates a newer turn or branch reset).+ internals._autoRefineBranchVersion++;++ await internals._runSerializedRefineCheckpoint();++ // Stale branch: no re-queue, no apply.+ expect(internals._applyRefine).not.toHaveBeenCalled();+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("newer pending supersedes failed older explicit refine.run", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ vi.spyOn(internals, "_planRefine").mockImplementation(async (opts) => {+ if (opts.instructions === "older") throw new Error("bg plan failed");+ return { id: "newer-plan", proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Queue older request — starts background planning.+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "older" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Queue newer request before the boundary.+ internals._pendingRequestedRefine = { instructions: "newer" };++ await internals._runSerializedRefineCheckpoint();++ // Newer request is serviced (plan with "newer", not "older").+ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("disposal does not double-refine after explicit drain", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let planCalls = 0;+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planCalls++;+ return { id: `plan-${planCalls}`, proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Set up: assistant turns met, explicit refine.run pending.+ internals._assistantTurnsSinceAutoRefine = 1;+ internals._pendingRequestedRefine = { instructions: "explicit" };++ // Drive the disposal drain path.+ (+ internals as unknown as { _drainPendingRefinementForDisposal: () => Promise<void> }+ )._drainPendingRefinementForDisposal();+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // The explicit drain should have planned + applied exactly once.+ expect(planCalls).toBe(1);+ expect(internals._applyRefine).toHaveBeenCalledTimes(1);+ // Counter reset prevents the interval check from triggering a second refine.+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("public refine waits for serialized bg plan: max concurrency 1, bg then public apply", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ // Tool that blocks until released. Signals from execute so we know the+ // real agent turn is active (isStreaming is true) before we proceed.+ let resolveGate: () => void = () => {};+ const gateReady = new Promise<void>((resolve) => {+ resolveGate = resolve;+ });+ let gateStarted: () => void = () => {};+ const gateStartedSignal = new Promise<void>((resolve) => {+ gateStarted = resolve;+ });+ const gateTool: AgentTool = {+ name: "gate",+ label: "Gate",+ description: "Blocking gate",+ parameters: Type.Object({}),+ execute: async () => {+ gateStarted();+ await gateReady;+ return { content: [{ type: "text" as const, text: "gate done" }], details: {} };+ },+ };+ // Use turnInterval=999 to avoid interval auto-refine; we trigger bg planning+ // explicitly via handleRefineHostRequest("refine.run").+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 999, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ tools: [gateTool],+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let planCalls = 0;+ let maxConcurrentPlans = 0;+ let activePlans = 0;+ let resolveBgPlan: () => void = () => {};+ const bgPlanReady = new Promise<void>((resolve) => {+ resolveBgPlan = resolve;+ });+ const applyCalls: { plan: unknown; options: unknown }[] = [];+ vi.spyOn(internals, "_planRefine").mockImplementation(async (_opts) => {+ activePlans++;+ maxConcurrentPlans = Math.max(maxConcurrentPlans, activePlans);+ planCalls++;+ if (planCalls === 1) {+ // Background plan — block until released.+ await bgPlanReady;+ }+ activePlans--;+ return { id: `plan-${planCalls}`, proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async (plan, options) => {+ applyCalls.push({ plan, options });+ return emptyRefinementResult();+ });++ // Set up faux responses: first turn calls the gate tool (turn stays active),+ // second response is plain text (turn ends after tool).+ harness.setResponses([+ fauxAssistantMessage([fauxToolCall("gate", {})], { stopReason: "toolUse" }),+ fauxAssistantMessage("done"),+ ]);++ // Start the real prompt — the gate tool will block, keeping the turn active.+ const promptPromise = harness.session.prompt("test");+ // Wait for the gate tool to enter execute (real active turn, isStreaming is true).+ await gateStartedSignal;+ expect(harness.session.isStreaming).toBe(true);++ // Queue an explicit refine.run — starts background planning at message_end.+ // Do NOT manually falsify isStreaming; the real turn owns it.+ harness.session.handleRefineHostRequest("refine.run", { instructions: "bg" });+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ expect(planCalls).toBe(1);+ expect(internals._serializedPlanInFlight).toBeDefined();++ // Call public refine concurrently while bg plan is in flight.+ const publicRefinePromise = harness.session.refine({ instructions: "public" });+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ // Public plan must NOT have started yet — max concurrency is 1.+ expect(planCalls).toBe(1);+ expect(maxConcurrentPlans).toBe(1);++ // Release the bg plan, then the gate tool, then await everything.+ resolveBgPlan();+ await new Promise<void>((resolve) => setTimeout(resolve, 50));+ // Bg plan applied; public refine should now proceed after the checkpoint.+ resolveGate();+ const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error("Test timed out")), 10000));+ await Promise.race([Promise.all([promptPromise, publicRefinePromise]), timeout]);++ // Max concurrency was 1 throughout.+ expect(maxConcurrentPlans).toBe(1);+ // Exactly two applies: background once, then public once.+ expect(applyCalls).toHaveLength(2);+ expect(planCalls).toBe(2);+ // Verify apply order/identity: first apply is the bg plan, second is public.+ const firstPlan = applyCalls[0].plan as { id: string };+ const secondPlan = applyCalls[1].plan as { id: string };+ expect(firstPlan.id).toBe("plan-1");+ expect(secondPlan.id).toBe("plan-2");+ const firstOptions = applyCalls[0].options as { instructions?: string };+ const secondOptions = applyCalls[1].options as { instructions?: string };+ expect(firstOptions.instructions).toBe("bg");+ expect(secondOptions.instructions).toBe("public");+ });++ it("public refine waits for active compaction without aborting it", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseCompaction: () => void = () => {};+ const compactionOperation = new Promise<void>((resolve) => {+ releaseCompaction = resolve;+ });+ internals._compactionOperation = compactionOperation;+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "public-plan", proposal: { edits: [] } });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ const abortCompaction = vi.spyOn(internals, "abortCompaction");++ const refinePromise = harness.session.refine({ instructions: "public" });+ await vi.waitFor(() => expect(internals._refineInFlight).toBeDefined());++ expect(abortCompaction).not.toHaveBeenCalled();+ expect(applyRefine).not.toHaveBeenCalled();+ expect(internals._refineAbortController?.signal.aborted).toBe(false);+ releaseCompaction();+ await refinePromise;++ expect(applyRefine).toHaveBeenCalledOnce();+ internals._compactionOperation = undefined;+ internals._refineAbortController = undefined;+ });++ it("public refine waits for active branch summary without aborting it", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseBranchSummary: () => void = () => {};+ const branchSummaryOperation = new Promise<void>((resolve) => {+ releaseBranchSummary = resolve;+ });+ internals._branchSummaryOperation = branchSummaryOperation;+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "public-plan", proposal: { edits: [] } });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ const abortBranchSummary = vi.spyOn(internals, "abortBranchSummary");++ const refinePromise = harness.session.refine({ instructions: "public" });+ await vi.waitFor(() => expect(internals._refineInFlight).toBeDefined());++ expect(abortBranchSummary).not.toHaveBeenCalled();+ expect(applyRefine).not.toHaveBeenCalled();+ expect(internals._refineAbortController?.signal.aborted).toBe(false);+ releaseBranchSummary();+ await refinePromise;++ expect(applyRefine).toHaveBeenCalledOnce();+ internals._branchSummaryOperation = undefined;+ internals._refineAbortController = undefined;+ });++ it("public refine snapshots final events and operations after the agent becomes idle", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseIdle: () => void = () => {};+ const idleOperation = new Promise<void>((resolve) => {+ releaseIdle = resolve;+ });+ const waitForIdle = vi.spyOn(harness.session.agent, "waitForIdle").mockReturnValue(idleOperation);+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "public-plan", proposal: { edits: [] } });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ const refinePromise = harness.session.refine({ instructions: "public" });+ await vi.waitFor(() => expect(waitForIdle).toHaveBeenCalledOnce());++ let releaseEventQueue: () => void = () => {};+ internals._agentEventQueue = new Promise<void>((resolve) => {+ releaseEventQueue = resolve;+ });+ let releaseCompaction: () => void = () => {};+ internals._compactionOperation = new Promise<void>((resolve) => {+ releaseCompaction = resolve;+ });++ releaseIdle();+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ expect(applyRefine).not.toHaveBeenCalled();++ releaseEventQueue();+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ expect(applyRefine).not.toHaveBeenCalled();++ releaseCompaction();+ await refinePromise;+ expect(applyRefine).toHaveBeenCalledOnce();++ internals._compactionOperation = undefined;+ internals._refineAbortController = undefined;+ });++ it("interval background plan derives instructions from review, not prepopulated", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "specific rationale from review",+ instructions: "specific instructions from review",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let capturedPlanOptions: { instructions?: string } | undefined;+ vi.spyOn(internals, "_planRefine").mockImplementation(async (opts: { instructions?: string }) => {+ capturedPlanOptions = opts;+ return { id: "p", proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Start background planning (interval-triggered)+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for background planning+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // The plan options should include the review's rationale/instructions,+ // not a generic prepopulated message.+ expect(capturedPlanOptions).toBeDefined();+ expect(capturedPlanOptions?.instructions).toContain("specific rationale from review");+ expect(capturedPlanOptions?.instructions).toContain("specific instructions from review");+ });++ it("emits refine_failed when a ready background plan fails to apply", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._serializedPlanInFlight = Promise.resolve({+ status: "plan",+ plan: { id: "failed-plan", proposal: { edits: [] } },+ options: { instructions: "explicit" },+ abort: new AbortController(),+ branchVersion: internals._autoRefineBranchVersion,+ });+ vi.spyOn(internals, "_applyRefine").mockRejectedValue(new Error("harness write failed"));+ const failed = new Promise<string>((resolve) => {+ const unsubscribe = harness.session.subscribe((event) => {+ if (event.type === "refine_failed") {+ unsubscribe();+ resolve(event.error);+ }+ });+ });++ await internals._runSerializedRefineCheckpoint();++ expect(await failed).toBe("harness write failed");+ });++ it("disposal applies ready background plan before teardown", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ const exactPlan = { id: "disposal-plan", proposal: { edits: [] } };+ vi.spyOn(internals, "_planRefine").mockResolvedValue(exactPlan);+ const applySpy = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Start background planning+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for the background plan to settle (plan ready)+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Dispose — should apply the ready plan before teardown.+ const timeout = new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error("Disposal deadlocked")), 5000),+ );+ await Promise.race([harness.session.disposeAsync(), timeout]);++ // _applyRefine was called with the exact plan (persisted before teardown).+ expect(applySpy).toHaveBeenCalledTimes(1);+ expect((applySpy.mock.calls[0] as unknown[])[0]).toBe(exactPlan);+ expect(internals._disposed).toBe(true);+ });++ it("services a compaction-triggered refine at the next serialized boundary", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "post-compaction lesson",+ instructions: "capture it",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const { applyRefine } = mockSerializedRefine(harness);++ internals._scheduleAutoRefineAfterCompaction(true);+ expect(internals._compactAutoRefinePending).toBe(true);+ await internals._runSerializedRefineCheckpoint();++ expect(reviewer).toHaveBeenCalledWith(expect.objectContaining({ reason: "compact" }), expect.any(AbortSignal));+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("defers serialized compaction refinement even when no continuation was scheduled", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "terminal compaction lesson",+ instructions: "capture it",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const interactiveSpy = vi.spyOn(internals, "_maybeAutoRefine");+ const { applyRefine } = mockSerializedRefine(harness);++ internals._scheduleAutoRefineAfterCompaction(false);+ expect(internals._compactAutoRefinePending).toBe(true);+ expect(interactiveSpy).not.toHaveBeenCalled();+ await internals._drainPendingRefinementForDisposal();++ expect(reviewer).toHaveBeenCalledWith(expect.objectContaining({ reason: "compact" }), expect.any(AbortSignal));+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("defers manual compaction refinement to the serialized checkpoint", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ vi.spyOn(internals, "_getRequiredRequestAuth").mockResolvedValue({ apiKey: "test" });+ vi.spyOn(internals, "_performCompaction").mockResolvedValue({+ summary: "manual summary",+ firstKeptEntryId: "entry-1",+ tokensBefore: 100,+ });+ const interactiveSpy = vi.spyOn(internals, "_scheduleAutoRefine");++ await harness.session.compact();++ expect(interactiveSpy).not.toHaveBeenCalled();+ expect(internals._compactAutoRefinePending).toBe(true);+ });++ it("preserves a serialized compaction trigger while cooldown is active", async () => {+ const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "not called" }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 60_000 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._lastAutoRefineReviewAt = Date.now();+ internals._scheduleAutoRefineAfterCompaction(true);++ await internals._runSerializedRefineCheckpoint();++ expect(reviewer).not.toHaveBeenCalled();+ expect(internals._compactAutoRefinePending).toBe(true);+ });++ it("clears a serialized compaction trigger when disposal occurs during cooldown", async () => {+ const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "not called" }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 60_000 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._lastAutoRefineReviewAt = Date.now();+ internals._compactAutoRefinePending = true;++ await internals._drainPendingRefinementForDisposal();++ expect(reviewer).not.toHaveBeenCalled();+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("continues to the interval drain after a compact trigger hits cooldown", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 1, cooldownMs: 60_000 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const settings = { enabled: true, compact: true, turnInterval: 1, cooldownMs: 60_000 };+ vi.spyOn(harness.session.settingsManager, "getAutoRefineSettings")+ .mockReturnValueOnce(settings)+ .mockReturnValue({ ...settings, cooldownMs: 0 });+ const checkpoint = vi.spyOn(internals, "_runSerializedRefineCheckpoint").mockResolvedValue();+ internals._lastAutoRefineReviewAt = Date.now();+ internals._assistantTurnsSinceAutoRefine = 1;+ internals._compactAutoRefinePending = true;++ await internals._drainPendingRefinementForDisposal();++ expect(internals._compactAutoRefinePending).toBe(false);+ expect(checkpoint).toHaveBeenCalledOnce();+ });++ it("falls back to an interval review when compact-triggered refinement is disabled", async () => {+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "interval lesson",+ instructions: "capture it",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: false, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const { applyRefine } = mockSerializedRefine(harness);+ internals._assistantTurnsSinceAutoRefine = 1;+ internals._scheduleAutoRefineAfterCompaction(true);++ await internals._runSerializedRefineCheckpoint();++ expect(reviewer).toHaveBeenCalledWith(+ expect.objectContaining({ reason: "turn_interval" }),+ expect.any(AbortSignal),+ );+ expect(applyRefine).toHaveBeenCalledTimes(1);+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("clears a compact trigger after a review decides no refinement is needed", async () => {+ const reviewer = vi.fn(async () => ({ shouldRefine: false, rationale: "nothing durable" }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const { applyRefine } = mockSerializedRefine(harness);+ internals._scheduleAutoRefineAfterCompaction(true);++ await internals._runSerializedRefineCheckpoint();++ expect(reviewer).toHaveBeenCalledWith(expect.objectContaining({ reason: "compact" }), expect.any(AbortSignal));+ expect(applyRefine).not.toHaveBeenCalled();+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("does not let a compact review failure block disposal", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, compact: true, turnInterval: 999, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._compactAutoRefinePending = true;+ vi.spyOn(internals, "_runSerializedAutoRefineReview").mockRejectedValue(+ new Error("unexpected compact review failure"),+ );++ await expect(internals._drainPendingRefinementForDisposal()).resolves.toBeUndefined();+ expect(internals._compactAutoRefinePending).toBe(false);+ });++ it("retries a failed explicit background plan during disposal", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 999, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const options = { instructions: "explicit recovery" };+ internals._serializedPlanInFlight = Promise.resolve({+ status: "failure",+ explicit: true,+ options,+ branchVersion: internals._autoRefineBranchVersion,+ });+ const runSpy = vi.spyOn(internals, "_runSerializedRefine").mockResolvedValue();++ await internals._drainPendingRefinementForDisposal();++ expect(runSpy).toHaveBeenCalledTimes(1);+ expect(runSpy).toHaveBeenCalledWith(options);+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });+});++describe("Serialized refine event-ordering integration", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("real message_end/turn_end ordering: threshold planning starts and applies before next model turn", async () => {+ // This test uses real agent.prompt() with faux responses to verify+ // that _shouldStopAfterTurn's await this._agentEventQueue ensures+ // the message_end counter increment and background plan kickoff+ // happen BEFORE the serialized checkpoint runs.+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "integration test",+ instructions: "capture lesson",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ const planSpy = vi+ .spyOn(internals, "_planRefine")+ .mockResolvedValue({ id: "p", proposal: { edits: [] } } as never);+ const applySpy = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Send a prompt that produces a text response (no tool calls).+ // This goes through the real agent loop: agent_start -> turn_start ->+ // message_start -> message_end (counter++) -> turn_end -> shouldStopAfterTurn+ // -> agent_end.+ harness.setResponses([fauxAssistantMessage("response 1")]);++ // Track counter before and after prompt+ const counterBefore = internals._assistantTurnsSinceAutoRefine;+ await harness.session.prompt("test prompt");++ // After the first turn, the counter should be incremented by the+ // real message_end handler (not by direct mutation).+ expect(internals._assistantTurnsSinceAutoRefine).toBe(counterBefore + 1);++ // Now send a second prompt to reach the interval (turnInterval=2).+ harness.setResponses([fauxAssistantMessage("response 2")]);+ await harness.session.prompt("test prompt 2");++ // After the second turn, the serialized checkpoint should have fired+ // (interval=2, counter reached 2). The _agentEventQueue await in+ // _shouldStopAfterTurn ensured the counter was incremented before+ // the checkpoint checked the threshold.+ expect(applySpy).toHaveBeenCalled();+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);++ // The reviewer was called exactly once (during background planning+ // or synchronous boundary review, not duplicated).+ expect(reviewer).toHaveBeenCalledTimes(1);+ // _planRefine called exactly once (no duplicate from re-planning).+ expect(planSpy).toHaveBeenCalledTimes(1);+ });+});++describe("P0 concurrency regressions", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("serialized threshold compaction: background plan applied before compaction fires", async () => {+ // Verify that when threshold compaction would fire, the serialized+ // checkpoint runs FIRST, draining the background plan, so the+ // compaction model call cannot overlap an in-flight refine.+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ let planResolved = false;+ let applyFinished = false;++ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ planResolved = true;+ return { id: "p", proposal: { edits: [] } };+ });+ vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ expect(planResolved).toBe(true);+ await new Promise<void>((resolve) => setTimeout(resolve, 10));+ applyFinished = true;+ return emptyRefinementResult();+ });++ // Spy on _shouldStopForThresholdCompaction: assert apply finished+ // when compaction check runs, return true to simulate compaction firing.+ const compactionSpy = vi+ .spyOn(+ internals as unknown as { _shouldStopForThresholdCompaction: (ctx: unknown) => Promise<boolean> },+ "_shouldStopForThresholdCompaction",+ )+ .mockImplementation(async () => {+ expect(applyFinished).toBe(true);+ return true;+ });++ // Start background planning at message_end+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for plan to start but not finish+ await new Promise<void>((resolve) => setTimeout(resolve, 10));++ // _shouldStopAfterTurn: serialized checkpoint runs BEFORE compaction.+ // Checkpoint awaits background plan, applies it. Then compaction fires.+ const result = await internals._shouldStopAfterTurn(makeCtx("turn"));++ expect(compactionSpy).toHaveBeenCalledTimes(1);+ expect(result).toBe(true);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });+ it("branch navigation with in-flight serialized plan: aborts signal, no apply", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ const applySpy = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Make _planRefine block on its AbortSignal so we can test abort behavior.+ let planSignal: AbortSignal | undefined;+ vi.spyOn(internals, "_planRefine").mockImplementation(async (_opts: unknown, signal: AbortSignal) => {+ planSignal = signal;+ // Block until the signal aborts, then throw.+ if (signal.aborted) throw new Error("Plan aborted by branch change");+ await new Promise<void>((_, reject) => {+ signal.addEventListener("abort", () => reject(new Error("aborted")));+ }).catch(() => undefined);+ if (signal.aborted) throw new Error("Plan aborted by branch change");+ return { id: "p", proposal: { edits: [] } };+ });++ // Start background planning+ internals._assistantTurnsSinceAutoRefine++;+ (+ internals as unknown as { _maybeStartSerializedBackgroundPlan: () => void }+ )._maybeStartSerializedBackgroundPlan();++ // Wait for the plan to start blocking+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ expect(internals._serializedPlanInFlight).toBeDefined();+ expect(planSignal).toBeDefined();++ // Call _invalidatePendingAutoRefineForBranchChange while plan is pending.+ // This increments _autoRefineBranchVersion and awaits _serializedPlanInFlight.+ const invalidatePromise = (+ harness.session as unknown as {+ _invalidatePendingAutoRefineForBranchChange: () => Promise<void>;+ }+ )._invalidatePendingAutoRefineForBranchChange();++ // The branchVersion was incremented, invalidating the plan.+ const branchVersionAfter = internals._autoRefineBranchVersion;+ expect(branchVersionAfter).toBeGreaterThan(0);++ // Wait for invalidation to complete (the plan promise settles as "failure"+ // because _planRefine threw, but the branchVersion mismatch means no apply).+ await invalidatePromise;++ // _serializedPlanInFlight is cleared.+ expect(internals._serializedPlanInFlight).toBeUndefined();++ // Run the checkpoint — no background plan to apply (cleared by invalidation).+ await internals._runSerializedRefineCheckpoint();++ // _applyRefine was NOT called.+ expect(applySpy).not.toHaveBeenCalled();+ });++ it("non-mocked apply pipeline: harness state persisted, prompt rebuilt, refine_complete emitted", async () => {+ // This test does NOT mock _applyRefine. It uses a faux planRefine+ // mock but lets the real _applyRefine run, which calls+ // applyRefinementProposal, saveHarnessState, _rebuildSystemPrompt,+ // and emits refine_complete.+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "add a memory",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Mock only _planRefine (the LLM planning call), NOT _applyRefine.+ const fauxPlan = {+ id: "refine_p0_test",+ proposal: {+ summary: "P0 test refinement",+ rationale: "testing non-mocked apply",+ expectedOutcome: "memory entry persisted",+ edits: [+ {+ action: "create" as const,+ kind: "memory" as const,+ title: "P0 concurrency test memory",+ content: "Added during non-mocked apply pipeline test",+ },+ {+ action: "update" as const,+ kind: "memory" as const,+ id: "missing-memory",+ title: "Missing",+ content: "Rejected edit",+ },+ ],+ },+ };+ vi.spyOn(internals, "_planRefine").mockResolvedValue(fauxPlan as never);++ // Spy on _rebuildSystemPrompt (call-through) to assert it was invoked.+ const rebuildSpy = vi.spyOn(+ harness.session as unknown as { _rebuildSystemPrompt: (tools: string[]) => string },+ "_rebuildSystemPrompt",+ );+ const extensionEmit = vi.spyOn(harness.session.extensionRunner, "emit");++ // Track refine_complete event+ let refineCompleteEmitted = false;+ harness.session.subscribe((event) => {+ if (event.type === "refine_complete") {+ refineCompleteEmitted = true;+ }+ });++ // Run the serialized refine (real _applyRefine runs).+ await internals._runSerializedRefine({ instructions: "add a memory" });++ // _rebuildSystemPrompt was called by _applyRefine.+ expect(rebuildSpy).toHaveBeenCalledTimes(1);++ // Harness state persisted to disk.+ const localDir = (await import("../../src/core/refinement/index.js")).getLocalHarnessStateDir(+ harness.sessionManager.getSessionArtifactDir(),+ );+ expect(localDir).toBeDefined();+ if (localDir) {+ const state = (await import("../../src/core/refinement/index.js")).loadHarnessState(localDir, "local");+ const memoryEntries = Object.values(state.entries.memory ?? {});+ const memoryEntry = memoryEntries.find((m) => m.title === "P0 concurrency test memory");+ expect(memoryEntry).toBeDefined();+ expect(memoryEntry?.content).toBe("Added during non-mocked apply pipeline test");+ }++ // refine_complete reports only successfully applied edits to extensions.+ expect(refineCompleteEmitted).toBe(true);+ expect(extensionEmit).toHaveBeenCalledWith(expect.objectContaining({ type: "refine_complete", appliedEdits: 1 }));+ });+ it("explicit refine.run planning failure: stamps cooldown, no apply, no retry", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 25, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Make planning fail for the explicit refine.run request.+ const planError = new Error("planning network failure");+ vi.spyOn(internals, "_planRefine").mockRejectedValue(planError);+ const applySpy = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Queue a refine.run request — this starts background planning.+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // Wait for background planning to fail.+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Run the checkpoint — the background plan failed ("failure" result).+ await internals._runSerializedRefineCheckpoint();++ // _applyRefine was NOT called (planning failed).+ expect(applySpy).not.toHaveBeenCalled();++ // Cooldown was stamped (failure -> stamp cooldown, no retry).+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(0);++ // _serializedPlanInFlight is cleared.+ expect(internals._serializedPlanInFlight).toBeUndefined();+ });++ it("serialized same-entry Python harness-write: concurrent kernel write rejected via baselineState", async () => {+ // Verify that a concurrent Python kernel harness write (e.g.+ // rlm.harness.create_memory) during serialized background planning+ // is detected via baselineState comparison and the stale edit is+ // rejected, preserving the concurrent write.+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Seed a memory entry on disk so the plan has something to update.+ const { getLocalHarnessStateDir, loadHarnessState, saveHarnessState } = await import(+ "../../src/core/refinement/index.js"+ );+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir());+ expect(localDir).toBeDefined();+ if (!localDir) return;+ const seedState = loadHarnessState(localDir, "local");+ seedState.entries.memory ??= {};+ seedState.entries.memory.shared = {+ id: "shared",+ kind: "memory",+ title: "Shared",+ content: "planning baseline",+ path: "general",+ scope: "local",+ reference: {},+ arguments: {},+ metadata: {},+ source: "refine",+ created_at: new Date().toISOString(),+ updated_at: new Date().toISOString(),+ version: 1,+ };+ saveHarnessState(localDir, seedState);++ // Mock _planRefine to block until released so we can simulate+ // a concurrent harness write during the planning phase.+ let releasePlan: (() => void) | undefined;+ const planGate = new Promise<void>((resolve) => {+ releasePlan = resolve;+ });+ let planStarted: (() => void) | undefined;+ const planStartedPromise = new Promise<void>((resolve) => {+ planStarted = resolve;+ });++ // Capture the baseline state at planning time (before the LLM call would run)+ // so the real _applyRefine can compare it against the current on-disk state.+ const baselineState = loadHarnessState(localDir, "local");+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planStarted?.();+ await planGate;+ return {+ id: "refine_conflict_test",+ proposal: {+ summary: "Update shared memory",+ rationale: "planned update",+ expectedOutcome: "updated",+ edits: [+ {+ action: "update",+ kind: "memory",+ id: "shared",+ title: "Shared",+ content: "stale planned content",+ },+ ],+ },+ baselineState,+ } as never;+ });++ // Start the serialized refine — begins background planning.+ const refinePromise = internals._runSerializedRefine({ instructions: "update shared memory" });++ // Wait for planning to start.+ await planStartedPromise;++ // Simulate a concurrent Python kernel harness write while planning is in flight.+ const concurrentState = loadHarnessState(localDir, "local");+ const sharedEntry = concurrentState.entries.memory?.shared;+ expect(sharedEntry).toBeDefined();+ if (sharedEntry) {+ sharedEntry.content = "concurrent kernel content";+ sharedEntry.version++;+ }+ saveHarnessState(localDir, concurrentState);++ // Release the plan so it completes with a stale proposal.+ releasePlan?.();++ // Wait for the serialized refine to finish (planning + apply).+ await refinePromise;++ // The on-disk state should still have the concurrent content+ // (the stale planned edit was rejected by baselineState comparison).+ const finalState = loadHarnessState(localDir, "local");+ expect(finalState.entries.memory?.shared?.content).toBe("concurrent kernel content");+ });++ it("aborted non-serialized turn clears _pendingRequestedRefine at agent_end", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ refine: (options: { instructions?: string }) => Promise<unknown>;+ };++ // Seed a pending explicit refine.run request.+ internals._pendingRequestedRefine = { instructions: "leaked-explicit" };+ const refineSpy = vi.spyOn(internals, "refine").mockResolvedValue(undefined);+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ // Simulate an aborted assistant message arriving at agent_end.+ // Do NOT mock _checkCompaction — the real aborted path must clear the pending refine.+ const abortedAssistant = fauxAssistantMessage("aborted turn", { stopReason: "aborted" });+ internals._lastAssistantMessage = abortedAssistant;+ internals._handleAgentEvent({ type: "agent_end", messages: [abortedAssistant] });+ await internals._agentEventQueue;+ await new Promise<void>((resolve) => setTimeout(resolve, 20));++ // _checkCompaction's aborted block cleared _pendingRequestedRefine.+ expect(internals._pendingRequestedRefine).toBeUndefined();+ // The non-serialized agent_end path did NOT call refine (pending was already cleared).+ expect(refineSpy).not.toHaveBeenCalled();+ });++ it("explicit abort during a tool call clears a non-serialized refine.run before agent_end", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ refine: (options: { instructions?: string }) => Promise<unknown>;+ };+ const refineSpy = vi.spyOn(internals, "refine").mockResolvedValue(undefined);++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ expect(+ harness.session.handleRefineHostRequest("refine.run", {+ instructions: "must not survive cancellation",+ }),+ ).toMatchObject({ scheduled: true });+ expect(internals._pendingRequestedRefine).toBeDefined();++ harness.session.requestAbort();+ expect(internals._pendingRequestedRefine).toBeUndefined();++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;+ const toolUseAssistant = fauxAssistantMessage([fauxToolCall("ipython", { code: "await refine.run()" })], {+ stopReason: "toolUse",+ });+ internals._lastAssistantMessage = toolUseAssistant;+ internals._handleAgentEvent({ type: "agent_end", messages: [toolUseAssistant] });+ await internals._agentEventQueue;+ await new Promise<void>((resolve) => setTimeout(resolve, 20));++ expect(refineSpy).not.toHaveBeenCalled();+ });++ it("explicit abort invalidates an in-flight serialized refine.run plan", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ let planSignal: AbortSignal | undefined;+ vi.spyOn(internals, "_planRefine").mockImplementation(+ (_options: { instructions?: string }, signal: AbortSignal) => {+ planSignal = signal;+ return new Promise((_, reject) => {+ signal.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });+ });+ },+ );++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", {+ instructions: "must not survive cancellation",+ });+ await vi.waitFor(() => expect(planSignal).toBeDefined());+ expect(internals._serializedPlanInFlight).toBeDefined();+ const branchVersion = internals._autoRefineBranchVersion;++ harness.session.requestAbort();+ expect(planSignal?.aborted).toBe(true);+ expect(internals._autoRefineBranchVersion).toBeGreaterThan(branchVersion);++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;+ await internals._runSerializedRefineCheckpoint();+ expect(applyRefine).not.toHaveBeenCalled();+ expect(internals._serializedPlanInFlight).toBeUndefined();+ });++ it("explicit abort cancels an in-flight public refinement plan", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let planSignal: AbortSignal | undefined;+ vi.spyOn(internals, "_planRefine").mockImplementation(+ (_options: { instructions?: string }, signal: AbortSignal) => {+ planSignal = signal;+ return new Promise((_, reject) => {+ signal.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });+ });+ },+ );++ const refine = harness.session.refine({ instructions: "cancel this plan" });+ await vi.waitFor(() => expect(planSignal).toBeDefined());++ harness.session.requestAbort();++ expect(planSignal?.aborted).toBe(true);+ await expect(refine).rejects.toThrow("cancelled");+ });++ it("explicit abort cancels direct serialized refinement planning", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ let planSignal: AbortSignal | undefined;+ vi.spyOn(internals, "_planRefine").mockImplementation(+ (_options: { instructions?: string }, signal: AbortSignal) => {+ planSignal = signal;+ return new Promise((_, reject) => {+ signal.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });+ });+ },+ );++ const refine = internals._runSerializedRefine({ instructions: "cancel direct plan" });+ await vi.waitFor(() => expect(planSignal).toBeDefined());+ expect(internals._serializedPlanInFlight).toBeUndefined();+ expect(internals._refinePlanInFlight).toBeDefined();+ expect(internals._refineInFlight).toBeUndefined();+ const branchVersion = internals._autoRefineBranchVersion;++ harness.session.requestAbort();++ expect(planSignal?.aborted).toBe(true);+ expect(internals._autoRefineBranchVersion).toBeGreaterThan(branchVersion);+ await expect(refine).rejects.toThrow("cancelled");+ expect(applyRefine).not.toHaveBeenCalled();+ });++ it("direct serialized planning blocks a concurrent public refinement plan", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseDirectPlan: () => void = () => {};+ const directPlanGate = new Promise<void>((resolve) => {+ releaseDirectPlan = resolve;+ });+ let planCalls = 0;+ let activePlans = 0;+ let maxActivePlans = 0;+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ planCalls++;+ activePlans++;+ maxActivePlans = Math.max(maxActivePlans, activePlans);+ if (planCalls === 1) {+ await directPlanGate;+ }+ activePlans--;+ return { id: `plan-${planCalls}`, proposal: { edits: [] } };+ });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ const directRefine = internals._runSerializedRefine({ instructions: "direct" });+ await vi.waitFor(() => expect(internals._refinePlanInFlight).toBeDefined());++ const publicRefine = harness.session.refine({ instructions: "public" });+ await new Promise<void>((resolve) => setTimeout(resolve, 20));+ expect(planCalls).toBe(1);+ expect(maxActivePlans).toBe(1);++ releaseDirectPlan();+ await Promise.all([directRefine, publicRefine]);++ expect(planCalls).toBe(2);+ expect(maxActivePlans).toBe(1);+ expect(applyRefine).toHaveBeenCalledTimes(2);+ });++ it("explicit abort cancels a serialized auto-refine review", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let reviewSignal: AbortSignal | undefined;+ vi.spyOn(internals, "_reviewAutoRefine").mockImplementation((_context, signal) => {+ reviewSignal = signal;+ return new Promise((_, reject) => {+ signal?.addEventListener("abort", () => reject(new Error("cancelled")), { once: true });+ });+ });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ const branchVersion = internals._autoRefineBranchVersion;+ const review = internals._runSerializedAutoRefineReview("turn_interval", branchVersion);+ await vi.waitFor(() => expect(reviewSignal).toBeDefined());+ expect(internals._autoRefineReviewAbort?.signal).toBe(reviewSignal);++ harness.session.requestAbort();++ expect(reviewSignal?.aborted).toBe(true);+ expect(internals._autoRefineBranchVersion).toBeGreaterThan(branchVersion);+ await expect(review).resolves.toBeUndefined();+ expect(applyRefine).not.toHaveBeenCalled();+ expect(internals._autoRefineReviewAbort).toBeUndefined();+ });++ it("does not stamp cooldown when the branch changes during serialized refinement", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 4;+ internals._lastAutoRefineReviewAt = 0;+ vi.spyOn(internals, "_reviewAutoRefine").mockResolvedValue({+ shouldRefine: true,+ rationale: "capture lesson",+ instructions: "capture it",+ });+ vi.spyOn(internals, "_runSerializedRefine").mockImplementation(async () => {+ internals._autoRefineBranchVersion++;+ });+ const branchVersion = internals._autoRefineBranchVersion;++ await internals._runSerializedAutoRefineReview("turn_interval", branchVersion);++ expect(internals._lastAutoRefineReviewAt).toBe(0);+ expect(internals._assistantTurnsSinceAutoRefine).toBe(4);+ });++ it("services a pending request after an invalidated background plan", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._serializedPlanInFlight = Promise.resolve({ status: "invalidated" });+ internals._pendingRequestedRefine = { instructions: "latest" };+ const run = vi.spyOn(internals, "_runSerializedRefine").mockResolvedValue();++ await internals._runSerializedRefineCheckpoint();++ expect(run).toHaveBeenCalledWith({ instructions: "latest" });+ expect(internals._pendingRequestedRefine).toBeUndefined();+ });++ it("records cooldown after dropping a stale ready background plan", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ const apply = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ const reviewAtBeforeCheckpoint = internals._lastAutoRefineReviewAt;+ internals._assistantTurnsSinceAutoRefine = 1;+ internals._serializedPlanInFlight = Promise.resolve({+ status: "plan",+ plan: { id: "stale-plan", proposal: { edits: [] } },+ options: {},+ abort: new AbortController(),+ branchVersion: internals._autoRefineBranchVersion - 1,+ });++ await internals._runSerializedRefineCheckpoint();++ expect(apply).not.toHaveBeenCalled();+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ expect(internals._lastAutoRefineReviewAt).toBeGreaterThan(reviewAtBeforeCheckpoint);+ });++ it("aborted serialized turn clears _pendingRequestedRefine so it does not leak to next checkpoint", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 999, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ refine: (options: { instructions?: string }) => Promise<unknown>;+ };++ // Seed a pending explicit refine.run request.+ internals._pendingRequestedRefine = { instructions: "leaked-explicit" };+ const refineSpy = vi.spyOn(internals, "refine").mockResolvedValue(undefined);+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });+ const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ const stalePlanAbort = new AbortController();+ internals._refineAbortController = stalePlanAbort;+ internals._serializedPlanInFlight = new Promise((resolve) => {+ stalePlanAbort.signal.addEventListener(+ "abort",+ () => resolve({ status: "invalidated", branchVersion: internals._autoRefineBranchVersion - 1 }),+ { once: true },+ );+ });++ // Simulate an aborted assistant message arriving at agent_end.+ // Do NOT mock _checkCompaction — the real aborted path must clear the pending refine.+ const abortedAssistant = fauxAssistantMessage("aborted turn", { stopReason: "aborted" });+ internals._lastAssistantMessage = abortedAssistant;+ internals._handleAgentEvent({ type: "agent_end", messages: [abortedAssistant] });+ await internals._agentEventQueue;+ await new Promise<void>((resolve) => setTimeout(resolve, 20));++ // _checkCompaction's aborted block cleared _pendingRequestedRefine.+ expect(internals._pendingRequestedRefine).toBeUndefined();+ expect(internals._serializedPlanInFlight).toBeUndefined();+ expect(stalePlanAbort.signal.aborted).toBe(true);+ expect(refineSpy).not.toHaveBeenCalled();++ // Run the next serialized checkpoint; no plan or apply should fire.+ await internals._runSerializedRefineCheckpoint();+ expect(internals._planRefine).not.toHaveBeenCalled();+ expect(applyRefine).not.toHaveBeenCalled();+ });++ it("public refine resumes pending messages after the application phase", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;++ // Provide a provider response first so a resumed turn can complete.+ harness.setResponses([fauxAssistantMessage("resumed")]);++ // Queue a follow-up via the public API (no resumeIfIdle flag).+ // This populates both the session and Agent queues.+ await harness.session.queueAgentMessagePrompt("queued follow-up", "followUp");+ expect(harness.session.pendingMessageCount).toBe(1);++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ await harness.session.refine({ instructions: "public" });++ // The forced resume should consume the follow-up and run the provider.+ await vi.waitFor(() => {+ expect(harness.session.pendingMessageCount).toBe(0);+ expect(harness.getPendingResponseCount()).toBe(0);+ });+ });++ it("surfaces an explicit serialized planning failure without terminating the turn", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._pendingRequestedRefine = { instructions: "fail planning" };+ vi.spyOn(internals, "_planRefine").mockRejectedValue(new Error("planner unavailable"));+ const failed = new Promise<string>((resolve) => {+ const unsubscribe = harness.session.subscribe((event) => {+ if (event.type === "refine_failed") {+ unsubscribe();+ resolve(event.error);+ }+ });+ });++ await expect(internals._runSerializedRefineCheckpoint()).resolves.toBeUndefined();+ expect(await failed).toBe("planner unavailable");+ });++ it("isolates an explicit serialized apply failure from the turn boundary", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._pendingRequestedRefine = { instructions: "fail at apply" };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockRejectedValue(new Error("disk full"));+ const failed = new Promise<string>((resolve) => {+ const unsubscribe = harness.session.subscribe((event) => {+ if (event.type === "refine_failed") {+ unsubscribe();+ resolve(event.error);+ }+ });+ });++ await expect(internals._runSerializedRefineCheckpoint()).resolves.toBeUndefined();+ expect(await failed).toBe("disk full");+ });++ it("consumes a serialized background plan only once across concurrent drains", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let resolvePlan: (value: unknown) => void = () => {};+ internals._serializedPlanInFlight = new Promise((resolve) => {+ resolvePlan = resolve;+ });+ let releaseProcessing: () => void = () => {};+ const processing = new Promise<void>((resolve) => {+ releaseProcessing = resolve;+ });+ const firstConsumer = vi.fn(async (result: unknown) => {+ expect(result).toEqual({ status: "skip" });+ await processing;+ return false;+ });+ const secondConsumer = vi.fn(async () => false);++ const first = internals._consumeSerializedBackgroundPlan(firstConsumer);+ const second = internals._consumeSerializedBackgroundPlan(secondConsumer);+ expect(internals._serializedPlanInFlight).toBeDefined();+ resolvePlan({ status: "skip" });+ await vi.waitFor(() => expect(firstConsumer).toHaveBeenCalledOnce());++ let secondSettled = false;+ void second.then(() => {+ secondSettled = true;+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(secondSettled).toBe(false);++ releaseProcessing();+ await expect(first).resolves.toBe("continue");+ await expect(second).resolves.toBe("waited");+ expect(secondConsumer).not.toHaveBeenCalled();+ });++ it("disposal waits for the checkpoint owner to finish applying a claimed plan", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let resolvePlan: (value: unknown) => void = () => {};+ internals._serializedPlanInFlight = new Promise((resolve) => {+ resolvePlan = resolve;+ });+ internals._assistantTurnsSinceAutoRefine = 1;+ let releaseApply: () => void = () => {};+ const applyBlocked = new Promise<void>((resolve) => {+ releaseApply = resolve;+ });+ const apply = vi.spyOn(internals, "_applyRefine").mockImplementation(async () => {+ await applyBlocked;+ return emptyRefinementResult();+ });++ const checkpoint = internals._runSerializedRefineCheckpoint();+ const drain = internals._drainPendingRefinementForDisposal();+ resolvePlan({+ status: "plan",+ plan: { id: "claimed-plan", proposal: { edits: [] } },+ options: {},+ abort: new AbortController(),+ branchVersion: internals._autoRefineBranchVersion,+ });+ await vi.waitFor(() => expect(apply).toHaveBeenCalledOnce());++ let drainSettled = false;+ void drain.then(() => {+ drainSettled = true;+ });+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(drainSettled).toBe(false);++ releaseApply();+ await Promise.all([checkpoint, drain]);+ expect(apply).toHaveBeenCalledOnce();+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);+ });++ it("drains a due interactive auto-refine without waiting for agent idle", async () => {+ const harness = await createHarness({+ persistSession: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ internals._assistantTurnsSinceAutoRefine = 1;+ const waitForIdle = vi.spyOn(harness.session.agent, "waitForIdle").mockResolvedValue();+ const maybeAutoRefine = vi.spyOn(internals, "_maybeAutoRefine").mockResolvedValue();++ await internals._drainPendingRefinementForDisposal();++ expect(waitForIdle).not.toHaveBeenCalled();+ expect(maybeAutoRefine).toHaveBeenCalledWith("turn_interval");+ });++ it("waits for an interactive auto-refine operation before disposal drain continues", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseOperation: () => void = () => {};+ const operation = new Promise<void>((resolve) => {+ releaseOperation = resolve;+ });+ internals._autoRefineOperations.add(operation);+ let settled = false;+ const drain = internals._drainPendingRefinementForDisposal().then(() => {+ settled = true;+ });++ await new Promise<void>((resolve) => setTimeout(resolve, 0));+ expect(settled).toBe(false);+ releaseOperation();+ await drain;+ expect(settled).toBe(true);+ });++ it("memoizes disposeAsync before refinement drain completes", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals;+ let releaseDrain: () => void = () => {};+ const drain = new Promise<void>((resolve) => {+ releaseDrain = resolve;+ });+ vi.spyOn(internals, "_drainPendingRefinementForDisposal").mockReturnValue(drain);++ const first = harness.session.disposeAsync();+ const second = harness.session.disposeAsync();+ expect(internals._drainPendingRefinementForDisposal).toHaveBeenCalledTimes(1);+ releaseDrain();+ await Promise.all([first, second]);+ });++ it("public refine clears a settled serialized plan left by an aborted turn", async () => {+ const harness = await createHarness({ persistSession: true, serializedRefine: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ _serializedExplicitRefineOptions?: { instructions?: string; global?: boolean };+ };+ internals._serializedPlanInFlight = Promise.resolve({ status: "skip" });+ internals._serializedExplicitRefineOptions = { instructions: "stale", global: true };+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "public-plan", proposal: { edits: [] } });+ const apply = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());++ await expect(harness.session.refine({ instructions: "public after abort" })).resolves.toEqual(+ emptyRefinementResult(),+ );++ expect(internals._serializedPlanInFlight).toBeUndefined();+ expect(internals._serializedExplicitRefineOptions).toBeUndefined();+ expect(apply).toHaveBeenCalledOnce();+ });++ it("public refine waits for idle without aborting the session or child runs", async () => {+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ const internals = harness.session as unknown as SerializedInternals & {+ _goalAbortInProgress: boolean;+ _cancelActiveRlmChildRuns: () => void;+ };++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "plan", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());+ const cancelChildRuns = vi.spyOn(internals, "_cancelActiveRlmChildRuns");+ const requestAbort = vi.spyOn(harness.session, "requestAbort");++ await harness.session.refine({ instructions: "public" });++ expect(requestAbort).not.toHaveBeenCalled();+ expect(cancelChildRuns).not.toHaveBeenCalled();+ expect(internals._goalAbortInProgress).toBe(false);+ });+});diff --git a/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.ts b/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.tsnew file mode 100644index 0000000000..74efd6fa92--- /dev/null+++ b/packages/coding-agent/test/suite/daemon-serialized-refine-process.test.ts@@ -0,0 +1,333 @@+/**+ * Real-process daemon-backed test for serializedRefine propagation.+ *+ * Spawns the actual CLI (`pi --mode json`) which goes through:+ * client -> unix socket -> daemon supervisor -> owned worker -> AgentSession.+ *+ * Uses the existing 4685 CLI/daemon and daemon-supervisor process fixtures.+ * Does NOT use private AgentDaemon.createRuntime or createHarness.+ *+ * This single test proves:+ * - The production daemon-launch env scrub strips inherited+ * PRIME_AGENT_INTERNAL_DAEMON_WORKER=1 so the auto-spawned supervisor+ * starts in supervisor mode (not worker mode) and sends daemon_hello.+ * - serializedRefine=true (derived from appMode="json") crosses the real+ * socket/process and arrives at the owned worker.+ * - refine_complete fires before agent_end (by seq), proving the+ * serialized checkpoint is applied at shouldStopAfterTurn in the real+ * worker before the agent loop terminates.+ * - The exact model ("faux/faux") supplied via --model arrives at the+ * worker extension context.+ * - --goal "Process proof goal" --goal-token-budget 1 seeds an initial+ * goal that is persisted to the session JSONL before the first message,+ * then becomes budget_limited from the first assistant response usage+ * (withUsageEstimate produces positive input/output) so the agent does+ * not auto-continue.+ */++import { type ChildProcess, spawn } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { ENV_AGENT_DIR } from "../../src/config.js";+import { ORPHAN_PROCESS_JOURNAL_ENV } from "../../src/core/orphan-process-journal.js";+import { SESSION_LEASE_OWNER_ID_ENV, SESSION_LEASES_ENABLED_ENV } from "../../src/core/session-lease.js";+import { DaemonClient } from "../../src/modes/daemon/daemon-client.js";+import {+ DAEMON_WORKER_ACTIVE_SESSION_ID_ENV,+ DAEMON_WORKER_RECOVERY_JOURNAL_ENV,+ DAEMON_WORKER_ROLE_ENV,+ DAEMON_WORKER_SUPERVISOR_SOCKET_ENV,+ DAEMON_WORKER_TOKEN_ENV,+} from "../../src/modes/daemon/daemon-worker-protocol.js";++const cliPath = resolve(__dirname, "../../src/cli.ts");+const tsxPath = resolve(__dirname, "../../../../node_modules/tsx/dist/cli.mjs");+const repoTsconfigPath = resolve(__dirname, "../../../../tsconfig.json");+const fauxRefineExtensionPath = resolve(__dirname, "../fixtures/eng-4685-faux-refine-extension.ts");+const eventOrderExtensionPath = resolve(__dirname, "../fixtures/eng-4685-event-order-extension.ts");+const children = new Set<ChildProcess>();+const daemonSockets = new Set<string>();+const tempRoots = new Set<string>();++afterEach(async () => {+ for (const child of children) {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill("SIGKILL");+ }+ }+ children.clear();+ for (const socketPath of daemonSockets) {+ const client = new DaemonClient(socketPath);+ try {+ await client.connect(500);+ await client.request({ type: "shutdown" }, 5000);+ } catch {+ // The process may have exited before publishing its socket.+ } finally {+ client.close();+ }+ for (let attempt = 0; attempt < 50 && existsSync(socketPath); attempt++) {+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 20));+ }+ }+ daemonSockets.clear();+ for (const root of tempRoots) {+ rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ }+ tempRoots.clear();+});++async function runCli(+ args: string[],+ options: { agentDir: string; stdin?: string; environment?: NodeJS.ProcessEnv },+): Promise<{ code: number | null; signal: NodeJS.Signals | null; stdout: string; stderr: string }> {+ const child = spawn(process.execPath, [tsxPath, cliPath, ...args], {+ env: {+ ...process.env,+ TSX_TSCONFIG_PATH: repoTsconfigPath,+ [ENV_AGENT_DIR]: options.agentDir,+ PI_SKIP_VERSION_CHECK: "1",+ PRIME_AGENT_INTERNAL_LEGACY_OWNED_WORKER_FRONTEND: "0",+ PRIME_AGENT_KERNEL_FORKSERVER: "0",+ RLM_DEPTH: "0",+ // The test deliberately RE-INJECTS the worker role env var+ // (via options.environment, applied last) to prove the+ // production daemon-launch.ts env scrub removes it before+ // spawning the daemon supervisor.+ [DAEMON_WORKER_ROLE_ENV]: undefined,+ [DAEMON_WORKER_TOKEN_ENV]: undefined,+ [DAEMON_WORKER_ACTIVE_SESSION_ID_ENV]: undefined,+ [DAEMON_WORKER_RECOVERY_JOURNAL_ENV]: undefined,+ [DAEMON_WORKER_SUPERVISOR_SOCKET_ENV]: undefined,+ [ORPHAN_PROCESS_JOURNAL_ENV]: undefined,+ [SESSION_LEASES_ENABLED_ENV]: undefined,+ [SESSION_LEASE_OWNER_ID_ENV]: undefined,+ ...options.environment,+ },+ stdio: ["pipe", "pipe", "pipe"],+ });+ children.add(child);+ let stdout = "";+ let stderr = "";+ child.stdout?.on("data", (chunk: Buffer) => {+ stdout += chunk.toString("utf8");+ });+ child.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString("utf8");+ });+ child.stdin?.end(options.stdin ?? "");+ const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolveExit, reject) => {+ const timeout = setTimeout(() => {+ child.kill("SIGKILL");+ reject(new Error(`CLI timed out\n${stderr}`));+ }, 120_000);+ child.once("exit", (code, signal) => {+ clearTimeout(timeout);+ resolveExit({ code, signal: signal as NodeJS.Signals | null });+ });+ });+ children.delete(child);+ return { ...exit, stdout, stderr };+}++interface EventLogEntry {+ seq: number;+ type: string;+ [key: string]: unknown;+}++function readEventLog(path: string): EventLogEntry[] {+ if (!existsSync(path)) return [];+ const content = readFileSync(path, "utf8").trim();+ if (!content) return [];+ return content+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as EventLogEntry);+}++function writeAutoRefineSettings(agentDir: string): void {+ writeFileSync(+ join(agentDir, "settings.json"),+ JSON.stringify({ autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } }),+ );+}++describe("Real-process serializedRefine — JSON mode", () => {+ it("daemon supervisor scrubs inherited worker env, checkpoint applies refine_complete before agent_end", async () => {+ const root = mkdtempSync(join(tmpdir(), "prime-agent-process-json-refine-"));+ tempRoots.add(root);+ const agentDir = join(root, "agent");+ mkdirSync(agentDir, { recursive: true });+ const socketPath = join(root, "daemon.sock");+ daemonSockets.add(socketPath);+ const eventLogPath = join(root, "events.jsonl");++ writeAutoRefineSettings(agentDir);++ // Deliberately re-inject the worker role env var AFTER the test+ // defaults so that the only thing preventing the daemon from+ // starting in worker mode is the production env scrub in+ // daemon-launch.ts ensureDaemonRunning().+ const result = await runCli(+ [+ "--mode",+ "json",+ "--daemon-socket",+ socketPath,+ "--model",+ "faux/faux",+ "--extension",+ fauxRefineExtensionPath,+ "--extension",+ eventOrderExtensionPath,+ "--no-tools",+ "--no-skills",+ "--no-prompt-templates",+ "--no-themes",+ "--no-context-files",+ "--goal",+ "Process proof goal",+ "--goal-token-budget",+ "1",+ "Say hello",+ ],+ {+ agentDir,+ environment: {+ PRIME_AGENT_TEST_EVENT_LOG: eventLogPath,+ [DAEMON_WORKER_ROLE_ENV]: "1",+ },+ },+ );++ // Clean exit — the production env scrub allowed the supervisor+ // to start correctly despite the inherited worker role env var.+ expect(result).toMatchObject({ code: 0, signal: null });+ expect(result.stderr).not.toContain("Timed out waiting for daemon");++ // Daemon socket exists — the daemon path was used.+ expect(existsSync(socketPath)).toBe(true);++ // Read the event log recorded by the extension in the real worker.+ const events = readEventLog(eventLogPath);+ expect(events.length).toBeGreaterThanOrEqual(3);++ // agent_start fired with the exact model from --model.+ const agentStart = events.find((e) => e.type === "agent_start");+ expect(agentStart).toBeDefined();+ expect(agentStart!.modelId).toBe("faux");+ expect(agentStart!.modelProvider).toBe("faux");++ // refine_complete fired — the serialized checkpoint applied+ // the refinement in the real owned worker.+ const refineComplete = events.find((e) => e.type === "refine_complete");+ expect(refineComplete).toBeDefined();+ expect(refineComplete!.id).toMatch(/^refine_/);+ expect(refineComplete!.appliedEdits).toBe(0);++ // agent_end fired — the agent loop terminated.+ const agentEnd = events.find((e) => e.type === "agent_end");+ expect(agentEnd).toBeDefined();++ // CRITICAL: refine_complete must precede agent_end (by seq).+ // This proves the serialized checkpoint was applied at the+ // shouldStopAfterTurn boundary BEFORE the agent loop emitted+ // agent_end — i.e. the refinement was applied in-process, not+ // deferred to a post-exit drain.+ expect(refineComplete!.seq).toBeLessThan(agentEnd!.seq);++ // ----------------------------------------------------------------+ // Goal persistence proof: recursively find the actual session JSONL+ // under AGENT_DIR, parse it, and assert the initial goal state+ // custom entry precedes the first message entry and has the exact+ // objective/budget from --goal/--goal-token-budget.+ // ----------------------------------------------------------------+ interface JsonlEntry {+ type: string;+ customType?: string;+ data?: Record<string, unknown>;+ message?: { role: string; usage?: { input?: number; output?: number } };+ }++ function findSessionJsonl(dir: string): string | undefined {+ for (const name of readdirSync(dir)) {+ const fullPath = join(dir, name);+ if (name.endsWith(".jsonl")) {+ // Validate this is a session JSONL, not a daemon recovery+ // or orphan journal: the first non-empty line must have+ // type === "session".+ try {+ const raw = readFileSync(fullPath, "utf8").trim().split("\n")[0];+ if (raw) {+ const first = JSON.parse(raw) as { type?: string };+ if (first.type === "session") return fullPath;+ }+ } catch {+ // not valid JSON, skip+ }+ continue;+ }+ try {+ readdirSync(fullPath);+ const found = findSessionJsonl(fullPath);+ if (found) return found;+ } catch {+ // not a directory+ }+ }+ return undefined;+ }++ const sessionJsonlPath = findSessionJsonl(join(agentDir, "sessions"));+ expect(sessionJsonlPath).toBeDefined();++ const jsonlContent = readFileSync(sessionJsonlPath!, "utf8");+ const jsonlEntries: JsonlEntry[] = jsonlContent+ .trim()+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as JsonlEntry);++ // Find the first thread_goal_state custom entry.+ const goalEntries = jsonlEntries.filter((e) => e.type === "custom" && e.customType === "thread_goal_state");+ expect(goalEntries.length).toBeGreaterThanOrEqual(1);++ const firstGoalEntry = goalEntries[0]!;+ const goalData = firstGoalEntry.data!;+ expect(goalData.objective).toBe("Process proof goal");+ expect(goalData.tokenBudget).toBe(1);+ expect(goalData.status).toBe("active");++ // Find the index of the first goal entry and first message entry.+ const firstGoalIndex = jsonlEntries.indexOf(firstGoalEntry);+ const firstMessageIndex = jsonlEntries.findIndex((e) => e.type === "message");+ expect(firstMessageIndex).toBeGreaterThan(-1);++ // CRITICAL: The initial goal state must be persisted BEFORE the+ // first message entry. This proves the goal was seeded at session+ // creation (before any model interaction) via flushNow.+ expect(firstGoalIndex).toBeLessThan(firstMessageIndex);++ // The first assistant message must have positive usage (input > 0+ // and output > 0) produced by withUsageEstimate, which means the+ // goal accounting will consume real tokens and reach the budget.+ const assistantMessages = jsonlEntries.filter((e) => e.type === "message" && e.message?.role === "assistant");+ expect(assistantMessages.length).toBeGreaterThanOrEqual(1);+ const firstAssistant = assistantMessages[0]!;+ expect(firstAssistant.message!.usage!.input!).toBeGreaterThan(0);+ expect(firstAssistant.message!.usage!.output!).toBeGreaterThan(0);++ // A budget_limited goal state entry must exist AFTER the first+ // message, proving the goal consumed real usage and stopped the+ // agent from auto-continuing.+ const budgetLimitedEntries = goalEntries.filter(+ (e) => (e.data as Record<string, unknown>)?.status === "budget_limited",+ );+ expect(budgetLimitedEntries.length).toBeGreaterThanOrEqual(1);+ const budgetLimitedIndex = jsonlEntries.indexOf(budgetLimitedEntries[0]!);+ expect(budgetLimitedIndex).toBeGreaterThan(firstMessageIndex);+ }, 120_000);+});diff --git a/packages/coding-agent/test/suite/daemon-serialized-refine.test.ts b/packages/coding-agent/test/suite/daemon-serialized-refine.test.tsnew file mode 100644index 0000000000..2cd468f9ab--- /dev/null+++ b/packages/coding-agent/test/suite/daemon-serialized-refine.test.ts@@ -0,0 +1,203 @@+/**+ * Real daemon-backed tests proving serializedRefine config arrives at+ * daemon-created sessions, controllers are available, and the autonomous+ * loop crosses the threshold.+ *+ * Uses AgentDaemon with a custom createRuntime that captures the merged+ * config and creates real AgentSession instances via the test harness.+ */++import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { CreateAgentSessionRuntimeFactory } from "../../src/core/agent-session-runtime.js";+import { SessionManager } from "../../src/core/session-manager.js";+import type { ActiveSessionState } from "../../src/modes/daemon/active-session-state.js";+import { AgentDaemon } from "../../src/modes/daemon/daemon-mode.js";+import type { DaemonCommand } from "../../src/modes/daemon/daemon-protocol.js";+import { createHarness, type Harness } from "./harness.js";++type SerializedInternals = {+ _serializedRefine: boolean;+ _rlmHeartbeatController?: unknown;+ _agentMessageController?: unknown;+ _agentObserveController?: unknown;+ _assistantTurnsSinceAutoRefine: number;+ _lastAutoRefineReviewAt: number;+ _planRefine: (opts: { instructions?: string }, signal: AbortSignal) => Promise<unknown>;+ _applyRefine: (plan: unknown, opts: unknown, abort: AbortController) => Promise<unknown>;+ _reviewAutoRefine: (ctx: { reason: string; turnsSinceLastReview: number }, signal?: AbortSignal) => Promise<unknown>;+};++describe("Daemon-backed serializedRefine propagation", () => {+ const tempDirs: string[] = [];++ afterEach(() => {+ for (const dir of tempDirs.splice(0)) {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ it("serializedRefine=true in defaultSessionConfig arrives at daemon-created session", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-serialized-refine-"));+ tempDirs.push(tempDir);+ const sessionDir = join(tempDir, "sessions");++ let capturedConfig: { serializedRefine?: boolean } | undefined;++ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ capturedConfig = options.sessionConfig;+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: options.sessionConfig?.serializedRefine ?? false,+ });+ return {+ session: harness.session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as never,+ services: { cwd: options.cwd, agentDir: options.agentDir } as never,+ diagnostics: [],+ } as never;+ });++ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir, serializedRefine: true },+ createRuntime,+ });++ const internals = daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };++ const sessionManager = SessionManager.create(tempDir, sessionDir);+ sessionManager.newSession();+ const sessionFile = sessionManager.getSessionFile()!;++ const state = await internals.createRuntime({ type: "create", sessionPath: sessionFile });++ // The merged config that arrived at createRuntime has serializedRefine=true.+ expect(capturedConfig?.serializedRefine).toBe(true);++ // The session created by the daemon has _serializedRefine=true.+ const sessionInternals = state.runtime.session as unknown as SerializedInternals;+ expect(sessionInternals._serializedRefine).toBe(true);++ state.runtime.session.dispose();+ });++ it("serializedRefine=false in defaultSessionConfig produces _serializedRefine=false session", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-bg-refine-"));+ tempDirs.push(tempDir);+ const sessionDir = join(tempDir, "sessions");++ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: options.sessionConfig?.serializedRefine ?? false,+ });+ return {+ session: harness.session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as never,+ services: { cwd: options.cwd, agentDir: options.agentDir } as never,+ diagnostics: [],+ } as never;+ });++ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir, serializedRefine: false },+ createRuntime,+ });++ const internals = daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };++ const sessionManager = SessionManager.create(tempDir, sessionDir);+ sessionManager.newSession();+ const sessionFile = sessionManager.getSessionFile()!;++ const state = await internals.createRuntime({ type: "create", sessionPath: sessionFile });++ const sessionInternals = state.runtime.session as unknown as SerializedInternals;+ expect(sessionInternals._serializedRefine).toBe(false);++ state.runtime.session.dispose();+ });++ it("daemon session with serializedRefine=true crosses threshold and applies refine", async () => {+ const tempDir = mkdtempSync(join(tmpdir(), "prime-daemon-threshold-"));+ tempDirs.push(tempDir);+ const sessionDir = join(tempDir, "sessions");++ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "daemon test",+ instructions: "capture",+ }));++ let stashedHarness: Harness | undefined;++ const createRuntime = vi.fn(async (options: Parameters<CreateAgentSessionRuntimeFactory>[0]) => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: options.sessionConfig?.serializedRefine ?? false,+ settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ stashedHarness = harness;+ const session = harness.session;+ const internals = session as unknown as SerializedInternals;+ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue({+ id: "refine_test",+ summary: "test",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ harnessStatePath: "/tmp/harness_state.json",+ });+ return {+ session,+ extensionsResult: { extensions: [], errors: [], runtime: {} } as never,+ services: { cwd: options.cwd, agentDir: options.agentDir } as never,+ diagnostics: [],+ } as never;+ });++ const daemon = new AgentDaemon(join(tempDir, "daemon.sock"), {+ defaultSessionConfig: { agentDir: tempDir, cwd: tempDir, sessionDir, serializedRefine: true },+ createRuntime,+ });++ const internals = daemon as unknown as {+ createRuntime(command: Extract<DaemonCommand, { type: "create" }>): Promise<ActiveSessionState>;+ };++ const sessionManager = SessionManager.create(tempDir, sessionDir);+ sessionManager.newSession();+ const sessionFile = sessionManager.getSessionFile()!;++ const state = await internals.createRuntime({ type: "create", sessionPath: sessionFile });+ const session = state.runtime.session;+ const sessionInternals = session as unknown as SerializedInternals;+ const harness = stashedHarness!;++ // Turn 1: counter goes to 1 (< threshold 2)+ harness.setResponses([fauxAssistantMessage("response 1")]);+ await session.prompt("prompt 1");+ expect(sessionInternals._assistantTurnsSinceAutoRefine).toBe(1);++ // Turn 2: counter goes to 2 (>= threshold), checkpoint fires+ harness.setResponses([fauxAssistantMessage("response 2")]);+ await session.prompt("prompt 2");++ // After checkpoint, counter reset to 0+ expect(sessionInternals._assistantTurnsSinceAutoRefine).toBe(0);+ // Reviewer called exactly once+ expect(reviewer).toHaveBeenCalledTimes(1);++ // Cleanup+ harness.cleanup();+ });+});diff --git a/packages/coding-agent/test/suite/harness.ts b/packages/coding-agent/test/suite/harness.tsindex 0e52ff4b49..d55fc1bf18 100644--- a/packages/coding-agent/test/suite/harness.ts+++ b/packages/coding-agent/test/suite/harness.ts@@ -72,6 +72,8 @@ export interface HarnessOptions {rlmDepth?: number;autonomous?: AgentAutonomousConfig;autoRefineReviewer?: AutoRefineReviewer;+ serializedRefine?: boolean;+ initialGoal?: { objective: string; tokenBudget?: number };}export interface Harness {@@ -191,6 +193,8 @@ export async function createHarness(options: HarnessOptions = {}): Promise<HarnerlmDepth: options.rlmDepth,autonomous: options.autonomous,autoRefineReviewer: options.autoRefineReviewer,+ serializedRefine: options.serializedRefine,+ initialGoal: options.initialGoal,});const events: AgentSessionEvent[] = [];diff --git a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.tsindex d706f5e1fe..9f30c2caed 100644--- a/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts+++ b/packages/coding-agent/test/suite/regressions/4602-snapshot-transfer-idempotency.test.ts@@ -72,9 +72,15 @@ function streamedResult(messages: AgentMessage[]): DaemonAttachResult {state: { activeSessionId, sessionId: "session-4602" } as DaemonAttachResult["snapshot"]["state"],messages,lastEventSequence: 1,+ lastEventCursor: { generation: "generation-4602", sequence: 1 },+ },+ replay: {+ status: "complete",+ toSequence: 1,+ toCursor: { generation: "generation-4602", sequence: 1 },},- replay: { status: "complete", toSequence: 1 },lastEventSequence: 1,+ lastEventCursor: { generation: "generation-4602", sequence: 1 },snapshotStream: { id: snapshotId, messageCount: messages.length, targetChunkBytes: 512 * 1024 },client: { id: "worker", capabilities: ["chunked_snapshot"] },};@@ -158,6 +164,7 @@ function snapshotFrames(messages: AgentMessage[]) {snapshotId,chunkCount: 1,lastEventSequence: 1,+ lastEventCursor: { generation: "generation-4602", sequence: 1 },} satisfies DaemonOutbound,};}@@ -325,7 +332,7 @@ describe("ENG-4602 snapshot transfer containment", () => {expect(worker.snapshotGenerations.has(activeSessionId)).toBe(false);});- it("quarantines a completed duplicate until exact replacement validation", async () => {+ it("quarantines a completed duplicate until transcript validation", async () => {const supervisor = new DaemonSupervisor("/tmp/eng-4602-supervisor.sock", {defaultSessionConfig: { agentDir: "/tmp", cwd: "/tmp" },descriptorDir: "/tmp/eng-4602-supervisor-state",@@ -368,6 +375,28 @@ describe("ENG-4602 snapshot transfer containment", () => {expect(close).not.toHaveBeenCalled();streamSnapshot.mockClear();+ const refreshedBegin = {+ ...frames.begin,+ snapshot: {+ ...frames.begin.snapshot,+ summary: {+ ...frames.begin.snapshot.summary,+ activity: "working" as const,+ attachedClients: 2,+ },+ },+ };+ internals.handleWorkerFrame(worker, frame(refreshedBegin, "replacement"));+ internals.handleWorkerFrame(worker, frame(frames.chunk, "replacement"));+ internals.handleWorkerFrame(worker, frame(frames.end, "replacement"));+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(worker.snapshotCache.get(activeSessionId)?.snapshot.summary).toMatchObject({+ activity: "working",+ });+ expect(streamSnapshot).toHaveBeenCalledOnce();+ expect(close).not.toHaveBeenCalled();+ streamSnapshot.mockClear();+internals.handleWorkerFrame(worker, frame(frames.begin, "replacement"));internals.handleWorkerFrame(worker,diff --git a/packages/coding-agent/test/suite/serialized-refine-config-integration.test.ts b/packages/coding-agent/test/suite/serialized-refine-config-integration.test.tsnew file mode 100644index 0000000000..17d0d8d781--- /dev/null+++ b/packages/coding-agent/test/suite/serialized-refine-config-integration.test.ts@@ -0,0 +1,306 @@+/**+ * Focused daemon-path integration tests for serializedRefine propagation,+ * heartbeat/message/observe controller availability, and model rehydration.+ *+ * Uses fake model streams only — no real model/sandbox.+ */++import { fauxAssistantMessage } from "@earendil-works/pi-ai";+import { afterEach, describe, expect, it, vi } from "vitest";+import { type AgentSessionRuntimeConfig, mergeAgentSessionRuntimeConfig } from "../../src/core/agent-session-config.js";+import type { AgentRlmHeartbeatController } from "../../src/core/cron-jobs.js";+import { createHarness, type Harness } from "./harness.js";++type SerializedInternals = {+ _serializedRefine: boolean;+ _pendingRequestedRefine: { instructions?: string; global?: boolean } | undefined;+ _assistantTurnsSinceAutoRefine: number;+ _lastAutoRefineReviewAt: number;+ _autoRefineInProgress: boolean;+ _rlmHeartbeatController?: unknown;+ _agentMessageController?: unknown;+ _agentObserveController?: unknown;+ _ipythonKernelProvisioner?: unknown;+ _createKernelHostHandlers(): Record<string, unknown>;+};++describe("Serialized refine config integration (unit)", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("serializedRefine round-trips through mergeAgentSessionRuntimeConfig", () => {+ const base: AgentSessionRuntimeConfig = {+ cwd: "/tmp",+ serializedRefine: true,+ };+ const override: AgentSessionRuntimeConfig = {+ cwd: "/tmp/override",+ };+ const merged = mergeAgentSessionRuntimeConfig(base, override);++ // Override does not set serializedRefine, so base value is preserved.+ expect(merged.serializedRefine).toBe(true);++ // Explicit override takes priority.+ const merged2 = mergeAgentSessionRuntimeConfig(base, { serializedRefine: false });+ expect(merged2.serializedRefine).toBe(false);++ // Clone preserves the flag.+ const cloned = mergeAgentSessionRuntimeConfig(merged, {});+ expect(cloned.serializedRefine).toBe(true);+ });++ it("serializedRefine=true produces a session with _serializedRefine=true", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals;+ expect(internals._serializedRefine).toBe(true);+ });++ it("serializedRefine=false (default) produces a session with _serializedRefine=false", async () => {+ const harness = await createHarness({+ persistSession: true,+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals;+ expect(internals._serializedRefine).toBe(false);+ });++ it("real autonomous loop crosses threshold and resumes with serialized refine", async () => {+ // Uses real agent.prompt() with faux responses to verify the+ // serialized checkpoint fires and the loop continues.+ const reviewer = vi.fn(async () => ({+ shouldRefine: true,+ rationale: "integration",+ instructions: "capture",+ }));+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 2, cooldownMs: 0 } },+ autoRefineReviewer: reviewer,+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals & {+ _planRefine: (opts: { instructions?: string }, signal: AbortSignal) => Promise<unknown>;+ _applyRefine: (plan: unknown, opts: unknown, abort: AbortController) => Promise<unknown>;+ };++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue({+ id: "refine_test",+ summary: "test",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ harnessStatePath: "/tmp/harness_state.json",+ });++ // Turn 1: counter goes to 1 (< threshold 2, no refine)+ harness.setResponses([fauxAssistantMessage("response 1")]);+ await harness.session.prompt("prompt 1");+ expect(internals._assistantTurnsSinceAutoRefine).toBe(1);++ // Turn 2: counter goes to 2 (>= threshold 2, serialized checkpoint fires)+ harness.setResponses([fauxAssistantMessage("response 2")]);+ await harness.session.prompt("prompt 2");++ // After the checkpoint, counter is reset to 0.+ expect(internals._assistantTurnsSinceAutoRefine).toBe(0);++ // Turn 3: counter goes to 1 again (< threshold, loop continues)+ harness.setResponses([fauxAssistantMessage("response 3")]);+ await harness.session.prompt("prompt 3");+ expect(internals._assistantTurnsSinceAutoRefine).toBe(1);++ // Reviewer called exactly once (at turn 2).+ expect(reviewer).toHaveBeenCalledTimes(1);+ });+});++describe("Serialized refine controller availability (unit)", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("setRlmHeartbeatController attaches a heartbeat controller to a session", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals;+ expect(internals._rlmHeartbeatController).toBeUndefined();+ const initialProvisioner = internals._ipythonKernelProvisioner;++ // Simulate print/headless mode attaching a controller after construction.+ const fakeController = {+ listRlmHeartbeats: () => [],+ createRlmHeartbeat: () => ({ id: "test", status: "active" }),+ updateRlmHeartbeat: () => undefined,+ deleteRlmHeartbeat: () => undefined,+ } as unknown as AgentRlmHeartbeatController;+ harness.session.setRlmHeartbeatController(fakeController);++ expect(internals._rlmHeartbeatController).toBe(fakeController);+ expect(internals._ipythonKernelProvisioner).not.toBe(initialProvisioner);+ expect(internals._createKernelHostHandlers()).toHaveProperty("rlm_heartbeat.create");++ // Verify the controller is usable via host request.+ const result = harness.session.handleRlmHeartbeatHostRequest("rlm_heartbeat.list");+ expect(result).toEqual({ heartbeats: [] });+ });++ it("refine.status reports in_flight when background plan is active", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals & {+ _planRefine: (opts: { instructions?: string }, signal: AbortSignal) => Promise<unknown>;+ };++ // Initially not in flight.+ const statusBefore = harness.session.handleRefineHostRequest("refine.status");+ expect(statusBefore.in_flight).toBe(false);++ // Start background planning.+ let resolvePlan: () => void = () => {};+ const planPromise = new Promise<void>((resolve) => {+ resolvePlan = resolve;+ });+ vi.spyOn(internals, "_planRefine").mockImplementation(async () => {+ await planPromise;+ return { id: "p", proposal: { edits: [] } };+ });++ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = true;+ harness.session.handleRefineHostRequest("refine.run", { instructions: "test" });+ (harness.session.agent.state as { isStreaming: boolean }).isStreaming = false;++ // Wait for the plan to start.+ await new Promise<void>((resolve) => setTimeout(resolve, 10));++ const statusDuring = harness.session.handleRefineHostRequest("refine.status");+ expect(statusDuring.in_flight).toBe(true);++ // Release the plan.+ resolvePlan();+ await new Promise<void>((resolve) => setTimeout(resolve, 50));++ // Run the checkpoint to consume the background plan.+ await (+ harness.session as unknown as { _runSerializedRefineCheckpoint: () => Promise<void> }+ )._runSerializedRefineCheckpoint();++ // After the checkpoint, nothing should be in flight.+ const statusAfter = harness.session.handleRefineHostRequest("refine.status");+ expect(statusAfter.in_flight).toBe(false);+ });+});++describe("PR #503 model preservation (unit)", () => {+ const harnesses: Harness[] = [];++ afterEach(() => {+ vi.restoreAllMocks();+ while (harnesses.length > 0) {+ harnesses.pop()?.cleanup();+ }+ });++ it("model is preserved and accessible after session creation", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ });+ harnesses.push(harness);++ // The session should have a model set from the faux provider.+ expect(harness.session.model).toBeDefined();+ expect(harness.session.model?.id).toBe(harness.getModel().id);+ expect(harness.session.model?.provider).toBe(harness.getModel().provider);+ });++ it("model survives a serialized refine checkpoint", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ settings: { autoRefine: { enabled: true, turnInterval: 1, cooldownMs: 0 } },+ autoRefineReviewer: vi.fn(async () => ({+ shouldRefine: true,+ rationale: "test",+ instructions: "test",+ })),+ });+ harnesses.push(harness);++ const internals = harness.session as unknown as SerializedInternals & {+ _planRefine: (opts: { instructions?: string }, signal: AbortSignal) => Promise<unknown>;+ _applyRefine: (plan: unknown, opts: unknown, abort: AbortController) => Promise<unknown>;+ };++ vi.spyOn(internals, "_planRefine").mockResolvedValue({ id: "p", proposal: { edits: [] } });+ vi.spyOn(internals, "_applyRefine").mockResolvedValue({+ id: "refine_test",+ summary: "test",+ rationale: "test",+ expectedOutcome: "test",+ appliedEdits: [],+ harnessStatePath: "/tmp/harness_state.json",+ });++ const modelBefore = harness.session.model;+ internals._assistantTurnsSinceAutoRefine = 1;++ await harness.session.prompt("test");+ // Wait for the checkpoint to complete.+ await new Promise<void>((resolve) => setTimeout(resolve, 100));++ // Model is preserved after the checkpoint.+ expect(harness.session.model).toBe(modelBefore);+ });++ it("model is preserved after clean disposal", async () => {+ const harness = await createHarness({+ persistSession: true,+ serializedRefine: true,+ });+ harnesses.push(harness);++ const modelBefore = harness.session.model;+ expect(modelBefore).toBeDefined();++ await harness.session.disposeAsync();++ // After disposal, the model reference is still accessible (it's on agent.state).+ // The session is disposed but the model object persists.+ expect(modelBefore).toBeDefined();+ });+});diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.tsindex 8792282ee6..7f35a4e716 100644--- a/packages/coding-agent/test/system-prompt.test.ts+++ b/packages/coding-agent/test/system-prompt.test.ts@@ -41,7 +41,7 @@ describe("buildRlmPrompt", () => {const prompt = buildRlmPrompt({cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",- installedSkills: ["websearch"],+ installedSkills: ["websearch", "refine"],activeTools: ["ipython"],allowRecursion: false,});@@ -57,7 +57,7 @@ describe("buildRlmPrompt", () => {`Pre-installed Python packages: ${DEFAULT_RLM_EXTRA_IMPORT_LABELS.join(", ")}.`,"Install additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).","",- "Installed Python skill modules (pre-imported): `websearch`.",+ "Installed Python skill modules (pre-imported): `websearch`, `refine`.","Read each skill's SKILL.md for its API. Inspect a module with `help(<skill>)` or `dir(<skill>)`, then inspect a documented callable with `inspect.signature(<skill>.<function>)`.","Each skill is also available as a shell command by the same name: `<skill> ...`. Discover its CLI usage with `<skill> --help`.","",@@ -81,7 +81,7 @@ describe("buildRlmPrompt", () => {"","RLM-native call contract: installed Python skills are pre-imported modules. Read the matching SKILL.md and call its documented function, such as `await <skill_import>.<function>(...)`; when a CLI exists, use `<skill_import> ...` from shell. Continual harness skill entries are Python REPL skills with an explicit Python `reference` and `arguments` contract. Continual harness subagent entries are reusable delegation specs; invoke them by turning the spec into a concise task prompt and starting `asyncio.create_task(rlm('sub-task'))` by default, then await the task only when its result is needed, or collect independent subagents with `await asyncio.gather(...)`. Use direct `await rlm('sub-task')` only when the result is immediately required. Do not invent non-native wrappers such as `call_skill(...)`, `run_subagent(...)`, or named subagent registries.","",- "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `/refine` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",+ "Treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so continue working normally after calling it. Do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.",].join("\n"),);});@@ -302,7 +302,7 @@ describe("buildSystemPrompt", () => {const prompt = buildSystemPrompt({selectedTools: ["ipython"],contextFiles: [],- skills: [],+ skills: [pythonSkill("refine")],cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",harnessState,@@ -312,7 +312,7 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("Local continual harness entries belong to this Prime Agent session");expect(prompt).toContain("The continual harness entries below are compact summaries, not full descriptions");expect(prompt).toContain("Use global continual harness refinement only for stable cross-session lessons");- expect(prompt).toContain("When to call `/refine`");+ expect(prompt).toContain("When to call `await refine.run()`");expect(prompt).toContain("Call contract: read each installed Python skill's SKILL.md");expect(prompt).toContain("Continual harness skill entries are Python REPL skills");expect(prompt).toContain("Continual harness subagent entries are invoked by composing a concise task prompt");@@ -383,7 +383,7 @@ describe("buildSystemPrompt", () => {const prompt = buildSystemPrompt({selectedTools: ["ipython"],contextFiles: [],- skills: [],+ skills: [pythonSkill("refine")],cwd: "/repo",messagesPath: "/repo/.pi/sessions/session.jsonl",});@@ -453,7 +453,9 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("await <skill_import>.<function>(...)");expect(prompt).toContain("Python `reference` and `arguments` contract");expect(prompt).toContain("await asyncio.gather(rlm('task1'), rlm('task2'))");- expect(prompt).toContain("Use `/refine` to turn repeated delegation patterns into reusable subagent specs");+ expect(prompt).toContain(+ "Use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs",+ );expect(prompt).toContain("repeated procedures into skills");expect(prompt).toContain("durable facts/preferences into memories");expect(prompt).toContain("narrow behavioral policies into prompt addendums");@@ -516,6 +518,7 @@ describe("buildSystemPrompt", () => {expect(prompt).not.toContain("agent_observe.list_agents");expect(prompt).not.toContain("asyncio.create_task");expect(prompt).not.toContain("await <skill_import>");+ expect(prompt).not.toContain("await refine.run()");});test("omits shell guidance from harness state when shell is inactive", () => {@@ -559,6 +562,7 @@ describe("buildSystemPrompt", () => {expect(prompt).not.toContain("<skill_import> ...");expect(prompt).not.toContain("asyncio.create_task");expect(prompt).not.toContain("await <skill_import>");+ expect(prompt).not.toContain("await refine.run()");});test("custom prompt override bypasses the rlm harness body", () => {