From cfd8f6ebc91b0eb1f06f44f75611bdfd7a210e4a Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 22:48:16 +0800 Subject: [PATCH 1/3] feat: mechanically preserve subagent session ids at fold commit (#481) When a fold range contains opencode subagent dispatch tool messages whose content carries ses_... session ids, extract those ids from the folded originals and force-append them to the compression block summary as a machine appendix line ([acp-preserved:subagent-session] ...). The model never transcribes the id, so fidelity no longer depends on summary-writing quality. Inserted at the single block-creation site in applySingleRange (covers T1 folds and T2/T3 distillation uniformly) plus applyRefolds so refold-in-place cannot drop ids either. Source texts are live folded tool messages plus consumed blocks' summaries (tier distillation carries ids forward through summaries on pruned hosts). A transparency note is surfaced via result.notes when an appendix is appended. --- src/compress.ts | 78 ++++++++++++++++++++++++++++++++++---- src/index.ts | 7 ++++ src/preserved-ids.ts | 89 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 167 insertions(+), 7 deletions(-) create mode 100644 src/preserved-ids.ts diff --git a/src/compress.ts b/src/compress.ts index ff0b29a..b2887e8 100644 --- a/src/compress.ts +++ b/src/compress.ts @@ -36,6 +36,11 @@ import { isToolMessage } from "./message-kind.js"; import { adjustBoundariesForToolPairs } from "./tool-pairs.js"; import { adjustBoundariesForReasoningPairs } from "./reasoning-pairs.js"; import { computeIntegrityWithdrawals } from "./turn-integrity.js"; +import { + buildFidelityAppendix, + extractFidelityIds, + fidelitySourceTexts, +} from "./preserved-ids.js"; import { computeProtectedRefs, buildCompressibleRanges, @@ -312,27 +317,53 @@ function evaluateRefold( /** In-place refold (#398): same block id/coverage/tier, new summary (+topic), * fresh runId, restoredInline flag cleared. Summary passes the same length - * checks as a fresh compression. */ + * checks as a fresh compression. Returns the #481 fidelity appendix appended + * ("" when none was needed). */ function applyRefolds(input: { spec: ApplyCompressionInput["ranges"][number]; state: CompressionState; runId: string; config: Config; blockIds: string[]; -}): void { + messages: CoreMessage[]; +}): string { validateSummaryLength(input.spec, input.config.compress); const targets = new Set(input.blockIds); + // #481: extract from the OLD summaries and still-visible tool messages + // before the map rewrites them — a re-fold must not drop ids. + const fidelityTexts: string[] = []; + for (const block of input.state.blocks) { + if (!targets.has(block.blockId)) continue; + fidelityTexts.push(block.summary); + const coverage = new Set(block.effectiveMessageIds); + for (const message of input.messages) { + if (!coverage.has(message.id)) continue; + fidelityTexts.push(...fidelitySourceTexts([message])); + } + } + const appendix = buildFidelityAppendix( + input.spec.summary, + extractFidelityIds(fidelityTexts), + ); + const summary = + appendix === "" ? input.spec.summary : input.spec.summary + appendix; input.state.blocks = input.state.blocks.map((block) => targets.has(block.blockId) ? { ...block, - summary: input.spec.summary, + summary, topic: input.spec.topic ?? block.topic, runId: input.runId, restoredInline: false, } : block, ); + return appendix; +} + +function fidelityNote(appendix: string): string | undefined { + if (appendix === "") return undefined; + return `Kernel appended mechanically-preserved identifier(s) to the block summary: ${appendix.trim()}`; } export function createCore(ports: Ports = {}): CompressionCore { @@ -606,14 +637,17 @@ export function createCore(ports: Ports = {}): CompressionCore { const decision = refoldDecisions.get(spec); if (decision?.kind === "refold") { try { - applyRefolds({ + const appendix = applyRefolds({ spec, state, runId, config: input.config, blockIds: decision.blocks.map((block) => block.blockId), + messages: input.messages, }); blocksCreated += decision.blocks.length; + const note = fidelityNote(appendix); + if (note) notes.push(note); } catch (error) { errors.push( rangeError( @@ -651,6 +685,7 @@ export function createCore(ports: Ports = {}): CompressionCore { blocksCreated += outcome.refolded ? outcome.refolded.length : 1; tokensCompressed += outcome.tokens; warnings.push(...outcome.warnings); + if (outcome.notes) notes.push(...outcome.notes); } catch (error) { errors.push( rangeError( @@ -1135,6 +1170,8 @@ interface SingleRangeOutcome { /** #400: set when the range ended as an in-place refold instead of creating * a fresh block — the ids of the blocks updated (caller counts these, not 1). */ refolded?: string[]; + /** Kernel-side transparency notes to surface to the caller (#481). */ + notes?: string[]; } function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { @@ -1373,17 +1410,20 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { // blocks in place; everything else keeps the legacy rejection verbatim. const decision = evaluateRefold(input.state, input.spec); if (decision.kind === "refold") { - applyRefolds({ + const appendix = applyRefolds({ spec: input.spec, state: input.state, runId: input.runId, config: input.config, blockIds: decision.blocks.map((block) => block.blockId), + messages: input.messages, }); + const note = fidelityNote(appendix); return { tokens: 0, warnings, refolded: decision.blocks.map((block) => block.blockId), + ...(note !== undefined ? { notes: [note] } : {}), }; } const first = consumedBlockIds[0]!; @@ -1411,13 +1451,32 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { } } + // Mechanical fidelity (#481): fold-commit post-processing. Extract verbatim + // identifiers from the folded source texts — live tool messages plus + // consumed blocks' summaries (tier distillation carries ids forward through + // summaries on pruned hosts) — and append any id missing from the model + // summary as a machine line the model never transcribes. + const foldedMessages = filteredIds + .map((id) => input.messages.find((entry) => entry.id === id)) + .filter((m): m is CoreMessage => m !== undefined); + const fidelityTexts = [ + ...fidelitySourceTexts(foldedMessages), + ...consumedBlockIds + .map((id) => blockById(input.state, id)?.summary) + .filter((s): s is string => s !== undefined), + ]; + const fidelityAppendix = buildFidelityAppendix( + input.spec.summary, + extractFidelityIds(fidelityTexts), + ); + const blockId = allocateBlockId(input.state); const block: CompressionBlock = { blockId, runId: input.runId, tier: outputTier, topic: input.spec.topic, - summary: input.spec.summary, + summary: input.spec.summary + fidelityAppendix, directMessageIds: filteredIds, effectiveMessageIds: [...effectiveMessageIds], directBlockIds: [...consumedBlockIds], @@ -1437,7 +1496,12 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { if (consumed) consumed.active = false; } - return { tokens: compressedTokens, warnings }; + const note = fidelityNote(fidelityAppendix); + return { + tokens: compressedTokens, + warnings, + ...(note !== undefined ? { notes: [note] } : {}), + }; } function applyPairBoundaryAdjustments( diff --git a/src/index.ts b/src/index.ts index d8f0f40..5942a32 100644 --- a/src/index.ts +++ b/src/index.ts @@ -147,6 +147,13 @@ export type { export { renderHandoff, renderMessage, matchSession } from "./handoff.js"; export type { HandoffInput, HandoffMeta, HandoffBlockFull } from "./handoff.js"; export { isToolMessage } from "./message-kind.js"; +export { + DEFAULT_FIDELITY_EXTRACTORS, + fidelitySourceTexts, + extractFidelityIds, + buildFidelityAppendix, +} from "./preserved-ids.js"; +export type { FidelityExtractor } from "./preserved-ids.js"; export { hideConsumedCompressCalls } from "./hide-consumed.js"; export type { HideConsumedResult } from "./hide-consumed.js"; export { diff --git a/src/preserved-ids.ts b/src/preserved-ids.ts new file mode 100644 index 0000000..0b2450c --- /dev/null +++ b/src/preserved-ids.ts @@ -0,0 +1,89 @@ +import type { CoreMessage } from "./types.js"; + +/** One verbatim-identifier extractor (#481): a machine label plus a global + * pattern whose matches are preserved byte-for-byte into a compression block + * appendix so they survive folding regardless of what the model summary + * writes. `pattern` must be global; exec state is cloned per call. */ +export interface FidelityExtractor { + label: string; + pattern: RegExp; +} + +/** Active extractors, deliberately narrow per #481 direction: only opencode + * subagent session ids for now. Commit-hash / PR-number extractors can join + * this list later — the appendix format already carries the label. */ +export const DEFAULT_FIDELITY_EXTRACTORS: readonly FidelityExtractor[] = [ + { label: "subagent-session", pattern: /\bses_[A-Za-z0-9]+\b/g }, +]; + +/** Texts that can carry dispatch-pair identifiers (#481): tool-call and + * tool-result messages only. User/assistant prose is out of scope — the + * directed fix targets the subagent dispatch pair shape, not free text. */ +export function fidelitySourceTexts(messages: CoreMessage[]): string[] { + const texts: string[] = []; + for (const message of messages) { + if (!message.text) continue; + if ( + message.contentType !== "tool-call" && + message.contentType !== "tool-result" + ) + continue; + texts.push(message.text); + } + return texts; +} + +/** Extract deduped identifiers from folded texts, grouped by extractor label. + * First-occurrence order is preserved within each label. */ +export function extractFidelityIds( + texts: Iterable, + extractors: readonly FidelityExtractor[] = DEFAULT_FIDELITY_EXTRACTORS, +): Map { + const out = new Map(); + for (const extractor of extractors) { + const pattern = new RegExp( + extractor.pattern.source, + extractor.pattern.flags.replace("g", "") + "g", + ); + const seen = new Set(); + const ids: string[] = []; + for (const text of texts) { + if (!text) continue; + let match: RegExpExecArray | null; + while ((match = pattern.exec(text)) !== null) { + const id = match[0]; + if (!seen.has(id)) { + seen.add(id); + ids.push(id); + } + if (match.index === pattern.lastIndex) pattern.lastIndex++; + } + } + if (ids.length > 0) out.set(extractor.label, ids); + } + return out; +} + +function idPresentIn(text: string, id: string): boolean { + const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + return new RegExp(`\\b${escaped}\\b`).test(text); +} + +/** Machine appendix lines for extracted ids missing from the model summary; + * "" when nothing was extracted or every id is already present verbatim. + * One line per label — the format stays extensible as extractors are added. */ +export function buildFidelityAppendix( + summary: string, + idsByLabel: Map, +): string { + if (idsByLabel.size === 0) return ""; + const lines: string[] = []; + for (const [label, ids] of idsByLabel) { + const missing = ids.filter((id) => !idPresentIn(summary, id)); + if (missing.length > 0) { + lines.push(`[acp-preserved:${label}] ${missing.join(", ")}`); + } + } + if (lines.length === 0) return ""; + return `\n${lines.join("\n")}`; +} From d4bccdd79aba84da167eecdd0db2edd9d5dd375f Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 22:48:16 +0800 Subject: [PATCH 2/3] test: pin mechanical-fidelity invariants for fold/refold/distill (#481) Mechanical assertions per #481 acceptance criteria: whatever the model summary outputs, the full ses_ string exists verbatim in the stored block summary across fresh T1 folds, T2 distillation propagation, and refold-in-place; plus byte-identity pins (no ids / ids already present), prose-narrowing pin, dedup/order, and prefix-collision safety. --- tests/preserved-ids.test.ts | 516 ++++++++++++++++++++++++++++++++++++ 1 file changed, 516 insertions(+) create mode 100644 tests/preserved-ids.test.ts diff --git a/tests/preserved-ids.test.ts b/tests/preserved-ids.test.ts new file mode 100644 index 0000000..3a00fa1 --- /dev/null +++ b/tests/preserved-ids.test.ts @@ -0,0 +1,516 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { createInitialState } from "../src/state.js"; +import { assignRefs } from "../src/refs.js"; +import { markBlockRestoredInline } from "../src/decompress.js"; +import { + buildFidelityAppendix, + extractFidelityIds, + fidelitySourceTexts, +} from "../src/preserved-ids.js"; +import type { + CompressionBlock, + CompressionState, + Config, + CoreMessage, +} from "../src/types.js"; + +// #481: mechanical fidelity — subagent-dispatch session ids (ses_...) found in +// folded tool content must survive into the compression block verbatim, +// regardless of what the model summary writes. These tests are the mechanical +// assertions: includes-full-string on the stored block summary. + +const SES_ID = "ses_f195c333effeab12cd34567890"; + +function config(overrides: Partial = {}): Config { + return { + tiers: { enabled: true, tier2Trigger: 5, tier3Trigger: 10 }, + nudge: { + maxContextLimitPct: 0.55, + minContextLimitPct: 0.45, + frequency: 5, + iterationThreshold: 15, + force: "soft", + growthRatio: 0.05, + growthFloor: 6000, + growthCap: 50000, + minGrowthFloor: 5000, + minGrowthRatio: 0.45, + emergencyThresholdPct: 0.98, + }, + promotionThreshold: 5, + truncate: { threshold: 1 }, + compress: { minCompressRange: 0, maxSummaryLength: 0, minSummaryLength: 0 }, + protectedTools: [], + preserveRecentMessages: 0, + preserveRecentTokens: 0, + modelContextLimit: 100000, + ...overrides, + }; +} + +function textMsg( + id: string, + text: string, + role: CoreMessage["role"] = "user", +): CoreMessage { + return { id, role, contentType: "text", text }; +} + +/** The opencode subagent dispatch pair shape: tool-call args + tool-result. */ +function dispatchPair(): CoreMessage[] { + return [ + { + id: "call-1", + role: "assistant", + contentType: "tool-call", + toolName: "task", + toolCallId: "tc-1", + text: JSON.stringify({ + prompt: "continue the build", + session_id: SES_ID, + }), + }, + { + id: "result-1", + role: "tool", + contentType: "tool-result", + toolName: "task", + toolCallId: "tc-1", + text: `Subagent finished. Log: resumed ${SES_ID}, rebuilt 4 targets.`, + }, + ]; +} + +function stateWithRefs(messages: CoreMessage[]): CompressionState { + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { + existing: state.messageRefs, + nextIndex: 1, + }).map; + return state; +} + +function makeBlock( + overrides: Partial & + Pick, +): CompressionBlock { + return { + runId: "r1", + tier: 1, + summary: "OLD SUMMARY", + directMessageIds: overrides.effectiveMessageIds, + directBlockIds: [], + compressedTokens: 100, + createdAt: 1758800000000, + survivedCount: 0, + generation: "young", + active: true, + ...overrides, + }; +} + +// Unit: extraction ------------------------------------------------------------- + +test("extractFidelityIds dedupes across texts and preserves first-occurrence order", () => { + const ids = extractFidelityIds([ + `dispatch ${SES_ID}`, + `again ${SES_ID} and ses_b2b2b2`, + ]); + assert.deepEqual(ids.get("subagent-session"), [SES_ID, "ses_b2b2b2"]); +}); + +test("extractFidelityIds is prefix-collision safe: ses_ab and ses_abcdef are distinct ids", () => { + const ids = extractFidelityIds(["id=ses_ab", "id=ses_abcdef"]); + assert.deepEqual(ids.get("subagent-session"), ["ses_ab", "ses_abcdef"]); +}); + +test("extractFidelityIds returns an empty map when nothing matches", () => { + assert.equal(extractFidelityIds(["no identifiers here"]).size, 0); + assert.equal(extractFidelityIds([]).size, 0); +}); + +test("fidelitySourceTexts selects tool-call and tool-result messages only", () => { + const texts = fidelitySourceTexts([ + textMsg("u", "prose with ses_shouldnotcount"), + textMsg("a", "more prose ses_alsonot", "assistant"), + { + id: "t1", + role: "assistant", + contentType: "tool-call", + toolName: "task", + text: "call ses_yes1", + }, + { + id: "t2", + role: "tool", + contentType: "tool-result", + toolName: "task", + text: "res ses_yes2", + }, + { + id: "r1", + role: "assistant", + contentType: "reasoning", + text: "think ses_no", + }, + ]); + assert.deepEqual(texts, ["call ses_yes1", "res ses_yes2"]); +}); + +test("buildFidelityAppendix skips ids already present verbatim and is prefix-collision safe", () => { + const ids = new Map([ + ["subagent-session", ["ses_ab", "ses_abcdef", "ses_present"]], + ]); + const appendix = buildFidelityAppendix( + "summary mentions ses_abcdef and ses_present", + ids, + ); + assert.equal(appendix, "\n[acp-preserved:subagent-session] ses_ab"); +}); + +test("buildFidelityAppendix returns '' when everything is already present or nothing extracted", () => { + const ids = new Map([["subagent-session", ["ses_only"]]]); + assert.equal(buildFidelityAppendix("kept ses_only verbatim", ids), ""); + assert.equal(buildFidelityAppendix("anything", new Map()), ""); +}); + +test("DEFAULT_FIDELITY_EXTRACTORS captures the opencode session-id shape only", () => { + const ids = extractFidelityIds([`x ${SES_ID} y`, "no identifiers here"]); + assert.deepEqual(ids.get("subagent-session"), [SES_ID]); +}); + +// Integration: fresh T1 fold ---------------------------------------------------- + +test("T1 fold: model summary drops the subagent session id -> kernel appends it verbatim", () => { + const core = createCore(); + const messages = [ + textMsg("u1", "please continue the build via subagent"), + ...dispatchPair(), + textMsg("a1", "continuing with the results", "assistant"), + ]; + const state = stateWithRefs(messages); + + const result = core.applyCompression({ + ranges: [ + { + startRef: "m00001", + endRef: "m00004", + summary: "Subagent dispatched and returned; work continued.", + }, + ], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + assert.equal(result.result.blocksCreated, 1); + const block = result.state.blocks[0]!; + // Mechanical assertion: the id exists verbatim whatever the model wrote. + assert.ok( + block.summary.includes(SES_ID), + `stored summary lost the id: ${block.summary}`, + ); + assert.ok( + block.summary.includes(`[acp-preserved:subagent-session] ${SES_ID}`), + `missing machine appendix line: ${block.summary}`, + ); + assert.ok( + result.result.notes?.some((n) => + n.includes("[acp-preserved:subagent-session]"), + ), + "kernel note surfaces the mechanical preservation", + ); + assert.deepEqual( + block.effectiveMessageIds.sort(), + ["a1", "call-1", "result-1", "u1"].sort(), + ); +}); + +test("T1 fold: model summary already carries the full id -> stored summary byte-identical, no duplicate line", () => { + const core = createCore(); + const messages = [ + textMsg("u1", "dispatch"), + ...dispatchPair(), + textMsg("a1", "done", "assistant"), + ]; + const state = stateWithRefs(messages); + const modelSummary = `Worked with session ${SES_ID} and finished.`; + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00004", summary: modelSummary }], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + const block = result.state.blocks[0]!; + assert.equal( + block.summary, + modelSummary, + "byte-identical when the model got it right", + ); + assert.equal(result.result.notes?.length ?? 0, 0); +}); + +test("T1 fold: no ses_ ids anywhere -> stored summary byte-identical", () => { + const core = createCore(); + const messages = [ + textMsg("u1", "plain question"), + { + id: "call-1", + role: "assistant", + contentType: "tool-call" as const, + toolName: "bash", + toolCallId: "tc-1", + text: JSON.stringify({ command: "ls -la" }), + }, + { + id: "result-1", + role: "tool", + contentType: "tool-result" as const, + toolName: "bash", + toolCallId: "tc-1", + text: "file.txt\ndir/", + }, + textMsg("a1", "listed files", "assistant"), + ]; + const state = stateWithRefs(messages); + const modelSummary = "Listed the directory contents."; + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00004", summary: modelSummary }], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + assert.equal(result.state.blocks[0]!.summary, modelSummary); +}); + +test("T1 fold: ses_ id only in prose (not tool content) is NOT preserved — directed narrowing holds", () => { + const core = createCore(); + const messages = [ + textMsg("u1", `the ticket mentions ${SES_ID} in passing`), + textMsg("a1", "noted the mention", "assistant"), + ]; + const state = stateWithRefs(messages); + const modelSummary = "User mentioned a session id in passing."; + + const result = core.applyCompression({ + ranges: [{ startRef: "m00001", endRef: "m00002", summary: modelSummary }], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + assert.equal( + result.state.blocks[0]!.summary, + modelSummary, + "prose ids stay model-owned", + ); +}); + +test("T1 fold: multiple distinct ids each preserved once, duplicates across call+result collapsed", () => { + const core = createCore(); + const other = "ses_aaaabbbbccccdddd"; + const messages = [ + textMsg("u1", "fan out"), + { + id: "call-1", + role: "assistant", + contentType: "tool-call" as const, + toolName: "task", + toolCallId: "tc-1", + text: JSON.stringify({ session_id: SES_ID }), + }, + { + id: "result-1", + role: "tool", + contentType: "tool-result" as const, + toolName: "task", + toolCallId: "tc-1", + text: `done ${SES_ID}`, + }, + { + id: "call-2", + role: "assistant", + contentType: "tool-call" as const, + toolName: "task", + toolCallId: "tc-2", + text: JSON.stringify({ session_id: other }), + }, + { + id: "result-2", + role: "tool", + contentType: "tool-result" as const, + toolName: "task", + toolCallId: "tc-2", + text: `done ${other}`, + }, + textMsg("a1", "both back", "assistant"), + ]; + const state = stateWithRefs(messages); + + const result = core.applyCompression({ + ranges: [ + { startRef: "m00001", endRef: "m00006", summary: "Two subagents ran." }, + ], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + const summary = result.state.blocks[0]!.summary; + assert.equal( + summary.match(new RegExp(SES_ID, "g"))!.length, + 1, + "each id recorded once", + ); + assert.equal(summary.match(new RegExp(other, "g"))!.length, 1); + assert.ok( + summary.includes(`[acp-preserved:subagent-session] ${SES_ID}, ${other}`), + ); +}); + +// Integration: tier distillation propagation ------------------------------------- + +test("T2 distillation: ids carried in consumed T1 summaries propagate into the T2 block", () => { + const core = createCore(); + const messages = [ + textMsg("a", "early work one"), + textMsg("b", "early work two"), + textMsg("c", "later work one"), + textMsg("d", "later work two"), + ]; + const state = stateWithRefs(messages); + state.blocks.push( + makeBlock({ + blockId: "b1", + effectiveMessageIds: ["a", "b"], + summary: `Dispatched and folded earlier. [acp-preserved:subagent-session] ${SES_ID}`, + }), + makeBlock({ + blockId: "b2", + effectiveMessageIds: ["c", "d"], + summary: "Later work recap.", + }), + ); + state.nextBlockId = 3; + + const result = core.applyCompression({ + ranges: [ + { + startRef: "b1", + endRef: "b2", + summary: "Distilled span.", + topic: "distill", + }, + ], + messages, + state, + config: config(), + }); + + assert.deepEqual(result.result.errors, [], JSON.stringify(result.result)); + const created = result.state.blocks.find((b) => b.active && b.tier === 2)!; + assert.ok(created, "a T2 block was created"); + assert.ok( + created.summary.includes(SES_ID), + `T2 block lost the id: ${created.summary}`, + ); + assert.deepEqual(created.directBlockIds.sort(), ["b1", "b2"]); +}); + +// Integration: refold-in-place ---------------------------------------------------- + +test("refold-in-place: re-fold dropping the id keeps it via the machine appendix", () => { + const core = createCore(); + const messages = Array.from({ length: 4 }, (_, i) => + textMsg(`msg-${i + 1}`, `content ${i + 1}`, "assistant"), + ); + const state = stateWithRefs(messages); + state.blocks.push( + makeBlock({ + blockId: "b1", + effectiveMessageIds: messages.map((m) => m.id), + startRef: "m00001", + endRef: "m00004", + summary: `Old fold. [acp-preserved:subagent-session] ${SES_ID}`, + }), + ); + state.nextBlockId = 2; + const { state: marked } = markBlockRestoredInline(state, "b1"); + + const result = core.applyCompression({ + ranges: [ + { startRef: "m00001", endRef: "m00004", summary: "Re-folded details." }, + ], + messages: [], + state: marked, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + assert.equal( + result.state.blocks.length, + 1, + "refolded in place, no new block", + ); + const block = result.state.blocks[0]!; + assert.equal(block.blockId, "b1"); + assert.ok( + block.summary.startsWith("Re-folded details."), + "new summary leads", + ); + assert.ok( + block.summary.includes(SES_ID), + `refold dropped the id: ${block.summary}`, + ); + assert.ok( + block.summary.includes(`[acp-preserved:subagent-session] ${SES_ID}`), + ); +}); + +test("refold-in-place: id present only in still-visible tool messages is appended too", () => { + const core = createCore(); + const messages = [ + ...dispatchPair(), + textMsg("a1", "aftermath", "assistant"), + textMsg("a2", "more aftermath", "assistant"), + ]; + const state = stateWithRefs(messages); + state.blocks.push( + makeBlock({ + blockId: "b1", + effectiveMessageIds: messages.map((m) => m.id), + startRef: "m00001", + endRef: "m00004", + summary: "Old fold without any id.", + }), + ); + state.nextBlockId = 2; + const { state: marked } = markBlockRestoredInline(state, "b1"); + + const result = core.applyCompression({ + ranges: [ + { startRef: "m00001", endRef: "m00004", summary: "Re-folded again." }, + ], + messages, + state: marked, + config: config(), + }); + + assert.deepEqual(result.result.errors, []); + const block = result.state.blocks[0]!; + assert.ok( + block.summary.includes(SES_ID), + `live tool content id lost: ${block.summary}`, + ); +}); From 8480b22530e1d74405863642caebecbbc941ff48 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Tue, 29 Sep 2026 22:48:16 +0800 Subject: [PATCH 3/3] docs: list preserved-ids module in the module map --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index 1b0d3d5..f59c0a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,6 +51,7 @@ acp-kernel/ │ ├── keep-markers.ts # KEEP/REF marker preservation in summaries │ ├── ccr.ts # CCR: placeholder contract, storeLargeResults, retrieveByRef, applyRetrieve, ccrStoreNode │ ├── content-store.ts # MessageContentStore — per-session content-addressed dedup store (per-ref append-only) +│ ├── preserved-ids.ts # Mechanical fidelity (#481): verbatim id extraction from folded tool content + block appendix │ ├── prompts.ts # Prompts (4 load-bearing rules) + defaultPrompts + resolvePrompts │ ├── compress-tools.ts # ACP tool schemas (3 wire shapes) + standing-prompt builders │ ├── surface-config.ts # Surface-text overrides: applySectionOverrides, cloneWithDescriptions, applyAcpToolOverrides