Skip to content

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

Rust

[RSI, performance] context: keep only the newest harness digest in built contexts (#2394)

Seth Kartena8ae6269ab1e
diff --git a/packages/coding-agent/.changes/keep-newest-harness-digest.md b/packages/coding-agent/.changes/keep-newest-harness-digest.md
new file mode 100644
index 0000000000..922172559b
--- /dev/null
+++ b/packages/coding-agent/.changes/keep-newest-harness-digest.md
@@ -0,0 +1 @@
+- Changed session context assembly to carry only the newest harness digest: older digest custom messages are skipped when the context is built, a fresh cold-boundary digest replaces the copies it supersedes instead of stacking, and a compaction head's digest snapshot yields to any digest appended after the compaction. Persisted transcripts are unchanged; the newest digest remains authoritative.
diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts
index cfaec0af3a..8a67c7c550 100644
--- a/packages/coding-agent/src/core/agent-session.ts
+++ b/packages/coding-agent/src/core/agent-session.ts
@@ -9460,6 +9460,24 @@ export class AgentSession {
} catch {
// Unpersisted session: context-only injection.
}
+ // The fresh digest is authoritative and older in-context copies are
+ // regenerable redundancy, so the append replaces them instead of stacking.
+ const withoutOlderDigests = this.agent.state.messages.filter(
+ (existing) => !(existing.role === "custom" && existing.customType === HARNESS_DIGEST_CUSTOM_TYPE),
+ );
+ if (withoutOlderDigests.length !== this.agent.state.messages.length) {
+ this.agent.state.messages = withoutOlderDigests;
+ }
+ // The fresh append outranks the compaction snapshot the same way a newer
+ // digest entry does at rebuild time, so the live summary must yield its
+ // snapshot now: the context would otherwise render both the superseded
+ // snapshot and the fresh digest until the next rebuild.
+ for (const existing of this.agent.state.messages) {
+ if (existing.role === "compactionSummary" && existing.harnessDigest !== undefined) {
+ existing.harnessDigest = undefined;
+ existing.harnessStateFingerprint = undefined;
+ }
+ }
this.agent.state.messages.push(message);
}
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index 87711854c5..e04815427b 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -28,6 +28,7 @@ import {
createBranchSummaryMessage,
createCompactionSummaryMessage,
createCustomMessage,
+ HARNESS_DIGEST_CUSTOM_TYPE,
} from "./messages.js";
import {
addAssistantUsage,
@@ -495,6 +496,30 @@ export function buildSessionContext(
}
}
+ // Harness digests are regenerable snapshots of persistent state, so only the
+ // newest one belongs in the built context: older digest custom messages are
+ // skipped at assembly time, and a compaction-entry snapshot yields to any
+ // digest appended after the compaction. Persisted entries keep every copy;
+ // the newest digest is authoritative and is re-delivered at cold boundaries.
+ let newestDigestEntryId: string | undefined;
+ let newestDigestIdx = -1;
+ for (let i = path.length - 1; i >= 0; i--) {
+ const entry = path[i];
+ if (entry.type === "custom_message" && entry.customType === HARNESS_DIGEST_CUSTOM_TYPE) {
+ newestDigestEntryId = entry.id;
+ newestDigestIdx = i;
+ break;
+ }
+ }
+
+ const compactionIdx = compaction ? path.findIndex((e) => e.type === "compaction" && e.id === compaction.id) : -1;
+ // True when the compaction snapshot is the newest digest in context, so every
+ // digest custom message is older and skipped entirely.
+ const snapshotOutranksDigest =
+ compaction?.harnessDigest !== undefined && (newestDigestIdx === -1 || newestDigestIdx < compactionIdx);
+ const keepDigestEntryId = snapshotOutranksDigest ? undefined : newestDigestEntryId;
+ const summaryHarnessDigest = newestDigestIdx > compactionIdx ? undefined : compaction?.harnessDigest;
+
// Build messages and collect corresponding entries
// When there's a compaction, model context remains summary-first while the
// summary records where clients should present it among retained messages.
@@ -504,6 +529,9 @@ export function buildSessionContext(
if (entry.type === "message") {
target.push(entry.message);
} else if (entry.type === "custom_message") {
+ if (entry.customType === HARNESS_DIGEST_CUSTOM_TYPE && entry.id !== keepDigestEntryId) {
+ return;
+ }
target.push(
createCustomMessage(entry.customType, entry.content, entry.display, entry.details, entry.timestamp),
);
@@ -513,8 +541,6 @@ export function buildSessionContext(
};
if (compaction) {
- const compactionIdx = path.findIndex((e) => e.type === "compaction" && e.id === compaction.id);
-
// Collect kept messages (before compaction, starting from firstKeptEntryId).
// The context remains summary-first for the model; retainedMessageCount records
// the exact chronological presentation boundary for clients.
@@ -537,8 +563,8 @@ export function buildSessionContext(
compaction.timestamp,
compaction.customInstructions,
retainedMessages.length,
- compaction.harnessDigest,
- compaction.harnessStateFingerprint,
+ summaryHarnessDigest,
+ summaryHarnessDigest === undefined ? undefined : compaction.harnessStateFingerprint,
),
...retainedMessages,
);
diff --git a/packages/coding-agent/test/session-manager/build-context.test.ts b/packages/coding-agent/test/session-manager/build-context.test.ts
index afbdd1d8bf..96dfd24e3c 100644
--- a/packages/coding-agent/test/session-manager/build-context.test.ts
+++ b/packages/coding-agent/test/session-manager/build-context.test.ts
@@ -1,20 +1,26 @@
import { describe, expect, it } from "vitest";
+import { HARNESS_DIGEST_CUSTOM_TYPE } from "../../src/core/messages.js";
import {
type BranchSummaryEntry,
buildSessionContext,
- type CompactionEntry,
- type ModelChangeEntry,
- type ServiceTierChangeEntry,
+ type CustomMessageEntry,
type SessionEntry,
type SessionMessageEntry,
- type ThinkingLevelChangeEntry,
} from "../../src/core/session-manager.js";
+const T = "2025-01-01T00:00:00Z";
+const usage = {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+};
+
function msg(id: string, parentId: string | null, role: "user" | "assistant", text: string): SessionMessageEntry {
- const base = { type: "message" as const, id, parentId, timestamp: "2025-01-01T00:00:00Z" };
- if (role === "user") {
- return { ...base, message: { role, content: text, timestamp: 1 } };
- }
+ const base = { type: "message" as const, id, parentId, timestamp: T };
+ if (role === "user") return { ...base, message: { role, content: text, timestamp: 1 } };
return {
...base,
message: {
@@ -23,261 +29,221 @@ function msg(id: string, parentId: string | null, role: "user" | "assistant", te
api: "anthropic-messages",
provider: "anthropic",
model: "claude-test",
- usage: {
- input: 1,
- output: 1,
- cacheRead: 0,
- cacheWrite: 0,
- totalTokens: 2,
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
- },
+ usage,
stopReason: "stop",
timestamp: 1,
},
};
}
-function compaction(id: string, parentId: string | null, summary: string, firstKeptEntryId: string): CompactionEntry {
+function branchSummary(id: string, parentId: string | null, summary: string, fromId: string): BranchSummaryEntry {
+ return { type: "branch_summary", id, parentId, timestamp: T, summary, fromId };
+}
+
+function digestEntry(id: string, parentId: string | null, digest: string): CustomMessageEntry {
return {
- type: "compaction",
+ type: "custom_message",
id,
parentId,
- timestamp: "2025-01-01T00:00:00Z",
- summary,
- firstKeptEntryId,
- tokensBefore: 1000,
+ timestamp: T,
+ customType: HARNESS_DIGEST_CUSTOM_TYPE,
+ content: digest,
+ details: { digest },
+ display: false,
};
}
-function branchSummary(id: string, parentId: string | null, summary: string, fromId: string): BranchSummaryEntry {
- return { type: "branch_summary", id, parentId, timestamp: "2025-01-01T00:00:00Z", summary, fromId };
-}
-
-function thinkingLevel(id: string, parentId: string | null, level: string): ThinkingLevelChangeEntry {
- return { type: "thinking_level_change", id, parentId, timestamp: "2025-01-01T00:00:00Z", thinkingLevel: level };
+/**
+ * Builds a linear parent-linked entry fixture from compact specs (ids 1..n,
+ * each parented to the previous one): "u text"/"a text" = user/assistant
+ * message, "d digest"/"n note" = harness-digest/unrelated custom message,
+ * "t level"/"s tier"/"m provider model" = change entries, and
+ * "c summary|kept[|instructions[|snapshot]]" = compaction with
+ * firstKeptEntryId = the 1-based id in `kept`.
+ */
+function chain(...specs: string[]): SessionEntry[] {
+ const entries: SessionEntry[] = [];
+ let parentId: string | null = null;
+ for (const [index, spec] of specs.entries()) {
+ const id = String(index + 1);
+ const kind = spec[0];
+ const text = spec.slice(2);
+ if (kind === "u" || kind === "a") {
+ entries.push(msg(id, parentId, kind === "u" ? "user" : "assistant", text));
+ } else if (kind === "d") {
+ entries.push(digestEntry(id, parentId, text));
+ } else if (kind === "n") {
+ entries.push({
+ type: "custom_message",
+ id,
+ parentId,
+ timestamp: T,
+ customType: "extension.note",
+ content: text,
+ display: true,
+ });
+ } else if (kind === "t") {
+ entries.push({ type: "thinking_level_change", id, parentId, timestamp: T, thinkingLevel: text });
+ } else if (kind === "s") {
+ entries.push({
+ type: "service_tier_change",
+ id,
+ parentId,
+ timestamp: T,
+ serviceTier: text as "default" | "priority",
+ });
+ } else if (kind === "m") {
+ const [provider, modelId] = text.split(" ");
+ entries.push({ type: "model_change", id, parentId, timestamp: T, provider, modelId });
+ } else if (kind === "c") {
+ const [summary, kept, instructions = "", snapshot] = text.split("|").map((part) => part.trim());
+ entries.push({
+ type: "compaction",
+ id,
+ parentId,
+ timestamp: T,
+ summary,
+ firstKeptEntryId: kept,
+ tokensBefore: 1000,
+ ...(instructions ? { customInstructions: instructions } : {}),
+ ...(snapshot ? { harnessDigest: snapshot } : {}),
+ });
+ } else {
+ throw new Error(`unknown chain spec: ${spec}`);
+ }
+ parentId = id;
+ }
+ return entries;
}
-function modelChange(id: string, parentId: string | null, provider: string, modelId: string): ModelChangeEntry {
- return { type: "model_change", id, parentId, timestamp: "2025-01-01T00:00:00Z", provider, modelId };
-}
+const digestOf = (messages: ReturnType<typeof buildSessionContext>["messages"]) =>
+ messages
+ .filter((m) => m.role === "custom" && m.customType === HARNESS_DIGEST_CUSTOM_TYPE)
+ .map((m) => (m as { details: { digest: string } }).details.digest);
-function serviceTier(id: string, parentId: string | null, tier: "default" | "priority"): ServiceTierChangeEntry {
- return { type: "service_tier_change", id, parentId, timestamp: "2025-01-01T00:00:00Z", serviceTier: tier };
-}
+const textOf = (m: ReturnType<typeof buildSessionContext>["messages"][number]): string => {
+ const content = (m as { content?: string | Array<{ text?: string }> }).content;
+ return typeof content === "string" ? content : (content?.[0]?.text ?? "");
+};
describe("buildSessionContext", () => {
- describe("trivial cases", () => {
- it("empty entries returns empty context", () => {
- const ctx = buildSessionContext([]);
- expect(ctx.messages).toEqual([]);
- expect(ctx.thinkingLevel).toBe("off");
- expect(ctx.serviceTier).toBe("default");
- expect(ctx.model).toBeNull();
- });
-
- it("single user message", () => {
- const entries: SessionEntry[] = [msg("1", null, "user", "hello")];
- const ctx = buildSessionContext(entries);
- expect(ctx.messages).toHaveLength(1);
- expect(ctx.messages[0].role).toBe("user");
- });
-
- it("simple conversation", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "hello"),
- msg("2", "1", "assistant", "hi there"),
- msg("3", "2", "user", "how are you"),
- msg("4", "3", "assistant", "great"),
- ];
- const ctx = buildSessionContext(entries);
- expect(ctx.messages).toHaveLength(4);
- expect(ctx.messages.map((m) => m.role)).toEqual(["user", "assistant", "user", "assistant"]);
- });
-
- it("tracks thinking level changes", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "hello"),
- thinkingLevel("2", "1", "high"),
- msg("3", "2", "assistant", "thinking hard"),
- ];
- const ctx = buildSessionContext(entries);
- expect(ctx.thinkingLevel).toBe("high");
- expect(ctx.messages).toHaveLength(2);
- });
-
- it("tracks service tier changes on the active branch", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "hello"),
- serviceTier("2", "1", "priority"),
- msg("3", "2", "assistant", "fast response"),
- serviceTier("4", "1", "default"),
- ];
-
- expect(buildSessionContext(entries, "3").serviceTier).toBe("priority");
- expect(buildSessionContext(entries, "4").serviceTier).toBe("default");
- });
-
- it("tracks model from assistant message", () => {
- const entries: SessionEntry[] = [msg("1", null, "user", "hello"), msg("2", "1", "assistant", "hi")];
- const ctx = buildSessionContext(entries);
- expect(ctx.model).toEqual({ provider: "anthropic", modelId: "claude-test" });
- });
-
- it("tracks model from model change entry", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "hello"),
- modelChange("2", "1", "openai", "gpt-4"),
- msg("3", "2", "assistant", "hi"),
- ];
- const ctx = buildSessionContext(entries);
- expect(ctx.model).toEqual({ provider: "anthropic", modelId: "claude-test" });
+ it("empty entries returns empty context", () => {
+ expect(buildSessionContext([])).toMatchObject({
+ messages: [],
+ thinkingLevel: "off",
+ serviceTier: "default",
+ model: null,
});
});
- describe("with compaction", () => {
- it("includes summary before kept messages", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "first"),
- msg("2", "1", "assistant", "response1"),
- msg("3", "2", "user", "second"),
- msg("4", "3", "assistant", "response2"),
- compaction("5", "4", "Summary of first two turns", "3"),
- msg("6", "5", "user", "third"),
- msg("7", "6", "assistant", "response3"),
- ];
- const ctx = buildSessionContext(entries);
-
- expect(ctx.messages).toHaveLength(5);
- expect((ctx.messages[0] as any).summary).toContain("Summary of first two turns");
- expect((ctx.messages[1] as any).content).toBe("second");
- expect((ctx.messages[2] as any).content[0].text).toBe("response2");
- expect((ctx.messages[3] as any).content).toBe("third");
- expect((ctx.messages[4] as any).content[0].text).toBe("response3");
- });
-
- it("handles compaction keeping from first message", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "first"),
- msg("2", "1", "assistant", "response"),
- compaction("3", "2", "Empty summary", "1"),
- msg("4", "3", "user", "second"),
- ];
- const ctx = buildSessionContext(entries);
-
- expect(ctx.messages).toHaveLength(4);
- expect((ctx.messages[0] as any).summary).toContain("Empty summary");
- });
-
- it("carries customInstructions onto the summary message", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "first"),
- msg("2", "1", "assistant", "response"),
- { ...compaction("3", "2", "Summary", "1"), customInstructions: "focus on the auth refactor" },
- msg("4", "3", "user", "second"),
- ];
- const ctx = buildSessionContext(entries);
-
- expect((ctx.messages[0] as any).summary).toContain("Summary");
- expect((ctx.messages[0] as any).customInstructions).toBe("focus on the auth refactor");
- });
-
- it("multiple compactions uses latest", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "a"),
- msg("2", "1", "assistant", "b"),
- compaction("3", "2", "First summary", "1"),
- msg("4", "3", "user", "c"),
- msg("5", "4", "assistant", "d"),
- compaction("6", "5", "Second summary", "4"),
- msg("7", "6", "user", "e"),
- ];
- const ctx = buildSessionContext(entries);
-
- expect(ctx.messages).toHaveLength(4);
- expect((ctx.messages[0] as any).summary).toContain("Second summary");
- });
+ it("tracks thinking level changes", () => {
+ expect(buildSessionContext(chain("u hello", "t high", "a thinking hard")).thinkingLevel).toBe("high");
});
- describe("with branches", () => {
- it("follows path to specified leaf", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "start"),
- msg("2", "1", "assistant", "response"),
- msg("3", "2", "user", "branch A"),
- msg("4", "2", "user", "branch B"),
- ];
-
- const ctxA = buildSessionContext(entries, "3");
- expect(ctxA.messages).toHaveLength(3);
- expect((ctxA.messages[2] as any).content).toBe("branch A");
+ it("tracks service tier changes on the active branch", () => {
+ const entries = chain("u hello", "s priority", "a fast response", "s default");
+ expect(buildSessionContext(entries, "3").serviceTier).toBe("priority");
+ expect(buildSessionContext(entries, "4").serviceTier).toBe("default");
+ });
- const ctxB = buildSessionContext(entries, "4");
- expect(ctxB.messages).toHaveLength(3);
- expect((ctxB.messages[2] as any).content).toBe("branch B");
+ it("tracks model from model change entry", () => {
+ expect(buildSessionContext(chain("u hello", "m openai gpt-4", "a hi")).model).toMatchObject({
+ provider: "anthropic",
+ modelId: "claude-test",
});
+ });
- it("includes branch summary in path", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "start"),
- msg("2", "1", "assistant", "response"),
- msg("3", "2", "user", "abandoned path"),
- branchSummary("4", "2", "Summary of abandoned work", "3"),
- msg("5", "4", "user", "new direction"),
- ];
- const ctx = buildSessionContext(entries, "5");
+ it("includes summary before kept messages", () => {
+ const ctx = buildSessionContext(chain("u first", "u second", "c First turn summarized|2", "u third"));
+ const head = ctx.messages[0] as { role: string; summary: string };
+ expect(head.role).toBe("compactionSummary");
+ expect(head.summary).toContain("First turn summarized");
+ expect(ctx.messages.slice(1).map(textOf)).toEqual(["second", "third"]);
+ });
- expect(ctx.messages).toHaveLength(4);
- expect((ctx.messages[2] as any).summary).toContain("Summary of abandoned work");
- expect((ctx.messages[3] as any).content).toBe("new direction");
- });
+ it("carries customInstructions onto the summary message", () => {
+ const ctx = buildSessionContext(
+ chain("u first", "a response", "c Summary|1|focus on the auth refactor", "u second"),
+ );
+ expect((ctx.messages[0] as { customInstructions?: string }).customInstructions).toBe(
+ "focus on the auth refactor",
+ );
+ });
- it("complex tree with multiple branches and compaction", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "start"),
- msg("2", "1", "assistant", "r1"),
- msg("3", "2", "user", "q2"),
- msg("4", "3", "assistant", "r2"),
- compaction("5", "4", "Compacted history", "3"),
- msg("6", "5", "user", "q3"),
- msg("7", "6", "assistant", "r3"),
- msg("8", "3", "user", "wrong path"),
- msg("9", "8", "assistant", "wrong response"),
- branchSummary("10", "3", "Tried wrong approach", "9"),
- msg("11", "10", "user", "better approach"),
- ];
+ it("multiple compactions uses latest", () => {
+ const ctx = buildSessionContext(
+ chain("u a", "a b", "c First summary|1", "u c", "a d", "c Second summary|4", "u e"),
+ );
+ expect((ctx.messages[0] as { summary: string }).summary).toContain("Second summary");
+ expect(ctx.messages.slice(1).map(textOf)).toEqual(["c", "d", "e"]);
+ });
- const ctxMain = buildSessionContext(entries, "7");
- expect(ctxMain.messages).toHaveLength(5);
- expect((ctxMain.messages[0] as any).summary).toContain("Compacted history");
- expect((ctxMain.messages[1] as any).content).toBe("q2");
- expect((ctxMain.messages[2] as any).content[0].text).toBe("r2");
- expect((ctxMain.messages[3] as any).content).toBe("q3");
- expect((ctxMain.messages[4] as any).content[0].text).toBe("r3");
+ it("includes branch summary in path", () => {
+ const entries = chain("u start", "a response", "u abandoned path");
+ entries.push(branchSummary("4", "2", "Summary of abandoned work", "3"));
+ entries.push(msg("5", "4", "user", "new direction"));
+ const ctx = buildSessionContext(entries, "5");
+ expect((ctx.messages[2] as any).summary).toContain("Summary of abandoned work");
+ expect((ctx.messages[3] as any).content).toBe("new direction");
+ });
- const ctxBranch = buildSessionContext(entries, "11");
- expect(ctxBranch.messages).toHaveLength(5);
- expect((ctxBranch.messages[0] as any).content).toBe("start");
- expect((ctxBranch.messages[1] as any).content[0].text).toBe("r1");
- expect((ctxBranch.messages[2] as any).content).toBe("q2");
- expect((ctxBranch.messages[3] as any).summary).toContain("Tried wrong approach");
- expect((ctxBranch.messages[4] as any).content).toBe("better approach");
- });
+ it("uses last entry when leafId not found", () => {
+ expect(buildSessionContext(chain("u hello", "a hi"), "nonexistent").messages).toHaveLength(2);
});
- describe("edge cases", () => {
- it("uses last entry when leafId not found", () => {
- const entries: SessionEntry[] = [msg("1", null, "user", "hello"), msg("2", "1", "assistant", "hi")];
- const ctx = buildSessionContext(entries, "nonexistent");
- expect(ctx.messages).toHaveLength(2);
- });
+ it("handles orphaned entries gracefully", () => {
+ const entries: SessionEntry[] = [msg("1", null, "user", "hello"), msg("2", "missing", "assistant", "orphan")];
+ expect(buildSessionContext(entries, "2").messages).toHaveLength(1);
+ });
- it("handles orphaned entries gracefully", () => {
- const entries: SessionEntry[] = [
- msg("1", null, "user", "hello"),
- msg("2", "missing", "assistant", "orphan"), // parent doesn't exist
- ];
- const ctx = buildSessionContext(entries, "2");
- expect(ctx.messages).toHaveLength(1);
+ describe("harness digest dedupe", () => {
+ it("keeps only the newest digest custom message", () => {
+ const ctx = buildSessionContext(chain("u hello", "d digest-a", "a first reply", "d digest-b"));
+ expect(digestOf(ctx.messages)).toEqual(["digest-b"]);
+ expect(ctx.messages.map((m) => m.role)).toEqual(["user", "assistant", "custom"]);
+ });
+
+ it("keeps only the newest digest on the navigated branch", () => {
+ const entries = chain("u hello", "d digest-old", "u branch point", "d digest-branch-a");
+ entries.push(digestEntry("5", "3", "digest-branch-b"));
+ expect(digestOf(buildSessionContext(entries, "4").messages)).toEqual(["digest-branch-a"]);
+ expect(digestOf(buildSessionContext(entries, "5").messages)).toEqual(["digest-branch-b"]);
+ });
+
+ it("leaves sessions without digests and non-digest custom messages unchanged", () => {
+ const ctx = buildSessionContext(chain("u hello", "n note one", "a reply", "n note two", "u again"));
+ expect(digestOf(ctx.messages)).toEqual([]);
+ expect(ctx.messages.map((m) => m.role)).toEqual(["user", "custom", "assistant", "custom", "user"]);
+ });
+
+ it("drops retained digest messages when the compaction snapshot is newer", () => {
+ const ctx = buildSessionContext(
+ chain(
+ "d retained digest",
+ "u kept question",
+ "a kept answer",
+ "c Summary|1||snapshot digest",
+ "u after compaction",
+ ),
+ );
+ expect(digestOf(ctx.messages)).toEqual([]);
+ expect((ctx.messages[0] as { harnessDigest?: string }).harnessDigest).toBe("snapshot digest");
+ });
+
+ it("keeps the newest post-compaction digest and drops the superseded snapshot", () => {
+ const ctx = buildSessionContext(
+ chain("u question", "a answer", "c Summary|1||snapshot digest", "d newest digest"),
+ );
+ expect(digestOf(ctx.messages)).toEqual(["newest digest"]);
+ expect((ctx.messages[0] as { harnessDigest?: string }).harnessDigest).toBeUndefined();
+ });
+
+ it("keeps the newest retained digest when the compaction has no snapshot", () => {
+ const ctx = buildSessionContext(
+ chain("d retained old", "d retained newest", "u kept question", "c Summary|1", "u after compaction"),
+ );
+ expect(digestOf(ctx.messages)).toEqual(["retained newest"]);
+ expect((ctx.messages[0] as { harnessDigest?: string }).harnessDigest).toBeUndefined();
});
});
});
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 65c5a2b4cd..e421455026 100644
--- a/packages/coding-agent/test/suite/agent-session-prompt.test.ts
+++ b/packages/coding-agent/test/suite/agent-session-prompt.test.ts
@@ -1080,4 +1080,27 @@ describe("Harness digest at cold boundaries", () => {
expect(HARNESS_DIGEST_PREFIX + freshDigest + HARNESS_DIGEST_SUFFIX).not.toBe(getMessageText(after[0]));
resumed.session.dispose();
});
+
+ it("appends a fresh digest on resume after disk state changed, replacing the old copy", async () => {
+ // Empty global store: digest content must reflect only the local test entry.
+ // The unchanged-disk resume dedupe is pinned by the fingerprint test above.
+ isolatedAgentDir("pi-digest-agent");
+ const harness = await createHarness({ persistSession: true });
+ harnesses.push(harness);
+ harness.setResponses([fauxAssistantMessage("hi")]);
+ await harness.session.prompt("hello");
+ const sessionFile = harness.sessionManager.getSessionFile();
+ harness.session.dispose();
+
+ const localDir = getLocalHarnessStateDir(harness.sessionManager.getSessionArtifactDir());
+ const state = loadHarnessState(localDir, "local");
+ seedMemory(state, "resume_test_memory", "Resume test memory", "Written between resumes.");
+ saveHarnessState(localDir!, state);
+
+ const resumedStale = await createHarness({ existingSessionFile: sessionFile });
+ harnesses.push(resumedStale);
+ const digests = digestMessages(resumedStale);
+ expect(digests).toHaveLength(1); // the fresh digest replaced the stale copy instead of stacking
+ expect(getMessageText(digests[0])).toContain("[local:resume_test_memory] Resume test memory");
+ });
});