Skip to content

Commit 49f27d6

Browse files
committed
refactor: make the selector pipeline the only door to the engine
Review of #1744: the structural rows were declared but bypassable. Read and wait routes composed `selectorPipelineCandidates(row, nodes)` with the raw `resolveSelectorChainWithPolicy(..., row.resolution)` and never entered the promotion or off-screen stages, so flipping a read row's `promotion` or `offscreen` changed only the policy unit tests — production `get`/`is`/`wait` were unaffected, which is the unverifiable-column failure #1656 exists to remove. Callers could also pair one row's candidate set with another row's ambiguity contract, and `find list` reached the engine directly. The owning interface (src/core/selector-pipeline.ts) now runs every stage a row declares, skips included, and the stage functions are private to it: - `resolveSelectorPipeline` — single-target rows: candidacy, ambiguity, the replay-guard hook, promotion, occlusion, off-screen. - `listSelectorPipelineMatches` — `reject-candidates` rows, returning the candidate set AND the tree the row sees, so ranking and equivalence classification judge the same nodes candidacy produced. - `runNodePipelineStages` — the node stages for a target from a non-chain matcher (`@ref`, find's fuzzy locator) or a narrowed candidate set. A row whose off-screen stage refuses must supply a refusal shape, so flipping an observation row to `refuse` fails on its real route instead of silently observing. `find list` now names a `readList` row (the new `reject-candidates`/no-rect ambiguity row) instead of calling the engine. R17 selector-pipeline-ownership (scripts/layering/) makes the bypass structurally inexpressible: only the owner may import the engine entry points. Proven against a planted import in selector-read.ts, which the repo-wide scan rejects with the entry points that replace it. Flips now fail through REAL command routes, verified one at a time: readUnique.occlusion/offscreen/promotion and wait.occlusion via get attrs / is / wait; readAny.offscreen via is exists and find; readList.occlusion via find list; promotedTarget.promotion via runtime click. The wait route test needed an advancing clock first — with the frozen one a refused wait spun instead of failing, so the flip hung rather than asserting.
1 parent b77b3bb commit 49f27d6

18 files changed

Lines changed: 866 additions & 391 deletions

