Skip to content

Commit 66e0c9f

Browse files
committed
refactor: restore ADR-0012 rationale docs and dedupe replay identity shapes
The #1478/#1581 extraction moved the identity/structural helpers but compressed their invariant documentation to one-liners; the deliberate no-ancestry-exclusion rule on idMatchCountInTree, the fail-closed guard comparison, and the who-throws/who-detects contracts on the two divergence reason markers now travel with their definitions again. LocalIdentity and NodeStructuralDenotation move to contracts/target-annotation.ts (beside TargetAncestryEntry, which WaitLandmarkMismatchEvidence now references directly), so the guard shapes in contracts/replay.ts are nominal instead of hand-rolled structural twins; ad-script re-exports the vocabulary beside the readers that produce it. Also inlines the demoteNonUniqueId pass-through wrapper in session-target-evidence.ts.
1 parent 53f9df7 commit 66e0c9f

8 files changed

Lines changed: 142 additions & 44 deletions

File tree

‎packages/ad-script/src/internal/__tests__/target-annotation-identity.test.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,14 @@ test('matchesLocalIdentity: with no recorded id, role+label must both match, abs
6868
});
6969

7070
// ---------------------------------------------------------------------------
71-
// Shared id demotion
71+
// Shared id demotion. `idMatchCountInTree` / `demoteNonUniqueLocalIdentity`
72+
// are the ONE shared uniqueness predicate behind both id-demotion sites (the
73+
// `target-v1` identity tuple `session-target-evidence.ts` writes at record
74+
// time, and the selector chain `buildSelectorChainForNode` builds — see
75+
// `src/selectors/build.test.ts` for that consumer's own coverage). Neither
76+
// consumer test exercises the pair directly; these tests pin the shared
77+
// predicate itself, so a re-derivation of identity demotion that drops or
78+
// scopes the uniqueness rule fails here first.
7279
// ---------------------------------------------------------------------------
7380

