diff --git a/.changeset/strict-cache-long-test-id.md b/.changeset/strict-cache-long-test-id.md new file mode 100644 index 0000000000..3ead905e10 --- /dev/null +++ b/.changeset/strict-cache-long-test-id.md @@ -0,0 +1,6 @@ +--- +'e2e': patch +'@e2e-dev/core': patch +--- + +`--strict-cache` no longer fails with `REPLAY_STALE` a never-recorded step whose test id, target, or agent name is over 300 characters and starts like a recorded one. diff --git a/docs/cache.mdx b/docs/cache.mdx index 545efed9e1..4a64450cb0 100644 --- a/docs/cache.mdx +++ b/docs/cache.mdx @@ -394,6 +394,7 @@ CI=1 bunx e2e run --strict-cache | `invalid-entry`, `wrong-context`, `target-not-found`, `target-ambiguous`, `viewport-changed`, `action-failed`, `action-uncertain`, `end-mismatch`: the app or the entry changed | A step never recorded (a new or edited instruction or params) | | `no-entry`, when the cache directory holds a recording of the same step under another key | A `gap` or a `truncated` recording | | | A step whose store read fails | +| | A step whose test's `testId` in `report.json`, target name, or agent name is over 300 characters, when an earlier `e2e` version recorded it under another key and no `read-write` run of this version has replayed it since | A recording under another key comes from an `e2e` upgrade that changed the keys, or a change to the project id, the app's identity, or the agent's diff --git a/docs/ja/cache.mdx b/docs/ja/cache.mdx index b774051d1d..fded905be1 100644 --- a/docs/ja/cache.mdx +++ b/docs/ja/cache.mdx @@ -254,6 +254,7 @@ CI=1 bunx e2e run --strict-cache | `invalid-entry`、`wrong-context`、`target-not-found`、`target-ambiguous`、`viewport-changed`、`action-failed`、`action-uncertain`、`end-mismatch`: アプリまたはエントリーが変わった | 一度も記録されていないステップ(新規または編集済みの指示やパラメーター) | | `no-entry`: キャッシュディレクトリに同じステップの記録が別のキーで存在する場合 | `gap` または `truncated` の記録 | | | ストアの読み取りが失敗したステップ | +| | テストの `report.json` の `testId`、ターゲット名、エージェント名のいずれかが 300 文字を超えるステップで、以前の `e2e` バージョンが別のキーで記録し、その後このバージョンの `read-write` の実行で再生されていないもの | 別のキーの記録は、キーを変える `e2e` のアップグレード、プロジェクト ID、アプリの識別情報、エージェントのコンテキストの変更などで生じます。メッセージにはそのファイルと、現行バージョンで作られた記録なら変更点も示されます。何も再生しなくなったファイルは削除してください。この検査は、独自の `cache.store` には適用されません。 diff --git a/docs/zh/cache.mdx b/docs/zh/cache.mdx index 2942acd6ec..ba017fd000 100644 --- a/docs/zh/cache.mdx +++ b/docs/zh/cache.mdx @@ -254,6 +254,7 @@ CI=1 bunx e2e run --strict-cache | `invalid-entry`、`wrong-context`、`target-not-found`、`target-ambiguous`、`viewport-changed`、`action-failed`、`action-uncertain`、`end-mismatch`:应用或条目发生了变化 | 从未录制过的步骤(新建或编辑过的指令或参数) | | `no-entry`,且缓存目录中存在使用其他键的同一步骤录制记录 | `gap` 或 `truncated` 录制记录 | | | 从存储读取失败的步骤 | +| | 测试在 `report.json` 中的 `testId`、目标名称或智能体名称超过 300 个字符的步骤,且其录制记录由较早的 `e2e` 版本以其他键生成,之后也没有此版本的 `read-write` 运行回放过它 | 其他键下的录制记录可能来自改变键的 `e2e` 升级,也可能来自项目 ID、应用标识或智能体上下文的变化。消息会指出该文件;如果记录由当前版本生成,还会说明变化内容。如果已无回放使用该文件,请删除它。此检查不涵盖自定义 `cache.store`。 diff --git a/packages/core/src/cache/context.ts b/packages/core/src/cache/context.ts index 27fbd4c922..31d3ea9386 100644 --- a/packages/core/src/cache/context.ts +++ b/packages/core/src/cache/context.ts @@ -37,9 +37,8 @@ import type { JsonValue } from '../types.ts'; * stands. A kept entry carries no payload, so the replay's expansion of it * (every `unique()` slot filled with this run's value) can never be written; * confirmed, the file keeps its bytes and `createdAt`, and a committed cache - * directory stays clean, unless its provenance predates the step's - * occurrence fields (`recordedFor`, as stored), which the replay proved and - * are then written in. Unconfirmed, both kinds are evicted alike. + * directory stays clean, but for the provenance the replay proved, which + * `completeProvenance` writes in. Unconfirmed, both kinds are evicted alike. */ export type StagedTrace = { readonly keyHash: string; @@ -140,15 +139,19 @@ function flowOf(trace: ActionTrace): string { } /** - * Writes the step's full provenance into a kept entry recorded before the - * occurrence fields were, leaving every other entry untouched. Its replay - * proved which step it belongs to, and `cache.strict` matches only entries - * that say so exactly (`rekeyed.ts`). + * Writes the step's full provenance into a kept entry whose stored provenance + * lacks the occurrence fields, or whose identity digest is not the step's: + * missing while the step has one, different, or present while the step has + * none. Every other entry is left untouched. Its replay proved which step it + * belongs to, and `cache.strict` matches only entries that say so exactly + * (`rekeyed.ts`). */ async function completeProvenance(store: CacheStore, keyHash: string, recordedFor: TraceProvenance): Promise { const existing = await store.read(keyHash); - if (existing.status !== 'hit' || existing.entry.payload.recordedFor?.callIndex !== undefined) return; - await store.write(keyHash, { ...existing.entry.payload, recordedFor }); + if (existing.status !== 'hit') return; + const stored = existing.entry.payload.recordedFor; + const complete = stored?.callIndex !== undefined && stored.identityDigest === recordedFor.identityDigest; + if (!complete) await store.write(keyHash, { ...existing.entry.payload, recordedFor }); } /** How an attempt ended, as the settlement of its staged entries reads it. */ @@ -200,7 +203,8 @@ export interface SurvivedFailure { * no settlement: interruption implicates nothing, so it writes nothing and * evicts nothing. An entry a step replayed whole is staged too, * so the same rule evicts it when nothing confirmed it; when something did, - * it is left exactly as it was found, but for provenance it lacked. + * it is left exactly as it was found, but for what `completeProvenance` + * writes in. */ export async function settleStagedTraces(context: AgentCacheContext, settlement: AttemptSettlement | undefined): Promise> { const outcomes = new Map(); diff --git a/packages/core/src/cache/recorder.ts b/packages/core/src/cache/recorder.ts index 9246ce5f6f..878f29c924 100644 --- a/packages/core/src/cache/recorder.ts +++ b/packages/core/src/cache/recorder.ts @@ -39,7 +39,8 @@ import { type TraceTargetDescriptor, } from './trace.ts'; import { readRecordedModel } from './trace-fields.ts'; -import { bound } from '../internal/text.ts'; +import { sha256Hex } from '../internal/ids.ts'; +import { bound, boundIsAmbiguous } from '../internal/text.ts'; /** The summary a run-time value gap records; the prose a project-tool gap would carry for a tool of that name. */ const DERIVED_GAP_SUMMARY = 'tool type (run-time value)'; @@ -342,12 +343,17 @@ function sameTarget(a: TraceTargetDescriptor | undefined, b: TraceTargetDescript * the store holds. */ export function recordedProvenance(provenance: TraceProvenance, redact: (text: string) => string): TraceProvenance { + const testId = redact(provenance.testId); + const targetId = redact(provenance.targetId); + const agent = provenance.agent === undefined ? undefined : redact(provenance.agent); + const ambiguous = [testId, targetId, agent ?? ''].some((text) => boundIsAmbiguous(text, MAX_TRACE_DESCRIPTOR_CHARS)); return { - testId: bound(redact(provenance.testId), MAX_TRACE_DESCRIPTOR_CHARS), - targetId: bound(redact(provenance.targetId), MAX_TRACE_DESCRIPTOR_CHARS), + testId: bound(testId, MAX_TRACE_DESCRIPTOR_CHARS), + targetId: bound(targetId, MAX_TRACE_DESCRIPTOR_CHARS), instructionDigest: provenance.instructionDigest, ...(provenance.paramsDigest === undefined ? {} : { paramsDigest: provenance.paramsDigest }), ...(provenance.callIndex === undefined ? {} : { callIndex: provenance.callIndex }), - ...(provenance.agent === undefined ? {} : { agent: bound(redact(provenance.agent), MAX_TRACE_DESCRIPTOR_CHARS) }), + ...(agent === undefined ? {} : { agent: bound(agent, MAX_TRACE_DESCRIPTOR_CHARS) }), + ...(ambiguous ? { identityDigest: sha256Hex(JSON.stringify([testId, targetId, agent ?? null])) } : {}), }; } diff --git a/packages/core/src/cache/rekeyed.ts b/packages/core/src/cache/rekeyed.ts index 3b966e7d31..b8337f4d3c 100644 --- a/packages/core/src/cache/rekeyed.ts +++ b/packages/core/src/cache/rekeyed.ts @@ -85,9 +85,13 @@ export function storedRecordingsFor(cache: ResolvedCacheConfig): StoredRecording return new StoredRecordings(new FileCacheStore({ directory: cache.dir, maxBytes: MAX_CACHE_WIRE_BYTES, writable: false })); } -/** The whole step as one map key, or undefined when the provenance does not record all of it. */ +/** + * The whole step as one map key, or undefined when the provenance does not + * record all of it. When an entry could store a name cut, the key includes + * `identityDigest`, so such a step never matches an entry without one. + */ function stepKey(step: TraceProvenance): string | undefined { - const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent } = step; + const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent, identityDigest } = step; if (paramsDigest === undefined || callIndex === undefined || agent === undefined) return undefined; - return JSON.stringify([testId, targetId, instructionDigest, paramsDigest, callIndex, agent]); + return JSON.stringify([testId, targetId, instructionDigest, paramsDigest, callIndex, agent, identityDigest ?? null]); } diff --git a/packages/core/src/cache/trace-read.ts b/packages/core/src/cache/trace-read.ts index df68f58a55..057a392187 100644 --- a/packages/core/src/cache/trace-read.ts +++ b/packages/core/src/cache/trace-read.ts @@ -408,6 +408,11 @@ function readPosition(document: unknown): TracePosition | undefined { return { index: index as number, of: of as number }; } +/** Whether a provenance field that may be absent is absent or a SHA-256 hex digest. */ +function isOptionalDigest(value: unknown): value is string | undefined { + return value === undefined || (typeof value === 'string' && SHA256_HEX.test(value)); +} + function readProvenance(document: unknown): TraceProvenance | undefined { if (typeof document !== 'object' || document === null || Array.isArray(document)) { return undefined; @@ -419,13 +424,15 @@ function readProvenance(document: unknown): TraceProvenance | undefined { if (testId === undefined || targetId === undefined) return undefined; if (typeof instructionDigest !== 'string' || !SHA256_HEX.test(instructionDigest)) return undefined; const paramsDigest = raw['paramsDigest']; - if (paramsDigest !== undefined && (typeof paramsDigest !== 'string' || !SHA256_HEX.test(paramsDigest))) return undefined; + if (!isOptionalDigest(paramsDigest)) return undefined; const callIndex = raw['callIndex']; if (callIndex !== undefined && (typeof callIndex !== 'number' || !Number.isSafeInteger(callIndex) || callIndex < 0)) { return undefined; } const agent = raw['agent'] === undefined ? undefined : readBoundedText(raw['agent'], MAX_TRACE_DESCRIPTOR_CHARS); if (raw['agent'] !== undefined && agent === undefined) return undefined; + const identityDigest = raw['identityDigest']; + if (!isOptionalDigest(identityDigest)) return undefined; return { testId, targetId, @@ -433,6 +440,7 @@ function readProvenance(document: unknown): TraceProvenance | undefined { ...(paramsDigest === undefined ? {} : { paramsDigest }), ...(callIndex === undefined ? {} : { callIndex }), ...(agent === undefined ? {} : { agent }), + ...(identityDigest === undefined ? {} : { identityDigest }), }; } diff --git a/packages/core/src/cache/trace.ts b/packages/core/src/cache/trace.ts index 4a142a52a0..55b257074a 100644 --- a/packages/core/src/cache/trace.ts +++ b/packages/core/src/cache/trace.ts @@ -105,6 +105,13 @@ export interface TraceProvenance { readonly callIndex?: number; /** Name of the configured agent the step ran with. */ readonly agent?: string; + /** + * SHA-256 of the whole redacted test id, target id, and agent name, only + * when one of them is longer than an entry keeps or ends like a cut (a + * `createAgent` cache key can): two steps whose stored text is the same + * share the digest only when their names differ in a secret value alone. + */ + readonly identityDigest?: string; } /** diff --git a/packages/core/src/internal/text.ts b/packages/core/src/internal/text.ts index fb8df7bdea..9c385ab307 100644 --- a/packages/core/src/internal/text.ts +++ b/packages/core/src/internal/text.ts @@ -17,6 +17,14 @@ export function bound(text: string, maxChars: number): string { return `${text.slice(0, end)}…`; } +/** + * Whether `bound(text, maxChars)` could equal what `bound` makes of a + * different text: it cuts `text`, or `text` already ends like a cut. + */ +export function boundIsAmbiguous(text: string, maxChars: number): boolean { + return text.length > maxChars || (text.length >= maxChars - 1 && text.endsWith('…')); +} + /** * Normalizes text by trimming leading/trailing whitespace and replacing every * nonempty run of Unicode whitespace with one ASCII space. diff --git a/packages/e2e/tests/unit/step-cache.test.ts b/packages/e2e/tests/unit/step-cache.test.ts index 581845b6a4..17681832f9 100644 --- a/packages/e2e/tests/unit/step-cache.test.ts +++ b/packages/e2e/tests/unit/step-cache.test.ts @@ -6,9 +6,10 @@ import { join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { settleStagedTraces, type AgentCacheContext, type ClaimedKey } from '@e2e-dev/core/lib/cache/context'; import { instructionDigest, paramsDigest } from '@e2e-dev/core/lib/cache/identity'; +import { recordedProvenance } from '@e2e-dev/core/lib/cache/recorder'; import { StoredRecordings } from '@e2e-dev/core/lib/cache/rekeyed'; import { FileCacheStore, MAX_CACHE_WIRE_BYTES } from '@e2e-dev/core/lib/cache/store'; -import { buildTraceEntry, type ActionTrace, type DerivedReason, type TraceEntry } from '@e2e-dev/core/lib/cache/trace'; +import { buildTraceEntry, MAX_TRACE_DESCRIPTOR_CHARS, type ActionTrace, type DerivedReason, type TraceEntry } from '@e2e-dev/core/lib/cache/trace'; import { failedStepOutcome, recordedVerdictOf, StepTraceSession, type StepCacheHost, type StepCacheOptions } from '@e2e-dev/core/lib/agent/step-cache'; import { AgentError } from '@e2e-dev/core/lib/agent/error'; import type { ExecutorActions } from '@e2e-dev/core/lib/agent/executor'; @@ -1394,6 +1395,57 @@ describe('cache.strict and a step whose key changed under its recording', () => } }); + describe.each(['testId', 'targetId', 'agent'] as const)('when the %s is longer than an entry keeps', (field) => { + const long = 'checkout for a signed in customer with a saved card '.repeat(6); + const stepWith = (value: string) => ({ ...exampleStep, [field]: value }); + const sessionFor = (context: AgentCacheContext, step: typeof exampleStep) => + makeSession({ ...context, claimKey: () => ({ keyHash: OWN_KEY, context: exampleContext, step }) }, makeHost(['/'])); + + it('runs live when only another step that starts the same way was recorded', async () => { + const context = await rekeyedContext(recordedPayload(recordedProvenance(stepWith(`${long} first`), (text) => text))); + const session = sessionFor(context, stepWith(`${long} second`)); + await expect(session.begin()).resolves.toBeUndefined(); + expect(session.cacheInfo).toMatchObject({ mode: 'missed', reason: 'no-entry' }); + }); + + it('fails with REPLAY_STALE when its own recording sits under another key', async () => { + const step = stepWith(`${long} first`); + const stored = recordedProvenance(step, (text) => text); + expect(stored[field]).toHaveLength(MAX_TRACE_DESCRIPTOR_CHARS); + const session = sessionFor(await rekeyedContext(recordedPayload(stored)), step); + await expect(session.begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' }); + }); + + it('runs live against an entry that cut it before entries kept an identity digest', async () => { + const step = stepWith(`${long} first`); + const { identityDigest: _digest, ...legacy } = recordedProvenance(step, (text) => text); + await expect(sessionFor(await rekeyedContext(recordedPayload(legacy)), step).begin()).resolves.toBeUndefined(); + }); + + it('runs live when its whole name equals the cut name of another step, stored without an identity digest', async () => { + const { identityDigest: _digest, ...legacy } = recordedProvenance(stepWith(`${long} first`), (text) => text); + const step = stepWith(legacy[field]!); + await expect(sessionFor(await rekeyedContext(recordedPayload(legacy)), step).begin()).resolves.toBeUndefined(); + }); + + it('fails with REPLAY_STALE when its whole name ends like a cut and its own recording sits under another key', async () => { + for (const length of [MAX_TRACE_DESCRIPTOR_CHARS - 1, MAX_TRACE_DESCRIPTOR_CHARS]) { + const step = stepWith(`${'x'.repeat(length - 1)}…`); + const stored = recordedProvenance(step, (text) => text); + expect(stored.identityDigest, String(length)).toMatch(/^[a-f0-9]{64}$/u); + const session = sessionFor(await rekeyedContext(recordedPayload(stored)), step); + await expect(session.begin(), String(length)).rejects.toMatchObject({ code: 'REPLAY_STALE' }); + } + }); + + it(`fails with REPLAY_STALE at exactly ${MAX_TRACE_DESCRIPTOR_CHARS} characters, which an entry keeps whole`, async () => { + const step = stepWith('x'.repeat(MAX_TRACE_DESCRIPTOR_CHARS)); + const stored = recordedProvenance(step, (text) => text); + expect(stored).toEqual(step); + await expect(sessionFor(await rekeyedContext(recordedPayload(stored)), step).begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' }); + }); + }); + it('runs live when the only recording is truncated or records no step', async () => { const tapUpgrade = { name: 'tap', summary: 'tap button "Upgrade"', target: { role: 'button', name: 'Upgrade' } } as const; const truncated = recordedPayload(exampleStep, { actions: Array.from({ length: 50 }, () => tapUpgrade), truncated: true }); diff --git a/packages/e2e/tests/unit/text.test.ts b/packages/e2e/tests/unit/text.test.ts index bd35f890cb..706f442775 100644 --- a/packages/e2e/tests/unit/text.test.ts +++ b/packages/e2e/tests/unit/text.test.ts @@ -1,6 +1,6 @@ import { runInNewContext } from 'node:vm'; import { describe, expect, it } from 'vitest'; -import { bound, compareText, matchesText, normalizeRegexpFlags, normalizeText, toTextPattern } from '@e2e-dev/core/lib/internal/text'; +import { bound, boundIsAmbiguous, compareText, matchesText, normalizeRegexpFlags, normalizeText, toTextPattern } from '@e2e-dev/core/lib/internal/text'; describe('normalizeText', () => { it('trims and collapses unicode whitespace runs to one ASCII space', () => { @@ -86,3 +86,14 @@ describe('bound', () => { expect(bound(`ab😀def`, 5)).toBe('ab😀…'); }); }); + +describe('boundIsAmbiguous', () => { + it('holds for text bound cuts and for text that ends like one of its cuts, and for nothing else', () => { + expect(boundIsAmbiguous('abcdef', 5)).toBe(true); + expect(boundIsAmbiguous('abcd…', 5)).toBe(true); + expect(boundIsAmbiguous('abc…', 5)).toBe(true); + expect(boundIsAmbiguous('abcde', 5)).toBe(false); + expect(boundIsAmbiguous('ab…', 5)).toBe(false); + expect(boundIsAmbiguous('loading…', 300)).toBe(false); + }); +}); diff --git a/packages/e2e/tests/unit/trace-cache-config.test.ts b/packages/e2e/tests/unit/trace-cache-config.test.ts index d9bffff67a..84236461f7 100644 --- a/packages/e2e/tests/unit/trace-cache-config.test.ts +++ b/packages/e2e/tests/unit/trace-cache-config.test.ts @@ -6,9 +6,11 @@ import { chmod, mkdtemp, readFile, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { describe, expect, it } from 'vitest'; import { createAgentCacheContext, settleStagedTraces } from '@e2e-dev/core/lib/cache/context'; +import { recordedProvenance } from '@e2e-dev/core/lib/cache/recorder'; import { FileCacheStore } from '@e2e-dev/core/lib/cache/store'; import { buildTraceEntry } from '@e2e-dev/core/lib/cache/trace'; import { readTraceEntry } from '@e2e-dev/core/lib/cache/trace-read'; +import { SecretLedger } from '@e2e-dev/core/lib/internal/redact'; import { resolveConfig } from '../../src/config/resolve-run.ts'; import type { ActionTrace, CacheStore } from '@e2e-dev/core/lib/types'; import type { E2EConfig } from '../../src/run-types.ts'; @@ -358,6 +360,68 @@ describe('settleStagedTraces', () => { expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload).toEqual({ ...recorded, recordedFor: STEP }); }); + it('writes the identity digest into a confirmed kept entry that cut a long test id before entries kept one', async () => { + const store = memoryStore(); + const long = { ...STEP, testId: `${STEP.testId}${'x'.repeat(400)}` }; + const recordedFor = recordedProvenance(long, (text) => text); + const { identityDigest, ...legacy } = recordedFor; + expect(identityDigest).toMatch(/^[a-f0-9]{64}$/u); + store.entries.set(KEY_A, JSON.stringify(buildTraceEntry({ ...trace('replayed flow'), recordedFor: legacy }))); + const context = contextWith(store); + context.staged.push({ kind: 'keep', keyHash: KEY_A, stepIndex: 1, recordedFor }); + await settleStagedTraces(context, { lastVerifiedStepIndex: 2, implicatesUnconfirmed: true }); + expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload.recordedFor).toEqual(recordedFor); + }); + + it('leaves a confirmed kept entry that already keeps the step\'s identity digest exactly as stored', async () => { + const store = memoryStore(); + const recordedFor = recordedProvenance({ ...STEP, testId: `${STEP.testId}${'x'.repeat(400)}` }, (text) => text); + expect(recordedFor.identityDigest).toMatch(/^[a-f0-9]{64}$/u); + const stored = JSON.stringify(buildTraceEntry({ ...trace('replayed flow'), recordedFor })); + store.entries.set(KEY_A, stored); + const written: string[] = []; + const context = contextWith({ + ...store, + write: async (keyHash, payload) => { + written.push(keyHash); + return store.write(keyHash, payload); + }, + }); + context.staged.push({ kind: 'keep', keyHash: KEY_A, stepIndex: 1, recordedFor }); + const writes = await settleStagedTraces(context, { lastVerifiedStepIndex: 2, implicatesUnconfirmed: true }); + expect(written).toEqual([]); + expect(store.entries.get(KEY_A)).toBe(stored); + expect(writes.get(1)).toBe('kept'); + }); + + it('replaces the identity digest of a confirmed kept entry whose names redact differently now', async () => { + const store = memoryStore(); + const step = { ...STEP, testId: `${STEP.testId}${'x'.repeat(400)} as hunter2` }; + store.entries.set(KEY_A, JSON.stringify(buildTraceEntry({ ...trace('replayed flow'), recordedFor: recordedProvenance(step, (text) => text) }))); + const secrets = new SecretLedger(); + secrets.register('password', 'hunter2'); + const recordedFor = recordedProvenance(step, secrets.redact); + const context = contextWith(store); + context.staged.push({ kind: 'keep', keyHash: KEY_A, stepIndex: 1, recordedFor }); + await settleStagedTraces(context, { lastVerifiedStepIndex: 2, implicatesUnconfirmed: true }); + expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload.recordedFor).toEqual(recordedFor); + }); + + it('drops the identity digest of a confirmed kept entry whose names no longer need one', async () => { + const store = memoryStore(); + const step = { ...STEP, testId: `${'x'.repeat(290)}hunter2` }; + const secrets = new SecretLedger(); + secrets.register('password', 'hunter2'); + const recorded = recordedProvenance(step, secrets.redact); + expect(recorded.identityDigest).toMatch(/^[a-f0-9]{64}$/u); + store.entries.set(KEY_A, JSON.stringify(buildTraceEntry({ ...trace('replayed flow'), recordedFor: recorded }))); + const recordedFor = recordedProvenance(step, (text) => text); + const context = contextWith(store); + context.staged.push({ kind: 'keep', keyHash: KEY_A, stepIndex: 1, recordedFor }); + await settleStagedTraces(context, { lastVerifiedStepIndex: 2, implicatesUnconfirmed: true }); + expect(readTraceEntry(JSON.parse(store.entries.get(KEY_A)!))?.payload.recordedFor?.identityDigest).toBeUndefined(); + }); + it('writes what was confirmed and leaves every unconfirmed entry as stored when the failure implicates nothing', async () => { const KEY_C = 'c'.repeat(64); const store = memoryStore(); @@ -399,3 +463,53 @@ describe('settleStagedTraces', () => { expect(other).not.toBe(first); }); }); + +describe('recorded provenance', () => { + it('takes the identity digest over the redacted names, so it never depends on a secret value', () => { + const long = `${STEP.testId}${'x'.repeat(400)}`; + const digestWith = (value: string) => { + const secrets = new SecretLedger(); + secrets.register('password', value); + return recordedProvenance({ ...STEP, testId: `${long} as ${value}` }, secrets.redact).identityDigest; + }; + expect(digestWith('hunter2')).toMatch(/^[a-f0-9]{64}$/u); + expect(digestWith('hunter2')).toBe(digestWith('swordfish')); + }); + + it.each(['targetId', 'agent'] as const)('stores the %s redacted and takes the digest over it redacted', (field) => { + const recorded = (value: string) => { + const secrets = new SecretLedger(); + secrets.register('password', value); + return recordedProvenance({ ...STEP, testId: `${STEP.testId}${'x'.repeat(400)}`, [field]: `staging-${value}` }, secrets.redact); + }; + expect(recorded('hunter2')[field]).not.toContain('hunter2'); + expect(recorded('hunter2').identityDigest).toMatch(/^[a-f0-9]{64}$/u); + expect(recorded('hunter2').identityDigest).toBe(recorded('swordfish').identityDigest); + }); + + it('measures the redacted names, so a name a secret makes longer than an entry keeps gets a digest', () => { + const secrets = new SecretLedger(); + secrets.register('password', 'hunter2'); + // Under 300 characters as written, over 300 once `hunter2` is redacted. + const variant = (title: string) => recordedProvenance({ ...STEP, testId: `${'x'.repeat(280)} hunter2 ${title}` }, secrets.redact); + const [first, second] = [variant('first'), variant('second')]; + expect(first.testId).toBe(second.testId); + expect(first.identityDigest).toMatch(/^[a-f0-9]{64}$/u); + expect(second.identityDigest).toMatch(/^[a-f0-9]{64}$/u); + expect(first.identityDigest).not.toBe(second.identityDigest); + }); +}); + +describe('reading recorded provenance', () => { + it.each([ + ['paramsDigest', 'not-a-digest'], + ['paramsDigest', 42], + ['identityDigest', 'not-a-digest'], + ['identityDigest', ['a'.repeat(64)]], + ['identityDigest', 42], + ])('refuses an entry whose %s is %j', (field, digest) => { + const entry = JSON.parse(JSON.stringify(buildTraceEntry({ ...trace('recorded flow'), recordedFor: STEP }))); + entry.payload.recordedFor[field] = digest; + expect(readTraceEntry(entry)).toBeUndefined(); + }); +});