‎packages/contracts/src/interaction-guarantees.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ const RUNTIME_TREE_SHARED_GUARANTEES = {
155155
// predicate it applies (and the annotation contract it reads).
156156
occlusion: {
157157
kind: 'runtime',
158-
via: 'src/core/selector-pipeline-policy.ts#resolveSelectorPipelineTarget',
158+
via: 'src/core/selector-pipeline.ts#runNodePipelineStages',
159159
},
160160
parentOwnedTouchPoint: {
161161
kind: 'runtime',
@@ -178,7 +178,7 @@ const RUNTIME_TREE_SHARED_GUARANTEES = {
178178
// is still resolveActionableTouchResolution.
179179
nonHittable: {
180180
kind: 'runtime',
181-
via: 'src/core/selector-pipeline-policy.ts#resolveSelectorPipelineTarget',
181+
via: 'src/core/selector-pipeline.ts#runNodePipelineStages',
182182
},
183183
responseConstruction: SHARED_RESPONSE_CONSTRUCTION,
184184
responseIdentity: {
@@ -254,7 +254,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
254254
},
255255
occlusion: {
256256
kind: 'runtime',
257-
via: 'src/core/selector-pipeline-policy.ts#resolveSelectorPipelineTarget',
257+
via: 'src/core/selector-pipeline.ts#runNodePipelineStages',
258258
},
259259
parentOwnedTouchPoint: {
260260
kind: 'runtime',
@@ -375,7 +375,7 @@ export const INTERACTION_DISPATCH_PATHS: Record<InteractionPathId, InteractionPa
375375
},
376376
occlusion: {
377377
kind: 'runtime',
378-
via: 'src/core/selector-pipeline-policy.ts#resolveSelectorPipelineTarget',
378+
via: 'src/core/selector-pipeline.ts#runNodePipelineStages',
379379
},
380380
parentOwnedTouchPoint: {
381381
kind: 'inapplicable',

‎packages/selectors/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ export type { IsPredicate } from './internal/predicates.ts';
5959
export type {
6060
PolicyResolutionOutcome,
6161
SelectorChainMatchList,
62+
SelectorMatchOptions,
6263
SelectorResolution,
6364
} from './internal/public-resolution-types.ts';
6465
export { formatSelectorFailure } from './internal/resolve.ts';

‎packages/selectors/src/internal/resolution-policy.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,14 @@ export const SELECTOR_RESOLUTION_POLICIES = {
8181
ambiguity: 'reject-candidates',
8282
requireRect: true,
8383
},
84+
/**
85+
* `find <q> list` — the inspection surface: every match is the ANSWER, so the
86+
* candidate set stays whole and nothing needs a tap point.
87+
*/
88+
readList: {
89+
ambiguity: 'reject-candidates',
90+
requireRect: false,
91+
},
8492
} as const satisfies Record<string, SelectorResolutionPolicy>;
8593

8694
/**

‎scripts/layering/check.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ import {
102102
sourceExecutedUsingDeclarationViolations,
103103
} from './logs-runtime-cutover-policy.ts';
104104
import { contractsImplementationAuthorityViolations } from './contracts-implementation-policy.ts';
105+
import { selectorPipelineOwnershipViolations } from './selector-pipeline-ownership.ts';
105106
import {
106107
networkLegacyRouteViolations,
107108
networkRuntimeNarrowingViolations,
@@ -670,6 +671,7 @@ export const LAYERING_RULE_IDS = [
670671
'value-import-cycles',
671672
'logs-runtime-cutover',
672673
'contracts-implementation-authority',
674+
'selector-pipeline-ownership',
673675
'network-runtime-cutover',
674676
'record-runtime-cutover',
675677
'back-edges',
@@ -691,6 +693,8 @@ export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
691693
'logs-runtime-cutover': (context) => checkLogsRuntimeCutover(context.sources),
692694
'contracts-implementation-authority': (context) =>
693695
checkContractsImplementationAuthority(context.sources),
696+
'selector-pipeline-ownership': (context) =>
697+
selectorPipelineOwnershipViolations(context.edges, workspaceSpecifierTargets(repoRoot)),
694698
'network-runtime-cutover': (context) => checkNetworkRuntimeCutover(context.sources),
695699
'record-runtime-cutover': (context) => checkRecordRuntimeCutover(context.sources),
696700
'back-edges': (context) => checkBackEdges(context.edges),
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
import {
4+
SELECTOR_ENGINE_OWNER,
5+
selectorPipelineOwnershipViolations,
6+
} from './selector-pipeline-ownership.ts';
7+
8+
function violations(source: string, path = 'src/daemon/handlers/planted.ts'): string[] {
9+
return selectorPipelineOwnershipViolations([{ path, source }]).map(
10+
(violation) => `${violation.file}: ${violation.message}`,
11+
);
12+
}
13+
14+
test('a route that reaches the selector engine directly is rejected', () => {
15+
for (const source of [
16+
"import { resolveSelectorChainWithPolicy } from '@agent-device/selectors';",
17+
"import { listSelectorChainMatches } from '@agent-device/selectors';",
18+
"import { formatSelectorFailure, resolveSelectorChainWithPolicy } from '@agent-device/selectors';",
19+
"import { listSelectorChainMatches as listMatches } from '@agent-device/selectors';",
20+
]) {
21+
assert.equal(violations(source).length, 1, source);
22+
}
23+
});
24+
25+
test('the owner may hold the engine, and everyone may hold the vocabulary around it', () => {
26+
assert.deepEqual(
27+
violations(
28+
"import { resolveSelectorChainWithPolicy } from '@agent-device/selectors';",
29+
SELECTOR_ENGINE_OWNER,
30+
),
31+
[],
32+
);
33+
assert.deepEqual(
34+
violations("import type { SelectorChainMatchList } from '@agent-device/selectors';"),
35+
[],
36+
);
37+
assert.deepEqual(
38+
violations(
39+
[
40+
"import { buildSelectorChainForNode, formatSelectorFailure } from '@agent-device/selectors';",
41+
"import { resolveSelectorPipeline } from '../../core/selector-pipeline.ts';",
42+
].join('\n'),
43+
),
44+
[],
45+
);
46+
// The engine's own package describes the engine rather than routing around it.
47+
assert.deepEqual(
48+
violations(
49+
"import { listSelectorChainMatches } from '@agent-device/selectors';",
50+
'packages/selectors/src/index.test.ts',
51+
),
52+
[],
53+
);
54+
});
55+
56+
test('the refusal names the owner and the entry points that replace the bypass', () => {
57+
const [message] = violations(
58+
"import { resolveSelectorChainWithPolicy } from '@agent-device/selectors';",
59+
);
60+
assert.ok(message?.includes(SELECTOR_ENGINE_OWNER), message);
61+
assert.ok(message?.includes('resolveSelectorPipeline'), message);
62+
assert.ok(message?.includes('SELECTOR_PIPELINE_POLICIES'), message);
63+
});
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* R17 selector-pipeline ownership (#1656).
3+
*
4+
* The structural stages of selector resolution — occlusion, off-screen,
5+
* hittable-ancestor promotion, the poll budget — are declared per caller in
6+
* `src/core/selector-pipeline-policy.ts` and executed by
7+
* `src/core/selector-pipeline.ts`. That only means something while the owner is
8+
* the ONLY way in: a route that calls the matching engine directly still gets a
9+
* row's ambiguity contract while silently skipping every structural stage,
10+
* which is how a declared cell turns back into an unverifiable claim (the
11+
* failure #1649 caught in the first matrix and #1656's review caught in the
12+
* second).
13+
*
14+
* So the engine entry points are owner-only. A structural gate rather than a
15+
* convention, because the failure is invisible at the call site: code that
16+
* skips the stages looks exactly like code that runs them.
17+
*/
18+
19+
export type SourceFile = { path: string; source: string };
20+
21+
export type LayeringViolation = {
22+
rule: string;
23+
file: string;
24+
line: number;
25+
message: string;
26+
};
27+
28+
/**
29+
* The engine surface that resolves or enumerates a selector against a tree —
30+
* the decision a policy row exists to qualify. `@agent-device/selectors` also
31+
* exports parsing, matching and formatting helpers, which carry no row
32+
* semantics and stay freely importable.
33+
*/
34+
export const OWNED_SELECTOR_ENGINE_SYMBOLS = [
35+
'resolveSelectorChainWithPolicy',
36+
'listSelectorChainMatches',
37+
] as const;
38+
39+
/** The pipeline owner. The selectors package implements the engine it wraps. */
40+
export const SELECTOR_ENGINE_OWNER = 'src/core/selector-pipeline.ts';
41+
42+
const IMPORT_BLOCK =
43+
/import\s+(type\s+)?\{([^}]*)\}\s*from\s*['"](@agent-device\/selectors[^'"]*)['"]/g;
44+
45+
export function selectorPipelineOwnershipViolations(
46+
files: readonly SourceFile[],
47+
): LayeringViolation[] {
48+
const violations: LayeringViolation[] = [];
49+
for (const file of files) {
50+
if (file.path === SELECTOR_ENGINE_OWNER) continue;
51+
// The engine's own package and its tests describe the engine rather than
52+
// route around it; the gate governs consumers.
53+
if (file.path.startsWith('packages/selectors/')) continue;
54+
for (const match of file.source.matchAll(IMPORT_BLOCK)) {
55+
// A type-only import cannot call anything, and routes legitimately name
56+
// the result types the owner hands back.
57+
if (match[1]) continue;
58+
for (const symbol of importedValueSymbols(match[2] ?? '')) {
59+
if (!(OWNED_SELECTOR_ENGINE_SYMBOLS as readonly string[]).includes(symbol)) continue;
60+
violations.push({
61+
rule: 'R17 selector-pipeline-ownership',
62+
file: file.path,
63+
line: lineOf(file.source, match.index ?? 0),
64+
message:
65+
`imports ${symbol} from @agent-device/selectors. The selector engine is owned by ` +
66+
`${SELECTOR_ENGINE_OWNER}: call resolveSelectorPipeline / listSelectorPipelineMatches / ` +
67+
'runNodePipelineStages with a SELECTOR_PIPELINE_POLICIES row instead, so this route runs ' +
68+
'the occlusion, off-screen and promotion stages the row declares rather than skipping them.',
69+
});
70+
}
71+
}
72+
}
73+
return violations;
74+
}
75+
76+
function importedValueSymbols(names: string): string[] {
77+
return names
78+
.split(',')
79+
.map((entry) => entry.trim())
80+
.filter((entry) => entry.length > 0 && !entry.startsWith('type '))
81+
.map((entry) => entry.split(/\s+as\s+/)[0]?.trim() ?? '');
82+
}
83+
84+
function lineOf(source: string, index: number): number {
85+
return source.slice(0, index).split('\n').length;
86+
}

‎src/commands/interaction/runtime/__tests__/selector-read-policy.test.ts‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import { AppError } from '@agent-device/kernel/errors';
44
import { selector } from '../selector-read-utils.ts';
55
import {
66
ambiguousSelectorReadSnapshot,
7+
createFakeClock,
78
createSelectorDevice,
9+
observationStagesSnapshot,
810
skippedAlternativeSelectorSnapshot,
911
} from './test-utils/index.ts';
1012

@@ -129,3 +131,95 @@ test('find takes the document-order head on the same tree (readAny row)', async
129131
});
130132
assert.deepEqual(exists, { kind: 'found', found: true });
131133
});
134+
135+
/**
136+
* #1656: the same question for the STRUCTURAL stages. These drive the real
137+
* command routes — `get`, `is`, `wait`, `find` — because that is the only
138+
* place a stage claim can be falsified: a row that declares `promotion: none`
139+
* and is never executed is a claim about a table, not about the product.
140+
* Flipping any observation row's occlusion, off-screen, or promotion cell
141+
* fails one of these.
142+
*/
143+
144+
const COVERED_SELECTOR = 'label="Covered action"';
145+
const OFFSCREEN_SELECTOR = 'label="Scrolled away"';
146+
const NESTED_TEXT_SELECTOR = 'label="Account"';
147+
148+
test('get attrs answers about a covered element (readUnique ignores occlusion)', async () => {
149+
const device = createSelectorDevice(observationStagesSnapshot());
150+
151+
const attrs = await device.selectors.getAttrs(selector(COVERED_SELECTOR), {
152+
session: 'default',
153+
});
154+
155+
// A covered element still exists and still has attributes. The acting rows
156+
// refuse it; a read that refused would leave an agent unable to inspect the
157+
// very element it needs to clear.
158+
assert.equal(attrs.kind, 'attrs');
159+
assert.equal(attrs.node.label, 'Covered action');
160+
});
161+
162+
test('is visible answers about an off-screen element (readUnique ignores off-screen)', async () => {
163+
const device = createSelectorDevice(observationStagesSnapshot());
164+
165+
const result = await device.selectors.is({
166+
session: 'default',
167+
predicate: 'exists',
168+
selector: OFFSCREEN_SELECTOR,
169+
});
170+
171+
assert.equal(result.pass, true);
172+
});
173+
174+
test('get attrs answers about the node it matched, never its hittable ancestor (readText/readUnique promote nothing)', async () => {
175+
const device = createSelectorDevice(observationStagesSnapshot());
176+
177+
const attrs = await device.selectors.getAttrs(selector(NESTED_TEXT_SELECTOR), {
178+
session: 'default',
179+
});
180+
181+
// The acting rows promote this static text to the hittable cell that owns
182+
// it. A read must not: the caller asked about `Account`, and answering with
183+
// `Account row` would describe an element it never selected.
184+
assert.equal(attrs.kind, 'attrs');
185+
assert.equal(attrs.node.label, 'Account');
186+
assert.equal(attrs.node.type, 'XCUIElementTypeStaticText');
187+
});
188+
189+
test('wait is satisfied by covered and off-screen matches (wait row ignores both stages)', async () => {
190+
for (const target of [COVERED_SELECTOR, OFFSCREEN_SELECTOR]) {
191+
// An advancing clock, so a row that stopped being satisfied here reaches
192+
// its deadline and FAILS rather than polling forever.
193+
const device = createSelectorDevice(observationStagesSnapshot(), {
194+
clock: createFakeClock(),
195+
});
196+
197+
const result = await device.selectors.wait({
198+
session: 'default',
199+
target: { kind: 'selector', selector: target, timeoutMs: 1_000 },
200+
});
201+
202+
assert.equal(result.kind, 'selector', target);
203+
}
204+
});
205+
206+
test('find reads answer about covered and off-screen matches (readAny ignores both stages)', async () => {
207+
const device = createSelectorDevice(observationStagesSnapshot());
208+
209+
for (const query of [COVERED_SELECTOR, OFFSCREEN_SELECTOR]) {
210+
const exists = await device.selectors.find({ session: 'default', query, action: 'exists' });
211+
assert.deepEqual(exists, { kind: 'found', found: true }, query);
212+
}
213+
214+
// `find list` enumerates through the same owner (`readList`), so its
215+
// candidate set is the row's, not a private call into the engine.
216+
const listed = await device.selectors.find({
217+
session: 'default',
218+
query: COVERED_SELECTOR,
219+
action: 'list',
220+
});
221+
assert.equal(listed.kind, 'list');
222+
assert.deepEqual(listed.kind === 'list' ? listed.matches.map((entry) => entry.node.label) : [], [
223+
'Covered action',
224+
]);
225+
});

0 commit comments

Comments
 (0)