Skip to content

Commit 54fe25e

Browse files
committed
refactor(capture-kit): encode post-gesture baseline provenance in types
The stability loop copied baselineSignature/baselineBackend into locals, tracked rebasing in a separate boolean, and re-derived distrust from 'needsBaselineDistrust && !baselineRebased'. The #3868 bug class was exactly the invalid combination that plumbing allowed: a post-action rebased baseline treated as pre-action evidence. Replace it with a discriminated union: no baseline, pre-action evidence, or a post-action baseline adopted by a rebase. Only the pre-action variant can produce distrust or stale acceptance, and accept-stale carries the original pre-action reading as its payload, so the no-effect proof consumes exactly the evidence that authorized it. Bundle signature and comparison key in the session's optional baseline value, constructed only where the writer decides Apple distrust applies, and drop the separately threaded needsBaselineDistrust parameter. Behavior and timing are unchanged. Refs #3868, #3875
1 parent 6ea9f81 commit 54fe25e

8 files changed

Lines changed: 173 additions & 151 deletions

‎packages/capture-kit/src/post-gesture-stability.test.ts‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
44
import type { ObservationClock } from './observe-until.ts';
55
import {
66
runPostGestureStabilityLoop,
7+
type PostGesturePreActionBaseline,
78
type PostGestureStabilityHooks,
89
} from './post-gesture-stability.ts';
910

