A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI, performance] Stabilize continual-harness prompt material for prompt-cache hits (#2400)
Seth Karten6d2c57d72235
diff --git a/packages/coding-agent/.changes/stable-harness-digest-cache.md b/packages/coding-agent/.changes/stable-harness-digest-cache.mdnew file mode 100644index 0000000000..2f97a0d1cf--- /dev/null+++ b/packages/coding-agent/.changes/stable-harness-digest-cache.md@@ -0,0 +1 @@+- Fixed harness digest re-delivery busting the provider prompt cache: cold boundaries (resume, context rebuild, post-compaction head) now compare a harness state fingerprint instead of the rendered digest text, so unchanged harness state no longer re-delivers a digest that turn-drifted relevance terms made look stale; the compaction summary carries the fingerprint for the same skip rule, and ranked digests break score ties on stable identifier order instead of `updated_at` recency so an unrelated entry update can no longer reshuffle the visible window.diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.tsindex 92b2427680..01bedd69d5 100644--- a/packages/coding-agent/src/core/agent-session.ts+++ b/packages/coding-agent/src/core/agent-session.ts@@ -234,6 +234,7 @@ import {getRefinementHistory,type HarnessQueryTerms,type HarnessState,+ harnessDigestFingerprint,harnessQueryTerms,inferRefinementResultScope,loadGlobalRefinementHistory,@@ -6897,9 +6898,13 @@ export class AgentSession {// 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 { digest, stateFingerprint } = this._harnessDigestWithFingerprint();+ const latest = this._latestContextHarnessDigestDetails();+ if (!latest || !this._harnessDigestIsFresh(latest, digest, stateFingerprint)) {+ nextTurnMessages = [+ createHarnessDigestMessage(digest, Date.now(), stateFingerprint),+ ...nextTurnMessages,+ ];}}const contextRecords = nextTurnMessages.map((message) =>@@ -8546,6 +8551,8 @@ export class AgentSession {}this._semanticEdges.finishCompaction(semanticCompaction.compactionId, "completed");// Attached mechanically; the digest never flows through the summarizer LLM.+ const { digest: harnessDigest, stateFingerprint: harnessStateFingerprint } =+ this._harnessDigestWithFingerprint();this.sessionManager.appendCompaction(summary,firstKeptEntryId,@@ -8554,7 +8561,8 @@ export class AgentSession {fromExtension,customInstructions,usage,- this._harnessDigest(),+ harnessDigest,+ harnessStateFingerprint,);} catch (error) {compactionSettled = true;@@ -9091,18 +9099,47 @@ export class AgentSession {);}- /** The compact harness digest delivered at cold context boundaries (session start, resume, compaction head). */- private _harnessDigest(): string {+ /**+ * Harness digest material loaded exactly once per digest build: the merged+ * state plus the render options (including the current query terms).+ */+ private _harnessDigestMaterial(): {+ state: HarnessState;+ options: {+ includeIpythonExamples: boolean;+ includeShellExamples: boolean;+ includeRefineExamples: boolean;+ queryTerms: HarnessQueryTerms;+ };+ } {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,- queryTerms: this._buildHarnessDigestQueryTerms(),- });+ return {+ state: this._loadMergedHarnessState(),+ options: {+ includeIpythonExamples: hasIpython,+ includeShellExamples: tools.includes("bash"),+ includeRefineExamples: hasIpython && hasRefineSkill,+ queryTerms: this._buildHarnessDigestQueryTerms(),+ },+ };+ }++ /**+ * Digest plus the fingerprint of the state that produced it. Cold boundaries+ * compare fingerprints instead of rendered text: relevance query terms+ * change per turn, so a rendered-text comparison re-delivers an unchanged+ * digest (and busts the provider prefix cache) at every boundary.+ */+ private _harnessDigestWithFingerprint(): { digest: string; stateFingerprint: string } {+ const { state, options } = this._harnessDigestMaterial();+ const { queryTerms: _queryTerms, ...renderFlags } = options;+ return {+ digest: formatHarnessStateForPrompt(state, options),+ stateFingerprint: harnessDigestFingerprint(state, renderFlags),+ };}/**@@ -9155,9 +9192,10 @@ export class AgentSession {}private _appendHarnessDigestIfStale(): void {- const digest = this._harnessDigest();- if (this._latestContextHarnessDigest() === digest) return;- const message = createHarnessDigestMessage(digest);+ const { digest, stateFingerprint } = this._harnessDigestWithFingerprint();+ const latest = this._latestContextHarnessDigestDetails();+ if (latest && this._harnessDigestIsFresh(latest, digest, stateFingerprint)) return;+ const message = createHarnessDigestMessage(digest, Date.now(), stateFingerprint);try {this.sessionManager.appendCustomMessageEntryWithRollback(message.customType,@@ -9171,23 +9209,48 @@ export class AgentSession {this.agent.state.messages.push(message);}- private _latestContextHarnessDigest(): string | undefined {+ /**+ * Whether the newest in-context digest already reflects the current harness+ * state. A digest is fresh when its state fingerprint matches the current+ * one; a digest without a fingerprint is compared by rendered+ * text instead.+ */+ private _harnessDigestIsFresh(+ latest: { digest: string; stateFingerprint?: string },+ freshDigest: string,+ freshFingerprint: string,+ ): boolean {+ return latest.stateFingerprint !== undefined+ ? latest.stateFingerprint === freshFingerprint+ : latest.digest === freshDigest;+ }++ private _latestContextHarnessDigestDetails():+ | { timestamp: number; digest: string; stateFingerprint?: string }+ | undefined {// Retained pre-compaction messages follow the compaction head, so recency is by timestamp, not position.- let latest: { timestamp: number; digest: string } | undefined;+ let latest: { timestamp: number; digest: string; stateFingerprint?: 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;+ const details = message.details as HarnessDigestDetails | undefined;+ if (details?.digest !== undefined && (!latest || message.timestamp >= latest.timestamp)) {+ latest = {+ timestamp: message.timestamp,+ digest: details.digest,+ stateFingerprint: details.stateFingerprint,+ };+ }} else if (message.role === "compactionSummary") {- digest = message.harnessDigest;- } else {- continue;- }- if (digest !== undefined && (!latest || message.timestamp >= latest.timestamp)) {- latest = { timestamp: message.timestamp, digest };+ if (message.harnessDigest !== undefined && (!latest || message.timestamp >= latest.timestamp)) {+ latest = {+ timestamp: message.timestamp,+ digest: message.harnessDigest,+ stateFingerprint: message.harnessStateFingerprint,+ };+ }}}- return latest?.digest;+ return latest;}/** Global harness state overlaid with this session's local state, when persisted. */diff --git a/packages/coding-agent/src/core/messages.ts b/packages/coding-agent/src/core/messages.tsindex fce065d42e..50270e113d 100644--- a/packages/coding-agent/src/core/messages.ts+++ b/packages/coding-agent/src/core/messages.ts@@ -189,6 +189,8 @@ export interface McpConnectionOutcomeMessage extends CustomMessage<McpOutcomeDetexport interface HarnessDigestDetails {digest: string;+ /** Fingerprint of the harness state at delivery time; cold boundaries skip re-delivery when it still matches. */+ stateFingerprint?: string;}export const HARNESS_DIGEST_PREFIX = `[harness-digest]@@ -204,13 +206,14 @@ export const HARNESS_DIGEST_SUFFIX = `export function createHarnessDigestMessage(digest: string,timestamp = Date.now(),+ stateFingerprint?: string,): CustomMessage<HarnessDigestDetails> {return {role: "custom",customType: HARNESS_DIGEST_CUSTOM_TYPE,content: HARNESS_DIGEST_PREFIX + digest + HARNESS_DIGEST_SUFFIX,display: false,- details: { digest },+ details: { digest, ...(stateFingerprint ? { stateFingerprint } : {}) },timestamp,};}@@ -356,6 +359,8 @@ export interface CompactionSummaryMessage {customInstructions?: string;/** Harness digest snapshot rendered before the summary in LLM context. Attached mechanically at compaction, never summarized. */harnessDigest?: string;+ /** Fingerprint of the harness state behind `harnessDigest` at compaction time; lets cold boundaries skip re-delivery. */+ harnessStateFingerprint?: string;timestamp: number;}@@ -422,6 +427,7 @@ export function createCompactionSummaryMessage(customInstructions?: string,retainedMessageCount?: number,harnessDigest?: string,+ harnessStateFingerprint?: string,): CompactionSummaryMessage {return {role: "compactionSummary",@@ -430,6 +436,7 @@ export function createCompactionSummaryMessage(retainedMessageCount,customInstructions,harnessDigest,+ harnessStateFingerprint,timestamp: new Date(timestamp).getTime(),};}diff --git a/packages/coding-agent/src/core/refinement/refinement.ts b/packages/coding-agent/src/core/refinement/refinement.tsindex 84557210f9..28f5badf05 100644--- a/packages/coding-agent/src/core/refinement/refinement.ts+++ b/packages/coding-agent/src/core/refinement/refinement.ts@@ -1,3 +1,4 @@+import { createHash } from "node:crypto";import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";import type { AgentMessage, ThinkingLevel } from "@earendil-works/pi-agent-core";@@ -20,6 +21,17 @@ const DEFAULT_OVERVIEW_ENTRY_LIMIT = 6;const DEFAULT_OVERVIEW_REFINEMENT_LIMIT = 5;const DEFAULT_OVERVIEW_CONTENT_LIMIT = 180;+/**+ * Bump when the fingerprinted material or its canonical serialization changes,+ * so fingerprints minted under different versions never compare equal.+ * Normalizing a render-ignored flag out of the material does not need a+ * bump: fingerprint equality still implies identical renders (with IPython+ * examples off the normalization is a no-op; with them on, equality means+ * the shell flag was already false, i.e. identical renders), so equality+ * across the change is render-safe.+ */+const HARNESS_DIGEST_FINGERPRINT_VERSION = 1;+export type RefinementKind = "prompt" | "memory" | "skill" | "subagent";export type RefinementAction = "create" | "update" | "delete";export type HarnessScope = "local" | "global";@@ -587,9 +599,9 @@ function compareRankedHarnessEntries(): number {const scoreDifference = scoreHarnessEntryForQuery(b, terms, idf) - scoreHarnessEntryForQuery(a, terms, idf);if (scoreDifference !== 0) return scoreDifference;- // Recency breaks ties; alphabetical order keeps selection deterministic.- const recencyDifference = (Date.parse(b.updated_at) || 0) - (Date.parse(a.updated_at) || 0);- if (recencyDifference !== 0) return recencyDifference;+ // Equal scores tie on stable identifier order (path, title, id), so+ // touching unrelated entries never reshuffles equal-score siblings and the+ // rendered digest keeps a stable prefix for provider prompt-cache reuse.return [a.path, a.title, a.id].join("\0").localeCompare([b.path, b.title, b.id].join("\0"));}@@ -700,6 +712,70 @@ export function formatHarnessStateForPrompt(return lines.join("\n").trim();}+/**+ * Stable fingerprint of the harness material a digest renders. Equal states+ * (per the fields the digest actually prints) produce equal fingerprints, so+ * cold boundaries can skip digest re-delivery with a state comparison instead+ * of a rendered-text comparison that query-term relevance keeps invalidating.+ *+ * Covered: entry identity and content (entry order is normalized away, as is+ * the call contract on non-skill entries, which the formatter never prints),+ * plus the render flags and each refinement's printed fields in stored order,+ * since the formatter renders a positional newest tail. The shell-examples+ * flag participates only when IPython examples are not rendered: the formatter+ * never reads it then, so it is normalized out of the fingerprint to keep an+ * unchanged digest fresh. Excluded: `metadata`, `source`, and the invisible+ * `created_at`/`updated_at` bookkeeping, and relevance query terms (the+ * digest stays frozen per delivery; see `compareRankedHarnessEntries`).+ */+export function harnessDigestFingerprint(+ state: HarnessState,+ renderFlags: {+ includeIpythonExamples: boolean;+ includeShellExamples: boolean;+ includeRefineExamples: boolean;+ },+): string {+ const entries = (Object.keys(state.entries) as RefinementKind[])+ .flatMap((kind) => Object.values(state.entries[kind]))+ .map((entry) => ({+ scope: entry.scope ?? "global",+ kind: entry.kind,+ id: entry.id,+ title: entry.title,+ path: entry.path,+ version: entry.version,+ content: entry.content,+ // Only skills render the kernel call contract, so another kind can+ // change these fields without changing a single digest byte.+ reference: entry.kind === "skill" ? entry.reference : undefined,+ arguments: entry.kind === "skill" ? entry.arguments : undefined,+ }))+ .sort((a, b) => [a.scope, a.kind, a.id].join("\0").localeCompare([b.scope, b.kind, b.id].join("\0")));+ // Refinements keep their stored order: the formatter renders the newest+ // tail of the array, so an order-only change renders differently and must+ // not reuse the previous digest.+ const refinements = state.refinements.map((event) => ({+ id: event.id,+ trigger: event.trigger,+ changes: event.changes,+ outcome: event.outcome,+ }));+ // The formatter renders the shell call-contract only when IPython examples+ // are absent, so the shell flag cannot change the digest while IPython+ // examples take precedence; fingerprint only the flags the render reads.+ const effectiveRenderFlags = renderFlags.includeIpythonExamples+ ? { ...renderFlags, includeShellExamples: false }+ : renderFlags;+ const material = JSON.stringify({+ version: HARNESS_DIGEST_FINGERPRINT_VERSION,+ renderFlags: effectiveRenderFlags,+ entries,+ refinements,+ });+ return createHash("sha256").update(material).digest("hex");+}+function overviewForPrompt(state: HarnessState): string {const lines: string[] = [];for (const kind of Object.keys(state.entries) as RefinementKind[]) {diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.tsindex 0b6f2b16a7..7ca9043d91 100644--- a/packages/coding-agent/src/core/session-manager.ts+++ b/packages/coding-agent/src/core/session-manager.ts@@ -131,6 +131,8 @@ export interface CompactionEntry<T = unknown> extends SessionEntryBase {usage?: Usage;/** Harness digest snapshot taken at compaction time; rendered before the summary in LLM context. */harnessDigest?: string;+ /** Fingerprint of the harness state behind `harnessDigest` at compaction time; lets cold boundaries skip re-delivery. */+ harnessStateFingerprint?: string;}export interface BranchSummaryEntry<T = unknown> extends SessionEntryBase {@@ -536,6 +538,7 @@ export function buildSessionContext(compaction.customInstructions,retainedMessages.length,compaction.harnessDigest,+ compaction.harnessStateFingerprint,),...retainedMessages,);@@ -1809,6 +1812,7 @@ export class SessionManager {customInstructions?: string,usage?: Usage,harnessDigest?: string,+ harnessStateFingerprint?: string,): string {const entry: CompactionEntry<T> = {type: "compaction",@@ -1823,6 +1827,7 @@ export class SessionManager {customInstructions,usage,harnessDigest,+ harnessStateFingerprint,};this._appendEntry(entry);return entry.id;diff --git a/packages/coding-agent/test/agent-session-recursion.test.ts b/packages/coding-agent/test/agent-session-recursion.test.tsindex 5e651f3ad9..637162cdb3 100644--- a/packages/coding-agent/test/agent-session-recursion.test.ts+++ b/packages/coding-agent/test/agent-session-recursion.test.ts@@ -2830,7 +2830,11 @@ describe("AgentSession RLM session dir", () => {);const root = createSession(SessionManager.inMemory(tempDir), undefined, undefined, false, ephemeralDir);- const digest = (root as unknown as { _harnessDigest(): string })._harnessDigest();+ const digest = (+ root as unknown as {+ _harnessDigestWithFingerprint(): { digest: string; stateFingerprint: string };+ }+ )._harnessDigestWithFingerprint().digest;expect(root.systemPrompt).not.toContain("Ephemeral note");expect(digest).toContain("Ephemeral note");diff --git a/packages/coding-agent/test/refinement.test.ts b/packages/coding-agent/test/refinement.test.tsindex 61714f05fc..1983a76f4f 100644--- a/packages/coding-agent/test/refinement.test.ts+++ b/packages/coding-agent/test/refinement.test.ts@@ -983,6 +983,22 @@ describe("harness digest relevance ranking", () => {expect(() => formatHarnessStateForPrompt(state, { queryTerms: new Map([["worktree", 1]]) })).not.toThrow();});+ it("breaks score ties by stable identifier order, not recency", () => {+ const state = loadHarnessState(join(makeTempDir(), "h2"), "local");+ const older = makeEntry("aaa", "Worktree policy", "Same worktree signal.", "2026-08-01T00:00:00.000Z");+ const newer = makeEntry("zzz", "Worktree policy", "Same worktree signal.", "2026-09-01T00:00:00.000Z");+ state.entries.memory.aaa = older;+ state.entries.memory.zzz = newer;+ const ranked = formatHarnessStateForPrompt(state, {+ maxEntriesPerKind: 1,+ queryTerms: new Map([["worktree", 1]]),+ });+ // Equal scores render in stable identifier order ([path, title, id]);+ // updated_at recency must not hoist the newer entry into the window.+ expect(ranked).toContain("[global:aaa]");+ expect(ranked).not.toContain("[global:zzz]");+ });+it.each<[string, string[]]>([["Worktree?", ["worktree"]],["path/to/skill", ["path", "skill"]],diff --git a/packages/coding-agent/test/suite/agent-session-compaction.test.ts b/packages/coding-agent/test/suite/agent-session-compaction.test.tsindex 4739d80b64..119a41a3bb 100644--- a/packages/coding-agent/test/suite/agent-session-compaction.test.ts+++ b/packages/coding-agent/test/suite/agent-session-compaction.test.ts@@ -1,4 +1,6 @@-import { appendFileSync } from "node:fs";+import { appendFileSync, mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import type { AgentMessage, ShouldStopAfterTurnContext } from "@earendil-works/pi-agent-core";import {type AssistantMessage,@@ -9,7 +11,7 @@ import {type Usage,} from "@earendil-works/pi-ai";import { Type } from "typebox";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import { ENV_AGENT_DIR } from "../../src/config.js";import type { AgentSession } from "../../src/core/agent-session.js";import type { ExtensionFactory } from "../../src/core/extensions/types.js";@@ -160,6 +162,7 @@ function setStreaming(harness: Harness, streaming: boolean): void {describe("AgentSession compaction", () => {const harnesses: Harness[] = [];+ const tempDirs: string[] = [];beforeEach(() => {vi.useRealTimers();@@ -172,6 +175,10 @@ describe("AgentSession compaction", () => {while (harnesses.length > 0) {harnesses.pop()?.cleanup();}+ while (tempDirs.length > 0) {+ const dir = tempDirs.pop();+ if (dir) rmSync(dir, { recursive: true, force: true });+ }});/** Tool-loop turn whose trailing tool result pushes the context past the threshold. */@@ -269,6 +276,17 @@ describe("AgentSession compaction", () => {});it("prepends the harness digest to the compaction head message on initial and update-merge compactions", async () => {+ // Hermetic global store: the ambient developer harness would crowd the+ // ranked digest window and hide the local fixture entry.+ const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;+ const agentDir = join(tmpdir(), `pi-compaction-digest-${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({settings: { compaction: { keepRecentTokens: 1 } },persistSession: true,diff --git a/packages/coding-agent/test/suite/agent-session-prompt.test.ts b/packages/coding-agent/test/suite/agent-session-prompt.test.tsindex 274fc5eccd..942ffd1e3d 100644--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts@@ -6,7 +6,12 @@ import { fauxAssistantMessage, fauxToolCall } from "@earendil-works/pi-ai";import { Type } from "typebox";import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";import type { BashResult } from "../../src/core/bash-executor.js";-import { convertToLlm, HARNESS_DIGEST_CUSTOM_TYPE } from "../../src/core/messages.js";+import {+ convertToLlm,+ HARNESS_DIGEST_CUSTOM_TYPE,+ HARNESS_DIGEST_PREFIX,+ HARNESS_DIGEST_SUFFIX,+} 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";@@ -962,10 +967,9 @@ describe("Harness digest at cold boundaries", () => {expect(harness.session.messages[0]).toMatchObject({ role: "custom", customType: HARNESS_DIGEST_CUSTOM_TYPE });});- 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.+ function isolatedAgentDir(prefix: string): string {const previousAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR;- const agentDir = join(tmpdir(), `pi-digest-agent-${Date.now()}-${Math.random().toString(36).slice(2)}`);+ const agentDir = join(tmpdir(), `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`);mkdirSync(agentDir, { recursive: true });tempDirs.push(agentDir);process.env.PRIME_AGENT_CODING_AGENT_DIR = agentDir;@@ -973,31 +977,23 @@ describe("Harness digest at cold boundaries", () => {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();+ return agentDir;+ }- // 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",+ function seedMemory(+ state: ReturnType<typeof loadHarnessState>,+ id: string,+ title: string,+ content: string,+ scope: "local" | "global" = "local",+ ): void {+ state.entries.memory[id] = {+ id,kind: "memory",- title: "Resume test memory",- content: "Written between resumes.",+ title,+ content,path: "general",- scope: "local",+ scope,reference: {},arguments: {},metadata: {},@@ -1006,13 +1002,48 @@ describe("Harness digest at cold boundaries", () => {updated_at: "2026-09-07T00:00:00.000Z",version: 1,};+ }++ it("skips digest re-delivery on resume when only query terms drifted and the state is unchanged", async () => {+ // Hermetic store: the ambient developer harness would crowd the ranked window.+ isolatedAgentDir("pi-digest-resume");+ const harness = await createHarness({ persistSession: true });+ harnesses.push(harness);+ // Local material whose entries the resume-time query terms re-rank: the+ // fresh render would differ, so only a state fingerprint can dedupe.+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir());+ expect(localDir).toBeDefined();+ const state = loadHarnessState(localDir, "local");+ seedMemory(state, "alpha_relevant", "Alpha second turn note", "Mentions second turns.");+ seedMemory(state, "middle_plain", "Middle plain note", "Neutral material about tea varieties.");+ seedMemory(state, "zeta_relevant", "Zeta hello note", "Greets with hello.");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");+ harness.setResponses([fauxAssistantMessage("ack"), fauxAssistantMessage("ack")]);+ await harness.session.prompt("hello");+ await harness.session.prompt("second turn with different wording");+ const before = digestMessages(harness);+ expect(before).toHaveLength(1);+ const digestTextBefore = getMessageText(before[0]);+ expect(digestTextBefore).toContain("[local:alpha_relevant]");+ const sessionFile = harness.sessionManager.getSessionFile();+ expect(sessionFile).toBeDefined();+ harness.session.dispose();++ // Identical disk state, drifted query terms: the fresh render would+ // differ, so only the fingerprint can dedupe. Exactly one byte-identical+ // digest, with no copy stacked by the resume.+ const resumed = await createHarness({ existingSessionFile: sessionFile });+ harnesses.push(resumed);+ const after = digestMessages(resumed);+ expect(after).toHaveLength(1);+ expect(getMessageText(after[0])).toBe(digestTextBefore);+ const freshDigest = (+ resumed.session as unknown as {+ _harnessDigestWithFingerprint(): { digest: string; stateFingerprint: string };+ }+ )._harnessDigestWithFingerprint().digest;+ expect(HARNESS_DIGEST_PREFIX + freshDigest + HARNESS_DIGEST_SUFFIX).not.toBe(getMessageText(after[0]));+ resumed.session.dispose();});});