7481
function sharedIdRows(): RawSnapshotNode[] {

‎packages/ad-script/src/internal/target-annotation-identity.ts‎

Lines changed: 54 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,12 @@
1818

1919
import type { RawSnapshotNode } from '@agent-device/kernel/snapshot';
2020
import { normalizeType } from '@agent-device/contracts/snapshot';
21-
import type { TargetAncestryEntry, TargetAnnotationV1 } from '@agent-device/contracts/replay';
21+
import type {
22+
LocalIdentity,
23+
NodeStructuralDenotation,
24+
TargetAncestryEntry,
25+
TargetAnnotationV1,
26+
} from '@agent-device/contracts/replay';
2227
import {
2328
normalizeIdentifierField,
2429
normalizeLabelField,
@@ -31,14 +36,26 @@ import {
3136
// Local identity + ancestry-prefix matching (decision 3 "Local identity" /
3237
// "Ancestry"). Pure over the small structural shapes above — no tree
3338
// dependency, so both the writer (over `SnapshotNode`-derived values) and a
34-
// replay verifier can share it verbatim.
39+
// replay verifier can share it verbatim. The type vocabulary (`LocalIdentity`,
40+
// `NodeStructuralDenotation`) lives in `@agent-device/contracts/replay` so the
41+
// guard shapes there reference it nominally; this module re-exports it beside
42+
// the readers that produce it.
3543
// ---------------------------------------------------------------------------
3644

37-
export type LocalIdentity = { id?: string; role: string; label?: string };
45+
export type { LocalIdentity, NodeStructuralDenotation };
3846

3947
type IdentityTreeNode = Pick<RawSnapshotNode, 'type' | 'identifier' | 'label'>;
4048

41-
/** The single normalized local-identity reader shared by record and replay paths. */
49+
/**
50+
* ADR 0012 decision 3: the ONE snapshot-node local-identity reader —
51+
* normalized (NFC, label whitespace collapse, `normalizeType` role) AND
52+
* 256-byte field-capped, on every path. Shared by the record-time writer
53+
* (`src/daemon/session-target-evidence.ts`), replay-time verification
54+
* (`src/daemon/handlers/session-replay-target-verification.ts`), and the
55+
* dispatch-side post-resolution guard
56+
* (`src/commands/interaction/runtime/resolution.ts`), so all three compute
57+
* a node's identity with byte-identical semantics.
58+
*/
4259
export function readNodeLocalIdentity(
4360
node: Pick<RawSnapshotNode, 'type' | 'identifier' | 'label'>,
4461
): LocalIdentity {
@@ -59,7 +76,22 @@ export function localIdentitiesEqual(a: LocalIdentity, b: LocalIdentity): boolea
5976
return a.id === b.id && a.role === b.role && a.label === b.label;
6077
}
6178

62-
/** Counts every node in a tree carrying the canonical identity id. */
79+
/**
80+
* ADR 0012 decision 3 amendment (#1269): how many nodes in `nodes` carry the
81+
* canonical identity `id`. THE single uniqueness predicate behind both
82+
* id-demotion sites — `computeTargetEvidence`'s `target-v1` identity tuple
83+
* and `buildSelectorChainForNode`'s selector chain. Sharing it is the
84+
* correctness guarantee: a non-unique id is dropped from BOTH or NEITHER,
85+
* never half-demoted (dropped from identity while still leading the chain, or
86+
* the reverse — the exact split #1269's fix exists to close).
87+
*
88+
* `id` is a canonical identity id (`readNodeLocalIdentity(node).id`: NFC +
89+
* 256-byte field cap, no trimming), and every candidate is measured through
90+
* the SAME reader, so the count is over exactly the identities the replay
91+
* verifier keys on. There is deliberately NO ancestry / parent-walk
92+
* exclusion: an id is non-selective the moment two nodes anywhere in the tree
93+
* carry it, independent of structural context or a broken parent linkage.
94+
*/
6395
export function idMatchCountInTree(nodes: readonly IdentityTreeNode[], id: string): number {
6496
let count = 0;
6597
for (const node of nodes) {
@@ -68,7 +100,17 @@ export function idMatchCountInTree(nodes: readonly IdentityTreeNode[], id: strin
68100
return count;
69101
}
70102

71-
/** Drops a non-unique id while preserving the role and label identity tiers. */
103+
/**
104+
* ADR 0012 decision 3 amendment (#1269): `identity` with its `id` demoted
105+
* whenever the id is non-unique in `nodes`, built on the SAME
106+
* `idMatchCountInTree` predicate `buildSelectorChainForNode`'s
107+
* `selectableId` keys off directly. `computeTargetEvidence` uses this
108+
* whole-identity form; extracted so a third call site (#1280's
109+
* press-retarget identity-empty check, `src/core/press-retarget.ts`)
110+
* shares it rather than re-deriving the rule a third way. A demoted id
111+
* falls back to role+label, the same shape an unrecorded id already
112+
* computes.
113+
*/
72114
export function demoteNonUniqueLocalIdentity(
73115
identity: LocalIdentity,
74116
nodes: readonly IdentityTreeNode[],
@@ -79,11 +121,6 @@ export function demoteNonUniqueLocalIdentity(
79121
return { role, ...(label !== undefined ? { label } : {}) };
80122
}
81123

82-
export type NodeStructuralDenotation = {
83-
documentOrder: number;
84-
sibling: number;
85-
};
86-
87124
type StructuralNode = Pick<RawSnapshotNode, 'index' | 'parentIndex'>;
88125

89126
/** Zero-based ordinal among the node's own parent's children, in document order. */
@@ -104,6 +141,12 @@ export function readNodeStructuralDenotation(
104141
return { documentOrder: node.index, sibling: siblingOrdinal(nodes, node) };
105142
}
106143

144+
/**
145+
* The guard passes only when BOTH structural discriminators agree — a
146+
* fail-closed comparison: two same-local-identity duplicates differ in
147+
* `documentOrder` (always) and usually `sibling`, so the guard refuses
148+
* whenever dispatch resolved a different member than verification isolated.
149+
*/
107150
export function structuralDenotationsEqual(
108151
a: NodeStructuralDenotation,
109152
b: NodeStructuralDenotation,

‎packages/contracts/src/replay.ts‎

Lines changed: 38 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,56 @@
11
import type { DaemonError } from '@agent-device/kernel/errors';
22
import type { SnapshotDiagnosticsSummary } from './snapshot-diagnostics.ts';
3+
import type {
4+
LocalIdentity,
5+
NodeStructuralDenotation,
6+
TargetAncestryEntry,
7+
} from './target-annotation.ts';
38
import { WAIT_REASONS } from './wait.ts';
49

510
/**
6-
* The verified snapshot member carried into the pre-action interaction guard.
7-
* These neutral shapes live in contracts so daemon and command layers can
8-
* share the guard without depending on the annotation codec package.
11+
* The verified-member denotation carried on the pre-action guard
12+
* (`DaemonRequest.internal.replayTargetGuard`): its normalized local identity
13+
* PLUS the structural discriminator path 6 used to isolate it among same
14+
* local-identity duplicates. Comparing local identity alone would let a
15+
* different duplicate (identical id/role/label) pass the guard — the exact
16+
* verified-but-taps-different-node mis-binding step 4 exists to prevent.
17+
* Lives in contracts so daemon and command layers can share the guard
18+
* without depending on the annotation codec package.
919
*/
1020
export type ReplayTargetGuardDenotation = {
11-
identity: { id?: string; role: string; label?: string };
12-
structural: { documentOrder: number; sibling: number };
21+
identity: LocalIdentity;
22+
structural: NodeStructuralDenotation;
1323
};
1424

25+
/**
26+
* `details.reason` marker on the pre-action refusal thrown by dispatch's
27+
* post-resolution guard (`assertExpectedResolvedTarget`,
28+
* `src/commands/interaction/runtime/resolution.ts`), detected by the replay
29+
* step loop to convert the refusal into an identity-mismatch target-binding
30+
* divergence.
31+
*/
1532
export const REPLAY_TARGET_GUARD_MISMATCH_REASON = 'replay_target_guard_mismatch';
1633

34+
/**
35+
* #1349: `details.reason` marker on the timeout refusal `wait` throws when
36+
* candidates matching the recorded selector appeared during polling but none
37+
* ever carried the recorded landmark identity (local identity + leaf-anchored
38+
* ancestry prefix). The replay step loop converts it into an
39+
* identity-mismatch target-binding divergence; the wait never reports
40+
* success.
41+
*/
1742
export const WAIT_LANDMARK_MISMATCH_REASON = WAIT_REASONS.landmarkIdentityMismatch;
1843

19-
/** Compact evidence retained by a selector wait's final mismatching poll. */
44+
/**
45+
* The compact evidence `wait` retains from its LAST poll whose capture
46+
* matched the recorded selector: the domain size and the first match's
47+
* identity/ancestry, enough for the daemon to build the divergence's
48+
* `targetBinding` payload without shipping node trees through error details.
49+
*/
2050
export type WaitLandmarkMismatchEvidence = {
2151
matchCount: number;
22-
observed: { id?: string; role: string; label?: string };
23-
observedAncestry: { role: string; label?: string }[];
52+
observed: LocalIdentity;
53+
observedAncestry: TargetAncestryEntry[];
2454
};
2555

2656
export type ReplayCommandResult = {

‎packages/contracts/src/snapshot-tap-point-policy.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ import type { Rect } from '@agent-device/kernel/snapshot';
1010
// AgentDeviceRunnerUITests/RunnerTapPointPolicy.swift, gated XCTest in the
1111
// same file), so drift between the runner's ELEMENT_OFFSCREEN guard and the
1212
// runtime's offscreen rule turns CI red on whichever side changed.
13+
//
14+
// Scope: the table proves the GEOMETRIC rule only — element-frame center
15+
// inside the window frame, edges inclusive, empty frame fails open. The
16+
// scrollable-ancestor (effective viewport) logic layered on top by
17+
// isNodeVisibleOnScreen is TS-only and out of scope here.
1318

1419
type FixtureCase = {
1520
name: string;

‎packages/contracts/src/snapshot-visibility.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ export function isNodeVisibleInEffectiveViewport(
7878
// interaction would tap — to sit inside the root Application/Window viewport.
7979
// Edge overlap is not enough: a mostly-off-screen drawer container can graze the
8080
// viewport by a fraction of a pixel while its center is far off-screen.
81+
// Interaction guards and selector disambiguation use this stricter form;
82+
// scroll-direction summaries keep the effective form.
8183
export function isNodeVisibleOnScreen(
8284
node: SnapshotVisibilityNode,
8385
nodes: SnapshotNode[],
@@ -96,7 +98,9 @@ export function isNodeVisibleOnScreen(
9698
// The tap-point rule shared with the iOS runner (ADR 0011 Layer 2): the tap
9799
// point is the rect's exact CENTER; it is inside the viewport iff it lies
98100
// within the frame, edges inclusive. A missing, empty, or invalid viewport
99-
// fails open (allowed). The Swift twin and this function are checked against
101+
// fails open (allowed) — resolving the best available viewport is the
102+
// caller's job, and the rule must not turn a missing frame into a refusal.
103+
// The Swift twin and this function are checked against
100104
// contracts/fixtures/tap-point-policy.json; change the rule only via that table.
101105
export function isTapPointInsideViewport(rect: Rect, viewport: Rect | null): boolean {
102106
if (!viewport || viewport.width <= 0 || viewport.height <= 0) {

‎packages/contracts/src/target-annotation.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,31 @@
88

99
export type TargetAncestryEntry = { role: string; label?: string };
1010
export type TargetScrollRegion = { role: string; id?: string; label?: string };
11+
12+
/**
13+
* ADR 0012 decision 3: a node's local identity tier — normalized id, role, and
14+
* label in drop-empty-keys form. Produced only by `@agent-device/ad-script`'s
15+
* `readNodeLocalIdentity` (NFC, label whitespace collapse, `normalizeType`
16+
* role, 256-byte field caps), so every path that compares identities does so
17+
* with byte-identical semantics.
18+
*/
19+
export type LocalIdentity = { id?: string; role: string; label?: string };
20+
21+
/**
22+
* ADR 0012 decision 3: the STRUCTURAL denotation of a node within its capture
23+
* — the discriminators path 6 uses to isolate ONE member among several nodes
24+
* that share the same local identity. `documentOrder` is the node's pre-order
25+
* tree-traversal index (decision 3's "canonical total order of this
26+
* contract"), which distinguishes ANY two distinct nodes. `sibling` is its
27+
* zero-based ordinal among its own parent's children (decision 3 path 6.i).
28+
* Both captures (the verifier's and dispatch's) run the same snapshot
29+
* pipeline, so for the same physical node in the same screen these values
30+
* agree; two distinct duplicates never share a `documentOrder`.
31+
*/
32+
export type NodeStructuralDenotation = {
33+
documentOrder: number;
34+
sibling: number;
35+
};
1136
export type TargetRect = { x: number; y: number; width: number; height: number };
1237
export type TargetVerification = 'verified' | 'unverifiable';
1338

‎scripts/layering/facade-symbols.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -578,6 +578,8 @@ export const FACADE_SYMBOLS: readonly (readonly [string, readonly string[]])[] =
578578
[
579579
'@agent-device/contracts/replay',
580580
[
581+
'LocalIdentity',
582+
'NodeStructuralDenotation',
581583
'REPLAY_TARGET_GUARD_MISMATCH_REASON',
582584
'RefFrameEffect',
583585
'ReplayCommandResult',

‎src/daemon/session-target-evidence.ts‎

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,11 @@ export function computeTargetEvidence(
7070
const { node, preActionNodes: nodes } = capture;
7171
if (typeof node.index !== 'number') return undefined;
7272
const byIndex = buildIndexMap(nodes);
73-
const identity = demoteNonUniqueId(boundedLocalIdentity(node), nodes);
73+
// #1269: a shared framework resource id (Android's `android:id/title` on
74+
// every list row is the measured case) is not selective — demote it to
75+
// role+label via the same shared predicate `buildSelectorChainForNode`
76+
// keys off, so the identity tuple and the selector chain never disagree.
77+
const identity = demoteNonUniqueLocalIdentity(boundedLocalIdentity(node), nodes);
7478
if (mode === 'landmark' && identity.id === undefined && identity.label === undefined) {
7579
return undefined;
7680
}
@@ -226,28 +230,6 @@ type DisambiguationDomain = {
226230
viewportOrder: number;
227231
};
228232

229-
/**
230-
* ADR 0012 decision 3 amendment (#1269): an id is identity only when it
231-
* uniquely denotes the target in the record-time tree. `boundedLocalIdentity`
232-
* reads a node's id unconditionally, but a shared framework resource id
233-
* (Android's `android:id/title` matching every list row is the measured
234-
* case — #1269) is not selective: on replay the id-led identity set spans
235-
* every row, position drifts, and verification correctly refuses a
236-
* confident bind. `idMatchCountInTree` — the SAME predicate
237-
* `buildSelectorChainForNode` uses for the selector chain — counts nodes
238-
* sharing this canonical id across the whole tree; when more than one, fall
239-
* back to role+label, exactly the identity an unrecorded id already computes.
240-
* Both sites sharing one predicate is what keeps the tuple and the chain from
241-
* disagreeing (demoting one but not the other). The rule is capture-time
242-
* uniqueness, not an id-namespace heuristic: a reused RN `FlatList` `testID`
243-
* hits the same demotion on iOS. Delegates to the shared
244-
* `demoteNonUniqueLocalIdentity` (`@agent-device/ad-script`), which #1280's
245-
* press-retarget check also uses.
246-
*/
247-
function demoteNonUniqueId(identity: LocalIdentity, nodes: readonly SnapshotNode[]): LocalIdentity {
248-
return demoteNonUniqueLocalIdentity(identity, nodes);
249-
}
250-
251233
function computeDisambiguationDomain(params: {
252234
nodes: readonly SnapshotNode[];
253235
byIndex: Map<number, SnapshotNode>;

0 commit comments

Comments
 (0)