@@ -46,7 +47,10 @@ function hooksFor(
4647
clock.advance(surface.costMs);
4748
return surface;
4849
},
49-
readSurface: (value) => ({ signature: value.signature, backend: value.backend ?? 'xctest' }),
50+
readSurface: (value) => ({
51+
signature: value.signature,
52+
comparisonKey: value.backend ?? 'xctest',
53+
}),
5054
signaturesStable: same,
5155
classifyBaselineEvidence: (baseline, quiet) =>
5256
same(baseline, quiet) ? 'unchanged' : 'changed',
@@ -57,6 +61,13 @@ function hooksFor(
5761

5862
const PENDING = { action: 'scroll', positionals: ['down'] };
5963

64+
function preActionBaseline(
65+
signature: readonly string[],
66+
comparisonKey: string,
67+
): PostGesturePreActionBaseline<readonly string[]> {
68+
return { provenance: 'pre-action', signature, comparisonKey };
69+
}
70+
6071
function diagnostics(phase: string): unknown[] {
6172
return vi.mocked(emitDiagnostic).mock.calls.filter(([event]) => event.phase === phase);
6273
}
@@ -71,7 +82,6 @@ test('a capture that runs past the remaining budget is judged and ends unsettled
7182

7283
const outcome = await runPostGestureStabilityLoop({
7384
pending: PENDING,
74-
needsBaselineDistrust: false,
7585
hooks: hooksFor(clock, [{ signature: ['a'], costMs: 0 }, late]),
7686
clock,
7787
});
@@ -90,7 +100,6 @@ test('a first capture slower than the whole budget still forms a quiet pair', as
90100

91101
const outcome = await runPostGestureStabilityLoop({
92102
pending: PENDING,
93-
needsBaselineDistrust: false,
94103
hooks: hooksFor(clock, [{ signature: ['a'], costMs: 2_000 }, quiet]),
95104
clock,
96105
});
@@ -108,7 +117,6 @@ test('a capture error ends the loop by rethrowing that error', async () => {
108117
await assert.rejects(
109118
runPostGestureStabilityLoop({
110119
pending: PENDING,
111-
needsBaselineDistrust: false,
112120
hooks: {
113121
...hooks,
114122
capture: async () => {
@@ -126,8 +134,7 @@ test('a quiet pair on a rebased baseline settles instead of distrusting it to th
126134
const atRest: Surface = { signature: ['moved'], costMs: 0, backend: 'bridge' };
127135

128136
const outcome = await runPostGestureStabilityLoop({
129-
pending: { ...PENDING, baselineSignature: ['moved'], baselineBackend: 'runner' },
130-
needsBaselineDistrust: true,
137+
pending: { ...PENDING, baseline: preActionBaseline(['moved'], 'runner') },
131138
hooks: hooksFor(clock, [atRest, atRest, atRest]),
132139
clock,
133140
});
@@ -144,8 +151,7 @@ test('a quiet pair matching a same-backend baseline is still distrusted to the c
144151
const unchanged: Surface = { signature: ['before'], costMs: 0, backend: 'bridge' };
145152

146153
await runPostGestureStabilityLoop({
147-
pending: { ...PENDING, baselineSignature: ['before'], baselineBackend: 'bridge' },
148-
needsBaselineDistrust: true,
154+
pending: { ...PENDING, baseline: preActionBaseline(['before'], 'bridge') },
149155
hooks: hooksFor(
150156
clock,
151157
Array.from({ length: 40 }, () => unchanged),
@@ -165,8 +171,7 @@ test('an effect that lands after a rebase keeps the loop polling until the moved
165171
const moved: Surface = { signature: ['moved'], costMs: 0, backend: 'bridge' };
166172

167173
const outcome = await runPostGestureStabilityLoop({
168-
pending: { ...PENDING, baselineSignature: ['before'], baselineBackend: 'runner' },
169-
needsBaselineDistrust: true,
174+
pending: { ...PENDING, baseline: preActionBaseline(['before'], 'runner') },
170175
hooks: hooksFor(clock, [rebasedRead, rebasedRead, moving, moved, moved]),
171176
clock,
172177
});

‎packages/capture-kit/src/post-gesture-stability.ts‎

Lines changed: 87 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,52 @@ const STABILIZATION_DISTRUST_DEADLINE_MS = POST_GESTURE_STABILITY_SCHEDULE.budge
4242

4343
export type BaselineSurfaceEvidence = 'changed' | 'unchanged' | 'ambiguous';
4444

45-
export type PostGestureStabilityVerdict = 'trust' | 'distrust' | 'accept-stale';
45+
/**
46+
* One surface reading that can stand as a comparison baseline. Signature and key travel together:
47+
* captures from different surfaces are not views of one screen (#1569, #2438). `comparisonKey` is
48+
* undefined for legacy observations that carry no key; absence is not proof of sameness.
49+
*/
50+
export type PostGestureSurfaceReading<S> = Readonly<{
51+
signature: S;
52+
comparisonKey: string | undefined;
53+
}>;
54+
55+
/**
56+
* What the loop compares a quiet pair against, tagged by provenance. Only `pre-action` — read
57+
* before the gesture dispatched — can show a stale read or prove no effect; a `post-action`
58+
* baseline was adopted mid-loop after the gesture, and matching it is what a surface at rest does
59+
* (#3868).
60+
*/
61+
export type PostGestureBaseline<S> =
62+
| (PostGestureSurfaceReading<S> & Readonly<{ provenance: 'pre-action' }>)
63+
| (PostGestureSurfaceReading<S> & Readonly<{ provenance: 'post-action' }>);
64+
65+
export type PostGesturePreActionBaseline<S> = Extract<
66+
PostGestureBaseline<S>,
67+
Readonly<{ provenance: 'pre-action' }>
68+
>;
69+
70+
/**
71+
* The quiet-pair verdict. `accept-stale` carries the pre-action reading that authorized it as its
72+
* payload, so the no-effect proof consumes exactly that evidence; a post-action baseline has no
73+
* route to this verdict.
74+
*/
75+
export type PostGestureStabilityDecision<S extends readonly unknown[]> =
76+
| Readonly<{ verdict: 'trust' }>
77+
| Readonly<{ verdict: 'distrust' }>
78+
| Readonly<{ verdict: 'accept-stale'; preActionBaseline: PostGesturePreActionBaseline<S> }>;
4679

4780
export type PostGestureStabilityPending<S> = {
4881
action: string;
4982
positionals: string[];
50-
baselineSignature?: S;
51-
baselineBackend?: string;
83+
/** Absent when the writer stored no baseline (non-Apple, or nothing usable pre-gesture). */
84+
baseline?: PostGesturePreActionBaseline<S>;
5285
};
5386

5487
export type PostGestureStabilityHooks<T, S extends readonly unknown[]> = {
5588
capture: () => Promise<T>;
56-
/** Signature + capture backend of one attempt, for quiet-window comparison. */
57-
readSurface: (value: T) => { signature: S; backend: string | undefined };
89+
/** One attempt's signature plus the surface that served it, for quiet-window comparison. */
90+
readSurface: (value: T) => PostGestureSurfaceReading<S>;
5891
/** Two consecutive polls agree — the quiet-window test. */
5992
signaturesStable: (previous: S, current: S) => boolean;
6093
/** Subset-tolerant baseline comparison feeding the distrust verdict. */
@@ -101,26 +134,28 @@ function postGestureOutcome(
101134
}
102135

103136
/**
104-
* Verdict for a quiet match that has already been observed. `'ambiguous'`
105-
* baseline evidence (no comparable content) falls through to `trust`, same as
106-
* `'changed'` — only a genuine "still equals the pre-gesture baseline" read
107-
* keeps the loop distrustful, and only until the bounded cap expires.
137+
* Verdict for a quiet match that has already been observed. Only a `pre-action` baseline can
138+
* distrust or accept stale: a `post-action` baseline was read after the gesture, and distrusting
139+
* it would hold the loop to the cap on every backend switch (#3868). A missing baseline trusts
140+
* outright. `'ambiguous'` evidence (no comparable content) falls through to `trust`, same as
141+
* `'changed'` — only a genuine "still equals the pre-gesture baseline" read keeps the loop
142+
* distrustful, and only until the bounded cap expires.
108143
*/
109144
export function decidePostGestureStabilityVerdict<S extends readonly unknown[]>(params: {
110-
needsBaselineDistrust: boolean;
111-
baselineSignature: S | undefined;
145+
baseline: PostGestureBaseline<S> | undefined;
112146
quietSignature: S;
113147
elapsedMs: number;
114148
distrustCapMs: number;
115149
classifyBaselineEvidence: (baseline: S, quiet: S) => BaselineSurfaceEvidence;
116-
}): PostGestureStabilityVerdict {
117-
const { needsBaselineDistrust, baselineSignature, quietSignature, elapsedMs, distrustCapMs } =
118-
params;
119-
if (!needsBaselineDistrust || !baselineSignature?.length) return 'trust';
120-
if (params.classifyBaselineEvidence(baselineSignature, quietSignature) !== 'unchanged') {
121-
return 'trust';
150+
}): PostGestureStabilityDecision<S> {
151+
const { baseline, quietSignature, elapsedMs, distrustCapMs } = params;
152+
if (baseline?.provenance !== 'pre-action') return { verdict: 'trust' };
153+
if (params.classifyBaselineEvidence(baseline.signature, quietSignature) !== 'unchanged') {
154+
return { verdict: 'trust' };
122155
}
123-
return elapsedMs < distrustCapMs ? 'distrust' : 'accept-stale';
156+
return elapsedMs < distrustCapMs
157+
? { verdict: 'distrust' }
158+
: { verdict: 'accept-stale', preActionBaseline: baseline };
124159
}
125160

126161
/**
@@ -132,18 +167,15 @@ export function decidePostGestureStabilityVerdict<S extends readonly unknown[]>(
132167
*/
133168
export async function runPostGestureStabilityLoop<T, S extends readonly unknown[]>(params: {
134169
pending: PostGestureStabilityPending<S>;
135-
needsBaselineDistrust: boolean;
136170
initial?: T;
137171
hooks: PostGestureStabilityHooks<T, S>;
138172
clock?: ObservationClock;
139173
}): Promise<PostGestureStabilityOutcome<T>> {
140-
const { pending, needsBaselineDistrust, hooks, clock } = params;
174+
const { pending, hooks, clock } = params;
141175
const now = () => clock?.now() ?? Date.now();
142176
const startedAt = now();
143177
let attempts = 0;
144-
let baselineSignature = pending.baselineSignature;
145-
let baselineBackend = pending.baselineBackend;
146-
let baselineRebased = false;
178+
let baseline: PostGestureBaseline<S> | undefined = pending.baseline;
147179
// A rebase or a distrust verdict keeps polling on a pair that DID agree, so
148180
// the budget can expire on a surface that is already at rest.
149181
let lastPairAgreed = false;
@@ -170,40 +202,43 @@ export async function runPostGestureStabilityLoop<T, S extends readonly unknown[
170202
if (!lastPairAgreed) return { kind: 'continue' };
171203

172204
const elapsedMs = now() - startedAt;
173-
// A capture plan may fall back or be pre-empted by the XCTest-channel
174-
// penalty at any time, so the backend can change mid-poll. Backends do
175-
// not agree on which nodes exist, so this pair says nothing about the
176-
// gesture: adopt it as the baseline and keep going rather than concluding
177-
// from it (#1569).
178-
if (baselineSignature && baselineBackend !== current.backend) {
205+
// A capture plan may fall back or be pre-empted by the XCTest-channel penalty at any time,
206+
// so the serving surface can change mid-poll. This quiet pair says nothing about the
207+
// gesture: adopt it as a post-action baseline and keep going (#1569). The pair that rebases
208+
// cannot also settle the loop.
209+
if (baseline && baseline.comparisonKey !== current.comparisonKey) {
179210
emitDiagnostic({
180211
level: 'debug',
181212
phase: 'post_gesture_snapshot_baseline_rebased',
182-
data: { action: pending.action, from: baselineBackend, to: current.backend, attempts },
213+
data: {
214+
action: pending.action,
215+
from: baseline.comparisonKey,
216+
to: current.comparisonKey,
217+
attempts,
218+
},
183219
});
184-
baselineSignature = current.signature;
185-
baselineBackend = current.backend;
186-
baselineRebased = true;
220+
// The adopted reading carries the new key: a further key change rebases again.
221+
baseline = {
222+
provenance: 'post-action',
223+
signature: current.signature,
224+
comparisonKey: current.comparisonKey,
225+
};
187226
return { kind: 'continue' };
188227
}
189-
const verdict = decidePostGestureStabilityVerdict({
190-
// A rebased baseline was read after the gesture. Matching it is what a surface at rest does,
191-
// so it is no evidence of a stale read, and distrusting it would hold the loop to the
192-
// distrust cap on every backend switch.
193-
needsBaselineDistrust: needsBaselineDistrust && !baselineRebased,
194-
baselineSignature,
228+
const decision = decidePostGestureStabilityVerdict({
229+
baseline,
195230
quietSignature: current.signature,
196231
elapsedMs,
197232
distrustCapMs: STABILIZATION_DISTRUST_DEADLINE_MS,
198233
classifyBaselineEvidence: hooks.classifyBaselineEvidence,
199234
});
200-
if (verdict === 'distrust') {
235+
if (decision.verdict === 'distrust') {
201236
return { kind: 'continue', budgetMs: STABILIZATION_DISTRUST_DEADLINE_MS };
202237
}
203-
emitSettleDiagnostic(verdict, pending.action, attempts, elapsedMs);
238+
emitSettleDiagnostic(decision.verdict, pending.action, attempts, elapsedMs);
204239
return {
205240
kind: 'done',
206-
result: buildAcceptedOutcome(verdict, pending, current, hooks),
241+
result: buildAcceptedOutcome(decision, pending, current, hooks),
207242
};
208243
},
209244
});
@@ -227,10 +262,8 @@ export async function runPostGestureStabilityLoop<T, S extends readonly unknown[
227262
return { value, postGestureOutcome: postGestureOutcome('unsettled', pending) };
228263
}
229264

230-
type CapturedSurface<T, S> = {
265+
type CapturedSurface<T, S> = PostGestureSurfaceReading<S> & {
231266
value: T;
232-
signature: S;
233-
backend: string | undefined;
234267
};
235268

236269
function emitSettleDiagnostic(
@@ -256,9 +289,9 @@ function emitSettleDiagnostic(
256289

257290
/**
258291
* The no-effect claim needs BOTH the accept-stale verdict AND full-surface
259-
* corroboration (`surfacesIdentical`) against the ORIGINAL pre-gesture
260-
* baseline. The verdict alone is subset-tolerant (#1601 review P1). A rebased
261-
* loop never reaches accept-stale, so a backend flip cannot launder a
292+
* corroboration (`surfacesIdentical`) against the pre-action baseline the verdict carries — never a
293+
* lookup back into the pending record. The verdict alone is subset-tolerant (#1601 review P1), and
294+
* a rebased baseline cannot produce accept-stale at all, so a backend flip cannot launder a
262295
* cross-backend pair into a no-effect claim.
263296
*
264297
* A veto here is invisible from the outside: the response looks exactly like
@@ -267,29 +300,24 @@ function emitSettleDiagnostic(
267300
* equality.
268301
*/
269302
function buildAcceptedOutcome<T, S extends readonly unknown[]>(
270-
verdict: 'trust' | 'accept-stale',
303+
decision: PostGestureStabilityDecision<S>,
271304
pending: PostGestureStabilityPending<S>,
272305
current: CapturedSurface<T, S>,
273306
hooks: PostGestureStabilityHooks<T, S>,
274307
): PostGestureStabilityOutcome<T> {
275-
if (verdict !== 'accept-stale') return { value: current.value };
276-
const baselineSignature = pending.baselineSignature;
277-
if (
278-
baselineSignature !== undefined &&
279-
hooks.surfacesIdentical(baselineSignature, current.signature)
280-
) {
308+
if (decision.verdict !== 'accept-stale') return { value: current.value };
309+
const baseline = decision.preActionBaseline;
310+
if (hooks.surfacesIdentical(baseline.signature, current.signature)) {
281311
return { value: current.value, postGestureOutcome: postGestureOutcome('no-effect', pending) };
282312
}
283313
emitDiagnostic({
284314
level: 'info',
285315
phase: 'post_gesture_no_effect_vetoed',
286316
data: {
287317
action: pending.action,
288-
backend: current.backend,
318+
backend: current.comparisonKey,
289319
reason: 'surface_divergence',
290-
...(baselineSignature === undefined
291-
? {}
292-
: hooks.summarizeDivergence(baselineSignature, current.signature)),
320+
...hooks.summarizeDivergence(baseline.signature, current.signature),
293321
},
294322
});
295323
return { value: current.value };

‎packages/daemon/src/core/__tests__/deferred-interaction-outcome.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ test('an Apple open that could not observe its app marks stabilization without a
107107

108108
assert.equal(isPostGestureStabilizationPending(session), true);
109109
assert.equal(pendingSurfaceStabilization(session)?.action, 'open');
110-
assert.equal(pendingSurfaceStabilization(session)?.baselineSignature, undefined);
110+
assert.equal(pendingSurfaceStabilization(session)?.baseline?.signature, undefined);
111111
});
112112

113113
test('every open verdict other than observable marks stabilization', () => {

‎packages/daemon/src/core/__tests__/post-gesture-no-effect-claim.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ test('no pre-gesture snapshot means no baseline, no rebase, and no no-effect cla
184184
const session = makeSession('ios');
185185
session.snapshot = undefined; // nothing captured before the gesture
186186
markPostGestureStabilization(session, 'scroll', ['up']);
187-
assert.equal(pendingSurfaceStabilization(session)?.baselineSignature, undefined);
187+
assert.equal(pendingSurfaceStabilization(session)?.baseline?.signature, undefined);
188188

189189
const { result, rebased, vetoed } = await runStabilization(session, () =>
190190
makeSnapshotState(pickupSnapshot(500).nodes, {

0 commit comments

Comments
 (0)