fix(snapshot): preserve volatile id correlations

This commit is contained in:
Dudu-0223
2026-07-27 15:25:50 +08:00
parent 82637524a3
commit 5eca318cdc
8 changed files with 249 additions and 17 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/support/acp-snapshot/README.md
README.md: 682ab478a2e7453fa18769de93ff88a9a5316317
README.zh.md: 8e67b9fbe3b6f66df303a1f4bbfaf1de46b64a8f
README.md: 6d9226d5fcf44f41b672cd8c1a8e3bdad0623162
README.zh.md: 56a79472b1730778aff497efeefd66f0fb625bb9

View File

@@ -9,7 +9,7 @@ Four layers, importable separately:
- **`launchAcpTestAgent` (launcher)** — boots a source agent under tsx or a built `lib` agent under plain Node from a supplied cwd, connects the SDK client over a raw-byte stdout tee, collects session updates and stderr, surfaces asynchronous spawn failures through startup, fails closed on unhandled permission requests, and owns graceful or signalled shutdown. Shutdown waits for process exit, inherited stdio closure, and ACP parser exhaustion before resolving or propagating a child error, so captures are complete and callers can remove owned paths after either outcome. When Windows accepts forced termination but publishes its exit marker asynchronously, shutdown gives that marker a bounded grace before treating fallback refusal as a second failure. Snapshot and ordinary e2e suites share this process boundary; a test supplies only agent paths, cwd, environment overrides, and any permission policy.
- **`runScenario` (harness)** — drives ACP JSON-RPC stdio from a deterministic `input.json` script through the launcher, tees raw stdout for the expected-output and purity checks, and harvests every persisted raw JSONL session log (parent and subagent children, primary-first) after graceful stdin EOF. `AgentUnderTest` supplies absolute `binScript`, optional `libBinScript`, `configPath`, and `tsconfigPath` paths because the subprocess cwd is outside the repo; `workspaceParent` may move the generated child cwd from the platform temp directory when that grant is itself under test. Startup failures preserve captured agent stderr in the rejected diagnostic.
- **Normalizers** — pure functions turning the two captured surfaces into stable text: `normalizeStdout` (JSON-RPC ids → first-seen sequence; UUIDs and every native/JavaScript filesystem spelling of the generated cwd → tokens, longest-first; cwd-rooted separators selected as canonical `/` or host-native; doubles as the stdout-purity check), `normalizeSessionLog` (times zeroed, `seq` kept, the same cwd-path policy), `scrubSystemPrompts` (prompt text → `{{system}}`), `scrubToolSchemas` (schema bulk → `{{tools}}`), and `scrubRequestHeaders` (all header bulk → `{{system}}`/`{{tools}}`/`{{messagePrefix}}` outside each pin, structure kept — [pinned-header Agent Note](../../../.agents/notes/archived/testing/2026-07-06-pin-request-header-content-in-one-scenario.md)).
- **`defineAcpSnapshotSuite` (factory)** — registers the whole describe/it tree for a scenario table: per-scenario expected-output and re-persisted-log comparisons, record/refresh fixture write-back, rejection of structured `UNKNOWN_TOOL` results, the per-header-class pin (`system-prompt.expected.md` plus `tool-schemas.expected.json`) with its live uniformity guard, and the fixture guard block (no orphan scenario dirs, required files present, exactly one pin per class, every JSONL prompt/schema-scrubbed, non-pinning fixtures fully header-scrubbed). Refresh reuses normalized-equivalent leaves from aligned existing records while fresh semantic values remain authoritative; it also expands packed timing envelopes before aligning event times, so switching between packed and unpacked layouts cannot shift later records. A newly inserted `session/title` receives its preceding event's time so feature-driven insertions do not churn the remainder of a fixture. Each scenario directory's `session.jsonl` plus contiguous `session.<n>.jsonl` siblings are the ordered primary/child inventory; the scenario table does not duplicate their count. Must be called at vitest collection time.
- **`defineAcpSnapshotSuite` (factory)** — registers the whole describe/it tree for a scenario table: per-scenario expected-output and re-persisted-log comparisons, record/refresh fixture write-back, rejection of structured `UNKNOWN_TOOL` results, the per-header-class pin (`system-prompt.expected.md` plus `tool-schemas.expected.json`) with its live uniformity guard, and the fixture guard block (no orphan scenario dirs, required files present, exactly one pin per class, every JSONL prompt/schema-scrubbed, non-pinning fixtures fully header-scrubbed). Refresh reuses normalized-equivalent leaves only when the complete logical-record layout aligns and volatile string replacements form a bijection; ambiguous logs keep fresh strings, and fresh semantic values remain authoritative. It also expands packed timing envelopes before aligning event times, so switching between packed and unpacked layouts cannot shift later records. A newly inserted `session/title` receives its preceding event's time so feature-driven insertions do not churn the remainder of a fixture. Each scenario directory's `session.jsonl` plus contiguous `session.<n>.jsonl` siblings are the ordered primary/child inventory; the scenario table does not duplicate their count. Must be called at vitest collection time.
Committed session fixtures use canonical packed rows. An in-flight branch that merges this contract runs the [temporary repository migrator](../../../scripts/migrate-packed-session-fixtures.ts) with `pnpm run migrate:packed-session-fixtures`; its [removal proposal](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md) owns deletion after affected branches converge.

