Skip to content

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

Rust

backgrounded refinement (#497)

Seth Kartenea035c8a0f7c
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index d26e46c7fe..80f8e0f087 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -11,6 +11,7 @@
- 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.
- 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.
## [0.3.2] - 2026-07-20
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index d0d8b875d4..5ceb5fddba 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -192,6 +192,7 @@ import {
mergeHarnessStates,
mergeRefinementHistory,
planRefinement,
+ type RefinementPlan,
type RefinementResult,
reviewAutoRefine,
saveHarnessState,
@@ -945,8 +946,10 @@ export class AgentSession {
private _autoRefineReviewAbort?: AbortController;
private _refineAbortController?: AbortController;
private readonly _autoRefineReviewer?: AutoRefineReviewer;
- /** Settles (never rejects) when the in-flight refine finishes; see _waitForRefineIdle. */
+ /** 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>;
constructor(config: AgentSessionConfig) {
this.agent = config.agent;
@@ -2963,6 +2966,7 @@ export class AgentSession {
let messages: AgentMessage[] | undefined;
let drainedNextTurnMessages: CustomMessage[] = [];
const previewLabel = injectedMessagePreviewLabel(message);
+ let extensionResult: Awaited<ReturnType<typeof this._extensionRunner.emitBeforeAgentStart>> | undefined;
try {
const shouldQueueForStreaming = this.isStreaming;
const shouldQueueForPendingWork =
@@ -3027,14 +3031,14 @@ export class AgentSession {
this._pendingNextTurnMessages = [];
messages = [...drainedNextTurnMessages, message];
- const result = await this._extensionRunner.emitBeforeAgentStart(
+ extensionResult = await this._extensionRunner.emitBeforeAgentStart(
text,
undefined,
this._baseSystemPrompt,
this._baseSystemPromptOptions,
);
- if (result?.messages) {
- for (const msg of result.messages) {
+ if (extensionResult?.messages) {
+ for (const msg of extensionResult.messages) {
messages.push({
role: "custom",
customType: msg.customType,
@@ -3045,7 +3049,7 @@ export class AgentSession {
});
}
}
- this.agent.state.systemPrompt = result?.systemPrompt ?? this._baseSystemPrompt;
+ this.agent.state.systemPrompt = extensionResult?.systemPrompt ?? this._baseSystemPrompt;
} catch (error) {
reportPreflight(false);
throw error;
@@ -3057,6 +3061,10 @@ 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;
}
const shouldQueueAtHandoff =
options?.queueIfBusy === true &&
@@ -3126,6 +3134,7 @@ export class AgentSession {
let drainedNextTurnMessages: CustomMessage[] = [];
let expandedText = text;
let currentImages = options?.images;
+ let extensionResult: Awaited<ReturnType<typeof this._extensionRunner.emitBeforeAgentStart>> | undefined;
try {
let currentText = text;
@@ -3337,15 +3346,15 @@ export class AgentSession {
}
// Emit before_agent_start extension event
- const result = await this._extensionRunner.emitBeforeAgentStart(
+ extensionResult = await this._extensionRunner.emitBeforeAgentStart(
expandedText,
currentImages,
this._baseSystemPrompt,
this._baseSystemPromptOptions,
);
// Add all custom messages from extensions
- if (result?.messages) {
- for (const msg of result.messages) {
+ if (extensionResult?.messages) {
+ for (const msg of extensionResult.messages) {
messages.push({
role: "custom",
customType: msg.customType,
@@ -3357,8 +3366,8 @@ export class AgentSession {
}
}
// Apply extension-modified system prompt, or reset to base
- if (result?.systemPrompt) {
- this.agent.state.systemPrompt = result.systemPrompt;
+ 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;
@@ -3380,6 +3389,10 @@ 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 (acceptedAgentMessagePrompt?.cleared) {
reportPreflight(false);
@@ -3915,6 +3928,14 @@ export class AgentSession {
if (epoch !== this._pendingMessageResumeEpoch || this.pendingMessageCount === 0) {
return;
}
+ // Re-check adjacent to the handoff: background planning may have
+ // completed and entered _applyRefine during the awaits above,
+ // disconnecting event handling. Wait for it to finish so the
+ // resumed turn's events are not lost.
+ await this._waitForRefineIdle();
+ if (epoch !== this._pendingMessageResumeEpoch || this.pendingMessageCount === 0) {
+ return;
+ }
this._flushPendingBashMessages();
if (this._pendingNextTurnMessages.length > 0) {
await this._drainQueuedMessagesAfterBash();
@@ -4857,6 +4878,9 @@ export class AgentSession {
this._discardPendingAutoRefine({ cancelPostCompactionContinue: true });
this._assistantTurnsSinceAutoRefine = 0;
this._autoRefineBranchVersion++;
+ while (this._refinePlanInFlight) {
+ await this._refinePlanInFlight;
+ }
await this._waitForRefineIdle();
}
@@ -5144,26 +5168,65 @@ export class AgentSession {
/**
* Refine editable continual harness state: prompt notes, memory, skills, and subagent specs.
* The base system prompt is intentionally not editable through this path.
+ *
+ * Planning runs in the background and does NOT block turn entry points
+ * (`_waitForRefineIdle` only waits for `_refineInFlight`). Only the fast
+ * application phase (disk I/O + in-memory mutation) blocks turn entry points.
*/
async refine(
options: { instructions?: string; rollbackId?: string; global?: boolean } = {},
): Promise<RefinementResult> {
- while (this._refineInFlight) {
- await this._refineInFlight;
+ // Wait for any existing refine (both planning and application) before
+ // 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);
}
- const run = this._refine(options);
- // Refine detaches session event handling for its whole LLM pass; expose a
- // settled promise so turn entry points can wait instead of losing events.
- const settled = run.then(
+ const refineAbort = new AbortController();
+ this._refineAbortController = refineAbort;
+
+ // Background planning phase — does NOT block turn entry points.
+ const planRun = this._planRefine(options, refineAbort.signal);
+ const planSettled = planRun.then(
() => undefined,
() => undefined,
);
- this._refineInFlight = settled;
+ this._refinePlanInFlight = planSettled;
+ let plan: RefinementPlan;
try {
- return await run;
+ plan = await planRun;
+ } catch (e) {
+ if (this._refineAbortController === refineAbort) {
+ this._refineAbortController = undefined;
+ }
+ this._schedulePendingMessageResume();
+ throw e;
} finally {
- if (this._refineInFlight === settled) {
+ if (this._refinePlanInFlight === planSettled) {
+ this._refinePlanInFlight = undefined;
+ }
+ }
+
+ // Block new turns before waiting for the current turn to finish. One shared
+ // settled promise covers the full transition and apply critical section.
+ let resolveApplySettled: () => void = () => {};
+ const applySettled = new Promise<void>((resolve) => {
+ resolveApplySettled = resolve;
+ });
+ this._refineInFlight = applySettled;
+ try {
+ // Wait for any agent turn that started during background planning
+ // to finish before entering the application critical section.
+ await this.agent.waitForIdle();
+ if (this._disposed || refineAbort.signal.aborted) {
+ throw new Error("Refinement cancelled because the session was disposed.");
+ }
+ return await this._applyRefine(plan, options, refineAbort);
+ } finally {
+ resolveApplySettled();
+ if (this._refineInFlight === applySettled) {
this._refineInFlight = undefined;
}
this._schedulePendingMessageResume();
@@ -5171,8 +5234,12 @@ export class AgentSession {
}
/**
- * Block a new agent turn until any in-flight refine has reattached event
- * handling; otherwise the turn's messages are never persisted or rendered.
+ * Block a new agent turn until any in-flight refine application phase has
+ * reattached event handling; otherwise the turn's messages are never
+ * persisted or rendered.
+ *
+ * The idle-wait and application phase (`_refineInFlight`) block here. The
+ * background planning phase (`_refinePlanInFlight`) does NOT block turns.
* Refine failures surface to the refine caller, not here.
*/
private async _waitForRefineIdle(): Promise<void> {
@@ -5181,51 +5248,87 @@ export class AgentSession {
}
}
- private async _refine(
- options: { instructions?: string; rollbackId?: string; global?: boolean } = {},
+ /**
+ * 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.
+ */
+ private async _planRefine(
+ options: { instructions?: string; rollbackId?: string; global?: boolean },
+ signal: AbortSignal,
+ ): Promise<RefinementPlan> {
+ if (this._disposed) {
+ throw new Error("Cannot refine a disposed session.");
+ }
+
+ if (!this.model) {
+ throw new Error(formatNoModelSelectedMessage());
+ }
+
+ const model = this.model;
+ const { apiKey, headers } = await this._getRequiredRequestAuth(model);
+ const globalHarnessStateDir = getGlobalHarnessStateDir();
+ const localHarnessStateDir = this._localHarnessStateDir();
+ const requestedScope = options.global ? "global" : "local";
+ if (!options.rollbackId && requestedScope === "local" && !localHarnessStateDir) {
+ throw new Error("Local harness refinement requires a persisted session; use global refinement instead.");
+ }
+ const planningState =
+ requestedScope === "global"
+ ? loadHarnessState(globalHarnessStateDir, "global")
+ : this._loadMergedHarnessState();
+ const history = this._loadRefinementHistory();
+ const rollbackTarget = options.rollbackId ? history.find((item) => item.id === options.rollbackId) : undefined;
+ let baselineScope = rollbackTarget?.scope ?? requestedScope;
+ let baselineHarnessStateDir = baselineScope === "global" ? globalHarnessStateDir : localHarnessStateDir;
+ if (rollbackTarget?.harnessStatePath) {
+ baselineHarnessStateDir = dirname(rollbackTarget.harnessStatePath);
+ baselineScope = resolve(baselineHarnessStateDir) === resolve(globalHarnessStateDir) ? "global" : "local";
+ }
+ if (!baselineHarnessStateDir) {
+ throw new Error("Local harness refinement requires a persisted session; use global refinement instead.");
+ }
+ const baselineState = loadHarnessState(baselineHarnessStateDir, baselineScope);
+ const plan = await planRefinement(
+ this.agent.state.messages,
+ planningState,
+ history,
+ model,
+ apiKey,
+ options,
+ headers,
+ signal,
+ this.thinkingLevel,
+ );
+ if (this._disposed || signal.aborted) {
+ throw new Error("Refinement cancelled because the session was disposed.");
+ }
+ return { ...plan, baselineState };
+ }
+
+ /**
+ * Synchronous application phase: disconnects from the agent, aborts any
+ * in-flight agent run, applies the refinement plan to disk and memory, then
+ * reconnects. This is the only phase that blocks turn entry points.
+ */
+ private async _applyRefine(
+ plan: RefinementPlan,
+ options: { instructions?: string; rollbackId?: string; global?: boolean },
+ refineAbort: AbortController,
): Promise<RefinementResult> {
if (this._disposed) {
throw new Error("Cannot refine a disposed session.");
}
- const refineAbort = new AbortController();
- this._refineAbortController = refineAbort;
+ // The caller has already set _refineInFlight and waited for agent idle.
+ // Disconnect only for the brief apply + save + reconnect critical section.
this._disconnectFromAgent();
try {
- await this.abort();
-
- if (!this.model) {
- throw new Error(formatNoModelSelectedMessage());
- }
-
- const model = this.model;
- const { apiKey, headers } = await this._getRequiredRequestAuth(model);
const globalHarnessStateDir = getGlobalHarnessStateDir();
const localHarnessStateDir = this._localHarnessStateDir();
const requestedScope = options.global ? "global" : "local";
- if (!options.rollbackId && requestedScope === "local" && !localHarnessStateDir) {
- throw new Error("Local harness refinement requires a persisted session; use global refinement instead.");
- }
- const planningState =
- requestedScope === "global"
- ? loadHarnessState(globalHarnessStateDir, "global")
- : this._loadMergedHarnessState();
const history = this._loadRefinementHistory();
const rollbackTarget = options.rollbackId ? history.find((item) => item.id === options.rollbackId) : undefined;
- const plan = await planRefinement(
- this.agent.state.messages,
- planningState,
- history,
- model,
- apiKey,
- options,
- headers,
- refineAbort.signal,
- this.thinkingLevel,
- );
- if (this._disposed || refineAbort.signal.aborted) {
- throw new Error("Refinement cancelled because the session was disposed.");
- }
let targetScope = plan.rollbackScope ?? requestedScope;
let targetHarnessStateDir = targetScope === "global" ? globalHarnessStateDir : localHarnessStateDir;
if (targetScope === "local" && rollbackTarget?.harnessStatePath) {
@@ -5269,6 +5372,7 @@ export class AgentSession {
id: plan.id,
rollbackOf: plan.rollbackOf,
scope: targetScope,
+ baselineState: plan.baselineState,
});
result.harnessStatePath = saveHarnessState(targetHarnessStateDir, state);
if (targetScope === "global") {
diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.ts
index 26714683bf..112cbefc87 100644
--- a/packages/coding-agent/src/core/refinement/refinement.ts
+++ b/packages/coding-agent/src/core/refinement/refinement.ts
@@ -610,7 +610,7 @@ function validateEdit(edit: RefinementEdit, computedId?: string): string | undef
export function applyRefinementProposal(
state: HarnessState,
proposal: RefinementProposal,
- options: { id: string; rollbackOf?: string; scope?: HarnessScope },
+ options: { id: string; rollbackOf?: string; scope?: HarnessScope; baselineState?: HarnessState },
): RefinementResult {
const appliedEdits: AppliedRefinementEdit[] = [];
for (const edit of proposal.edits) {
@@ -624,6 +624,17 @@ export function applyRefinementProposal(
const records = state.entries[edit.kind];
const before = cloneEntry(records[id]);
+ const baseline = cloneEntry(options.baselineState?.entries[edit.kind][id]);
+ if (options.baselineState && JSON.stringify(before) !== JSON.stringify(baseline)) {
+ appliedEdits.push({
+ ...edit,
+ id,
+ before,
+ applied: false,
+ error: "entry changed during refinement planning",
+ });
+ continue;
+ }
if (edit.action === "delete") {
if (!before) {
appliedEdits.push({ ...edit, id, applied: false, error: "entry not found" });
@@ -733,6 +744,8 @@ export interface RefinementPlan {
id: string;
rollbackOf?: string;
rollbackScope?: HarnessScope;
+ /** Target-scope state captured before planning, used to reject conflicting edits at apply time. */
+ baselineState?: HarnessState;
}
/**
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index 7327da314b..63779382cf 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -9540,18 +9540,20 @@ ${interrupt ? `| \`${interrupt}\` | Interrupt current operation |\n` : ""}${shor
: `Refining ${options.global ? "global" : "local"} continual harness state...`,
);
- try {
- const result = await this.agentConnection.refine(options);
- const applied = result.appliedEdits.filter((edit) => edit.applied).length;
- const failed = result.appliedEdits.length - applied;
- const failedSuffix = failed > 0 ? `, ${failed} failed` : "";
- this.showStatus(
- `Refined continual harness state: ${applied} edit${applied === 1 ? "" : "s"} applied${failedSuffix}`,
- );
- this.showStatus(`Harness state: ${result.harnessStatePath}`);
- } catch (error) {
- this.showError(`Refinement failed: ${error instanceof Error ? error.message : String(error)}`);
- }
+ this.agentConnection
+ .refine(options)
+ .then((result) => {
+ const applied = result.appliedEdits.filter((edit) => edit.applied).length;
+ const failed = result.appliedEdits.length - applied;
+ const failedSuffix = failed > 0 ? `, ${failed} failed` : "";
+ this.showStatus(
+ `Refined continual harness state: ${applied} edit${applied === 1 ? "" : "s"} applied${failedSuffix}`,
+ );
+ this.showStatus(`Harness state: ${result.harnessStatePath}`);
+ })
+ .catch((error) => {
+ this.showError(`Refinement failed: ${error instanceof Error ? error.message : String(error)}`);
+ });
}
stop(options: { preserveAltScreen?: boolean } = {}): void {
diff --git a/packages/coding-agent/test/interactive-mode-refine-command.test.ts b/packages/coding-agent/test/interactive-mode-refine-command.test.ts
index 482b58648d..88c2d49c9c 100644
--- a/packages/coding-agent/test/interactive-mode-refine-command.test.ts
+++ b/packages/coding-agent/test/interactive-mode-refine-command.test.ts
@@ -153,4 +153,67 @@ describe("InteractiveMode.handleRefineCommand", () => {
expect(context.showWarning).toHaveBeenCalledWith("Nothing to refine (no trajectory yet)");
expect(context.agentConnection.refine).not.toHaveBeenCalled();
});
+
+ test("shows success status after refine resolves without blocking the caller", async () => {
+ let resolveRefine: ((value: unknown) => void) | undefined;
+ const refinePromise = new Promise((resolve) => {
+ resolveRefine = resolve;
+ });
+ const context = {
+ agentConnection: {
+ getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
+ refine: vi.fn().mockReturnValue(refinePromise),
+ },
+ stopWorkingLoader: vi.fn(),
+ showStatus: vi.fn(),
+ showWarning: vi.fn(),
+ showError: vi.fn(),
+ };
+
+ await handleRefineCommand.call(context, "focus on validation");
+
+ // The "Refining..." status is shown synchronously.
+ expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
+ // The success status is NOT shown yet because refine has not resolved.
+ expect(context.showStatus).not.toHaveBeenCalledWith("Refined continual harness state: 2 edits applied, 1 failed");
+
+ // Resolve the refine promise and let the microtask queue drain.
+ resolveRefine?.({
+ appliedEdits: [{ applied: true }, { applied: true }, { applied: false, error: "entry not found" }],
+ harnessStatePath: "/tmp/harness_state.json",
+ });
+ await vi.waitFor(() => {
+ expect(context.showStatus).toHaveBeenCalledWith("Refined continual harness state: 2 edits applied, 1 failed");
+ });
+ expect(context.showStatus).toHaveBeenCalledWith("Harness state: /tmp/harness_state.json");
+ });
+
+ test("shows error status after refine rejects without blocking the caller", async () => {
+ let rejectRefine: ((error: Error) => void) | undefined;
+ const refinePromise = new Promise<never>((_, reject) => {
+ rejectRefine = reject;
+ });
+ const context = {
+ agentConnection: {
+ getSessionStats: vi.fn().mockResolvedValue({ totalMessages: 2 }),
+ refine: vi.fn().mockReturnValue(refinePromise),
+ },
+ stopWorkingLoader: vi.fn(),
+ showStatus: vi.fn(),
+ showWarning: vi.fn(),
+ showError: vi.fn(),
+ };
+
+ await handleRefineCommand.call(context, "focus on validation");
+
+ // The "Refining..." status is shown synchronously.
+ expect(context.showStatus).toHaveBeenCalledWith("Refining local continual harness state...");
+ // The error is NOT shown yet because refine has not rejected.
+ expect(context.showError).not.toHaveBeenCalled();
+
+ rejectRefine?.(new Error("LLM timed out"));
+ await vi.waitFor(() => {
+ expect(context.showError).toHaveBeenCalledWith("Refinement failed: LLM timed out");
+ });
+ });
});
diff --git a/packages/coding-agent/test/refinement.test.ts b/packages/coding-agent/test/refinement.test.ts
index fcb3304790..d29caca63e 100644
--- a/packages/coding-agent/test/refinement.test.ts
+++ b/packages/coding-agent/test/refinement.test.ts
@@ -138,6 +138,35 @@ function seedEntry(state: HarnessState, kind: RefinementKind, id = `${kind}_entr
}
describe("harness refinement", () => {
+ it("rejects an edit when the target entry changed after planning", () => {
+ const harnessStateDir = makeTempDir();
+ const baselineState = loadHarnessState(harnessStateDir);
+ seedEntry(baselineState, "memory");
+ saveHarnessState(harnessStateDir, baselineState);
+ const currentState = loadHarnessState(harnessStateDir);
+ currentState.entries.memory.memory_entry.content = "concurrent kernel content";
+ currentState.entries.memory.memory_entry.version++;
+
+ const result = applyRefinementProposal(
+ currentState,
+ proposal("Update memory", [
+ {
+ action: "update",
+ kind: "memory",
+ id: "memory_entry",
+ title: "Planned title",
+ content: "stale planned content",
+ },
+ ]),
+ { id: "refine_conflict", baselineState },
+ );
+
+ expect(result.appliedEdits).toMatchObject([
+ { applied: false, error: "entry changed during refinement planning" },
+ ]);
+ expect(currentState.entries.memory.memory_entry.content).toBe("concurrent kernel content");
+ });
+
it("applies create, update, and delete for every editable harness kind", () => {
const state = loadHarnessState(makeTempDir());
diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
index c7dcb02001..05e9dc1ba8 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -342,6 +342,41 @@ stale extension instructions`,
expect(providerSystemPrompts[1]).not.toContain("stale extension instructions");
});
+ it("preserves an extension system prompt across a refine handoff wait", async () => {
+ let sessionInternals: { _refineInFlight?: Promise<void> };
+ const harness = await createHarness({
+ systemPrompt: "base prompt",
+ extensionFactories: [
+ (pi) => {
+ pi.on("before_agent_start", async (event) => {
+ let releaseRefine: (() => void) | undefined;
+ sessionInternals._refineInFlight = new Promise<void>((resolve) => {
+ releaseRefine = resolve;
+ });
+ setTimeout(() => {
+ sessionInternals._refineInFlight = undefined;
+ releaseRefine?.();
+ }, 0);
+ return { systemPrompt: `${event.systemPrompt}\n\nextension instructions` };
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ sessionInternals = harness.session as unknown as { _refineInFlight?: Promise<void> };
+ let providerSystemPrompt = "";
+ harness.setResponses([
+ (context) => {
+ providerSystemPrompt = context.systemPrompt ?? "";
+ return fauxAssistantMessage("done");
+ },
+ ]);
+
+ await harness.session.prompt("normal prompt");
+
+ expect(providerSystemPrompt).toContain("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.ts
index efe0561d15..ed98401c65 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -1199,9 +1199,11 @@ describe("AgentSession queue characterization", () => {
const promptPromise = harness.session.prompt("hello during refine");
await new Promise((resolve) => setTimeout(resolve, 10));
- // The prompt must wait for the refine (its response is still queued);
- // running now would drop its events while the session is detached.
- expect(harness.getPendingResponseCount()).toBe(1);
+ // 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
+ // the agent to be idle before disconnecting and applying.
+ expect(harness.getPendingResponseCount()).toBe(0);
releasePlan?.();
await refinePromise;
@@ -1225,6 +1227,87 @@ describe("AgentSession queue characterization", () => {
}
});
+ it("preserves a same-entry harness write made during background planning", async () => {
+ const harness = await createAutoRefineHarness();
+ harnesses.push(harness);
+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = `${harness.tempDir}/agent`;
+ try {
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir())!;
+ const initialState = loadHarnessState(localDir, "local");
+ applyRefinementProposal(
+ initialState,
+ {
+ summary: "Seed memory",
+ rationale: "seed",
+ expectedOutcome: "seeded",
+ edits: [
+ {
+ action: "create",
+ kind: "memory",
+ id: "shared",
+ title: "Shared",
+ content: "planning baseline",
+ },
+ ],
+ },
+ { id: "seed_shared", scope: "local" },
+ );
+ saveHarnessState(localDir, initialState);
+
+ let releasePlan: (() => void) | undefined;
+ const planGate = new Promise<void>((resolve) => {
+ releasePlan = resolve;
+ });
+ let planStarted: (() => void) | undefined;
+ const planStartedPromise = new Promise<void>((resolve) => {
+ planStarted = resolve;
+ });
+ harness.setResponses([
+ async () => {
+ planStarted?.();
+ await planGate;
+ return fauxAssistantMessage(
+ JSON.stringify({
+ summary: "Update shared memory",
+ rationale: "planned update",
+ expectedOutcome: "updated",
+ edits: [
+ {
+ action: "update",
+ kind: "memory",
+ id: "shared",
+ title: "Shared",
+ content: "stale planned content",
+ },
+ ],
+ }),
+ );
+ },
+ ]);
+
+ const refinePromise = harness.session.refine({ instructions: "update shared memory" });
+ await planStartedPromise;
+ const concurrentState = loadHarnessState(localDir, "local");
+ concurrentState.entries.memory.shared.content = "concurrent kernel content";
+ concurrentState.entries.memory.shared.version++;
+ saveHarnessState(localDir, concurrentState);
+ releasePlan?.();
+
+ const result = await refinePromise;
+ expect(result.appliedEdits).toMatchObject([
+ { applied: false, error: "entry changed during refinement planning" },
+ ]);
+ expect(loadHarnessState(localDir, "local").entries.memory.shared.content).toBe("concurrent kernel content");
+ } finally {
+ if (previousAgentDir === undefined) {
+ delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ } else {
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ }
+ }
+ });
+
it("rolls back a local refinement in a non-persisted session via the recorded state path", async () => {
const harness = await createHarness();
harnesses.push(harness);