Skip to content

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

Rust

Static system prompt across refinements; harness state moves in-context (RES-1318) (#2098)

Sebastian Müller71766abb2c1e
diff --git a/packages/coding-agent/.changes/res-1318-refinement-cache-visibility.md b/packages/coding-agent/.changes/res-1318-refinement-cache-visibility.md
new file mode 100644
index 0000000000..a28d0420c7
--- /dev/null
+++ b/packages/coding-agent/.changes/res-1318-refinement-cache-visibility.md
@@ -0,0 +1 @@
+- Changed refinement delivery to preserve the provider prefix cache: applying a refinement no longer rebuilds or swaps the system prompt. Applied edits now reach the model as a durable in-context `[auto-refinement]`/`[user-refinement]`/`[self-refinement]` notice at the apply boundary (zero-applied-edit refinements emit nothing, and the notice never starts a turn), and the harness digest moved from the system prompt to cold context boundaries: fresh sessions start with a digest message, post-compaction head messages render the digest before the summary on both compaction paths, and resumes append a fresh digest only when it no longer matches disk state.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index b6c93aa521..90733d4d72 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -175,16 +175,21 @@ import {
convertToLlm,
createAsyncBashCompletionMessage,
createCompactionOutcomeMessage,
+ createHarnessDigestMessage,
createHeartbeatPromptMessage,
+ createRefinementNoticeMessage,
createRefinementOutcomeMessage,
createRlmChildFailureMessage,
createRlmChildTerminalNoticeMessage,
createSessionSlashCommandMessage,
createSessionSlashCommandResultMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
+ type HarnessDigestDetails,
HEARTBEAT_PROMPT_CUSTOM_TYPE,
HEARTBEAT_PROMPT_PREVIEW_LABEL,
IPYTHON_STATE_RESTORED_CUSTOM_TYPE,
isSessionSlashCommandMessage,
+ type RefinementSource,
RLM_CHILD_FAILURE_CUSTOM_TYPE,
RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE,
} from "./messages.js";
@@ -205,6 +210,7 @@ import {
type AutoRefineReview,
appendGlobalRefinement,
applyRefinementProposal,
+ formatHarnessStateForPrompt,
generateRefinementId,
getGlobalHarnessStateDir,
getLocalHarnessStateDir,
@@ -525,6 +531,7 @@ export type SerializedBackgroundPlanResult =
options: { instructions?: string; rollbackId?: string; global?: boolean };
abort: AbortController;
branchVersion: number;
+ source: Exclude<RefinementSource, "user">;
}
| { status: "skip"; explicit?: boolean }
| { status: "invalidated"; branchVersion: number }
@@ -1185,6 +1192,8 @@ export class AgentSession {
private _lateIpythonSentAgentMessages = new Map<string, KernelSentAgentMessage[]>();
/** Outcome disclosures whose session-file append failed; retained for context rebuilds. */
private readonly _unpersistedOutcomes: CustomMessage[] = [];
+ /** Fresh/empty contexts defer digest injection to the first committed turn so untouched sessions stay empty. */
+ private _harnessDigestPending = false;
private _bashAbortControllers = new Set<AbortController>();
private _userBashRunning = false;
@@ -1397,6 +1406,7 @@ export class AgentSession {
activeToolNames: this._initialActiveToolNames,
includeAllExtensionTools: true,
});
+ this._ensureHarnessDigestContext();
}
/** Refreshes MCP provider registrations without rebuilding the session runtime. */
@@ -1866,10 +1876,21 @@ export class AgentSession {
(record): record is DeliveryRecord & { message: CustomMessage } =>
(record.role === "next_turn" || (payload.acceptedAgentMessage && record.role === "prefix")) &&
record.message.role === "custom" &&
+ record.message.customType !== HARNESS_DIGEST_CUSTOM_TYPE &&
!record.durable,
)
.map((record) => cloneCustomMessage(record.message));
restorableMessages.push(...restorable);
+ // Lazy injection owns digest delivery: a cancelled turn re-arms it
+ // instead of restoring a possibly stale digest message.
+ if (
+ payload.records.some(
+ (record) =>
+ record.message.role === "custom" && record.message.customType === HARNESS_DIGEST_CUSTOM_TYPE,
+ )
+ ) {
+ this._harnessDigestPending = true;
+ }
if (dispatched) {
payload.captureRunMessages = new Set(payload.records.map((record) => record.message));
this.agent.state.messages = this.agent.state.messages.filter(
@@ -2480,7 +2501,7 @@ export class AgentSession {
if (pending) {
this._pendingRequestedRefine = undefined;
try {
- await this._runSerializedRefine(pending);
+ await this._runSerializedRefine(pending, "self");
} catch (error) {
this._emitRefineFailed(error);
}
@@ -2626,7 +2647,7 @@ export class AgentSession {
});
this._refineInFlight = applySettled;
try {
- await this._applyRefine(bgResult.plan, bgResult.options, bgResult.abort);
+ await this._applyRefine(bgResult.plan, bgResult.options, bgResult.abort, bgResult.source);
} finally {
resolveApplySettled();
if (this._refineInFlight === applySettled) {
@@ -2739,6 +2760,7 @@ export class AgentSession {
options: planOptions,
abort: refineAbort,
branchVersion,
+ source: skipReview ? "self" : "auto",
};
} catch (error) {
if (this._disposed || this._disposing || branchVersion !== this._autoRefineBranchVersion) {
@@ -2773,7 +2795,7 @@ export class AgentSession {
rollbackId?: string;
global?: boolean;
},
- trigger: "manual" | "auto" = "manual",
+ source: Exclude<RefinementSource, "user">,
): Promise<void> {
if (this._disposed || this._disposing) {
return;
@@ -2798,7 +2820,7 @@ export class AgentSession {
const refineAbort = new AbortController();
this._refineAbortController = refineAbort;
- const planRun = this._planRefine(options, refineAbort.signal, trigger);
+ const planRun = this._planRefine(options, refineAbort.signal, source === "auto" ? "auto" : "manual");
const planSettled = planRun.then(
() => undefined,
() => undefined,
@@ -2835,7 +2857,7 @@ export class AgentSession {
});
this._refineInFlight = applySettled;
try {
- await this._applyRefine(plan, options, refineAbort);
+ await this._applyRefine(plan, options, refineAbort, source);
} finally {
resolveApplySettled();
if (this._refineInFlight === applySettled) {
@@ -3189,7 +3211,7 @@ export class AgentSession {
}
return {
scheduled: true,
- note: "Refinement runs when the current turn ends; the harness rebuilds the system prompt and resumes you automatically. Continue working normally.",
+ note: "Refinement runs when the current turn ends; applied edits are appended to your context as a refinement notice and you resume automatically. Continue working normally.",
};
}
default:
@@ -4088,7 +4110,7 @@ export class AgentSession {
const pending = this._pendingRequestedRefine;
this._pendingRequestedRefine = undefined;
try {
- await this._runSerializedRefine(pending);
+ await this._runSerializedRefine(pending, "self");
} catch {
// Best-effort drain; refinement errors must not block disposal.
}
@@ -4508,7 +4530,6 @@ export class AgentSession {
allowRecursion: this._rlmDepth < this._rlmMaxDepth,
rlmDepth: this._rlmDepth,
rlmParentAgent: this._rlmParentAgent,
- harnessState: this._loadMergedHarnessState(),
genericMcpServers: this._mcpManager?.getEnabledPersistentGenericServers(),
};
return buildSystemPrompt(this._baseSystemPromptOptions);
@@ -6092,8 +6113,14 @@ export class AgentSession {
const firstTurn = activeTurns()[0];
if (!firstTurn) return;
const executionPolicy = firstTurn.payload.executionPolicy;
+ // The digest is never parked as pending context; lazy injection re-arms instead.
+ const parkNextTurnMessages = (messages: CustomMessage[]) => {
+ const parked = messages.filter((message) => message.customType !== HARNESS_DIGEST_CUSTOM_TYPE);
+ if (parked.length !== messages.length) this._harnessDigestPending = true;
+ this._pendingNextTurnMessages.unshift(...parked);
+ };
const restoreNextTurnContext = () => {
- this._pendingNextTurnMessages.unshift(...nextTurnMessages);
+ parkNextTurnMessages(nextTurnMessages);
nextTurnMessages = [];
};
try {
@@ -6159,6 +6186,15 @@ export class AgentSession {
if (executionPolicy.nextTurnContextTiming === "commit") {
nextTurnMessages = this._takePendingNextTurnMessages();
}
+ if (this._harnessDigestPending) {
+ // The first-turn digest rides the turn's delivery records so a
+ // cancelled first turn strips it with the rest of the turn.
+ this._harnessDigestPending = false;
+ const digest = this._harnessDigest();
+ if (this._latestContextHarnessDigest() !== digest) {
+ nextTurnMessages = [createHarnessDigestMessage(digest), ...nextTurnMessages];
+ }
+ }
const contextRecords = nextTurnMessages.map((message) =>
this._createDeliveryRecord(turns[0].id, "next_turn", message),
);
@@ -6204,7 +6240,7 @@ export class AgentSession {
this._forgetConsumedPostCompactionContinuations(turns.map((action) => primaryDeliveryRecord(action).message));
} catch (error) {
const delivered = new Set(this.agent.state.messages);
- this._pendingNextTurnMessages.unshift(...nextTurnMessages.filter((message) => !delivered.has(message)));
+ parkNextTurnMessages(nextTurnMessages.filter((message) => !delivered.has(message)));
for (const action of actions) {
if (action.payload.kind === "turn") {
action.payload.records = action.payload.records.filter((record) => record.role !== "next_turn");
@@ -7726,6 +7762,7 @@ export class AgentSession {
this._semanticEdges.finishRequest(requestId);
}
this._semanticEdges.finishCompaction(semanticCompaction.compactionId, "completed");
+ // Attached mechanically; the digest never flows through the summarizer LLM.
this.sessionManager.appendCompaction(
summary,
firstKeptEntryId,
@@ -7734,6 +7771,7 @@ export class AgentSession {
fromExtension,
customInstructions,
usage,
+ this._harnessDigest(),
);
} catch (error) {
compactionSettled = true;
@@ -7857,7 +7895,7 @@ export class AgentSession {
const pending = this._pendingRequestedRefine;
if (!pending) return false;
this._pendingRequestedRefine = undefined;
- void this.refine(pending).catch((error) => this._emitRefineFailed(error));
+ void this.refine(pending, { source: "self" }).catch((error) => this._emitRefineFailed(error));
return true;
}
@@ -8233,6 +8271,65 @@ export class AgentSession {
);
}
+ /** The compact harness digest delivered at cold context boundaries (session start, resume, compaction head). */
+ private _harnessDigest(): string {
+ const tools = this.getActiveToolNames();
+ const hasIpython = tools.includes("ipython");
+ const visibleSkills = this._modelVisibleSkills().filter((skill) => !skill.disableModelInvocation);
+ const hasRefineSkill = visibleSkills.some((skill) => skill.name === REFINE_SKILL_NAME);
+ return formatHarnessStateForPrompt(this._loadMergedHarnessState(), {
+ includeIpythonExamples: hasIpython,
+ includeShellExamples: tools.includes("bash"),
+ includeRefineExamples: hasIpython && hasRefineSkill,
+ });
+ }
+
+ /** Cold-boundary digest delivery: empty contexts defer to the first committed turn (untouched sessions must stay empty); non-empty contexts append only when the newest in-context digest mismatches disk. */
+ private _ensureHarnessDigestContext(): void {
+ if (this.agent.state.messages.length === 0) {
+ this._harnessDigestPending = true;
+ return;
+ }
+ this._harnessDigestPending = false;
+ this._appendHarnessDigestIfStale();
+ }
+
+ private _appendHarnessDigestIfStale(): void {
+ const digest = this._harnessDigest();
+ if (this._latestContextHarnessDigest() === digest) return;
+ const message = createHarnessDigestMessage(digest);
+ try {
+ this.sessionManager.appendCustomMessageEntryWithRollback(
+ message.customType,
+ message.content,
+ message.display,
+ message.details,
+ );
+ } catch {
+ // Unpersisted session: context-only injection.
+ }
+ this.agent.state.messages.push(message);
+ }
+
+ private _latestContextHarnessDigest(): string | undefined {
+ // Retained pre-compaction messages follow the compaction head, so recency is by timestamp, not position.
+ let latest: { timestamp: number; digest: string } | undefined;
+ for (const message of this.agent.state.messages) {
+ let digest: string | undefined;
+ if (message.role === "custom" && message.customType === HARNESS_DIGEST_CUSTOM_TYPE) {
+ digest = (message.details as HarnessDigestDetails | undefined)?.digest;
+ } else if (message.role === "compactionSummary") {
+ digest = message.harnessDigest;
+ } else {
+ continue;
+ }
+ if (digest !== undefined && (!latest || message.timestamp >= latest.timestamp)) {
+ latest = { timestamp: message.timestamp, digest };
+ }
+ }
+ return latest?.digest;
+ }
+
/** Global harness state overlaid with this session's local state, when persisted. */
private _loadMergedHarnessState(): HarnessState {
const localHarnessStateDir = this._localHarnessStateDir();
@@ -8263,7 +8360,7 @@ export class AgentSession {
rollbackId?: string;
global?: boolean;
} = {},
- internal: { skipAbort?: boolean; trigger?: "manual" | "auto" } = {},
+ internal: { skipAbort?: boolean; trigger?: "manual" | "auto"; source?: RefinementSource } = {},
): Promise<RefinementResult> {
// Queued /refine executes from the session-input pump between turns;
// refine never aborts the agent (planning is backgrounded and the apply
@@ -8356,7 +8453,12 @@ export class AgentSession {
if (this._disposed || refineAbort.signal.aborted) {
throw new Error("Refinement cancelled because the session was disposed.");
}
- return await this._applyRefine(plan, options, refineAbort);
+ return await this._applyRefine(
+ plan,
+ options,
+ refineAbort,
+ internal.source ?? (internal.trigger === "auto" ? "auto" : "user"),
+ );
} finally {
resolveApplySettled();
if (this._refineInFlight === applySettled) {
@@ -8477,7 +8579,16 @@ export class AgentSession {
}
private _recordRefinementOutcome(result: RefinementResult): void {
- const message = createRefinementOutcomeMessage(result);
+ this._appendDurableRefineMessage(createRefinementOutcomeMessage(result));
+ }
+
+ /** In-context notice for an applied refinement. Refinements with zero applied edits emit nothing. */
+ private _recordRefinementNotice(result: RefinementResult, source: RefinementSource): void {
+ if (!result.appliedEdits.some((edit) => edit.applied)) return;
+ this._appendDurableRefineMessage(createRefinementNoticeMessage(result, source));
+ }
+
+ private _appendDurableRefineMessage(message: CustomMessage): void {
try {
this.sessionManager.appendCustomMessageEntryWithRollback(
message.customType,
@@ -8503,6 +8614,7 @@ export class AgentSession {
plan: RefinementPlan,
options: { instructions?: string; rollbackId?: string; global?: boolean },
refineAbort: AbortController,
+ source: RefinementSource,
): Promise<RefinementResult> {
if (this._disposed) {
throw new Error("Cannot refine a disposed session.");
@@ -8578,8 +8690,8 @@ export class AgentSession {
if (!refinementAuditAppendError) throw error;
}
if (refinementAuditAppendError) throw refinementAuditAppendError.error;
- this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
- this.agent.state.systemPrompt = this._baseSystemPrompt;
+ // The prompt stays byte-identical so the provider prefix cache survives; the notice carries the change.
+ this._recordRefinementNotice(result, source);
try {
this._emit({ type: "refine_complete", result });
} catch {
@@ -12031,6 +12143,8 @@ export class AgentSession {
this.agent.state.messages = sessionContext.messages;
this._mergeUnpersistedOutcomes(this.agent.state.messages);
this._restoreLateIpythonSentAgentMessages();
+ // Context rebuild = cold boundary: refresh the digest like resume.
+ this._ensureHarnessDigestContext();
this._reloadGoalStateFromBranch();
this._reloadRlmMaxDepthFromBranch();
this._invalidateQueuedPromptPreparation();
diff --git a/packages/coding-agent/src/core/compaction/branch-summarization.ts b/packages/coding-agent/src/core/compaction/branch-summarization.ts
index d6a5df0315..4088a9a4c2 100644
--- a/packages/coding-agent/src/core/compaction/branch-summarization.ts
+++ b/packages/coding-agent/src/core/compaction/branch-summarization.ts
@@ -13,6 +13,7 @@ import {
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
} from "../messages.js";
import { completeWithProviderRetry, type ProviderRetryPolicy } from "../provider-retry.js";
import type { ReadonlySessionManager, SessionEntry } from "../session-manager.js";
@@ -130,6 +131,8 @@ function getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {
return entry.message;
case "custom_message":
+ // Harness digests are regenerated at cold boundaries; never summarizer input.
+ if (entry.customType === HARNESS_DIGEST_CUSTOM_TYPE) return undefined;
return createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp);
case "branch_summary":
diff --git a/packages/coding-agent/src/core/compaction/compaction.ts b/packages/coding-agent/src/core/compaction/compaction.ts
index a85d0b65e2..1dd8bd0f3c 100644
--- a/packages/coding-agent/src/core/compaction/compaction.ts
+++ b/packages/coding-agent/src/core/compaction/compaction.ts
@@ -13,6 +13,7 @@ import {
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
} from "../messages.js";
import { completeWithProviderRetry, type ProviderRetryPolicy } from "../provider-retry.js";
import { buildSessionContext, type CompactionEntry, type SessionEntry } from "../session-manager.js";
@@ -95,6 +96,10 @@ function getMessageFromEntryForCompaction(entry: SessionEntry): AgentMessage | u
if (entry.type === "compaction") {
return undefined;
}
+ // Harness digests are regenerated on the new compaction head; never summarizer input.
+ if (entry.type === "custom_message" && entry.customType === HARNESS_DIGEST_CUSTOM_TYPE) {
+ return undefined;
+ }
return getMessageFromEntry(entry);
}
diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.ts
index b1f470b56f..8ca3a2a92b 100644
--- a/packages/coding-agent/src/core/messages.ts
+++ b/packages/coding-agent/src/core/messages.ts
@@ -8,7 +8,12 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";
import type { ImageContent, Message, TextContent } from "@earendil-works/pi-ai";
import type { AgentCronJob } from "./cron-jobs.js";
-import type { AppliedRefinementEdit, HarnessScope, RefinementResult } from "./refinement/refinement.js";
+import {
+ type AppliedRefinementEdit,
+ formatRefinementNoticeBody,
+ type HarnessScope,
+ type RefinementResult,
+} from "./refinement/refinement.js";
import { isSessionSlashCommandName, parseSessionSlashCommand, type SessionSlashCommand } from "./slash-commands.js";
export const COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:
@@ -33,6 +38,8 @@ export const SESSION_SLASH_COMMAND_CUSTOM_TYPE = "session_slash_command";
export const SESSION_SLASH_COMMAND_RESULT_CUSTOM_TYPE = "session_slash_command_result";
export const COMPACTION_OUTCOME_CUSTOM_TYPE = "compaction_outcome";
export const REFINEMENT_OUTCOME_CUSTOM_TYPE = "refinement_outcome";
+export const REFINEMENT_NOTICE_CUSTOM_TYPE = "refinement_notice";
+export const HARNESS_DIGEST_CUSTOM_TYPE = "harness_digest";
export const RLM_CHILD_FAILURE_CUSTOM_TYPE = "rlm_child_failure";
export const RLM_CHILD_TERMINAL_NOTICE_CUSTOM_TYPE = "rlm_child_terminal_notice";
export const ASYNC_BASH_COMPLETION_CUSTOM_TYPE = "async_bash_completion";
@@ -91,6 +98,45 @@ export interface RefinementOutcomeMessage extends CustomMessage<RefinementOutcom
details: RefinementOutcomeDetails;
}
+/** How a refinement was initiated: reviewer-triggered auto-refine, the /refine slash command, or the model's own refine.run(). */
+export type RefinementSource = "auto" | "user" | "self";
+
+export interface RefinementNoticeDetails extends RefinementOutcomeDetails {
+ source: RefinementSource;
+}
+
+export interface RefinementNoticeMessage extends CustomMessage<RefinementNoticeDetails> {
+ customType: typeof REFINEMENT_NOTICE_CUSTOM_TYPE;
+ content: string;
+ details: RefinementNoticeDetails;
+}
+
+export interface HarnessDigestDetails {
+ digest: string;
+}
+
+export const HARNESS_DIGEST_PREFIX = `The persistent memories produced across this session so far:
+
+<harness_state>
+`;
+
+export const HARNESS_DIGEST_SUFFIX = `
+</harness_state>`;
+
+export function createHarnessDigestMessage(
+ digest: string,
+ timestamp = Date.now(),
+): CustomMessage<HarnessDigestDetails> {
+ return {
+ role: "custom",
+ customType: HARNESS_DIGEST_CUSTOM_TYPE,
+ content: HARNESS_DIGEST_PREFIX + digest + HARNESS_DIGEST_SUFFIX,
+ display: false,
+ details: { digest },
+ timestamp,
+ };
+}
+
export interface RlmChildFailureDetails {
childId: string;
sessionName: string;
@@ -230,6 +276,8 @@ export interface CompactionSummaryMessage {
retainedMessageCount?: number;
/** User instructions that guided the summary (from `/compact <instructions>`) */
customInstructions?: string;
+ /** Harness digest snapshot rendered before the summary in LLM context. Attached mechanically at compaction, never summarized. */
+ harnessDigest?: string;
timestamp: number;
}
@@ -295,6 +343,7 @@ export function createCompactionSummaryMessage(
timestamp: string,
customInstructions?: string,
retainedMessageCount?: number,
+ harnessDigest?: string,
): CompactionSummaryMessage {
return {
role: "compactionSummary",
@@ -302,6 +351,7 @@ export function createCompactionSummaryMessage(
tokensBefore,
retainedMessageCount,
customInstructions,
+ harnessDigest,
timestamp: new Date(timestamp).getTime(),
};
}
@@ -393,6 +443,29 @@ export function createRefinementOutcomeMessage(
};
}
+/** Model-facing refinement notice: passes convertToLlm (unlike the refinement_outcome audit entry); display false because the TUI renders the outcome message. */
+export function createRefinementNoticeMessage(
+ result: RefinementResult,
+ source: RefinementSource,
+ timestamp = Date.now(),
+): RefinementNoticeMessage {
+ return {
+ role: "custom",
+ customType: REFINEMENT_NOTICE_CUSTOM_TYPE,
+ content: `[${source}-refinement]\n\n${formatRefinementNoticeBody(result)}`,
+ display: false,
+ details: {
+ refinementId: result.id,
+ summary: result.summary,
+ scope: result.scope ?? "local",
+ ...(result.rollbackOf ? { rollbackOf: result.rollbackOf } : {}),
+ edits: result.appliedEdits,
+ source,
+ },
+ timestamp,
+ };
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
@@ -551,14 +624,21 @@ export function convertToLlm(messages: AgentMessage[]): Message[] {
content: [{ type: "text" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],
timestamp: m.timestamp,
};
- case "compactionSummary":
+ case "compactionSummary": {
+ const digestBlock = m.harnessDigest
+ ? `${HARNESS_DIGEST_PREFIX}${m.harnessDigest}${HARNESS_DIGEST_SUFFIX}\n\n`
+ : "";
return {
role: "user",
content: [
- { type: "text" as const, text: COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX },
+ {
+ type: "text" as const,
+ text: digestBlock + COMPACTION_SUMMARY_PREFIX + m.summary + COMPACTION_SUMMARY_SUFFIX,
+ },
],
timestamp: m.timestamp,
};
+ }
case "user":
case "assistant":
case "toolResult":
diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.ts
index 1c6b2081a3..5242819411 100644
--- a/packages/coding-agent/src/core/refinement/refinement.ts
+++ b/packages/coding-agent/src/core/refinement/refinement.ts
@@ -412,6 +412,23 @@ function compactText(text: string, maxLength: number): string {
return `${normalized.slice(0, Math.max(0, maxLength - 3))}...`;
}
+/** Notice body in digest notation: trigger line plus applied edits as `action kind [scope:id] title: content`; rollbacks print via their rollback summaries. */
+export function formatRefinementNoticeBody(result: RefinementResult): string {
+ const lines = [compactText(result.summary, DEFAULT_OVERVIEW_CONTENT_LIMIT)];
+ for (const edit of result.appliedEdits) {
+ if (!edit.applied) continue;
+ const entry = edit.after ?? edit.before;
+ const scope = entry?.scope ?? result.scope ?? "local";
+ lines.push(
+ `- ${edit.action} ${edit.kind} [${scope}:${edit.id}] ${entry?.title ?? edit.id}: ${compactText(
+ entry?.content ?? "",
+ DEFAULT_OVERVIEW_CONTENT_LIMIT,
+ )}`,
+ );
+ }
+ return lines.join("\n");
+}
+
export function formatHarnessStateForPrompt(
state: HarnessState,
options: {
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 6a10997311..dc7b593072 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -128,6 +128,8 @@ export interface CompactionEntry<T = unknown> extends SessionEntryBase {
fromHook?: boolean;
customInstructions?: string;
usage?: Usage;
+ /** Harness digest snapshot taken at compaction time; rendered before the summary in LLM context. */
+ harnessDigest?: string;
}
export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {
@@ -513,6 +515,7 @@ export function buildSessionContext(
compaction.timestamp,
compaction.customInstructions,
retainedMessages.length,
+ compaction.harnessDigest,
),
...retainedMessages,
);
@@ -1753,6 +1756,7 @@ export class SessionManager {
fromHook?: boolean,
customInstructions?: string,
usage?: Usage,
+ harnessDigest?: string,
): string {
const entry: CompactionEntry<T> = {
type: "compaction",
@@ -1766,6 +1770,7 @@ export class SessionManager {
fromHook,
customInstructions,
usage,
+ harnessDigest,
};
this._appendEntry(entry);
return entry.id;
diff --git a/packages/coding-agent/src/core/system-prompt.ts b/packages/coding-agent/src/core/system-prompt.ts
index a4cc0ec236..474a2c619b 100644
--- a/packages/coding-agent/src/core/system-prompt.ts
+++ b/packages/coding-agent/src/core/system-prompt.ts
@@ -3,7 +3,7 @@
*/
import { buildChildAgentDoctrine, buildRlmPrompt, buildSubagentGuidance } from "./prompts/index.js";
-import { formatHarnessStateForPrompt, type HarnessState, REFINE_SKILL_NAME } from "./refinement/index.js";
+import { REFINE_SKILL_NAME } from "./refinement/index.js";
import { formatSkillsForPrompt, getPythonSkillRuntimeInfo, type Skill } from "./skills.js";
export interface BuildSystemPromptOptions {
@@ -31,8 +31,6 @@ export interface BuildSystemPromptOptions {
rlmDepth?: number;
/** Human-readable parent name or id for child communication doctrine. */
rlmParentAgent?: string;
- /** Global harness state to inject as compact persistent context. */
- harnessState?: HarnessState;
/** Enabled user-configured servers available through the generic kernel MCP API. */
genericMcpServers?: string[];
}
@@ -49,7 +47,6 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
contextFiles: providedContextFiles,
skills: providedSkills,
allowRecursion,
- harnessState,
} = options;
const promptCwd = cwd.replace(/\\/g, "/");
const promptMessagesPath = (messagesPath ?? "not persisted").replace(/\\/g, "/");
@@ -66,7 +63,6 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
const skills = providedSkills ?? [];
const tools = selectedTools ?? ["ipython"];
const hasIpython = tools.includes("ipython");
- const hasBash = tools.includes("bash");
const visibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
const visiblePythonSkillImportNames = getPythonSkillRuntimeInfo(visibleSkills).map((skill) => skill.importName);
const hasRefineSkill = visibleSkills.some((skill) => skill.name === REFINE_SKILL_NAME);
@@ -105,10 +101,6 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
prompt += `\n\n${childDoctrine}`;
}
- if (harnessState) {
- prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash, includeRefineExamples: hasIpython && hasRefineSkill })}`;
- }
-
if (genericMcpSection) {
prompt += `\n\n${genericMcpSection}`;
}
@@ -130,9 +122,7 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
parentAgent: options.rlmParentAgent,
});
- // Appended AFTER the trained buildRlmPrompt prefix, and before the harness-state
- // 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.
+ // Appended AFTER the trained buildRlmPrompt prefix: delegation doctrine precedes the subagent specs delivered via the harness digest.
if ((allowRecursion ?? true) && hasIpython) {
const visiblePythonSkillNames = new Set(
getPythonSkillRuntimeInfo(visibleSkills).map((skill) => skill.importName),
@@ -144,10 +134,6 @@ export function buildSystemPrompt(options: BuildSystemPromptOptions): string {
})}`;
}
- if (harnessState) {
- prompt += `\n\n${formatHarnessStateForPrompt(harnessState, { includeIpythonExamples: hasIpython, includeShellExamples: hasBash, includeRefineExamples: hasIpython && hasRefineSkill })}`;
- }
-
if (genericMcpSection) {
prompt += `\n\n${genericMcpSection}`;
}
diff --git a/packages/coding-agent/src/modes/headless-completion.ts b/packages/coding-agent/src/modes/headless-completion.ts
index e6524d314e..ee257b8462 100644
--- a/packages/coding-agent/src/modes/headless-completion.ts
+++ b/packages/coding-agent/src/modes/headless-completion.ts
@@ -9,8 +9,10 @@ import {
import {
COMPACTION_OUTCOME_CUSTOM_TYPE,
type CompactionOutcomeMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
isCompactionOutcomeMessage,
isSessionSlashCommandResultMessage,
+ REFINEMENT_NOTICE_CUSTOM_TYPE,
REFINEMENT_OUTCOME_CUSTOM_TYPE,
type SessionSlashCommandResultMessage,
} from "../core/messages.js";
@@ -41,7 +43,9 @@ export function selectHeadlessTerminalResult(messages: readonly AgentMessage[]):
if (
message.role === "custom" &&
(message.customType === COMPACTION_OUTCOME_CUSTOM_TYPE ||
- message.customType === REFINEMENT_OUTCOME_CUSTOM_TYPE)
+ message.customType === REFINEMENT_OUTCOME_CUSTOM_TYPE ||
+ message.customType === REFINEMENT_NOTICE_CUSTOM_TYPE ||
+ message.customType === HARNESS_DIGEST_CUSTOM_TYPE)
) {
index--;
continue;
diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.ts
index a946ee3bc6..c2b6e4f212 100644
--- a/packages/coding-agent/test/agent-session-recursion.test.ts
+++ b/packages/coding-agent/test/agent-session-recursion.test.ts
@@ -38,6 +38,7 @@ import { createSyntheticSourceInfo } from "../src/core/source-info.js";
import type { BashOperations } from "../src/core/tools/bash.js";
import { type ActiveSessionState, resolveActiveSessionState } from "../src/modes/daemon/active-session-state.js";
import { AgentDaemon } from "../src/modes/daemon/daemon-mode.js";
+import { getMessageText } from "./suite/harness.js";
import { createTestExtensionsResult, createTestResourceLoader } from "./utilities.js";
const model = getModel("anthropic", "claude-sonnet-4-5")!;
@@ -849,7 +850,10 @@ describe("AgentSession rlm recursion", () => {
}),
]);
const child = root.getRlmChildSession(result.rlm_child_id);
- expect(child?.messages[0]).toMatchObject({
+ expect(getMessageText(child?.messages[0])).toContain(
+ "The persistent memories produced across this session so far:",
+ );
+ expect(child?.messages[1]).toMatchObject({
role: "custom",
customType: "agent_message",
content: "[task from parent]\n\nsummarize shard 1",
@@ -4811,7 +4815,7 @@ describe("AgentSession RLM session dir", () => {
expect(env.RLM_HARNESS_STATE_DIR).toBe(join(ephemeralDir, "harness"));
});
- it("loads the ephemeral RLM harness path into the host system prompt", () => {
+ it("loads the ephemeral RLM harness path into the session-start harness digest", () => {
const ephemeralDir = join(tempDir, "ephemeral-rlm");
mkdirSync(join(ephemeralDir, "harness"), { recursive: true });
writeFileSync(
@@ -4846,10 +4850,11 @@ describe("AgentSession RLM session dir", () => {
);
const root = createSession(SessionManager.inMemory(tempDir), undefined, undefined, false, ephemeralDir);
- const prompt = root.systemPrompt;
+ const digest = (root as unknown as { _harnessDigest(): string })._harnessDigest();
- expect(prompt).toContain("Ephemeral note");
- expect(prompt).toContain("Loaded from the RLM session harness path.");
+ expect(root.systemPrompt).not.toContain("Ephemeral note");
+ expect(digest).toContain("Ephemeral note");
+ expect(digest).toContain("Loaded from the RLM session harness path.");
});
it("exports the configured agentDir to the kernel so skills find auth.json", () => {
diff --git a/packages/coding-agent/test/daemon-extension-binding.test.ts b/packages/coding-agent/test/daemon-extension-binding.test.ts
index c71f4ba565..84f68b08cd 100644
--- a/packages/coding-agent/test/daemon-extension-binding.test.ts
+++ b/packages/coding-agent/test/daemon-extension-binding.test.ts
@@ -18,6 +18,7 @@ import { createAgentConnectionState } from "../src/modes/agent-connection/snapsh
import type { ActiveSessionState } from "../src/modes/daemon/active-session-state.js";
import { bindActiveSessionState } from "../src/modes/daemon/daemon-extension-binding.js";
import type { DaemonOutbound } from "../src/modes/daemon/daemon-protocol.js";
+import { conversationMessages } from "./suite/harness.js";
function getText(message: AgentSession["messages"][number]): string {
if (!("content" in message)) {
@@ -248,7 +249,7 @@ describe("daemon extension binding", () => {
message.type === "session_replaced",
);
expect(replaced?.state.recap).toBeUndefined();
- expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
+ expect(conversationMessages(runtime.session).map((message) => `${message.role}:${getText(message)}`)).toEqual([
"user:daemon replacement message",
"assistant:replacement reply",
]);
diff --git a/packages/coding-agent/test/daemon-supervisor-process.test.ts b/packages/coding-agent/test/daemon-supervisor-process.test.ts
index 765a9edc26..5ddedfc445 100644
--- a/packages/coding-agent/test/daemon-supervisor-process.test.ts
+++ b/packages/coding-agent/test/daemon-supervisor-process.test.ts
@@ -466,7 +466,8 @@ describe("daemon supervisor resident workers", () => {
// A fresh current-binary worker owns the reloaded idle session; the fake pre-roster pid is not adopted.
expect(restarted.workerPid).not.toBe(legacyProcess.pid);
expect(restarted.isSessionActive).toBe(false);
- expect(restarted.messageCount).toBe(1);
+ // The seeded user message plus the harness digest injected on resume.
+ expect(restarted.messageCount).toBe(2);
await waitForProcessGone(legacyProcess.pid);
fakeWorker.close();
client.close();
@@ -1514,12 +1515,25 @@ describe("daemon supervisor resident workers", () => {
connection.subscribe((event) => {
connectionEvents.push(event.type === "connection_status" ? `${event.type}:${event.status}` : event.type);
if (event.type === "session_replaced") {
- replacementMessageCounts.push(event.messages.length);
+ // Count conversation messages only; every session carries a harness digest.
+ replacementMessageCounts.push(
+ event.messages.filter(
+ (message) =>
+ !(
+ message.role === "custom" &&
+ (message as { customType?: string }).customType === "harness_digest"
+ ),
+ ).length,
+ );
}
});
const snapshot = await connection.getInitialSnapshot();
- expect(snapshot.messages).toHaveLength(2);
- expect(snapshot.messages[0]).toMatchObject({ role: "user", content: largePrompt });
+ const snapshotConversation = snapshot.messages.filter(
+ (message) =>
+ !(message.role === "custom" && (message as { customType?: string }).customType === "harness_digest"),
+ );
+ expect(snapshotConversation).toHaveLength(2);
+ expect(snapshotConversation[0]).toMatchObject({ role: "user", content: largePrompt });
const activeSessionId = createdSummary.activeSessionId ?? createdSummary.id;
const createdNew = await client.request({ type: "new_session", activeSessionId });
diff --git a/packages/coding-agent/test/print-mode.test.ts b/packages/coding-agent/test/print-mode.test.ts
index 065d5d04ae..d21ebf43e3 100644
--- a/packages/coding-agent/test/print-mode.test.ts
+++ b/packages/coding-agent/test/print-mode.test.ts
@@ -5,6 +5,7 @@ import type { AgentAutonomousStatus } from "../src/core/autonomous.js";
import {
createCompactionOutcomeMessage,
createCustomMessage,
+ createHarnessDigestMessage,
createRefinementOutcomeMessage,
createSessionSlashCommandResultMessage,
} from "../src/core/messages.js";
@@ -236,6 +237,16 @@ describe("runPrintMode", () => {
});
});
+ it("selects the saved assistant output past a resume-injected harness digest", () => {
+ const assistant = createAssistantMessage({ text: "final answer" });
+ const digest = createHarnessDigestMessage("# Continual Harness State\n\nmemory: 0");
+
+ expect(selectHeadlessTerminalResult([assistant, digest])).toEqual({
+ primary: assistant,
+ compactionOutcomes: [],
+ });
+ });
+
it("does not select a result across a message barrier", () => {
const outcome = createCompactionOutcomeMessage("Requested compaction skipped", {
reason: "requested",
diff --git a/packages/coding-agent/test/refinement-outcome-message.test.ts b/packages/coding-agent/test/refinement-outcome-message.test.ts
index 7802ebf941..8c8b206175 100644
--- a/packages/coding-agent/test/refinement-outcome-message.test.ts
+++ b/packages/coding-agent/test/refinement-outcome-message.test.ts
@@ -2,7 +2,12 @@ import { setKeybindings, type TUI, visibleWidth } from "@earendil-works/pi-tui";
import stripAnsi from "strip-ansi";
import { beforeAll, describe, expect, test } from "vitest";
import { KeybindingsManager } from "../src/core/keybindings.js";
-import { convertToLlm, createRefinementOutcomeMessage, isRefinementOutcomeMessage } from "../src/core/messages.js";
+import {
+ convertToLlm,
+ createRefinementNoticeMessage,
+ createRefinementOutcomeMessage,
+ isRefinementOutcomeMessage,
+} from "../src/core/messages.js";
import type { HarnessEntry, RefinementResult } from "../src/core/refinement/refinement.js";
import { buildConversationComponents } from "../src/modes/interactive/components/conversation-components.js";
import { RefinementOutcomeMessageComponent } from "../src/modes/interactive/components/refinement-outcome-message.js";
@@ -51,6 +56,14 @@ function result(): RefinementResult {
};
}
+function getLlmText(message: unknown): string {
+ const content = (message as { content: Array<{ type: string; text?: string }> }).content;
+ return content
+ .filter((part) => part.type === "text")
+ .map((part) => part.text)
+ .join("\n");
+}
+
function rendered(component: RefinementOutcomeMessageComponent): string {
return stripAnsi(component.render(120).join("\n"));
}
@@ -148,4 +161,25 @@ describe("RefinementOutcomeMessageComponent", () => {
expect(convertToLlm([message])).toEqual([]);
expect(isRefinementOutcomeMessage({ ...message, details: { ...message.details, edits: [{}] } })).toBe(false);
});
+
+ test("refinement notices pass through to the model while outcomes stay filtered", () => {
+ const outcome = createRefinementOutcomeMessage(result());
+ const notice = createRefinementNoticeMessage(result(), "self");
+
+ const llm = convertToLlm([outcome, notice]);
+ expect(llm).toHaveLength(1);
+ expect(llm[0]?.role).toBe("user");
+ const text = getLlmText(llm[0]);
+ expect(text).toMatch(/^\[self-refinement\]\n\n/);
+ expect(text).toContain("Added local guidance to make conversational responses rhyme.");
+ expect(text).toContain(
+ "- create prompt [local:rhyme-response-guidance] Rhyme response guidance: Make conversational responses rhyme.",
+ );
+ expect(getLlmText(convertToLlm([createRefinementNoticeMessage(result(), "auto")])[0])).toMatch(
+ /^\[auto-refinement\]/,
+ );
+ expect(getLlmText(convertToLlm([createRefinementNoticeMessage(result(), "user")])[0])).toMatch(
+ /^\[user-refinement\]/,
+ );
+ });
});
diff --git a/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts b/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
index bfdbcb810a..71e2fb330f 100644
--- a/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-action-contracts.test.ts
@@ -1,6 +1,6 @@
import { fauxAssistantMessage } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it } from "vitest";
-import { createHarness, getUserTexts, type Harness } from "./harness.js";
+import { conversationMessages, createHarness, getUserTexts, type Harness } from "./harness.js";
import { withStreaming } from "./scheduling.js";
describe("AgentSession action contracts", () => {
@@ -64,12 +64,16 @@ describe("AgentSession action contracts", () => {
{ triggerTurn: true, deliverAs: "nextTurn" },
);
- expect(harness.session.messages).toEqual([]);
+ expect(conversationMessages(harness.session)).toEqual([]);
expect(harness.session.queuedActionCount).toBe(0);
expect(harness.getPendingResponseCount()).toBe(1);
await harness.session.prompt("consume context");
- expect(harness.session.messages.map((message) => message.role)).toEqual(["custom", "user", "assistant"]);
+ expect(conversationMessages(harness.session).map((message) => message.role)).toEqual([
+ "custom",
+ "user",
+ "assistant",
+ ]);
expect(harness.getPendingResponseCount()).toBe(0);
});
@@ -103,7 +107,7 @@ describe("AgentSession action contracts", () => {
expect(extensionCommandRuns).toBe(0);
expect(harness.session.getSteeringMessages()).toEqual(["/literal keep text"]);
expect(harness.session.getFollowUpMessages()).toEqual(["/compact"]);
- expect(harness.session.messages).toEqual([]);
+ expect(conversationMessages(harness.session)).toEqual([]);
expect(harness.session.resumeQueuedWork()).toBe(true);
await harness.session.waitForIdle();
diff --git a/packages/coding-agent/test/suite/agent-session-action-races.test.ts b/packages/coding-agent/test/suite/agent-session-action-races.test.ts
index 8239c1f2f2..1204b0558e 100644
--- a/packages/coding-agent/test/suite/agent-session-action-races.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-action-races.test.ts
@@ -2,7 +2,7 @@ import { fauxAssistantMessage } from "@earendil-works/pi-ai";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { CustomMessage } from "../../src/core/messages.js";
import type { ActionStore, SessionAction } from "../../src/core/session-action-store.js";
-import { createHarness, getMessageText, getUserTexts, type Harness } from "./harness.js";
+import { conversationMessages, createHarness, getMessageText, getUserTexts, type Harness } from "./harness.js";
import { createDeferred } from "./scheduling.js";
type ActionKind = "turn" | "command";
@@ -255,7 +255,7 @@ describe("AgentSession action commit-fence races", () => {
await yieldToEventLoop();
expect(internals._actionStore.unfinishedActions()[0]?.lifecycle.state).toBe("selected");
- expect(harness.session.messages).toEqual([]);
+ expect(conversationMessages(harness.session)).toEqual([]);
refineGate.resolve();
await command;
@@ -325,7 +325,11 @@ describe("AgentSession action commit-fence races", () => {
harnesses.push(harness);
harness.setResponses([
(context) => {
- deliveredMessages.push(...context.messages.map(getMessageText));
+ deliveredMessages.push(
+ ...context.messages
+ .map(getMessageText)
+ .filter((text) => !text.startsWith("The persistent memories produced across this session so far:")),
+ );
return fauxAssistantMessage("done");
},
]);
diff --git a/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts b/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
index ba061ef6df..fc76c6618f 100644
--- a/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-bash-persistence.test.ts
@@ -159,7 +159,9 @@ describe("AgentSession bash and persistence characterization", () => {
await harness.session.prompt("start");
const entries = harness.sessionManager.getEntries();
+ // The first custom_message entry is the session-start harness digest.
expect(entries.map((entry) => entry.type)).toEqual([
+ "custom_message",
"custom_message",
"message",
"message",
@@ -167,6 +169,7 @@ describe("AgentSession bash and persistence characterization", () => {
"message",
]);
expect(harness.session.messages.map((message) => message.role)).toEqual([
+ "custom",
"custom",
"user",
"assistant",
diff --git a/packages/coding-agent/test/suite/agent-session-compaction.test.ts b/packages/coding-agent/test/suite/agent-session-compaction.test.ts
index 53d40829b5..21db8fb9ac 100644
--- a/packages/coding-agent/test/suite/agent-session-compaction.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-compaction.test.ts
@@ -8,6 +8,8 @@ import {
type Usage,
} from "@earendil-works/pi-ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { convertToLlm } from "../../src/core/messages.js";
+import { getLocalHarnessStateDir, loadHarnessState, saveHarnessState } from "../../src/core/refinement/index.js";
import { SessionManager } from "../../src/core/session-manager.js";
import { createHarness, getMessageText, type Harness } from "./harness.js";
import { createDeferred } from "./scheduling.js";
@@ -196,6 +198,87 @@ describe("AgentSession compaction characterization", () => {
});
});
+ it("prepends the harness digest to the compaction head message on initial and update-merge compactions", async () => {
+ const harness = await createHarness({
+ settings: { compaction: { keepRecentTokens: 1 } },
+ persistSession: true,
+ });
+ harnesses.push(harness);
+ const summarizerInputs: string[] = [];
+ harness.setResponses([
+ fauxAssistantMessage("one response"),
+ fauxAssistantMessage("two response"),
+ (context) => {
+ summarizerInputs.push(context.messages.map(getMessageText).join("\n"));
+ return fauxAssistantMessage("first summary");
+ },
+ (context) => {
+ summarizerInputs.push(context.messages.map(getMessageText).join("\n"));
+ return fauxAssistantMessage("first turn summary");
+ },
+ ]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+
+ // Written after construction: the compaction digest must be a fresh disk read.
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir());
+ expect(localDir).toBeDefined();
+ const state = loadHarnessState(localDir, "local");
+ state.entries.memory.compaction_test_memory = {
+ id: "compaction_test_memory",
+ kind: "memory",
+ title: "Compaction test memory",
+ content: "Written before compaction.",
+ path: "general",
+ scope: "local",
+ reference: {},
+ arguments: {},
+ metadata: {},
+ source: "refine",
+ created_at: "2026-09-07T00:00:00.000Z",
+ updated_at: "2026-09-07T00:00:00.000Z",
+ version: 1,
+ };
+ saveHarnessState(localDir!, state);
+
+ await harness.session.compact();
+
+ const head = harness.session.messages[0];
+ expect(head).toMatchObject({ role: "compactionSummary", summary: expect.stringContaining("first summary") });
+ const digest = (head as { harnessDigest?: string }).harnessDigest;
+ expect(digest).toContain("[local:compaction_test_memory] Compaction test memory");
+ // The session-start digest never reaches the summarizer input.
+ expect(summarizerInputs.length).toBeGreaterThan(0);
+ for (const input of summarizerInputs) {
+ expect(input).not.toContain("# Continual Harness State");
+ }
+ // Mechanical attachment: the digest never flows through the summarizer.
+ expect((head as { summary: string }).summary).not.toContain("# Continual Harness State");
+ // Memories-first rendering in LLM context: digest preamble before the summary wrapper.
+ const text = getMessageText(convertToLlm([head!])[0]);
+ expect(text.indexOf("The persistent memories produced across this session so far:")).toBe(0);
+ expect(text.indexOf("# Continual Harness State")).toBeLessThan(
+ text.indexOf("was compacted into the following summary"),
+ );
+
+ // Update-merge path: the second compaction head carries the digest too.
+ harness.setResponses([
+ fauxAssistantMessage("three response"),
+ fauxAssistantMessage("merged summary"),
+ fauxAssistantMessage("merged turn summary"),
+ ]);
+ await harness.session.prompt("three");
+ await harness.session.compact();
+ const mergedHead = harness.session.messages[0];
+ expect(mergedHead).toMatchObject({
+ role: "compactionSummary",
+ summary: expect.stringContaining("merged summary"),
+ });
+ expect((mergedHead as { harnessDigest?: string }).harnessDigest).toContain(
+ "[local:compaction_test_memory] Compaction test memory",
+ );
+ });
+
it("renders an executing /compact as activity instead of queued work", async () => {
let releaseCompaction: () => void = () => {};
const compactionGate = new Promise<void>((resolve) => {
diff --git a/packages/coding-agent/test/suite/agent-session-goal.test.ts b/packages/coding-agent/test/suite/agent-session-goal.test.ts
index 29528f0362..e806ac04d7 100644
--- a/packages/coding-agent/test/suite/agent-session-goal.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-goal.test.ts
@@ -12,7 +12,7 @@ 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";
+import { conversationMessages, createHarness, getAssistantTexts, getMessageText, type Harness } from "./harness.js";
function assistantWithUsage(message: string | AssistantMessage, usage: Partial<Usage>): AssistantMessage {
const base = typeof message === "string" ? fauxAssistantMessage(message) : message;
@@ -645,7 +645,9 @@ describe("AgentSession goals", () => {
await harness.session.prompt("/goal clear");
expect(
- harness.session.messages.map((message) => (message.role === "custom" ? message.customType : message.role)),
+ conversationMessages(harness.session).map((message) =>
+ message.role === "custom" ? message.customType : message.role,
+ ),
).toEqual(["session_slash_command", "session_slash_command_result"]);
expect(harness.eventsOfType("goal_update").at(-1)?.goal.status).toBe("idle");
expect(harness.getPendingResponseCount()).toBe(1);
@@ -867,7 +869,9 @@ describe("AgentSession goals", () => {
await harness.session.prompt("/goal status");
expect(
- harness.session.messages.map((message) => (message.role === "custom" ? message.customType : message.role)),
+ conversationMessages(harness.session).map((message) =>
+ message.role === "custom" ? message.customType : message.role,
+ ),
).toEqual(["session_slash_command", "session_slash_command_result"]);
expect(harness.eventsOfType("goal_update").at(-1)?.goal.status).toBe("idle");
expect(harness.getPendingResponseCount()).toBe(1);
diff --git a/packages/coding-agent/test/suite/agent-session-model-extension.test.ts b/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
index cefe6831d3..8d0b925008 100644
--- a/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-model-extension.test.ts
@@ -4,7 +4,7 @@ import { Type } from "typebox";
import { afterEach, describe, expect, it } from "vitest";
import type { AgentCronJob } from "../../src/core/cron-jobs.js";
import type { ExtensionAPI } from "../../src/index.js";
-import { createHarness, getAssistantTexts, getMessageText, type Harness } from "./harness.js";
+import { conversationMessages, createHarness, getAssistantTexts, getMessageText, type Harness } from "./harness.js";
function createDeferred<T = void>(): {
promise: Promise<T>;
@@ -299,7 +299,7 @@ describe("AgentSession model and extension characterization", () => {
const prompt = harness.session.prompt("hi");
await flushAsyncWork();
- expect(harness.session.messages).toHaveLength(0);
+ expect(conversationMessages(harness.session)).toHaveLength(0);
finishHandler.resolve();
await prompt;
@@ -308,7 +308,9 @@ describe("AgentSession model and extension characterization", () => {
}
expect(
- harness.session.messages.slice(0, 2).map((message) => ({ role: message.role, text: getMessageText(message) })),
+ conversationMessages(harness.session)
+ .slice(0, 2)
+ .map((message) => ({ role: message.role, text: getMessageText(message) })),
).toEqual([
{ role: "custom", text: "model context" },
{ role: "user", text: "hi" },
@@ -352,14 +354,16 @@ describe("AgentSession model and extension characterization", () => {
});
await flushAsyncWork();
- expect(harness.session.messages).toHaveLength(0);
+ expect(conversationMessages(harness.session)).toHaveLength(0);
finishHandler.resolve();
await accepted;
await harness.session.agent.waitForIdle();
expect(
- harness.session.messages.slice(0, 2).map((message) => ({ role: message.role, text: getMessageText(message) })),
+ conversationMessages(harness.session)
+ .slice(0, 2)
+ .map((message) => ({ role: message.role, text: getMessageText(message) })),
).toEqual([
{ role: "custom", text: "accepted model context" },
{ role: "user", text: "agent-to-agent payload" },
@@ -434,14 +438,16 @@ describe("AgentSession model and extension characterization", () => {
const heartbeat = harness.session.promptHeartbeat(createHeartbeat());
await flushAsyncWork();
- expect(harness.session.messages).toHaveLength(0);
+ expect(conversationMessages(harness.session)).toHaveLength(0);
finishHandler.resolve();
await heartbeat;
await harness.session.agent.waitForIdle();
expect(
- harness.session.messages.slice(0, 2).map((message) => ({ role: message.role, text: getMessageText(message) })),
+ conversationMessages(harness.session)
+ .slice(0, 2)
+ .map((message) => ({ role: message.role, text: getMessageText(message) })),
).toEqual([
{ role: "custom", text: "heartbeat model context" },
{ role: "custom", text: "Check whether the long-running task needs another step." },
@@ -662,7 +668,7 @@ describe("AgentSession model and extension characterization", () => {
let providerUserText = "";
harness.setResponses([
(context) => {
- const user = context.messages.find((message) => message.role === "user");
+ const user = context.messages.filter((message) => message.role === "user").at(-1);
providerUserText =
user && typeof user.content !== "string"
? user.content
@@ -703,7 +709,7 @@ describe("AgentSession model and extension characterization", () => {
let providerUserText = "";
transformedHarness.setResponses([
(context) => {
- const user = context.messages.find((message) => message.role === "user");
+ const user = context.messages.filter((message) => message.role === "user").at(-1);
providerUserText =
user && typeof user.content !== "string"
? user.content
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 8ade5795d0..c06fb3035f 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -4,9 +4,16 @@ 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, vi } from "vitest";
+import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import type { BashResult } from "../../src/core/bash-executor.js";
+import {
+ convertToLlm,
+ createCompactionSummaryMessage,
+ createHarnessDigestMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
+} from "../../src/core/messages.js";
import type { PromptTemplate } from "../../src/core/prompt-templates.js";
+import { getLocalHarnessStateDir, loadHarnessState, saveHarnessState } from "../../src/core/refinement/index.js";
import { createSyntheticSourceInfo } from "../../src/core/source-info.js";
import { createTestResourceLoader } from "../utilities.js";
import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.js";
@@ -99,8 +106,9 @@ describe("AgentSession prompt characterization", () => {
await harness.session.prompt("hi");
- expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
- expect(getMessageText(harness.session.messages[0]!)).toBe("hi");
+ // The leading custom message is the session-start harness digest.
+ expect(harness.session.messages.map((message) => message.role)).toEqual(["custom", "user", "assistant"]);
+ expect(getMessageText(harness.session.messages[1]!)).toBe("hi");
expect(harness.getPendingResponseCount()).toBe(0);
expect(harness.eventsOfType("session_action_update")).toEqual([]);
});
@@ -224,13 +232,14 @@ describe("AgentSession prompt characterization", () => {
expect(toolRuns).toEqual(["hello"]);
expect(harness.session.messages.map((message) => message.role)).toEqual([
+ "custom",
"user",
"assistant",
"toolResult",
"assistant",
]);
- expect(harness.session.messages[2]?.role).toBe("toolResult");
- expect(harness.session.messages[3]?.role).toBe("assistant");
+ expect(harness.session.messages[3]?.role).toBe("toolResult");
+ expect(harness.session.messages[4]?.role).toBe("assistant");
});
it("executes multiple tool calls from one response and continues with a single follow-up response", async () => {
@@ -278,11 +287,12 @@ describe("AgentSession prompt characterization", () => {
harness.setResponses([
(context) => {
- const user = context.messages.find((message) => message.role === "user");
- sawImage =
- user?.role === "user" &&
- typeof user.content !== "string" &&
- user.content.some((part) => part.type === "image");
+ sawImage = context.messages.some(
+ (message) =>
+ message.role === "user" &&
+ typeof message.content !== "string" &&
+ message.content.some((part) => part.type === "image"),
+ );
return fauxAssistantMessage("ok");
},
]);
@@ -335,7 +345,7 @@ describe("AgentSession prompt characterization", () => {
harness.setResponses([
(context) => {
- const user = context.messages.find((message) => message.role === "user");
+ const user = context.messages.filter((message) => message.role === "user").at(-1);
expandedPrompt = user ? getMessageText(user) : "";
return fauxAssistantMessage("ok");
},
@@ -370,7 +380,7 @@ describe("AgentSession prompt characterization", () => {
harness.setResponses([
(context) => {
- const user = context.messages.find((message) => message.role === "user");
+ const user = context.messages.filter((message) => message.role === "user").at(-1);
expandedPrompt = user ? getMessageText(user) : "";
return fauxAssistantMessage("ok");
},
@@ -401,7 +411,7 @@ describe("AgentSession prompt characterization", () => {
await harness.session.prompt("/testcmd hello world");
expect(commandRuns).toEqual(["hello world"]);
- expect(harness.session.messages).toEqual([]);
+ expect(harness.session.messages.filter((message) => message.role !== "custom")).toEqual([]);
expect(harness.getPendingResponseCount()).toBe(1);
});
@@ -413,8 +423,8 @@ describe("AgentSession prompt characterization", () => {
await harness.session.sendUserMessage("from extension");
- expect(harness.session.messages.map((message) => message.role)).toEqual(["user", "assistant"]);
- expect(getMessageText(harness.session.messages[0]!)).toBe("from extension");
+ expect(harness.session.messages.map((message) => message.role)).toEqual(["custom", "user", "assistant"]);
+ expect(getMessageText(harness.session.messages[1]!)).toBe("from extension");
});
it("rejects an aborted prompt while streaming instead of enqueueing it", async () => {
@@ -1117,9 +1127,11 @@ stale post-hook extension instructions`,
await harness.session.acceptAgentMessagePrompt("agent-to-agent payload", { expandPromptTemplates: false });
await harness.session.agent.waitForIdle();
- expect(contextRoles).toEqual([["user", "assistant", "user", "user"]]);
+ // The direct agent.prompt bypassed the pipeline, so the first pipeline turn injects the digest here.
+ expect(contextRoles).toEqual([["user", "assistant", "user", "user", "user"]]);
expect(contextTexts[0]?.[2]).toContain("Ran `echo hi`");
- expect(contextTexts[0]?.[3]).toBe("agent-to-agent payload");
+ expect(contextTexts[0]?.[3]).toContain("The persistent memories produced across this session so far:");
+ expect(contextTexts[0]?.[4]).toBe("agent-to-agent payload");
expect(harness.session.hasPendingBashMessages).toBe(false);
});
@@ -2066,3 +2078,263 @@ stale post-hook extension instructions`,
expect(getAssistantTexts(harness)).toContain("clean after");
});
});
+
+describe("Harness digest at cold boundaries", () => {
+ const harnesses: Harness[] = [];
+ const tempDirs: string[] = [];
+
+ afterEach(() => {
+ while (harnesses.length > 0) {
+ harnesses.pop()?.cleanup();
+ }
+ while (tempDirs.length > 0) {
+ const dir = tempDirs.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ function digestMessages(harness: Harness) {
+ return harness.session.messages.filter(
+ (message) => message.role === "custom" && message.customType === HARNESS_DIGEST_CUSTOM_TYPE,
+ );
+ }
+
+ it("keeps untouched sessions empty and injects the digest at the first committed turn", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+
+ // Untouched sessions must stay empty for draft cleanup and emptiness checks.
+ expect(harness.session.messages).toHaveLength(0);
+ expect(
+ harness.sessionManager
+ .getEntries()
+ .filter((entry) => entry.type === "custom_message" || entry.type === "message"),
+ ).toHaveLength(0);
+
+ harness.setResponses([fauxAssistantMessage("hi")]);
+ await harness.session.prompt("hello");
+
+ const first = harness.session.messages[0];
+ expect(first).toMatchObject({ role: "custom", customType: HARNESS_DIGEST_CUSTOM_TYPE });
+ expect(harness.session.messages[1]).toMatchObject({ role: "user" });
+ expect(getMessageText(first)).toContain("The persistent memories produced across this session so far:");
+ // Passes through to the model as a user message and is durably persisted.
+ expect(convertToLlm([first!])[0]?.role).toBe("user");
+ expect(
+ harness.sessionManager
+ .getEntries()
+ .some((entry) => entry.type === "custom_message" && entry.customType === HARNESS_DIGEST_CUSTOM_TYPE),
+ ).toBe(true);
+ });
+
+ it("delivers the digest on a custom-triggered first turn", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ let firstContextText = "";
+ harness.setResponses([
+ (context) => {
+ firstContextText = getMessageText(context.messages[0]);
+ return fauxAssistantMessage("ok");
+ },
+ ]);
+
+ await harness.session.sendCustomMessage(
+ { customType: "kickoff", content: "go", display: false },
+ { triggerTurn: true },
+ );
+ await harness.session.waitForIdle();
+
+ expect(firstContextText).toContain("The persistent memories produced across this session so far:");
+ });
+
+ it("re-arms the digest when a failed commit parks next-turn context", async () => {
+ const harness = await createHarness();
+ harnesses.push(harness);
+ vi.spyOn(harness.session.agent, "prompt").mockImplementationOnce(async () => {
+ throw new Error("dispatch failed");
+ });
+ await expect(harness.session.prompt("first")).rejects.toThrow("dispatch failed");
+
+ // A skip-policy custom-trigger turn never drains parked context, so the
+ // digest must arrive via re-armed lazy injection - and exactly once.
+ let texts: string[] = [];
+ harness.setResponses([
+ (context) => {
+ texts = context.messages.map(getMessageText);
+ return fauxAssistantMessage("ok");
+ },
+ ]);
+ await harness.session.sendCustomMessage(
+ { customType: "kickoff", content: "go", display: false },
+ { triggerTurn: true },
+ );
+ await harness.session.waitForIdle();
+
+ expect(
+ texts.filter((text) => text.startsWith("The persistent memories produced across this session so far:")),
+ ).toHaveLength(1);
+ });
+
+ it("strips the digest with a cleared first turn and re-delivers it on the next turn", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const agentMessageId = "agentmsg_digest_clear";
+ const agentPrompt = `Agent-to-agent message received.\nSource: agent_message\nTo: T, active t, session s\nMessage id: ${agentMessageId}\n\nagent text`;
+ harness.setResponses([fauxAssistantMessage("never delivered")]);
+ let markAdmitted = () => {};
+ const admitted = new Promise<void>((resolve) => {
+ markAdmitted = resolve;
+ });
+ let releaseAdmission = () => {};
+ const admissionGate = new Promise<void>((resolve) => {
+ releaseAdmission = resolve;
+ });
+ let unsubscribe = () => {};
+ unsubscribe = harness.session.agent.subscribe(async (event) => {
+ if (event.type !== "agent_start") return;
+ unsubscribe();
+ markAdmitted();
+ await admissionGate;
+ });
+
+ const accepted = harness.session.acceptAgentMessagePrompt(agentPrompt, { expandPromptTemplates: false });
+ const acceptedRejection = expect(accepted).rejects.toThrow("cleared before delivery");
+ await admitted;
+ harness.session.clearQueuedUserMessagesMatching((text) => text.includes(agentMessageId));
+ releaseAdmission();
+ await acceptedRejection;
+ await harness.session.agent.waitForIdle();
+
+ // The cleared first turn takes its digest with it: the session is empty again.
+ expect(harness.session.messages).toHaveLength(0);
+
+ harness.setResponses([fauxAssistantMessage("hi")]);
+ await harness.session.prompt("hello");
+ expect(digestMessages(harness)).toHaveLength(1);
+ expect(harness.session.messages[0]).toMatchObject({ role: "custom", customType: HARNESS_DIGEST_CUSTOM_TYPE });
+ });
+
+ it("treats tree navigation as a cold boundary with digest dedupe", async () => {
+ // Empty global store: digest content must reflect only the local test entry.
+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ const agentDir = join(tmpdir(), `pi-digest-agent-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(agentDir, { recursive: true });
+ tempDirs.push(agentDir);
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = agentDir;
+ onTestFinished(() => {
+ if (previousAgentDir === undefined) delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ else process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ });
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("one reply"), fauxAssistantMessage("two reply")]);
+ await harness.session.prompt("one");
+ await harness.session.prompt("two");
+ const [firstUser, secondUser] = harness.session.getUserMessagesForForking();
+ expect(digestMessages(harness)).toHaveLength(1);
+
+ // Navigation with an unchanged harness keeps the existing digest (dedupe).
+ await harness.session.navigateTree(secondUser!.entryId);
+ expect(digestMessages(harness)).toHaveLength(1);
+
+ // After a disk change, navigation refreshes the digest at the tail.
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir());
+ const state = loadHarnessState(localDir, "local");
+ state.entries.memory.nav_test_memory = {
+ id: "nav_test_memory",
+ kind: "memory",
+ title: "Nav test memory",
+ content: "Written before navigation.",
+ path: "general",
+ scope: "local",
+ reference: {},
+ arguments: {},
+ metadata: {},
+ source: "refine",
+ created_at: "2026-09-07T00:00:00.000Z",
+ updated_at: "2026-09-07T00:00:00.000Z",
+ version: 1,
+ };
+ saveHarnessState(localDir!, state);
+
+ await harness.session.navigateTree(firstUser!.entryId);
+ const digests = digestMessages(harness);
+ expect(digests).toHaveLength(2);
+ expect(harness.session.messages.at(-1)).toBe(digests.at(-1));
+ expect(getMessageText(digests.at(-1))).toContain("[local:nav_test_memory] Nav test memory");
+ });
+
+ it("prefers the newest digest by timestamp over a retained pre-compaction digest", async () => {
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ const internals = harness.session as unknown as { _latestContextHarnessDigest(): string | undefined };
+ const base = Date.now();
+ // The retained digest follows the head in the array but is older; the head must win.
+ harness.session.agent.state.messages.push(
+ createCompactionSummaryMessage(
+ "summary",
+ 10,
+ new Date(base + 2000).toISOString(),
+ undefined,
+ 1,
+ "head digest",
+ ),
+ createHarnessDigestMessage("retained digest", base + 1000),
+ );
+ expect(internals._latestContextHarnessDigest()).toBe("head digest");
+ });
+
+ it("resume dedupes identical digests and appends a fresh one when disk state changed", async () => {
+ // Empty global store: digest content must reflect only the local test entry.
+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ const agentDir = join(tmpdir(), `pi-digest-agent-${Date.now()}-${Math.random().toString(36).slice(2)}`);
+ mkdirSync(agentDir, { recursive: true });
+ tempDirs.push(agentDir);
+ process.env.PRIME_AGENT_CODING_AGENT_DIR = agentDir;
+ onTestFinished(() => {
+ if (previousAgentDir === undefined) delete process.env.PRIME_AGENT_CODING_AGENT_DIR;
+ else process.env.PRIME_AGENT_CODING_AGENT_DIR = previousAgentDir;
+ });
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("hi")]);
+ await harness.session.prompt("hello");
+ const sessionFile = harness.sessionManager.getSessionFile();
+ expect(sessionFile).toBeDefined();
+ harness.session.dispose();
+
+ // Identical disk state: repeated resumes must not stack digest copies.
+ const resumed = await createHarness({ existingSessionFile: sessionFile });
+ harnesses.push(resumed);
+ expect(digestMessages(resumed).length).toBe(1);
+ resumed.session.dispose();
+
+ // Stale digest: the local harness changed on disk since the last injection.
+ const localDir = getLocalHarnessStateDir(resumed.sessionManager.getSessionArtifactDir());
+ expect(localDir).toBeDefined();
+ const state = loadHarnessState(localDir, "local");
+ state.entries.memory.resume_test_memory = {
+ id: "resume_test_memory",
+ kind: "memory",
+ title: "Resume test memory",
+ content: "Written between resumes.",
+ path: "general",
+ scope: "local",
+ reference: {},
+ arguments: {},
+ metadata: {},
+ source: "refine",
+ created_at: "2026-09-07T00:00:00.000Z",
+ updated_at: "2026-09-07T00:00:00.000Z",
+ version: 1,
+ };
+ saveHarnessState(localDir!, state);
+
+ const resumedStale = await createHarness({ existingSessionFile: sessionFile });
+ harnesses.push(resumedStale);
+ const digests = digestMessages(resumedStale);
+ expect(digests.length).toBe(2);
+ expect(resumedStale.session.messages.at(-1)).toBe(digests.at(-1));
+ expect(getMessageText(digests.at(-1))).toContain("[local:resume_test_memory] Resume test memory");
+ });
+});
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 14e31404a1..c993bd6582 100644
--- a/packages/coding-agent/test/suite/agent-session-queue.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-queue.test.ts
@@ -29,7 +29,14 @@ import {
saveHarnessState,
} from "../../src/core/refinement/index.js";
import { parseSessionSlashCommand } from "../../src/core/slash-commands.js";
-import { createHarness, getAssistantTexts, getMessageText, getUserTexts, type Harness } from "./harness.js";
+import {
+ conversationMessages,
+ createHarness,
+ getAssistantTexts,
+ getMessageText,
+ getUserTexts,
+ type Harness,
+} from "./harness.js";
import { createDeferred, createWaitingHarness, gatedHook, withStreaming } from "./scheduling.js";
type AutoRefineReason = "turn_interval" | "compact";
@@ -1415,7 +1422,7 @@ describe("AgentSession queue characterization", () => {
await completion;
await expect(harness.session.promptAndWait("/fail")).rejects.toThrow("extension exploded");
expect(extensionErrors).toEqual(["extension exploded"]);
- expect(harness.session.messages).toEqual([]);
+ expect(conversationMessages(harness.session)).toEqual([]);
});
it("settles a visibly queued session command while an earlier action is preparing", async () => {
@@ -1949,7 +1956,7 @@ describe("AgentSession queue characterization", () => {
await harness.session.prompt("normal prompt");
expect(sawCustomMessage).toBe(true);
- expect(harness.session.messages.map((message) => message.role)).toEqual([
+ expect(conversationMessages(harness.session).map((message) => message.role)).toEqual([
"user",
"assistant",
"custom",
@@ -2337,7 +2344,9 @@ describe("AgentSession queue characterization", () => {
]);
expect(
- harness.session.messages.filter((message) => message.role === "custom").map((message) => message.content),
+ conversationMessages(harness.session)
+ .filter((message) => message.role === "custom")
+ .map((message) => message.content),
).toEqual(["first", "second"]);
});
diff --git a/packages/coding-agent/test/suite/agent-session-refine-extension.test.ts b/packages/coding-agent/test/suite/agent-session-refine-extension.test.ts
index 98c3db2fbd..6a94ed8045 100644
--- a/packages/coding-agent/test/suite/agent-session-refine-extension.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-refine-extension.test.ts
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { RefineSkippedError } from "../../src/core/agent-session.js";
import type { SessionBeforeRefineEvent } from "../../src/core/extensions/index.js";
import { loadHarnessState, type RefinementProposal } from "../../src/core/refinement/index.js";
-import { createHarness, type Harness } from "./harness.js";
+import { createHarness, getMessageText, type Harness } from "./harness.js";
describe("AgentSession session_before_refine extension hook", () => {
const harnesses: Harness[] = [];
@@ -49,6 +49,12 @@ describe("AgentSession session_before_refine extension hook", () => {
expect(result.summary).toBe("extension summary");
expect(result.appliedEdits).toHaveLength(1);
expect(result.appliedEdits[0]?.applied).toBe(true);
+ // The notice reaches context without starting a turn of its own.
+ const notice = harness.session.messages.find(
+ (message) => message.role === "custom" && message.customType === "refinement_notice",
+ );
+ expect(getMessageText(notice)).toMatch(/^\[user-refinement\]\n\n/);
+ expect(harness.session.isStreaming).toBe(false);
expect(events).toHaveLength(1);
expect(events[0]?.preparation.trigger).toBe("manual");
expect(events[0]?.preparation.scope).toBe("local");
@@ -87,6 +93,12 @@ describe("AgentSession session_before_refine extension hook", () => {
expect(result.appliedEdits[0]?.applied).toBe(false);
expect(result.appliedEdits[0]?.error).toContain("requires id");
+ // Zero applied edits emit no refinement notice.
+ expect(
+ harness.session.messages.some(
+ (message) => message.role === "custom" && message.customType === "refinement_notice",
+ ),
+ ).toBe(false);
});
it("normalizes malformed runtime extension proposals before applying them", async () => {
@@ -127,6 +139,50 @@ describe("AgentSession session_before_refine extension hook", () => {
}
});
+ it("labels auto- and self-triggered refinements in the notice", async () => {
+ const harness = await createHarness({
+ persistSession: true,
+ extensionFactories: [
+ (pi) => {
+ let round = 0;
+ pi.on("session_before_refine", async () => {
+ round += 1;
+ return {
+ proposal: {
+ summary: "auto summary",
+ rationale: "auto rationale",
+ expectedOutcome: "auto outcome",
+ edits: [
+ {
+ action: "create" as const,
+ kind: "memory" as const,
+ title: `Auto memory ${round}`,
+ content: "auto",
+ },
+ ],
+ },
+ };
+ });
+ },
+ ],
+ });
+ harnesses.push(harness);
+ harness.setResponses([]);
+ await harness.session.prompt("hello").catch(() => {});
+
+ await harness.session.refine({ instructions: "capture" }, { trigger: "auto" });
+
+ const notices = () =>
+ harness.session.messages.filter(
+ (message) => message.role === "custom" && message.customType === "refinement_notice",
+ );
+ expect(getMessageText(notices().at(-1))).toMatch(/^\[auto-refinement\]\n\n/);
+
+ // Agent-callable refine.run flows carry the explicit self source.
+ await harness.session.refine({ instructions: "capture" }, { source: "self" });
+ expect(getMessageText(notices().at(-1))).toMatch(/^\[self-refinement\]\n\n/);
+ });
+
it("skips the refinement round when an extension returns skip", async () => {
const harness = await createHarness({
persistSession: true,
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.ts
index 109e824b12..fa10a7c4d6 100644
--- a/packages/coding-agent/test/suite/agent-session-refine-skill.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-refine-skill.test.ts
@@ -181,7 +181,7 @@ describe("AgentSession refine skill host requests", () => {
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(refineSpy).toHaveBeenCalledWith({ instructions: "test", global: undefined }, { source: "self" });
expect(internals._pendingRequestedRefine).toBeUndefined();
});
diff --git a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
index d9c6e5e4b9..acd0a433e6 100644
--- a/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-retry-events.test.ts
@@ -542,6 +542,11 @@ describe("AgentSession retry and event characterization", () => {
await harness.session.prompt("hi");
expect(order).toEqual([
+ // Leading custom pair: the session-start harness digest rides the first turn.
+ "extension:message_start:custom",
+ "public:message_start:custom",
+ "extension:message_end:custom",
+ "public:message_end:custom",
"extension:message_start:user",
"public:message_start:user",
"extension:message_end:user",
@@ -563,6 +568,8 @@ describe("AgentSession retry and event characterization", () => {
expect(normalizeEventOrder(harness.events)).toEqual([
"agent_start",
"turn_start",
+ "message_start:custom",
+ "message_end:custom",
"message_start:user",
"message_end:user",
"message_start:assistant",
@@ -599,6 +606,8 @@ describe("AgentSession retry and event characterization", () => {
expect(normalizeEventOrder(harness.events)).toEqual([
"agent_start",
"turn_start",
+ "message_start:custom",
+ "message_end:custom",
"message_start:user",
"message_end:user",
"message_start:assistant",
diff --git a/packages/coding-agent/test/suite/agent-session-runtime.test.ts b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
index 7e840acc6c..cfe1b5f162 100644
--- a/packages/coding-agent/test/suite/agent-session-runtime.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-runtime.test.ts
@@ -30,6 +30,7 @@ import type {
SessionStartEvent,
} from "../../src/index.js";
import { createDefaultRuntimeFactory } from "../../src/main.js";
+import { conversationMessages } from "./harness.js";
type RecordedSessionEvent =
| SessionBeforeSwitchEvent
@@ -616,7 +617,7 @@ describe("AgentSessionRuntime characterization", () => {
expect(newSessionResult.cancelled).toBe(false);
await runtime.session.bindExtensions({});
expect(runtime.session).not.toBe(originalSession);
- expect(runtime.session.messages).toEqual([]);
+ expect(conversationMessages(runtime.session)).toEqual([]);
const secondSessionFile = runtime.session.sessionFile;
expect(events).toEqual([
{ type: "session_before_switch", reason: "new", targetSessionFile: undefined },
@@ -730,7 +731,7 @@ describe("AgentSessionRuntime characterization", () => {
expect(result).toEqual({ cancelled: false, selectedText: "Say two" });
expect(
- runtime.session.messages.map((message) =>
+ conversationMessages(runtime.session).map((message) =>
message.role === "user"
? typeof message.content === "string"
? message.content
@@ -752,7 +753,7 @@ describe("AgentSessionRuntime characterization", () => {
const result = await runtime.fork(userMessages[0]!.entryId);
expect(result).toEqual({ cancelled: false, selectedText: "Say one" });
- expect(runtime.session.messages).toEqual([]);
+ expect(conversationMessages(runtime.session)).toEqual([]);
expect(runtime.session.sessionFile).toBeUndefined();
});
@@ -761,7 +762,7 @@ describe("AgentSessionRuntime characterization", () => {
await runtime.session.prompt("hello");
await runtime.session.prompt("again");
- const beforeMessages = runtime.session.messages.map((message) => ({
+ const beforeMessages = conversationMessages(runtime.session).map((message) => ({
role: message.role,
text:
message.role === "user"
@@ -781,7 +782,7 @@ describe("AgentSessionRuntime characterization", () => {
expect(result).toEqual({ cancelled: false, selectedText: undefined });
expect(runtime.session.sessionFile).not.toBe(previousSessionFile);
expect(
- runtime.session.messages.map((message) => ({
+ conversationMessages(runtime.session).map((message) => ({
role: message.role,
text:
message.role === "user"
@@ -802,7 +803,7 @@ describe("AgentSessionRuntime characterization", () => {
await runtime.session.prompt("hello");
await runtime.session.prompt("again");
- const beforeMessages = runtime.session.messages.map((message) => ({
+ const beforeMessages = conversationMessages(runtime.session).map((message) => ({
role: message.role,
text:
message.role === "user"
@@ -822,7 +823,7 @@ describe("AgentSessionRuntime characterization", () => {
expect(result).toEqual({ cancelled: false, selectedText: undefined });
expect(runtime.session.sessionFile).toBeUndefined();
expect(
- runtime.session.messages.map((message) => ({
+ conversationMessages(runtime.session).map((message) => ({
role: message.role,
text:
message.role === "user"
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.ts
index f3409fb696..948dba16b8 100644
--- a/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-serialized-refine.test.ts
@@ -2,7 +2,7 @@ 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";
+import { createHarness, getMessageText, type Harness } from "./harness.js";
type SerializedInternals = {
_shouldStopAfterTurn(context: {
@@ -12,7 +12,7 @@ type SerializedInternals = {
newMessages: unknown[];
}): Promise<boolean>;
_runSerializedRefineCheckpoint(): Promise<void>;
- _runSerializedRefine(options: { instructions?: string; global?: boolean }): Promise<void>;
+ _runSerializedRefine(options: { instructions?: string; global?: boolean }, source: "auto" | "self"): Promise<void>;
_consumeSerializedBackgroundPlan(consume: (result: unknown) => Promise<boolean>): Promise<string>;
_runSerializedAutoRefineReview(reason: "turn_interval" | "compact", branchVersion: number): Promise<void>;
_consumePendingRequestedRefine(): boolean;
@@ -1612,7 +1612,7 @@ describe("Serialized refine review-fix regressions", () => {
await internals._drainPendingRefinementForDisposal();
expect(runSpy).toHaveBeenCalledTimes(1);
- expect(runSpy).toHaveBeenCalledWith(options);
+ expect(runSpy).toHaveBeenCalledWith(options, "self");
expect(internals._pendingRequestedRefine).toBeUndefined();
});
});
@@ -1823,11 +1823,11 @@ describe("P0 concurrency regressions", () => {
expect(applySpy).not.toHaveBeenCalled();
});
- it("non-mocked apply pipeline: harness state persisted, prompt rebuilt, refine_complete emitted", async () => {
+ it("non-mocked apply pipeline: harness state persisted, prompt untouched, notice 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.
+ // applyRefinementProposal, saveHarnessState, appends the in-context
+ // refinement notice, and emits refine_complete.
const reviewer = vi.fn(async () => ({
shouldRefine: true,
rationale: "test",
@@ -1884,10 +1884,16 @@ describe("P0 concurrency regressions", () => {
});
// Run the serialized refine (real _applyRefine runs).
- await internals._runSerializedRefine({ instructions: "add a memory" });
-
- // _rebuildSystemPrompt was called by _applyRefine.
- expect(rebuildSpy).toHaveBeenCalledTimes(1);
+ const promptBefore = harness.session.agent.state.systemPrompt;
+ await internals._runSerializedRefine({ instructions: "add a memory" }, "self");
+
+ // The cache pin: applying a refinement never rebuilds or swaps the prompt.
+ expect(rebuildSpy).not.toHaveBeenCalled();
+ expect(harness.session.agent.state.systemPrompt).toBe(promptBefore);
+ const notice = harness.session.messages.find(
+ (message) => message.role === "custom" && message.customType === "refinement_notice",
+ );
+ expect(getMessageText(notice)).toMatch(/^\[self-refinement\]\n\n/);
// Harness state persisted to disk.
const localDir = (await import("../../src/core/refinement/index.js")).getLocalHarnessStateDir(
@@ -2018,7 +2024,7 @@ describe("P0 concurrency regressions", () => {
});
// Start the serialized refine — begins background planning.
- const refinePromise = internals._runSerializedRefine({ instructions: "update shared memory" });
+ const refinePromise = internals._runSerializedRefine({ instructions: "update shared memory" }, "self");
// Wait for planning to start.
await planStartedPromise;
@@ -2174,7 +2180,7 @@ describe("P0 concurrency regressions", () => {
},
);
- const refine = internals._runSerializedRefine({ instructions: "cancel direct plan" });
+ const refine = internals._runSerializedRefine({ instructions: "cancel direct plan" }, "self");
await vi.waitFor(() => expect(planSignal).toBeDefined());
expect(internals._serializedPlanInFlight).toBeUndefined();
expect(internals._refinePlanInFlight).toBeDefined();
@@ -2212,7 +2218,7 @@ describe("P0 concurrency regressions", () => {
});
const applyRefine = vi.spyOn(internals, "_applyRefine").mockResolvedValue(emptyRefinementResult());
- const directRefine = internals._runSerializedRefine({ instructions: "direct" });
+ const directRefine = internals._runSerializedRefine({ instructions: "direct" }, "self");
await vi.waitFor(() => expect(internals._refinePlanInFlight).toBeDefined());
const publicRefine = harness.session.refine({ instructions: "public" });
@@ -2287,7 +2293,7 @@ describe("P0 concurrency regressions", () => {
await internals._runSerializedRefineCheckpoint();
- expect(run).toHaveBeenCalledWith({ instructions: "latest" });
+ expect(run).toHaveBeenCalledWith({ instructions: "latest" }, "self");
expect(internals._pendingRequestedRefine).toBeUndefined();
});
diff --git a/packages/coding-agent/test/suite/harness.ts b/packages/coding-agent/test/suite/harness.ts
index 97bda0d282..98cd048580 100644
--- a/packages/coding-agent/test/suite/harness.ts
+++ b/packages/coding-agent/test/suite/harness.ts
@@ -15,7 +15,7 @@ import { AgentSession, type AgentSessionEvent, type AutoRefineReviewer } from ".
import { AuthStorage } from "../../src/core/auth-storage.js";
import type { AgentAutonomousConfig } from "../../src/core/autonomous.js";
import type { ExtensionRunner } from "../../src/core/extensions/index.js";
-import { convertToLlm } from "../../src/core/messages.js";
+import { convertToLlm, HARNESS_DIGEST_CUSTOM_TYPE } from "../../src/core/messages.js";
import { ModelRegistry } from "../../src/core/model-registry.js";
import type { SubagentRuntimeHost } from "../../src/core/rlm-runtime.js";
import { SessionManager } from "../../src/core/session-manager.js";
@@ -47,6 +47,13 @@ export function getMessageText(message: unknown): string {
.join("\n");
}
+/** Session messages without the session-start harness digest injected at construction. */
+export function conversationMessages(source: { messages: AgentMessage[] }): AgentMessage[] {
+ return source.messages.filter(
+ (message) => !(message.role === "custom" && message.customType === HARNESS_DIGEST_CUSTOM_TYPE),
+ );
+}
+
export function getUserTexts(harness: Harness): string[] {
return harness.session.messages
.filter((message) => message.role === "user")
@@ -73,6 +80,8 @@ export interface HarnessOptions {
agentMessageController?: AgentSessionMessageController;
subagentRuntimeHost?: SubagentRuntimeHost;
persistSession?: boolean;
+ /** Resume over an existing session file, mirroring production rehydration. */
+ existingSessionFile?: string;
rlmDepth?: number;
rlmMaxDepth?: number;
autonomous?: AgentAutonomousConfig;
@@ -118,9 +127,11 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
const withConfiguredAuth = options.withConfiguredAuth ?? true;
const extensionRunnerRef: { current?: ExtensionRunner } = {};
- const sessionManager = options.persistSession
- ? SessionManager.create(tempDir, join(tempDir, "sessions"))
- : SessionManager.inMemory();
+ const sessionManager = options.existingSessionFile
+ ? SessionManager.open(options.existingSessionFile)
+ : options.persistSession
+ ? SessionManager.create(tempDir, join(tempDir, "sessions"))
+ : SessionManager.inMemory();
const settingsManager = SettingsManager.inMemory(options.settings);
const authStorage = AuthStorage.inMemory();
@@ -179,6 +190,9 @@ export async function createHarness(options: HarnessOptions = {}): Promise<Harne
return runner.emitContext(messages);
},
});
+ if (options.existingSessionFile) {
+ agent.state.messages = sessionManager.buildSessionContext().messages;
+ }
const extensionsResult = options.extensionFactories
? await createTestExtensionsResult(options.extensionFactories, tempDir)
: undefined;
diff --git a/packages/coding-agent/test/suite/regressions/2860-replaced-session-context.test.ts b/packages/coding-agent/test/suite/regressions/2860-replaced-session-context.test.ts
index 651061a41d..9825f73cde 100644
--- a/packages/coding-agent/test/suite/regressions/2860-replaced-session-context.test.ts
+++ b/packages/coding-agent/test/suite/regressions/2860-replaced-session-context.test.ts
@@ -13,6 +13,7 @@ import {
import { AuthStorage } from "../../../src/core/auth-storage.js";
import { SessionManager } from "../../../src/core/session-manager.js";
import type { ExtensionAPI, ExtensionCommandContext, ExtensionFactory } from "../../../src/index.js";
+import { conversationMessages } from "../harness.js";
function getText(message: AgentSession["messages"][number]): string {
if (!("content" in message)) {
@@ -196,7 +197,7 @@ describe("regression #2860: replaced session callbacks", () => {
expect(replacementSessionFile).not.toBe(oldSessionFile);
expect(staleCtxThrows).toBe(true);
expect(stalePiThrows).toBe(true);
- expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
+ expect(conversationMessages(runtime.session).map((message) => `${message.role}:${getText(message)}`)).toEqual([
"user:Hello from the new session!",
"assistant:hello reply",
]);
@@ -227,7 +228,7 @@ describe("regression #2860: replaced session callbacks", () => {
await runtime.session.prompt("seed");
await runtime.session.prompt("/fork-it");
- expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
+ expect(conversationMessages(runtime.session).map((message) => `${message.role}:${getText(message)}`)).toEqual([
"user:seed",
"assistant:seed reply",
"user:fork callback message",
@@ -264,7 +265,7 @@ describe("regression #2860: replaced session callbacks", () => {
await runtime.session.prompt("/switch-it");
expect(runtime.session.sessionFile).toBe(targetSessionPath);
- expect(runtime.session.messages.map((message) => `${message.role}:${getText(message)}`)).toEqual([
+ expect(conversationMessages(runtime.session).map((message) => `${message.role}:${getText(message)}`)).toEqual([
"user:target",
"assistant:target reply",
"user:switch callback message",
diff --git a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
index 394f860d78..266f3ab772 100644
--- a/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4482-heartbeat-injected-prompt.test.ts
@@ -12,7 +12,7 @@ import {
} from "../../../src/modes/interactive/components/injected-prompt-message.js";
import { InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
import { getMarkdownTheme, initTheme } from "../../../src/modes/interactive/theme/theme.js";
-import { createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
+import { conversationMessages, createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
type AddMessageToChatHost = {
addMessageToChat(
@@ -124,12 +124,12 @@ describe("ENG-4482 heartbeat injected prompt UI", () => {
await harness.session.promptHeartbeat(createHeartbeat());
expect(getUserTexts(harness)).toEqual([]);
- expect(harness.session.messages[0]).toMatchObject({
+ expect(conversationMessages(harness.session)[0]).toMatchObject({
role: "custom",
customType: HEARTBEAT_PROMPT_CUSTOM_TYPE,
display: true,
});
- expect(getMessageText(harness.session.messages[0])).toBe(
+ expect(getMessageText(conversationMessages(harness.session)[0])).toBe(
"Check whether the long-running task needs another step.",
);
expect(providerMessages.at(-1)).toMatchObject({ role: "user" });
diff --git a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
index 99520639e8..b1a56f5a10 100644
--- a/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4509-side-questions.test.ts
@@ -41,6 +41,7 @@ describe("ENG-4509 side questions", () => {
expect(context.systemPrompt).toBe(systemPromptBefore);
expect(context.tools).toEqual([]);
expect(context.messages.map(getMessageText)).toEqual([
+ expect.stringContaining("The persistent memories produced across this session so far:"),
"The project codename is kestrel.",
"The codename is kestrel.",
expect.stringContaining("What is the project codename?"),
@@ -81,6 +82,7 @@ describe("ENG-4509 side questions", () => {
(context) => {
const texts = context.messages.map(getMessageText);
expect(texts).toEqual([
+ expect.stringContaining("The persistent memories produced across this session so far:"),
"Main context message.",
"main answer",
expect.stringContaining("First side question?"),
@@ -89,8 +91,8 @@ describe("ENG-4509 side questions", () => {
]);
expect(context.tools).toEqual([]);
// The instruction is repeated only on the first side turn.
- expect(texts[2]).toContain("Answer this side question");
- expect(texts[4]).not.toContain("Answer this side question");
+ expect(texts[3]).toContain("Answer this side question");
+ expect(texts[5]).not.toContain("Answer this side question");
return fauxAssistantMessage("second side answer");
},
]);
@@ -159,6 +161,7 @@ describe("ENG-4509 side questions", () => {
(context) => {
expect(context.tools).toEqual([]);
expect(context.messages.map(getMessageText)).toEqual([
+ expect.stringContaining("The persistent memories produced across this session so far:"),
"Run the main task.",
expect.stringContaining("Can I ask this concurrently?"),
]);
diff --git a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
index 85a7359a88..68808bf80d 100644
--- a/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4530-ipython-state-restore-message.test.ts
@@ -13,7 +13,7 @@ import {
isInjectedPromptMessage,
} from "../../../src/modes/interactive/components/injected-prompt-message.js";
import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
-import { createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
+import { conversationMessages, createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
type StateRestoreHost = {
_onIpythonStateRestored(result: RestoreResult): void;
@@ -154,7 +154,7 @@ describe("ENG-4530 IPython state restore message", () => {
expect(
queued?.payload.kind === "turn" ? queued.payload.records.filter((record) => record.role === "prefix") : [],
).toEqual([]);
- expect(harness.session.messages).toEqual([
+ expect(conversationMessages(harness.session)).toEqual([
expect.objectContaining({ customType: IPYTHON_STATE_RESTORED_CUSTOM_TYPE }),
]);
});
diff --git a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
index e16dc56287..abf65a9376 100644
--- a/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4531-agent-message-ui.test.ts
@@ -23,7 +23,7 @@ import {
import { IPythonCellComponent } from "../../../src/modes/interactive/components/ipython-cell.js";
import { formatQueuedMessagePreview, InteractiveMode } from "../../../src/modes/interactive/interactive-mode.js";
import { initTheme } from "../../../src/modes/interactive/theme/theme.js";
-import { createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
+import { conversationMessages, createHarness, getMessageText, getUserTexts, type Harness } from "../harness.js";
function createPayload(message: string): AgentSessionMessagePayload {
return {
@@ -89,7 +89,7 @@ describe("ENG-4531 agent message UI", () => {
await harness.session.agent.waitForIdle();
expect(getUserTexts(harness)).toEqual([]);
- expect(harness.session.messages[0]).toMatchObject({
+ expect(conversationMessages(harness.session)[0]).toMatchObject({
role: "custom",
customType: "agent_message",
display: true,
@@ -113,7 +113,7 @@ describe("ENG-4531 agent message UI", () => {
await harness.session.agent.waitForIdle();
expect(getUserTexts(harness)).toEqual([prompt]);
- expect(harness.session.messages[0]?.role).toBe("user");
+ expect(conversationMessages(harness.session)[0]?.role).toBe("user");
});
it("preserves structured messages passed through the normal prompt path", async () => {
@@ -130,7 +130,7 @@ describe("ENG-4531 agent message UI", () => {
await harness.session.agent.waitForIdle();
expect(getUserTexts(harness)).toEqual([]);
- expect(harness.session.messages[0]).toMatchObject({
+ expect(conversationMessages(harness.session)[0]).toMatchObject({
role: "custom",
customType: "agent_message",
details: { id: "agentmsg_4531", message: "Run the idle-session review." },
diff --git a/packages/coding-agent/test/suite/regressions/4620-fast-mode-empty-resume.test.ts b/packages/coding-agent/test/suite/regressions/4620-fast-mode-empty-resume.test.ts
index ef82c957f9..8dcde81cb5 100644
--- a/packages/coding-agent/test/suite/regressions/4620-fast-mode-empty-resume.test.ts
+++ b/packages/coding-agent/test/suite/regressions/4620-fast-mode-empty-resume.test.ts
@@ -3,7 +3,7 @@ import { afterEach, describe, expect, it } from "vitest";
import type { AgentSession } from "../../../src/core/agent-session.js";
import { createAgentSession } from "../../../src/core/sdk.js";
import { createTestResourceLoader } from "../../utilities.js";
-import { createHarness, type Harness } from "../harness.js";
+import { conversationMessages, createHarness, type Harness } from "../harness.js";
describe("ENG-4620 fast mode empty resume", () => {
let harness: Harness | undefined;
@@ -43,7 +43,7 @@ describe("ENG-4620 fast mode empty resume", () => {
const { session } = await createSession();
sessions.push(session);
session.setServiceTier("priority");
- expect(session.messages).toHaveLength(0);
+ expect(conversationMessages(session)).toHaveLength(0);
session.dispose();
const { session: resumedSession } = await createSession();
diff --git a/packages/coding-agent/test/system-prompt.test.ts b/packages/coding-agent/test/system-prompt.test.ts
index 41b038c672..dde3273f62 100644
--- a/packages/coding-agent/test/system-prompt.test.ts
+++ b/packages/coding-agent/test/system-prompt.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
import { buildRlmPrompt } from "../src/core/prompts/index.js";
-import type { HarnessState } from "../src/core/refinement/index.js";
+import { formatHarnessStateForPrompt, type HarnessState } from "../src/core/refinement/index.js";
import type { Skill } from "../src/core/skills.js";
import { buildSystemPrompt } from "../src/core/system-prompt.js";
import { createIpythonToolDefinition } from "../src/core/tools/ipython.js";
@@ -235,7 +235,7 @@ describe("buildSystemPrompt", () => {
expect(shellPrompt).not.toContain("Generic MCP Connections");
});
- test("injects compact global harness context and refine guidance by default", () => {
+ test("formats the harness digest with refine guidance for REPL sessions", () => {
const harnessState: HarnessState = {
schema: 1,
entries: {
@@ -323,13 +323,10 @@ describe("buildSystemPrompt", () => {
],
};
- const prompt = buildSystemPrompt({
- selectedTools: ["ipython"],
- contextFiles: [],
- skills: [pythonSkill("refine"), pythonSkill("agent-message"), pythonSkill("agent-observe")],
- cwd: "/repo",
- messagesPath: "/repo/.pi/sessions/session.jsonl",
- harnessState,
+ const prompt = formatHarnessStateForPrompt(harnessState, {
+ includeIpythonExamples: true,
+ includeShellExamples: false,
+ includeRefineExamples: true,
});
expect(prompt).toContain("# Continual Harness State");
@@ -361,10 +358,29 @@ describe("buildSystemPrompt", () => {
expect(prompt).toContain("[global:refinement_reviewer] Refinement reviewer (review, v1)");
expect(prompt).toContain("recent refinements: 1");
expect(prompt).toContain("[refine_1] Observed validation miss: create memory:validation");
- expect(prompt.indexOf("# Continual Harness State")).toBeGreaterThan(prompt.indexOf("Conversation log:"));
});
- test("keeps injected harness context compact", () => {
+ test("system prompts no longer embed harness state", () => {
+ const rlmPrompt = buildSystemPrompt({
+ selectedTools: ["ipython"],
+ contextFiles: [],
+ skills: [pythonSkill("refine")],
+ cwd: "/repo",
+ messagesPath: "/repo/.pi/sessions/session.jsonl",
+ });
+ const customPrompt = buildSystemPrompt({
+ customPrompt: "custom body",
+ selectedTools: ["ipython"],
+ contextFiles: [],
+ skills: [],
+ cwd: "/repo",
+ });
+
+ expect(rlmPrompt).not.toContain("# Continual Harness State");
+ expect(customPrompt).not.toContain("# Continual Harness State");
+ });
+
+ test("keeps the harness digest compact", () => {
const longContent = "x".repeat(500);
const memoryEntries: HarnessState["entries"]["memory"] = {};
for (let i = 0; i < 8; i++) {
@@ -394,13 +410,7 @@ describe("buildSystemPrompt", () => {
refinements: [],
};
- const prompt = buildSystemPrompt({
- selectedTools: ["ipython"],
- contextFiles: [],
- skills: [],
- cwd: "/repo",
- harnessState,
- });
+ const prompt = formatHarnessStateForPrompt(harnessState);
expect(prompt).toContain("memory: 8");
expect(prompt).toContain("- +2 more memory entries");
@@ -466,19 +476,22 @@ describe("buildSystemPrompt", () => {
skills: [],
cwd: "/repo",
messagesPath: "/repo/.pi/sessions/session.jsonl",
- harnessState,
+ });
+ const digest = formatHarnessStateForPrompt(harnessState, {
+ includeIpythonExamples: false,
+ includeShellExamples: true,
});
expect(prompt).toContain("You are a general purpose agent that uses code to solve tasks.");
- expect(prompt).toContain("# Continual Harness State");
- expect(prompt).toContain("Call contract: use installed skills as shell commands");
- expect(prompt).toContain("subagent: 1");
expect(prompt).not.toContain("persistent Python REPL");
expect(prompt).not.toContain("Default to non-blocking subagents");
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()");
+ expect(digest).toContain("# Continual Harness State");
+ expect(digest).toContain("Call contract: use installed skills as shell commands");
+ expect(digest).toContain("subagent: 1");
+ expect(digest).not.toContain("asyncio.create_task");
+ expect(digest).not.toContain("await <skill_import>");
+ expect(digest).not.toContain("await refine.run()");
});
test("omits shell guidance from harness state when shell is inactive", () => {
@@ -507,51 +520,21 @@ describe("buildSystemPrompt", () => {
},
refinements: [],
};
- const prompt = buildSystemPrompt({
- selectedTools: ["edit"],
- contextFiles: [],
- skills: [],
- cwd: "/repo",
- messagesPath: "/repo/.pi/sessions/session.jsonl",
- harnessState,
+ const digest = formatHarnessStateForPrompt(harnessState, {
+ includeIpythonExamples: false,
+ includeShellExamples: false,
});
- expect(prompt).toContain("# Continual Harness State");
- expect(prompt).toContain("without the Python REPL or shell access");
- expect(prompt).not.toContain("use installed skills as shell commands");
- 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()");
+ expect(digest).toContain("# Continual Harness State");
+ expect(digest).toContain("without the Python REPL or shell access");
+ expect(digest).not.toContain("use installed skills as shell commands");
+ expect(digest).not.toContain("<skill_import> ...");
+ expect(digest).not.toContain("asyncio.create_task");
+ expect(digest).not.toContain("await <skill_import>");
+ expect(digest).not.toContain("await refine.run()");
});
test("custom prompt override bypasses the rlm harness body", () => {
- const harnessState: HarnessState = {
- schema: 1,
- entries: {
- prompt: {},
- memory: {
- custom_memory: {
- id: "custom_memory",
- kind: "memory",
- title: "Custom memory",
- content: "Custom prompts still receive harness state.",
- path: "custom",
- reference: {},
- arguments: {},
- metadata: {},
- source: "refine",
- created_at: "2026-06-08T00:00:00.000Z",
- updated_at: "2026-06-08T00:00:00.000Z",
- version: 1,
- },
- },
- skill: {},
- subagent: {},
- },
- refinements: [],
- };
-
const prompt = buildSystemPrompt({
customPrompt: "custom body",
selectedTools: ["ipython"],
@@ -559,19 +542,12 @@ describe("buildSystemPrompt", () => {
contextFiles: [],
skills: [],
cwd: "/repo",
- harnessState,
});
expect(prompt).toContain("custom body");
- expect(prompt).toContain("# Continual Harness State");
- expect(prompt).toContain("[global:custom_memory] Custom memory (custom, v1)");
expect(prompt).not.toContain("# IPython Kernel Guidance");
expect(prompt).not.toContain("You are a general purpose agent that uses code to solve tasks.");
- expect(prompt.indexOf("Current working directory: /repo")).toBeLessThan(
- prompt.indexOf("# Continual Harness State"),
- );
expect(prompt.indexOf("Current working directory: /repo")).toBeLessThan(prompt.indexOf("custom append"));
- expect(prompt.indexOf("# Continual Harness State")).toBeLessThan(prompt.indexOf("custom append"));
});
test("adds child reply doctrine to custom prompts when messaging is available", () => {