View File

@@ -9,7 +9,7 @@ ACP 快照套件工具包:无密钥快照层(`pnpm run test:snapshot`,见[
- **`launchAcpTestAgent`(启动器)**:从指定 cwd 在 tsx 下启动源 agent或在普通 Node 下启动已构建 `lib` agent通过原始字节 stdout tee 连接 SDK 客户端,收集会话更新和 stderr在启动过程中公开异步 spawn 失败,对未处理权限请求快速失败,并负责优雅或带信号关闭。关闭会等待进程退出、继承 stdio 关闭和 ACP parser 耗尽,然后才解析或传播子级错误,使捕获内容完整,且调用方可在任一结果后移除自有路径。当 Windows 接受强制终止但异步发布退出标记时,关闭会给该标记有界宽限,然后才将回退拒绝视为第二次失败。快照和普通 e2e 套件共享该进程边界;测试只需提供 agent 路径、cwd、环境覆盖和任何权限策略。
- **`runScenario`harness**:通过启动器从确定性 `input.json` 脚本驱动 ACP JSON-RPC stdio将原始 stdout tee 给预期输出和纯度检查,并在优雅 stdin EOF 后收集每个持久化原始 JSONL 会话日志(父级和 subagent 子级,主级优先)。`AgentUnderTest` 提供绝对 `binScript`、可选 `libBinScript``configPath``tsconfigPath` 路径,因为子进程 cwd 位于仓库外。当生成子级 cwd 自身位于待测授权中时,`workspaceParent` 可以将它从平台临时目录移出。启动失败会在拒绝诊断中保留已捕获 agent stderr。
- **规范化器**:将两个已捕获接口转换为稳定文本的纯函数:`normalizeStdout`JSON-RPC id → 首次出现序列UUID 以及生成 cwd 的每个原生/JavaScript 文件系统写法 → token按最长优先根据 cwd 的分隔符选择规范 `/` 或宿主原生形式;同时作为 stdout 纯度检查)、`normalizeSessionLog`(时间归零、保留 `seq`、使用同一 cwd 路径策略)、`scrubSystemPrompts`(提示词文本 → `{{system}}`)、`scrubToolSchemas`schema bulk → `{{tools}}`)和 `scrubRequestHeaders`(每个 pin 之外的所有 header bulk → `{{system}}`/`{{tools}}`/`{{messagePrefix}}`,保留结构;见[header 固定 Agent Note](../../../.agents/notes/archived/testing/2026-07-06-pin-request-header-content-in-one-scenario.md))。
- **`defineAcpSnapshotSuite`(工厂)**:为场景表注册完整 describe/it 树:每场景预期输出与重新持久化日志比较、录制/刷新 fixture 回写、拒绝结构化 `UNKNOWN_TOOL` 结果、每 header 类别 pin`system-prompt.expected.md``tool-schemas.expected.json`)及其实时一致性保护,以及 fixture 保护块(无遗留场景目录、必需文件存在、每类别恰好一个 pin、每个 JSONL 的提示词/schema 已擦除、非 pin fixture 的 header 已完全擦除)。刷新会从已对齐的现有记录复用规范化后等价的叶值,而新生成的语义值仍为权威数据它还会在对齐事件时间前展开打包时序 envelope因此切换打包/非打包布局无法移动后续记录。新插入的 `session/title` 使用前一个事件的时间,因此功能驱动的插入不会扰动 fixture 余下部分。每个场景目录的 `session.jsonl` 和连续 `session.<n>.jsonl` 同级文件是有序主级/子级清单;场景表不重复其数量。必须在 vitest 收集时调用。
- **`defineAcpSnapshotSuite`(工厂)**:为场景表注册完整 describe/it 树:每场景预期输出与重新持久化日志比较、录制/刷新 fixture 回写、拒绝结构化 `UNKNOWN_TOOL` 结果、每 header 类别 pin`system-prompt.expected.md``tool-schemas.expected.json`)及其实时一致性保护,以及 fixture 保护块(无遗留场景目录、必需文件存在、每类别恰好一个 pin、每个 JSONL 的提示词/schema 已擦除、非 pin fixture 的 header 已完全擦除)。只有完整逻辑记录布局对齐且易变字符串替换形成双射时,刷新才会复用规范化后等价的叶值;有歧义的日志保留本次生成的字符串,而本次生成的语义值仍为权威数据它还会在对齐事件时间前展开打包时序 envelope因此切换打包/非打包布局无法移动后续记录。新插入的 `session/title` 使用前一个事件的时间,因此功能驱动的插入不会扰动 fixture 余下部分。每个场景目录的 `session.jsonl` 和连续 `session.<n>.jsonl` 同级文件是有序主级/子级清单;场景表不重复其数量。必须在 vitest 收集时调用。
签入仓库的会话 fixture 使用规范打包行。合并此契约的在途分支通过 `pnpm run migrate:packed-session-fixtures` 运行[临时仓库迁移器](../../../scripts/migrate-packed-session-fixtures.ts);待受影响分支收敛后,由其[移除提案](../../../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md)负责删除该迁移器。

View File

@@ -524,6 +524,7 @@ function preserveNormalizedVolatiles(
existing: unknown,
normalizedFresh: unknown,
normalizedExisting: unknown,
stringMappings: ReadonlyMap<string, string>,
): unknown {
if (
Array.isArray(fresh)
@@ -541,6 +542,7 @@ function preserveNormalizedVolatiles(
existing[index],
normalizedFresh[index],
normalizedExisting[index],
stringMappings,
))
}
if (
@@ -559,10 +561,21 @@ function preserveNormalizedVolatiles(
existing[key],
normalizedFresh[key],
normalizedExisting[key],
stringMappings,
)
: value,
]))
}
if (
typeof fresh === 'string'
&& typeof existing === 'string'
&& typeof normalizedFresh === 'string'
&& normalizedFresh === normalizedExisting
) {
return stringMappings.get(JSON.stringify([normalizedFresh, fresh])) === existing
? existing
: fresh
}
return Object.is(normalizedFresh, normalizedExisting) ? existing : fresh
}
@@ -574,14 +587,124 @@ function normalizedRefreshRecord(
return JSON.parse(normalizeSessionLog(`${JSON.stringify(record)}\n`, context)) as Record<string, unknown>
}
/**
* Add normalized-equivalent string replacements to a bijection.
* Structural differences are fresh-owned and therefore contribute no mapping.
*/
function collectNormalizedStringMappings(
fresh: unknown,
existing: unknown,
normalizedFresh: unknown,
normalizedExisting: unknown,
forward: Map<string, string>,
reverse: Map<string, string>,
): boolean {
if (
Array.isArray(fresh)
&& Array.isArray(existing)
&& Array.isArray(normalizedFresh)
&& Array.isArray(normalizedExisting)
) {
if (
fresh.length !== existing.length
|| fresh.length !== normalizedFresh.length
|| fresh.length !== normalizedExisting.length
) return true
return fresh.every((value, index) => collectNormalizedStringMappings(
value,
existing[index],
normalizedFresh[index],
normalizedExisting[index],
forward,
reverse,
))
}
if (
isRecord(fresh)
&& isRecord(existing)
&& isRecord(normalizedFresh)
&& isRecord(normalizedExisting)
) {
return Object.entries(fresh).every(([key, value]) =>
!Object.hasOwn(existing, key)
|| !Object.hasOwn(normalizedFresh, key)
|| !Object.hasOwn(normalizedExisting, key)
|| collectNormalizedStringMappings(
value,
existing[key],
normalizedFresh[key],
normalizedExisting[key],
forward,
reverse,
))
}
if (
typeof fresh !== 'string'
|| typeof existing !== 'string'
|| typeof normalizedFresh !== 'string'
|| normalizedFresh !== normalizedExisting
|| fresh === existing
) return true
const freshKey = JSON.stringify([normalizedFresh, fresh])
const existingKey = JSON.stringify([normalizedFresh, existing])
const mappedExisting = forward.get(freshKey)
const mappedFresh = reverse.get(existingKey)
if (
mappedExisting !== undefined && mappedExisting !== existing
|| mappedFresh !== undefined && mappedFresh !== fresh
) return false
forward.set(freshKey, existing)
reverse.set(existingKey, fresh)
return true
}
/**
* Build a log-wide bijection for normalized-equivalent strings.
* Any unexplained record mismatch or conflicting replacement disables reuse.
*/
function normalizedStringMappings(
records: Record<string, unknown>[],
existingRecords: Record<string, unknown>[],
context: NormalizeContext,
): Map<string, string> | undefined {
const forward = new Map<string, string>()
const reverse = new Map<string, string>()
let existingIndex = 0
for (const record of records) {
const existingRecord = existingRecords[existingIndex]
const memberCount = packedTimes(record)?.length ?? 1
if (record.type === 'session/title' && existingRecord?.type !== 'session/title') continue
if (memberCount > 1) {
const existingMembers = existingRecords.slice(existingIndex, existingIndex + memberCount)
if (
existingMembers.length !== memberCount
|| existingMembers.some(member => member.type !== 'assistant/chunk')
) return undefined
} else {
if (existingRecord === undefined || existingRecord.type !== record.type) return undefined
if (!collectNormalizedStringMappings(
record,
existingRecord,
normalizedRefreshRecord(record, context),
normalizedRefreshRecord(existingRecord, context),
forward,
reverse,
)) return undefined
}
existingIndex += memberCount
}
return existingIndex === existingRecords.length ? forward : undefined
}
/**
* Rewrite a fresh replay-produced log so repeated refreshes do not churn
* volatile fixture fields. Meaningful event payloads come from `fresh`; the
* existing fixture lends normalized-equivalent values, including ids, paths,
* creation/event times, spill locators, and hook durations, where records
* still align. Packed timing envelopes expand for alignment, so packing does
* not shift later records; fresh semantic values and fragment arrays remain
* authoritative.
* creation/event times, spill locators, and hook durations, only when the
* complete record layout aligns and volatile strings form a consistent
* bijection. Ambiguous layouts or mappings keep fresh strings. Packed timing
* envelopes expand for alignment, so packing does not shift later records;
* fresh semantic values and fragment arrays remain authoritative.
*
* @param fresh The newly harvested session JSONL.
* @param existing The committed fixture JSONL being refreshed.
@@ -594,6 +717,7 @@ export function stabilizeRefreshLog(fresh: string, existing: string, replacement
const existingRecords = logicalRecords(parseJsonlRecords(existing))
const records = parseJsonlRecords(stable)
const context = fixtureContext(existing)
const stringMappings = normalizedStringMappings(records, existingRecords, context)
let existingIndex = 0
let previousEventTime: unknown
for (let i = 0; i < records.length; i++) {
@@ -606,12 +730,18 @@ export function stabilizeRefreshLog(fresh: string, existing: string, replacement
if (typeof previousEventTime !== 'number') throw new Error('acp-snapshot: inserted title has no preceding event time')
record.time = previousEventTime
} else {
if (memberCount === 1 && existingRecord !== undefined && existingRecord.type === record.type) {
if (
stringMappings !== undefined
&& memberCount === 1
&& existingRecord !== undefined
&& existingRecord.type === record.type
) {
record = preserveNormalizedVolatiles(
record,
existingRecord,
normalizedRefreshRecord(record, context),
normalizedRefreshRecord(existingRecord, context),
stringMappings,
) as Record<string, unknown>
records[i] = record
}

View File

@@ -695,4 +695,102 @@ describe('stabilizeRefreshLog', () => {
},
])
})
it('preserves one correlated volatile id through a consistent log-wide mapping', () => {
const freshId = '11111111-1111-4111-8111-111111111111'
const existingId = '22222222-2222-4222-8222-222222222222'
const fresh = [
'{"type":"session","id":"same","createdAt":200,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: freshId } }),
JSON.stringify({ type: 'approval/decided', data: { id: freshId, outcome: 'allowed-once' } }),
'',
].join('\n')
const existing = [
'{"type":"session","id":"same","createdAt":100,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: existingId } }),
JSON.stringify({ type: 'approval/decided', data: { id: existingId, outcome: 'rejected' } }),
'',
].join('\n')
expect(stabilizeRefreshLog(fresh, existing, [])).toBe([
'{"type":"session","id":"same","createdAt":100,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: existingId } }),
JSON.stringify({ type: 'approval/decided', data: { id: existingId, outcome: 'allowed-once' } }),
'',
].join('\n'))
})
it('keeps fresh correlated ids when record alignment is structurally ambiguous', () => {
const firstFreshId = '11111111-1111-4111-8111-111111111111'
const secondFreshId = '22222222-2222-4222-8222-222222222222'
const existingId = '33333333-3333-4333-8333-333333333333'
const fresh = [
'{"type":"session","id":"same","createdAt":200,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: firstFreshId } }),
JSON.stringify({ type: 'approval/asked', data: { id: secondFreshId } }),
JSON.stringify({ type: 'approval/decided', data: { id: firstFreshId } }),
JSON.stringify({ type: 'approval/decided', data: { id: secondFreshId } }),
'',
].join('\n')
const existing = [
'{"type":"session","id":"same","createdAt":100,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: existingId } }),
JSON.stringify({ type: 'approval/decided', data: { id: existingId } }),
'',
].join('\n')
const ids = stabilizeRefreshLog(fresh, existing, []).trim().split('\n').slice(1)
.map(line => (JSON.parse(line) as { data: { id: string } }).data.id)
expect(ids).toEqual([firstFreshId, secondFreshId, firstFreshId, secondFreshId])
})
it('keeps fresh ids when existing records remain unmatched', () => {
const freshId = '11111111-1111-4111-8111-111111111111'
const existingId = '22222222-2222-4222-8222-222222222222'
const fresh = [
'{"type":"session","id":"same","createdAt":200,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: freshId } }),
'',
].join('\n')
const existing = [
'{"type":"session","id":"same","createdAt":100,"cwd":"/old"}',
JSON.stringify({ type: 'approval/asked', data: { id: existingId } }),
JSON.stringify({ type: 'approval/decided', data: { id: existingId } }),
'',
].join('\n')
const output = stabilizeRefreshLog(fresh, existing, []).trim().split('\n')
.map(line => JSON.parse(line) as Record<string, unknown>)
expect(output[1]).toEqual({ type: 'approval/asked', data: { id: freshId } })
})
it.each([
{
name: 'one fresh id would map to two existing ids',
fresh: ['a', 'b', 'b', 'a'],
existing: ['x', 'y', 'x', 'y'],
},
{
name: 'two fresh ids would map to one existing id',
fresh: ['a', 'b'],
existing: ['x', 'x'],
},
])('keeps fresh ids when $name', ({ fresh: freshNames, existing: existingNames }) => {
const ids = {
a: '11111111-1111-4111-8111-111111111111',
b: '22222222-2222-4222-8222-222222222222',
x: '33333333-3333-4333-8333-333333333333',
y: '44444444-4444-4444-8444-444444444444',
} as const
const types = ['approval/asked', 'approval/asked', 'approval/decided', 'approval/decided']
const log = (names: string[]): string => [
'{"type":"session","id":"same","createdAt":100,"cwd":"/old"}',
...names.map((name, index) => JSON.stringify({ type: types[index], data: { id: ids[name as keyof typeof ids] } })),
'',
].join('\n')
const outputIds = stabilizeRefreshLog(log(freshNames), log(existingNames), []).trim().split('\n').slice(1)
.map(line => (JSON.parse(line) as { data: { id: string } }).data.id)
expect(outputIds).toEqual(freshNames.map(name => ids[name as keyof typeof ids]))
})
})