From 1428df0f2247e5c12cf2b09e7fd45b591dcf3b6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:29:53 +0100 Subject: [PATCH 01/17] fix(maestro): bound selector regex matching --- packages/maestro/package.json | 3 +- .../daemon-runtime-port-observation.ts | 1 + ...cade-execution-failure-suggestions.test.ts | 9 + .../runtime-selector-resolution.test.ts | 62 ++++ .../__tests__/runtime-target-policy.test.ts | 17 +- .../__tests__/runtime-targets-typed.test.ts | 40 +++ .../internal/__tests__/selector-regex.test.ts | 182 +++++++++- .../maestro/src/internal/engine-context.ts | 3 +- .../maestro/src/internal/facade-execution.ts | 20 +- .../internal/runtime-selector-resolution.ts | 50 ++- .../src/internal/runtime-target-policy.ts | 81 ++++- .../src/internal/runtime-target-ranking.ts | 27 +- .../maestro/src/internal/runtime-targets.ts | 73 +++- .../maestro/src/internal/selector-regex.ts | 331 +++++++++++++++++- pnpm-lock.yaml | 3 + scripts/bundled-dependency-names.ts | 33 ++ tsdown.config.ts | 34 +- website/docs/docs/error-reasons.md | 7 + website/docs/docs/run-maestro-flows.md | 1 + 19 files changed, 886 insertions(+), 91 deletions(-) create mode 100644 scripts/bundled-dependency-names.ts diff --git a/packages/maestro/package.json b/packages/maestro/package.json index e21431628e5..5737d6edcf9 100644 --- a/packages/maestro/package.json +++ b/packages/maestro/package.json @@ -13,7 +13,8 @@ "@agent-device/host-kit": "workspace:*", "@agent-device/kernel": "workspace:*", "@agent-device/provision-kit": "workspace:*", - "@agent-device/selectors": "workspace:*" + "@agent-device/selectors": "workspace:*", + "@eslint-community/regexpp": "4.12.2" }, "exports": { ".": { diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts index df6e7071427..c9d7ed5d8e8 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts @@ -118,6 +118,7 @@ function resolveTargetFromSnapshot(params: { params.platform, { interactiveBounds: params.mode === 'tap', + confirmedUnindexedExistence: params.mode === 'observe', presentation: presentation ? { snapshot: interactiveSnapshot, diff --git a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts index 852ec9a81f1..f356b97a8bd 100644 --- a/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts +++ b/packages/maestro/src/internal/__tests__/facade-execution-failure-suggestions.test.ts @@ -68,6 +68,15 @@ describe('Maestro failure suggestion queries', () => { expect(suggestions.map(({ node, basis }) => [node.ref, basis])).toEqual([['e1', 'id']]); }); + test('an unsafe failed selector yields no suggestions', async () => { + const suggestions = await suggestionsFor( + ['appId: com.example.app', '---', '- tapOn:', ' id: (a+)+$', ''].join('\n'), + 'android', + [{ ...saveButton, identifier: 'a'.repeat(4096) }], + ); + expect(suggestions).toEqual([]); + }); + test('a coordinate tapOn has no selector to suggest from', async () => { const suggestions = await suggestionsFor( ['appId: com.example.app', '---', '- tapOn:', ' point: 50%,50%', ''].join('\n'), diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index acec5e12a9e..7da724862c1 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -55,6 +55,68 @@ test('rejects cyclic selector graphs explicitly', () => { expect(() => resolver.resolve(selector)).toThrow(/cannot contain cycles/); }); +test('matches a complete interior multiline span before ordered target selection', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'prefix\nstart\nmiddle\nend\nsuffix' }, + { index: 1, label: 'start\nend' }, + ]); + const resolver = createMaestroSnapshotResolver(snapshot); + + expect( + resolver.resolve({ text: 'start.*end', index: 0 }).indexed.map((node) => node.index), + ).toEqual([0]); +}); + +test('a nonmatching multiline node does not prevent a later confirmed selector match', () => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Welcome back\nPlease log in' }, + { index: 1, label: 'Sign in' }, + ]), + ); + expect(resolver.resolve({ text: '.*Sign in.*' }).matches.map((node) => node.index)).toEqual([1]); +}); + +test('an exact long selector checks every candidate before refusing regex execution', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: `${pattern} extra` }, + { index: 1, label: ` ${pattern} ` }, + ]), + ); + expect(resolver.resolve({ text: pattern }).matches.map((node) => node.index)).toEqual([1]); + expect(() => resolver.resolve({ text: `${pattern} missing` })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Header\n'.repeat(10_000) }, + { index: 1, label: 'Ready' }, + { index: 2, label: 'Header\n'.repeat(10_000), identifier: 'Ready' }, + ]); + const resolver = createMaestroSnapshotResolver( + snapshot, + {}, + { confirmedUnindexedExistence: true }, + ); + expect(resolver.resolve({ text: '.*Ready.*' }).matches.map((node) => node.index)).toEqual([1, 2]); + expect(() => resolver.resolve({ text: '.*Ready.*', index: 0 })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => createMaestroSnapshotResolver(snapshot).resolve({ text: '.*Ready.*' })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('resolves containment through array-offset parent links with non-contiguous indexes', () => { const snapshot = makeSnapshot([ { index: 10, identifier: 'container' }, diff --git a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts index e2a5972c4d3..664e4071c4d 100644 --- a/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-target-policy.test.ts @@ -58,18 +58,18 @@ test('intersects every field in a compound Maestro selector', () => { ); }); -test('treats selector values as full Maestro regex without punctuation inference', () => { +test('treats admitted selector values as full Maestro regex without punctuation inference', () => { const node = makeSnapshot([ { index: 1, type: 'TextView', - label: 'Item 22 [ready', + label: 'Item 22 ready', }, ]).nodes[0]!; - expect(matchesMaestroTypedSelector(node, { text: 'item \\d{2} \\[ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'item \\d\\d ready' })).toBe(true); expect(matchesMaestroTypedSelector(node, { text: 'Item 2' })).toBe(false); - expect(matchesMaestroTypedSelector(node, { text: 'Item 22 [ready' })).toBe(true); + expect(matchesMaestroTypedSelector(node, { text: 'Item 22 ready' })).toBe(true); }); test('the node-only matcher rejects full selectors at the type boundary', () => { @@ -82,3 +82,12 @@ test('the node-only matcher rejects full selectors at the type boundary', () => }); expect(node.label).toBe('Save'); }); + +test('typed selectors validate even when node text equals the unsafe pattern', () => { + const node = makeSnapshot([{ index: 1, label: 'a*a*' }]).nodes[0]!; + expect(() => matchesMaestroTypedSelector(node, { text: 'a*a*' })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); diff --git a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts index 457bc2afb35..416df73a4fd 100644 --- a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts @@ -180,6 +180,46 @@ test('reports matched-but-invisible targets with a typed no-visible-match reason }); }); +test('a hidden confirmed match cannot hide uncertainty in a visible observation candidate', () => { + const snapshot = makeSnapshot([ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 320, height: 640 } }, + { + index: 1, + parentIndex: 0, + label: 'Ready', + rect: { x: 16, y: 20, width: 120, height: 44 }, + visibleToUser: false, + }, + { + index: 2, + parentIndex: 0, + label: 'Header\n'.repeat(10_000), + rect: { x: 16, y: 80, width: 120, height: 44 }, + }, + ]); + + expect(() => + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: '.*Ready.*' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + + const visibleMatch = makeSnapshot([ + snapshot.nodes[0]!, + { ...snapshot.nodes[1]!, visibleToUser: true }, + snapshot.nodes[2]!, + ]); + expect( + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready.*' } }, 'android', { + confirmedUnindexedExistence: true, + }), + ).toMatchObject({ ok: true, node: { index: 1 } }); +}); + test('keeps Maestro-visible app content matchable while a React Native overlay is present', () => { const snapshot = makeSnapshot([ { diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index ef53e98949b..96baf1aff09 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -1,10 +1,74 @@ -import { expect, test } from 'vitest'; +import { RegExpParser } from '@eslint-community/regexpp'; +import { expect, test, vi } from 'vitest'; import { literalFromMaestroRegex, matchesMaestroRegex } from '../selector-regex.ts'; test('matches Maestro regex as case-insensitive full patterns', () => { + expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d\d.+ready`)).toBe(true); expect(matchesMaestroRegex('Item 22\nready', String.raw`item \d{2}.+ready`)).toBe(true); expect(matchesMaestroRegex('Item 22 ready later', 'Item 22 ready')).toBe(false); - expect(matchesMaestroRegex('Item [ready', 'item [ready')).toBe(true); + expect(matchesMaestroRegex('Item \\', 'item \\')).toBe(true); + expect(matchesMaestroRegex('Sign in', '.*Sign in.*')).toBe(true); + expect(matchesMaestroRegex('candidate-low', 'candidate-(low|high)')).toBe(true); + expect(matchesMaestroRegex('item 22', String.raw`item [0-9]+`)).toBe(true); + expect(matchesMaestroRegex('Item 22 ready', String.raw`Item \d+\s+ready`)).toBe(true); + expect(matchesMaestroRegex('Item 8', String.raw`Item \8`)).toBe(true); + expect(matchesMaestroRegex('aaab', '(a+)b')).toBe(true); + expect(matchesMaestroRegex('aaabbb', '(a+)b+')).toBe(true); + expect(matchesMaestroRegex('AB12', '[A-Z]+[0-9]+')).toBe(true); + expect(matchesMaestroRegex('aa12', String.raw`a+\d+`)).toBe(true); + expect(matchesMaestroRegex('ab12', String.raw`[a-z]+\d+`)).toBe(true); + expect(matchesMaestroRegex('12kg', String.raw`\d+(kg|lb)`)).toBe(true); + expect(matchesMaestroRegex('Status\nReady\nDetails', 'Ready')).toBe(true); +}); + +test.each([ + '(a+)+', + '(a|aa)+', + '(?:(?:a|aa))*', + '(?:(?:a|ab)(?:c|bc))*', + 'a*a*', + 'a*b*a*', + '.*a.*b', + '.*x.*y.*z', + '.*a.*a.*a.*b', + '(a*)(a*)b', + '(?:aa)+a+b', + 'a{10001}', + 'a{10001,}', + 'a+(?:|a)a+b', + 'a+(?=a)a+b', + 'a+(?:a*)b', + '(?:a+)a+b', + '(a+){2}', + String.raw`(a+)\1`, + '(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)(a|aa)', +])('refuses a backtracking Maestro selector pattern %s', (pattern) => { + expect(() => matchesMaestroRegex(`${'a'.repeat(4096)}X`, pattern)).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('refuses a nullable separator before matching a maximum-length node value', () => { + expect(() => matchesMaestroRegex(`${'a'.repeat(8191)}X`, 'a+(?:|a)a+b')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('refuses overlapping wildcard and grouped repetitions before a long node value runs', () => { + const value = `${'a\n'.repeat(4096)}X`; + for (const pattern of ['.*a.*b', '.*a.*a.*a.*b', '(a*)(a*)b']) { + expect(() => matchesMaestroRegex(value, pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + } }); test('extracts only patterns that are exact literals', () => { @@ -12,4 +76,118 @@ test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); expect(literalFromMaestroRegex(String.raw`item \d{2}`)).toBeUndefined(); expect(literalFromMaestroRegex('item [ready')).toBe('item [ready'); + expect(literalFromMaestroRegex('a'.repeat(8193))).toBe('a'.repeat(8193)); + expect(literalFromMaestroRegex(`${'a'.repeat(8193)}*`)).toBeUndefined(); +}); + +test('long device labels retain literal and bounded regex matches', () => { + expect(matchesMaestroRegex('a'.repeat(8193), 'item')).toBe(false); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8193)}\nDetails`, 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex(`Status\n${'A'.repeat(8192)}X\nDetails`, 'a'.repeat(8193))).toBe( + false, + ); + expect(matchesMaestroRegex(`Details: ${'x'.repeat(8300)} End`, 'Details: x+ End')).toBe(true); + expect(matchesMaestroRegex('item', 'item')).toBe(true); +}); + +test('a long regex-shaped selector matches exact text without executing its regex', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + expect(matchesMaestroRegex(` total: 12.5 ${'x'.repeat(300)} `, pattern)).toBe(true); + expect(() => matchesMaestroRegex(`${pattern} more`, pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('multiline regex matches whole values and individual lines without retrying every suffix', () => { + expect(matchesMaestroRegex('start\nmiddle\nend', 'start.*end')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', 'Ready')).toBe(true); + expect(matchesMaestroRegex('before\nReady\nafter', '.*Ready.*')).toBe(true); + expect(matchesMaestroRegex('prefix\nstart\nmiddle\nend\nsuffix', 'start.*end')).toBe(true); + const wholeValuePastRestartBudget = `start${'\ndetails'.repeat(150)}\nend`; + expect(wholeValuePastRestartBudget.length).toBe(1209); + expect(matchesMaestroRegex(wholeValuePastRestartBudget, 'start.*end')).toBe(true); + for (const pattern of ['.*Sign in.*', 'Sign.*', 'Item .', String.raw`Hello\s+World`]) { + expect(matchesMaestroRegex('Welcome back\nPlease log in', pattern)).toBe(false); + } + expect(matchesMaestroRegex('x\nx', '[^x]+')).toBe(false); + expect(matchesMaestroRegex('a\n'.repeat(192_000), 'a+Z')).toBe(false); + expect(() => matchesMaestroRegex('a\n'.repeat(192_000), '.*Z')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('invalid regex syntax uses whole-value literal equality', () => { + expect(matchesMaestroRegex('[', '[')).toBe(true); + expect(matchesMaestroRegex('prefix\n[\nsuffix', '[')).toBe(false); +}); + +test('CR and LF each provide a multiline anchor boundary', () => { + expect(matchesMaestroRegex('one\r\ntwo', '^$')).toBe(true); + expect(matchesMaestroRegex('one\rtwo', '^two$')).toBe(true); + expect(matchesMaestroRegex('one\ntwo', '^two$')).toBe(true); +}); + +test('escaped brackets and braces match literal node text', () => { + expect(matchesMaestroRegex('a(b', String.raw`a\(b`)).toBe(true); + expect(matchesMaestroRegex('price {2}', String.raw`price \{2\}`)).toBe(true); + expect(matchesMaestroRegex('price 22', String.raw`price {2}`)).toBe(false); +}); + +test('literal matches preserve text before safe regex-shaped patterns use regex semantics', () => { + expect(matchesMaestroRegex(' Save now ', 'save now')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(257), 'a'.repeat(257))).toBe(true); + expect(() => matchesMaestroRegex('a*a*', 'a*a*')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + expect(matchesMaestroRegex('Item 22 [ready', 'Item 22 [ready')).toBe(true); + expect(matchesMaestroRegex('Terms | Privacy', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('(a|b)', '(a|b)')).toBe(true); + expect(matchesMaestroRegex('Terms ', 'Terms | Privacy')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(8193), 'a+')).toBe(true); + expect(matchesMaestroRegex('a'.repeat(8193), 'a'.repeat(8193))).toBe(true); + expect(matchesMaestroRegex('a'.repeat(256), 'a'.repeat(257))).toBe(false); + expect(() => matchesMaestroRegex('a'.repeat(8193), `${'a'.repeat(8193)}*`)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + expect(() => matchesMaestroRegex('a'.repeat(256), `(${`a`.repeat(255)})`)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('reuses a parsed selector pattern across node values', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern'); + try { + expect(matchesMaestroRegex('memoized-123', 'memoized-[0-9]+')).toBe(true); + expect(matchesMaestroRegex('memoized-abc', 'memoized-[0-9]+')).toBe(false); + expect(parse).toHaveBeenCalledTimes(1); + } finally { + parse.mockRestore(); + } +}); + +test('reports a parser failure through the typed selector reason', () => { + const parse = vi.spyOn(RegExpParser.prototype, 'parsePattern').mockImplementationOnce(() => { + throw new SyntaxError('unsupported parser syntax'); + }); + try { + expect(() => matchesMaestroRegex('parser-error-123', 'parser-error-[0-9]+')).toThrow( + expect.objectContaining({ + code: 'INVALID_ARGS', + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); + } finally { + parse.mockRestore(); + } }); diff --git a/packages/maestro/src/internal/engine-context.ts b/packages/maestro/src/internal/engine-context.ts index 2cd000efe74..c869754115c 100644 --- a/packages/maestro/src/internal/engine-context.ts +++ b/packages/maestro/src/internal/engine-context.ts @@ -140,8 +140,7 @@ function resolveValue( } function assertNoUnsupportedInterpolation(value: string): void { - const interpolation = /\$\{[^{}]*\}/g; - for (const match of value.matchAll(interpolation)) { + for (const match of value.matchAll(/\$\{[^{}]*\}/g)) { if (isMaestroPlatformExpression(match[0])) continue; throw new AppError( 'INVALID_ARGS', diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 7295fde20c8..8e318c54290 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -1,5 +1,6 @@ import path from 'node:path'; import { isDeepLinkTarget } from '@agent-device/contracts/command'; +import { AppError } from '@agent-device/kernel/errors'; import type { SessionRuntimeHints } from '@agent-device/kernel/contracts'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; @@ -28,6 +29,7 @@ import { import type { MaestroReplayPlan } from './replay-plan-types.ts'; import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; import { rankMaestroCandidates } from './runtime-target-ranking.ts'; +import { MAESTRO_SELECTOR_REGEX_REASONS } from './selector-regex.ts'; const flowProgram = Symbol('maestroFlowProgram'); const failureCommand = Symbol('maestroFailureCommand'); @@ -190,10 +192,20 @@ export function collectMaestroFailureSuggestions( const query = suggestionQuery(failure[failureCommand]); const platform = failure[failurePlan].platform; if (!query || (platform !== 'android' && platform !== 'ios')) return []; - return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ - node, - basis: suggestionBasis(query.selector, node), - })); + try { + return rankMaestroCandidates(snapshot, query.selector, platform).ranked.map((node) => ({ + node, + basis: suggestionBasis(query.selector, node), + })); + } catch (error) { + if ( + error instanceof AppError && + (error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason || + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason) + ) + return []; + throw error; + } } function createObserver( diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index c4b14cb9039..053db632d14 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -11,13 +11,17 @@ import { selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { + assertLongMaestroSelectorsHaveExactCandidates, + matchesMaestroTypedSelector, +} from './runtime-target-policy.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ readonly matches: SnapshotNode[]; /** Matches after applying this selector's own index or no-index ordering policy. */ readonly indexed: SnapshotNode[]; + readonly uncertain?: AppError; }; export type MaestroResolutionProbe = { @@ -31,6 +35,7 @@ export type MaestroResolutionProbe = { export type MaestroResolutionOptions = { orderUnindexed?: (matches: readonly SnapshotNode[]) => SnapshotNode[]; + confirmedUnindexedExistence?: boolean; }; export type MaestroSnapshotResolver = { @@ -54,6 +59,7 @@ export function createMaestroSnapshotResolver( probe.onVisibilityContextCreated?.(); const selectorCache = new WeakMap(); const resolving = new WeakSet(); + let resolutionDepth = 0; const ancestorIndexesByNode = new WeakMap>(); const positionCaches = new Map< MaestroPositionRelation, @@ -117,23 +123,31 @@ export function createMaestroSnapshotResolver( throw new AppError('INVALID_ARGS', 'Maestro selector relations cannot contain cycles.'); } resolving.add(selector); - probe.onSelectorComputed?.(selector); + const confirmedUnindexedExistence = + resolutionDepth === 0 && + options.confirmedUnindexedExistence === true && + selector.index === undefined; + resolutionDepth += 1; try { - const matches = resolveWithoutOwnIndex( + probe.onSelectorComputed?.(selector); + const { matches, uncertain } = resolveWithoutOwnIndex( snapshot, selector, parentOf, ancestorIndexes, resolve, resolvePositionIndexes, + confirmedUnindexedExistence, ); const resolution = { matches, indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), + ...(uncertain ? { uncertain } : {}), }; selectorCache.set(selector, resolution); return resolution; } finally { + resolutionDepth -= 1; resolving.delete(selector); } }; @@ -154,7 +168,8 @@ function resolveWithoutOwnIndex( ancestorIndexes: (node: SnapshotNode) => ReadonlySet, resolve: ResolveSelector, resolvePositionIndexes: ResolvePositionIndexes, -): SnapshotNode[] { + confirmedUnindexedExistence: boolean, +): { matches: SnapshotNode[]; uncertain?: AppError } { const { index: _index, childOf, @@ -166,9 +181,27 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - let matches = hasMaestroLeafSelectorFields(leaf) - ? snapshot.nodes.filter((node) => matchesMaestroTypedSelector(node, leaf)) - : [...snapshot.nodes]; + let uncertain: AppError | undefined; + let matches: SnapshotNode[]; + if (hasMaestroLeafSelectorFields(leaf)) { + assertLongMaestroSelectorsHaveExactCandidates(snapshot.nodes, leaf); + matches = snapshot.nodes.filter((node) => { + try { + return matchesMaestroTypedSelector(node, leaf); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + uncertain ??= error; + return false; + } + throw error; + } + }); + } else { + matches = [...snapshot.nodes]; + } if (childOf) { const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); @@ -195,7 +228,8 @@ function resolveWithoutOwnIndex( const relatedIndexes = resolvePositionIndexes(relation, anchor); matches = matches.filter((node) => relatedIndexes.has(node.index)); } - return matches; + if (uncertain && (!confirmedUnindexedExistence || matches.length === 0)) throw uncertain; + return { matches, ...(uncertain ? { uncertain } : {}) }; } function collectContainingAncestorIndexes( diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index bc025276802..741aabc14a2 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -1,13 +1,14 @@ +import { AppError } from '@agent-device/kernel/errors'; +import type { SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; import type { MaestroLeafSelector, MaestroRelationalSelectorFields } from './program-ir.ts'; +import { matchesMaestroRegex, requiresExactMaestroRegexMatch } from './selector-regex.ts'; +import { extractNodeText } from './shared.ts'; +import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroFlatSelector = MaestroLeafSelector & { [Key in keyof MaestroRelationalSelectorFields]?: never; }; -import type { SnapshotNode } from '@agent-device/kernel/snapshot'; -import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; -import { matchesMaestroRegex } from './selector-regex.ts'; -import { extractNodeText, normalizeText } from './shared.ts'; -import { isMaestroNodeVisible } from './snapshot-policy.ts'; export type MaestroRuntimePlatform = 'ios' | 'android'; @@ -28,13 +29,13 @@ export function matchesMaestroTypedSelector( const textTerms = [ selector.id === undefined ? undefined - : matchesMaestroSelectorValue(node.identifier, selector.id), + : tryMatchMaestroSelectorValue(node.identifier, selector.id), selector.text === undefined ? undefined : matchesMaestroVisibleText(node, selector.text), - ].filter((matched): matched is boolean => matched !== undefined); + ].filter((matched): matched is boolean | AppError => matched !== undefined); if (textTerms.length === 0 && selector.enabled === undefined && selector.selected === undefined) { return false; } - if (textTerms.some((matched) => !matched)) return false; + if (textTerms.includes(false)) return false; if (selector.enabled !== undefined && Boolean(node.enabled !== false) !== selector.enabled) { return false; @@ -42,9 +43,34 @@ export function matchesMaestroTypedSelector( if (selector.selected !== undefined && Boolean(node.selected === true) !== selector.selected) { return false; } + const uncertain = textTerms.find((term): term is AppError => term instanceof AppError); + if (uncertain) throw uncertain; return true; } +export function assertLongMaestroSelectorsHaveExactCandidates( + nodes: readonly SnapshotNode[], + selector: MaestroFlatSelector, +): void { + const { id, text } = selector; + if ( + id !== undefined && + requiresExactMaestroRegexMatch(id) && + !nodes.some((node) => matchesMaestroRegex(node.identifier ?? '', id, true)) + ) { + matchesMaestroRegex('', id); + } + if ( + text !== undefined && + requiresExactMaestroRegexMatch(text) && + !nodes.some((node) => + visibleTextValues(node).some((value) => matchesMaestroRegex(value, text, true)), + ) + ) { + matchesMaestroRegex('', text); + } +} + export function filterVisibleMaestroMatches(params: { visibility: SnapshotVisibility; matches: SnapshotNode[]; @@ -55,16 +81,35 @@ export function filterVisibleMaestroMatches(params: { ); } -function matchesMaestroSelectorValue(value: string | undefined, query: string): boolean { - const text = value ?? ''; - const normalizedText = normalizeText(text); - const normalizedQuery = normalizeText(query); - if (normalizedText === normalizedQuery) return true; - return matchesMaestroRegex(text, query); +function tryMatchMaestroSelectorValue( + value: string | undefined, + query: string, +): boolean | AppError { + try { + return matchesMaestroRegex(value ?? '', query, true); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + return error; + } + throw error; + } +} + +function visibleTextValues(node: SnapshotNode): string[] { + return [node.label, extractNodeText(node), node.identifier].filter((value): value is string => + Boolean(value), + ); } -function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean { - return [node.label, extractNodeText(node), node.identifier] - .filter((value): value is string => Boolean(value)) - .some((value) => matchesMaestroSelectorValue(value, query)); +function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean | AppError { + let uncertain: AppError | undefined; + for (const value of visibleTextValues(node)) { + const result = tryMatchMaestroSelectorValue(value, query); + if (result === true) return true; + if (result instanceof AppError) uncertain ??= result; + } + return uncertain ?? false; } diff --git a/packages/maestro/src/internal/runtime-target-ranking.ts b/packages/maestro/src/internal/runtime-target-ranking.ts index 56619125d38..5326b0f3fb3 100644 --- a/packages/maestro/src/internal/runtime-target-ranking.ts +++ b/packages/maestro/src/internal/runtime-target-ranking.ts @@ -1,4 +1,5 @@ import type { Rect, SnapshotNode } from '@agent-device/kernel/snapshot'; +import type { AppError } from '@agent-device/kernel/errors'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import { isPositiveFiniteRect } from '@agent-device/kernel/rect'; import { normalizeType, type SnapshotVisibility } from '@agent-device/contracts/snapshot'; @@ -27,18 +28,28 @@ export type MaestroRankedCandidates = { readonly ranked: SnapshotNode[]; readonly parentMatched: boolean; readonly clickability: MaestroClickabilityDecision; + readonly uncertain?: AppError; }; -export type MaestroCandidateMatches = Pick; +export type MaestroCandidateMatches = Pick< + MaestroRankedCandidates, + 'matches' | 'parentMatched' | 'uncertain' +>; export function rankMaestroCandidates( snapshot: SnapshotState, selector: MaestroSelector, platform: MaestroRuntimePlatform, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, platform); - const resolver = createMaestroResolver(snapshot, clickability, probe); + const resolver = createMaestroResolver( + snapshot, + clickability, + probe, + confirmedUnindexedExistence, + ); const scoped = matchMaestroCandidatesWithResolver(selector, resolver); const visible = filterVisibleMaestroMatches({ visibility: resolver.visibility, @@ -63,23 +74,27 @@ export function matchMaestroCandidatesWithResolver( selector: MaestroSelector, resolver: MaestroSnapshotResolver, ): MaestroCandidateMatches { - const matches = resolver.resolve(selector).matches; + const { matches, uncertain } = resolver.resolve(selector); const parentMatched = selector.childOf === undefined || resolver.resolve(selector.childOf).indexed.length > 0; - return { matches, parentMatched }; + return { matches, parentMatched, ...(uncertain ? { uncertain } : {}) }; } export function createMaestroResolver( snapshot: SnapshotState, clickability: MaestroClickabilityDecision | undefined, probe: MaestroResolutionProbe = {}, + confirmedUnindexedExistence = false, ): MaestroSnapshotResolver { return createMaestroSnapshotResolver( snapshot, probe, clickability - ? { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) } - : {}, + ? { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + } + : { confirmedUnindexedExistence }, ); } diff --git a/packages/maestro/src/internal/runtime-targets.ts b/packages/maestro/src/internal/runtime-targets.ts index c904bbb5062..9462b5f3975 100644 --- a/packages/maestro/src/internal/runtime-targets.ts +++ b/packages/maestro/src/internal/runtime-targets.ts @@ -43,6 +43,8 @@ type MaestroInteractivePresentation = { presentedIndexesBySourceIndex: ReadonlyMap; }; +type PresentedNodeLookup = ReturnType; + export type MaestroTargetResolution = | { ok: true; @@ -66,15 +68,20 @@ export function resolveMaestroTargetFromSnapshot( options: { interactiveBounds?: boolean; presentation?: MaestroInteractivePresentation; + confirmedUnindexedExistence?: boolean; } = {}, ): MaestroTargetResolution { const presentedNodes = platform === 'ios' && options.presentation ? createPresentedNodeLookup(options.presentation) : undefined; - const candidates = presentedNodes - ? rankPresentedMaestroCandidates(snapshot, query, presentedNodes) - : rankMaestroCandidates(snapshot, query.selector, platform); + const candidates = rankTargetCandidates( + snapshot, + query, + platform, + presentedNodes, + options.confirmedUnindexedExistence, + ); if (!candidates.parentMatched) { return { ok: false, @@ -89,6 +96,7 @@ export function resolveMaestroTargetFromSnapshot( : selectMaestroSnapshotMatch(rankedMatches, query.selector.index)?.node; const evidence = buildMaestroTargetEvidence(query, matches, rankedMatches, target); if (!target) { + if (candidates.uncertain) throw candidates.uncertain; return failedTargetResolution(query, matches, rankedMatches, evidence); } const presentedTarget = presentedNodes @@ -99,6 +107,7 @@ export function resolveMaestroTargetFromSnapshot( ? (presentedTarget?.rect ?? semanticRect) : (semanticRect ?? presentedTarget?.rect); if (!rect) { + if (candidates.uncertain) throw candidates.uncertain; return { ok: false, message: 'Maestro target did not provide usable geometry.', @@ -112,17 +121,55 @@ export function resolveMaestroTargetFromSnapshot( node: target, rect, matches: rankedMatches.length, - dispatchCandidates: - platform === 'ios' && - query.allowAtomicSelectorDispatch && - !hasMaestroRecursiveRelations(query.selector) && - presentedNodes - ? countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget) - : 0, + dispatchCandidates: atomicDispatchCandidates( + platform, + query, + presentedNodes, + semanticRect, + rankedMatches, + presentedTarget, + ), evidence, }; } +function rankTargetCandidates( + snapshot: SnapshotState, + query: MaestroSnapshotTargetQuery, + platform: MaestroRuntimePlatform, + presentedNodes: PresentedNodeLookup | undefined, + confirmedUnindexedExistence: boolean | undefined, +): MaestroRankedCandidates { + if (presentedNodes) { + return rankPresentedMaestroCandidates( + snapshot, + query, + presentedNodes, + confirmedUnindexedExistence, + ); + } + return rankMaestroCandidates(snapshot, query.selector, platform, {}, confirmedUnindexedExistence); +} + +function atomicDispatchCandidates( + platform: MaestroRuntimePlatform, + query: MaestroSnapshotTargetQuery, + presentedNodes: PresentedNodeLookup | undefined, + semanticRect: Rect | undefined, + rankedMatches: SnapshotNode[], + presentedTarget: { node: SnapshotNode; rect: Rect } | null, +): number { + if ( + platform !== 'ios' || + !query.allowAtomicSelectorDispatch || + hasMaestroRecursiveRelations(query.selector) || + !presentedNodes + ) { + return 0; + } + return countInteractionDispatchCandidates(semanticRect, rankedMatches, presentedTarget); +} + export const hasMaestroRecursiveRelations = hasRecursiveRelations; function createPresentedNodeLookup(presentation: MaestroInteractivePresentation): { @@ -156,12 +203,16 @@ function rankPresentedMaestroCandidates( snapshot: SnapshotState, query: MaestroSnapshotTargetQuery, presentedNodes: ReturnType, + confirmedUnindexedExistence = false, ): MaestroRankedCandidates { const clickability = resolveMaestroClickability(snapshot, 'ios'); const resolver = createMaestroSnapshotResolver( snapshot, {}, - { orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability) }, + { + orderUnindexed: (matches) => orderMaestroClickableFirst(matches, clickability), + confirmedUnindexedExistence, + }, ); const scoped = matchMaestroCandidatesWithResolver(query.selector, resolver); const visible = scoped.matches.filter(presentedNodes.isVisible); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b03d0982561..71dc73873a5 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -1,20 +1,345 @@ +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import { RegExpParser, visitRegExpAST, type AST } from '@eslint-community/regexpp'; +import { normalizeText } from './shared.ts'; + +export const MAESTRO_SELECTOR_REGEX_REASONS = { + // The selector pattern uses constructs that the bounded matcher cannot safely execute. + unsafe: { reason: 'maestro_selector_regex_unsafe' }, + // A multiline value might match across partial lines, so absence cannot be confirmed safely. + indeterminate: { reason: 'maestro_selector_regex_indeterminate' }, +} as const satisfies ReasonTable<'maestro selector regex'>; + const REGEX_SYNTAX = new Set(String.raw`^$\.*+?()[]{}|`); +const MAX_PATTERN_LENGTH = 256; +const MAX_COUNTED_REPETITION = 10_000; +const MAX_CACHED_PATTERNS = 128; +const MAX_PATTERN_PATHS = 32; +const MAX_MULTILINE_VALUE_LENGTH = 16_384; +const MAX_MULTILINE_WORK = 131_072; +const parser = new RegExpParser(); +type RegexElement = AST.Alternative['elements'][number]; +type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; +type Matcher = LiteralMatcher | { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; +const matcherCache = new Map(); + +export function requiresExactMaestroRegexMatch(pattern: string): boolean { + return pattern.length > MAX_PATTERN_LENGTH && hasRegexSyntax(pattern); +} + +export function matchesMaestroRegex( + value: string, + pattern: string, + deferLongPatternRefusal = false, +): boolean { + if (requiresExactMaestroRegexMatch(pattern)) { + if (normalizeText(value) === normalizeText(pattern)) return true; + if (deferLongPatternRefusal) return false; + unsafeMaestroRegex(); + } + const matcher = matcherForPattern(pattern); + if ('literal' in matcher) return matchesLiteral(value, matcher); + if (normalizeText(value) === normalizeText(pattern)) return true; + if (!hasLineTerminator(value)) return matcher.regex.test(value); + // A whole-value match has one anchored start. The work budget below limits how many + // line-boundary starts the multiline engine may try, not this bounded single start. + if (value.length <= MAX_MULTILINE_VALUE_LENGTH && matcher.regex.test(value)) return true; + if (boundedMultilineWork(value)) return matcher.multilineRegex.test(value); + if (matchesAnyLine(value, matcher.regex)) return true; + if (matcher.canSpanLines) indeterminateMaestroRegex(); + return false; +} + +function matchesLiteral(value: string, matcher: LiteralMatcher): boolean { + if (normalizeText(value) === normalizeText(matcher.literal)) return true; + if (matcher.wholeOnly) return false; + if (matcher.literal.length > MAX_PATTERN_LENGTH) { + return matchesLongLiteralLine(value, matcher.literal); + } + matcher.lineRegex ??= new RegExp( + `^(?:${matcher.literal.replaceAll(/[\\^$.*+?()[\]{}|]/g, String.raw`\$&`)})$`, + 'im', + ); + return matcher.lineRegex.test(value); +} + +function matchesLongLiteralLine(value: string, literal: string): boolean { + const text = value.toLowerCase(); + const query = literal.toLowerCase(); + const fallbacks = literalPrefixFallbacks(query); + let matched = 0; + for (let index = 0; index < text.length; index += 1) { + while (matched > 0 && text[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (text[index] === query[matched]) matched += 1; + if (matched !== query.length) continue; + const start = index + 1 - matched; + const before = start === 0 || isLineTerminator(text[start - 1]); + const after = index + 1 === text.length || isLineTerminator(text[index + 1]); + if (before && after) return true; + matched = fallbacks[matched - 1]!; + } + return false; +} + +function literalPrefixFallbacks(query: string): Uint32Array { + const fallbacks = new Uint32Array(query.length); + let matched = 0; + for (let index = 1; index < query.length; index += 1) { + while (matched > 0 && query[index] !== query[matched]) matched = fallbacks[matched - 1]!; + if (query[index] === query[matched]) matched += 1; + fallbacks[index] = matched; + } + return fallbacks; +} + +function isLineTerminator(character: string | undefined): boolean { + return ( + character === '\n' || character === '\r' || character === '\u2028' || character === '\u2029' + ); +} + +function hasLineTerminator(value: string): boolean { + return /[\n\r\u2028\u2029]/.test(value); +} + +function boundedMultilineWork(value: string): boolean { + if (value.length > MAX_MULTILINE_VALUE_LENGTH) return false; + let boundaries = 1; + for (const character of value) { + if (isLineTerminator(character)) boundaries += 1; + if (boundaries * value.length > MAX_MULTILINE_WORK) return false; + } + return true; +} + +function matchesAnyLine(value: string, regex: RegExp): boolean { + let start = 0; + for (let index = 0; index < value.length; index += 1) { + if (!isLineTerminator(value[index])) continue; + if (regex.test(value.slice(start, index))) return true; + start = index + 1; + } + return regex.test(value.slice(start)); +} -export function matchesMaestroRegex(value: string, pattern: string): boolean { +function matcherForPattern(pattern: string): Matcher { + const cached = matcherCache.get(pattern); + if (cached) return cached; + const literal = literalFromMaestroRegex(pattern); + let matcher: Matcher; + if (literal !== undefined) { + let wholeOnly = false; + try { + new RegExp(pattern); + } catch { + wholeOnly = true; + } + matcher = { literal, wholeOnly }; + } else { + if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); + const canSpanLines = assertBoundedMaestroPattern(pattern); + try { + matcher = { + regex: new RegExp(`^(?:${pattern})$`, 'is'), + multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), + canSpanLines, + }; + } catch { + unsafeMaestroRegex(); + } + } + if (matcherCache.size >= MAX_CACHED_PATTERNS) { + matcherCache.delete(matcherCache.keys().next().value!); + } + matcherCache.set(pattern, matcher); + return matcher; +} + +function assertBoundedMaestroPattern(pattern: string): boolean { + let parsed: AST.Pattern; try { - return new RegExp(`^(?:${pattern})$`, 'ims').test(value); + parsed = parser.parsePattern(pattern); } catch { - return value.toLocaleLowerCase() === pattern.toLocaleLowerCase(); + unsafeMaestroRegex(); + } + let ambiguousGroups = 0; + const countAlternatives = (count: number): void => { + if (count > 1 && ++ambiguousGroups > 4) unsafeMaestroRegex(); + }; + visitRegExpAST(parsed, { + onBackreferenceEnter: unsafeMaestroRegex, + onAssertionEnter(node) { + if ('alternatives' in node) unsafeMaestroRegex(); + }, + onGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onCapturingGroupEnter(node) { + countAlternatives(node.alternatives.length); + }, + onQuantifierEnter(node) { + if ( + node.min > MAX_COUNTED_REPETITION || + (Number.isFinite(node.max) && node.max > MAX_COUNTED_REPETITION) + ) { + unsafeMaestroRegex(); + } + visitRegExpAST(node.element, { + onGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onCapturingGroupEnter(group) { + if (group.alternatives.length > 1) unsafeMaestroRegex(); + }, + onQuantifierEnter: unsafeMaestroRegex, + }); + }, + }); + for (const alternative of parsed.alternatives) { + for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); + } + return parsed.alternatives.some((alternative) => alternative.elements.some(elementCanSpanLines)); +} + +function elementCanSpanLines(element: RegexElement): boolean { + if (element.type === 'Assertion') return false; + if (element.type === 'Quantifier') return elementCanSpanLines(element.element); + if (element.type === 'Group' || element.type === 'CapturingGroup') { + return element.alternatives.some((alternative) => + alternative.elements.some(elementCanSpanLines), + ); + } + const atom = new RegExp(`^(?:${element.raw})$`, 'is'); + return ['\n', '\r', '\u2028', '\u2029'].some((character) => atom.test(character)); +} + +function expandedPaths(elements: AST.Alternative['elements']): RegexElement[][] { + let paths: RegexElement[][] = [[]]; + for (const element of elements) { + paths = appendElement(paths, element); + } + return paths; +} + +function appendElement(paths: RegexElement[][], element: RegexElement): RegexElement[][] { + const isGroup = element.type === 'Group' || element.type === 'CapturingGroup'; + const branches = isGroup + ? element.alternatives.flatMap((alternative) => expandedPaths(alternative.elements)) + : [[element]]; + const next: RegexElement[][] = []; + for (const prefix of paths) { + for (const branch of branches) { + if (isGroup) assertSafeGroupAfterQuantifier(prefix.at(-1), branch); + next.push([...prefix, ...branch]); + if (next.length > MAX_PATTERN_PATHS) unsafeMaestroRegex(); + } + } + return next; +} + +function assertSafeGroupAfterQuantifier( + previous: RegexElement | undefined, + branch: RegexElement[], +) { + if (previous?.type !== 'Quantifier' || previous.max === previous.min) return; + const first = branch.find((element) => element.type !== 'Assertion'); + if (!first || (first.type === 'Quantifier' && first.min === 0)) unsafeMaestroRegex(); + const atom = first.type === 'Quantifier' ? first.element : first; + if (!quantifiedAtomsAreDisjoint(previous.element, atom)) unsafeMaestroRegex(); +} + +function assertDisjointQuantifiers(path: RegexElement[]): void { + const quantifiers = path.flatMap((element, index) => + element.type === 'Quantifier' && element.max > element.min ? [{ element, index }] : [], + ); + for (let left = 0; left < quantifiers.length; left += 1) { + for (let right = left + 1; right < quantifiers.length; right += 1) { + const later = quantifiers[right]!; + if (later.index === path.length - 1 && isTrailingWildcard(later.element)) continue; + if (!quantifiedAtomsAreDisjoint(quantifiers[left]!.element.element, later.element.element)) { + unsafeMaestroRegex(); + } + } + } +} + +function isTrailingWildcard(quantifier: AST.Quantifier): boolean { + return quantifier.element.raw === '.' && quantifier.max === Infinity && quantifier.min <= 1; +} + +function quantifiedAtomsAreDisjoint( + left: AST.QuantifiableElement, + right: AST.QuantifiableElement, +): boolean { + if ( + left.type === 'Group' || + left.type === 'CapturingGroup' || + right.type === 'Group' || + right.type === 'CapturingGroup' + ) { + return false; } + if (!isAsciiOnly(left) && !isAsciiOnly(right)) return false; + const leftMatcher = new RegExp(`^(?:${left.raw})$`, 'is'); + const rightMatcher = new RegExp(`^(?:${right.raw})$`, 'is'); + for (let codePoint = 0; codePoint < 128; codePoint += 1) { + const character = String.fromCharCode(codePoint); + if (leftMatcher.test(character) && rightMatcher.test(character)) return false; + } + return true; +} + +function isAsciiOnly(element: AST.QuantifiableElement): boolean { + if (element.type === 'Character') return element.value < 128; + if (element.type === 'CharacterSet') { + return (element.kind === 'digit' || element.kind === 'word') && !element.negate; + } + if (element.type !== 'CharacterClass' || element.negate) return false; + return element.elements.every((part) => { + if (part.type === 'Character') return part.value < 128; + if (part.type === 'CharacterClassRange') return part.max.value < 128; + return part.type === 'CharacterSet' && isAsciiOnly(part); + }); +} + +function unsafeMaestroRegex(): never { + throw new AppError('INVALID_ARGS', 'Maestro selector regular expression is too complex.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.unsafe.reason, + retriable: false, + }); +} + +function indeterminateMaestroRegex(): never { + throw new AppError( + 'UNSUPPORTED_OPERATION', + 'Maestro selector cannot safely decide a multiline match.', + { + reason: MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason, + retriable: false, + }, + ); } export function literalFromMaestroRegex(pattern: string): string | undefined { + if (pattern.length > MAX_PATTERN_LENGTH) { + return hasRegexSyntax(pattern) ? undefined : pattern; + } try { new RegExp(pattern); } catch { return pattern; } + return literalFromEscapedPattern(pattern); +} + +function hasRegexSyntax(pattern: string): boolean { + for (const character of pattern) { + if (REGEX_SYNTAX.has(character)) return true; + } + return false; +} + +function literalFromEscapedPattern(pattern: string): string | undefined { let literal = ''; for (let index = 0; index < pattern.length; index += 1) { const character = pattern[index]!; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 311e223d79e..26c5fca09e6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -737,6 +737,9 @@ importers: '@agent-device/selectors': specifier: workspace:* version: link:../selectors + '@eslint-community/regexpp': + specifier: 4.12.2 + version: 4.12.2 devDependencies: undici: specifier: 7.30.1 diff --git a/scripts/bundled-dependency-names.ts b/scripts/bundled-dependency-names.ts new file mode 100644 index 00000000000..ee400e548f0 --- /dev/null +++ b/scripts/bundled-dependency-names.ts @@ -0,0 +1,33 @@ +export const bundledDependencyNames = [ + '@eslint-community/regexpp', + '@limrun/api', + '@limrun/xdelta3-wasm', + '@xmldom/xmldom', + 'agent-base', + 'b4a', + 'debug', + 'events-universal', + 'eventsource-client', + 'eventsource-parser', + 'fast-fifo', + 'has-flag', + 'https-proxy-agent', + 'ignore', + 'ipaddr.js', + 'jpeg-js', + 'ms', + 'pend', + 'plist', + 'pngjs', + 'proxy-from-env', + 'streamx', + 'supports-color', + 'tar-stream', + 'text-decoder', + 'undici', + 'undici-types', + 'ws', + 'xmlbuilder', + 'yaml', + 'yauzl', +]; diff --git a/tsdown.config.ts b/tsdown.config.ts index 5412d1a2040..dc699f86194 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -1,4 +1,5 @@ import { buildEntries } from './scripts/build-entries.ts'; +import { bundledDependencyNames } from './scripts/bundled-dependency-names.ts'; import fs from 'node:fs'; import { defineConfig, type TsdownPluginOption } from 'tsdown'; import { bundledLicenseNotices } from './scripts/lib/bundled-license-notices.ts'; @@ -86,38 +87,7 @@ export default defineConfig({ entry: buildEntries, deps: { alwaysBundle: [/^@agent-device\//], - onlyBundle: [ - '@limrun/api', - '@limrun/xdelta3-wasm', - '@xmldom/xmldom', - 'agent-base', - 'b4a', - 'debug', - 'events-universal', - 'eventsource-client', - 'eventsource-parser', - 'fast-fifo', - 'has-flag', - 'https-proxy-agent', - 'ignore', - 'ipaddr.js', - 'jpeg-js', - 'ms', - 'pend', - 'plist', - 'pngjs', - 'proxy-from-env', - 'streamx', - 'supports-color', - 'tar-stream', - 'text-decoder', - 'undici', - 'undici-types', - 'ws', - 'xmlbuilder', - 'yaml', - 'yauzl', - ], + onlyBundle: bundledDependencyNames, // The Limrun SDK is dev-bundled, so a published install has no `@limrun/api` to resolve: // the limrun facade declares the session and runtime types consumers may use. dts: { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index e3a89daa61d..3c30bb75f5d 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -881,6 +881,13 @@ These reasons can come from more than one command. | `event_creation_failed` | macOS could not create the keyboard or mouse event to post. | | `missing_button` | No button on the alert fits the requested accept or dismiss. | +### Maestro selector regex + +| Reason | Meaning | +| --- | --- | +| `maestro_selector_regex_unsafe` | The selector pattern uses constructs that the bounded matcher cannot safely execute. | +| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so absence cannot be confirmed safely. | + ### Metro reload | Reason | Meaning | diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index fdf4e5d7606..d99dacb17af 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,6 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, lookahead and lookbehind assertions, overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 4c113d12465b7b3c39bf488c8e2bb1e88700dbe1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:30:01 +0100 Subject: [PATCH 02/17] chore(gates): prove bundled Maestro regex dependency --- .../__tests__/package-closure-audit.test.ts | 65 +++++- scripts/check-package.ts | 33 ++- scripts/layering/package-boundaries.test.ts | 20 +- scripts/lib/shipped-imports.ts | 36 +++ scripts/size-report-package.d.mts | 1 + scripts/size-report-package.mjs | 2 +- test/repo-guards/maestro-regex-owner.test.ts | 213 ++++++++++++++++++ 7 files changed, 362 insertions(+), 8 deletions(-) create mode 100644 test/repo-guards/maestro-regex-owner.test.ts diff --git a/scripts/__tests__/package-closure-audit.test.ts b/scripts/__tests__/package-closure-audit.test.ts index 4f2742eb26e..b91c790d268 100644 --- a/scripts/__tests__/package-closure-audit.test.ts +++ b/scripts/__tests__/package-closure-audit.test.ts @@ -17,7 +17,70 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { afterEach, test } from 'vitest'; -import { auditDependencyClosure, type PackedManifest } from '../lib/shipped-imports.ts'; +import { + auditDependencyClosure, + assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, + type PackedManifest, +} from '../lib/shipped-imports.ts'; + +test('bundled workspace proof includes package devDependencies', () => { + const names = bundledWorkspaceDependencyNames( + new Map([ + [ + 'packages/maestro/package.json', + JSON.stringify({ + dependencies: { + '@eslint-community/regexpp': '4.12.2', + '@agent-device/kernel': 'workspace:*', + }, + devDependencies: { + '@limrun/api': '^0.69.1', + '@eslint-community/regexpp': 'workspace:*', + 'test-only': '1.0.0', + }, + }), + ], + ]), + new Set(['@eslint-community/regexpp', '@limrun/api', '@agent-device/kernel']), + ); + assert.deepEqual([...names].sort(), ['@eslint-community/regexpp', '@limrun/api']); + assert.throws( + () => + assertBundledWorkspaceDependencies( + names, + new Set(['@eslint-community/regexpp@4.12.2 (MIT)']), + new Map(), + ), + /does not attribute rendered @limrun\/api modules/, + ); +}); + +test('a bundled workspace dependency needs rendered notice attribution', () => { + assert.throws( + () => assertBundledWorkspaceDependencies(new Set(['regexpp']), new Set(), new Map()), + /does not attribute rendered regexpp modules/, + ); + assert.doesNotThrow(() => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map(), + ), + ); +}); + +test('a bundled workspace dependency cannot retain a shipped runtime import', () => { + assert.throws( + () => + assertBundledWorkspaceDependencies( + new Set(['regexpp']), + new Set(['regexpp@4.12.2 (MIT)']), + new Map([['regexpp', ['dist/cli.js']]]), + ), + /still imports regexpp at runtime/, + ); +}); const tempRoots: string[] = []; diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 0bb72f67331..778fa7009df 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -9,7 +9,8 @@ * 1. `publint` — packaging metadata against the packed tarball (exports/bin/types conditions). * 2. `attw` — declaration resolution for the module systems this package supports. * 3. runtime dependency closure — every bare specifier the shipped files import is a Node builtin - * or a declared `dependencies` entry, and every declared entry is actually imported. + * or a declared `dependencies` entry, every declared entry is imported, and every bundled + * workspace dependency is attributed in the packed artifact without a runtime import. * 4. every `exports` subpath imports, and the `bin` runs, from outside the workspace. * 5. the installed tree carries no daemon source, which is what lets an installed * client treat its version as the whole of its code identity (#2458). @@ -28,11 +29,17 @@ import os from 'node:os'; import path from 'node:path'; import { auditDependencyClosure, + assertBundledWorkspaceDependencies, + bundledWorkspaceDependencyNames, type PackedManifest as PackedDependencies, } from './lib/shipped-imports.ts'; import { assertInstalledSnapshotBridge } from './size-report-install.mjs'; +import { readLicenseNotices } from './size-report-package-notices.mjs'; +import { bundledDependencyNames } from './bundled-dependency-names.ts'; +import { listTrackedPackageManifests } from './layering/tracked-sources.ts'; import { assertBundledLicenseNotices, + BUNDLED_LICENSE_NOTICES_PATH, parseNpmPackOutput, type NpmPackEntry, } from './size-report-package.mjs'; @@ -282,6 +289,30 @@ try { ) as PackedManifest; const importedBy = auditDependencyClosure(installedRoot, manifest); step(`Verified the dependency closure: ${[...importedBy.keys()].sort().join(', ')}.`); + // R11 permits a workspace runtime dependency to be absent from the root manifest only when + // tsdown bundles it. The notices plugin attributes only modules rendered into the artifact. + // Check that proof for every such dependency in the installed tarball, not only today's regexpp. + const bundled = new Set(bundledDependencyNames); + const bundledWorkspaceDependencies = bundledWorkspaceDependencyNames( + new Map( + listTrackedPackageManifests(repoRoot).map((file) => [ + file, + fs.readFileSync(path.join(repoRoot, file), 'utf8'), + ]), + ), + bundled, + ); + const notices = readLicenseNotices( + fs.readFileSync(path.join(installedRoot, BUNDLED_LICENSE_NOTICES_PATH), 'utf8'), + ); + assertBundledWorkspaceDependencies( + bundledWorkspaceDependencies, + new Set(notices.attributions.map(({ label }) => label)), + importedBy, + ); + step( + `Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`, + ); importEveryExport(manifest); smokeTestBin(installedRoot, manifest); } catch (error) { diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts index 8b255939b37..8144d39b9ff 100644 --- a/scripts/layering/package-boundaries.test.ts +++ b/scripts/layering/package-boundaries.test.ts @@ -8,6 +8,7 @@ import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { test } from 'node:test'; +import { bundledDependencyNames } from '../bundled-dependency-names.ts'; import { listSourceFiles } from './check.ts'; import { readNamedExports, readReExportSources } from './facade-exports.ts'; import { @@ -881,13 +882,22 @@ test('the real tree parses, declares, and passes R11', () => { '@agent-device/platform-android', ]); const rootExternalDependencies = rootExternalDependencyRanges(repoRoot); + const bundled = new Set(bundledDependencyNames); for (const pkg of packages) { for (const [name, range] of pkg.externalDependencies) { - assert.equal( - rootExternalDependencies.get(name), - range, - `${pkg.name} external dependency ${name} must match the root dependency range`, - ); + if (bundled.has(name)) { + assert.equal( + rootExternalDependencies.has(name), + false, + `${pkg.name} bundled dependency ${name} must not ship as a root runtime dependency`, + ); + } else { + assert.equal( + rootExternalDependencies.get(name), + range, + `${pkg.name} externalized dependency ${name} must match the root runtime range`, + ); + } } } const xmlPackage = packages.find((pkg) => pkg.name === '@agent-device/xml'); diff --git a/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 6acf2b83abb..7dd6a08531a 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -59,6 +59,42 @@ export type PackedManifest = { peerDependencies?: Record; }; +/** Bundled external dependencies declared by tracked workspace package manifests. */ +export function bundledWorkspaceDependencyNames( + manifests: ReadonlyMap, + bundledNames: ReadonlySet, +): Set { + const names = new Set(); + for (const source of manifests.values()) { + const manifest = JSON.parse(source) as { + dependencies?: Record; + devDependencies?: Record; + }; + for (const field of [manifest.dependencies, manifest.devDependencies]) { + for (const [name, range] of Object.entries(field ?? {})) { + if (bundledNames.has(name) && !range.startsWith('workspace:')) names.add(name); + } + } + } + return names; +} + +/** Prove that a workspace runtime dependency omitted from the root manifest is in the packed code. */ +export function assertBundledWorkspaceDependencies( + names: ReadonlySet, + attributionLabels: ReadonlySet, + importedBy: ReadonlyMap, +): void { + for (const name of names) { + if (![...attributionLabels].some((label) => label.startsWith(`${name}@`))) { + throw new Error(`The packed bundle does not attribute rendered ${name} modules.`); + } + if (importedBy.has(name)) { + throw new Error(`The packed bundle still imports ${name} at runtime.`); + } + } +} + /** Every file extension the package ships that Node can resolve a specifier from. */ const SHIPPED_SOURCE = /\.(?:m?js|cjs|d\.ts)$/; diff --git a/scripts/size-report-package.d.mts b/scripts/size-report-package.d.mts index 2056499a205..48b1afc91f8 100644 --- a/scripts/size-report-package.d.mts +++ b/scripts/size-report-package.d.mts @@ -2,6 +2,7 @@ // it is not in the typechecked program). TypeScript resolves this file when a checked module // imports `./size-report-package.mjs`; keep it in step with the exports there. export const DOCUMENTED_PACK_STUBS: readonly string[]; +export const BUNDLED_LICENSE_NOTICES_PATH: string; export function readMacosHelperTestTargets(manifestSource: string): string[]; export type NpmPackEntry = Readonly<{ path: string; size: number }>; export function assertBundledLicenseNotices( diff --git a/scripts/size-report-package.mjs b/scripts/size-report-package.mjs index f873a1c5575..a56fe2932fe 100644 --- a/scripts/size-report-package.mjs +++ b/scripts/size-report-package.mjs @@ -75,7 +75,7 @@ export function collectNpmPack(root) { * The notices asset a packed tree ships, and the build output it comes from. One path keeps the * manifest check and the content check naming the same file. */ -const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; +export const BUNDLED_LICENSE_NOTICES_PATH = 'dist/src/THIRD_PARTY_NOTICES.txt'; function describeUnresolvedAttribution(attribution) { return ( diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts new file mode 100644 index 00000000000..5911943cc9a --- /dev/null +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -0,0 +1,213 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseSync } from 'oxc-parser'; +import { test } from 'vitest'; + +const SOURCE_ROOT = path.join( + path.dirname(fileURLToPath(import.meta.url)), + '../../packages/maestro/src', +); +const REGEX_OWNER = path.join(SOURCE_ROOT, 'internal/selector-regex.ts'); + +function sourceFiles(directory: string): string[] { + return fs.readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { + if (entry.name === '__tests__' || entry.name === 'test-utils') return []; + const entryPath = path.join(directory, entry.name); + if (entry.isDirectory()) return sourceFiles(entryPath); + if (!entry.name.endsWith('.ts') || entry.name.endsWith('.test.ts')) return []; + return [entryPath]; + }); +} + +function regexBypassViolations(source: string, filePath: string): string[] { + const parsed = parseSync(filePath, source); + assert.deepEqual(parsed.errors, []); + const violations: string[] = []; + type Node = { + type?: string; + name?: string; + value?: unknown; + regex?: unknown; + start?: number; + callee?: Node; + id?: Node; + init?: Node; + left?: Node; + object?: Node; + property?: Node; + arguments?: Node[]; + body?: Node[]; + declarations?: Node[]; + params?: Node[]; + [key: string]: unknown; + }; + type Scope = { parent?: Scope; bindings: Map }; + function calledName(callee: Node | undefined): unknown { + if (callee?.type === 'Identifier') return callee.name; + if (callee?.type === 'MemberExpression') return callee.property?.name ?? callee.property?.value; + return undefined; + } + function binding(scope: Scope, name: string): boolean | undefined { + for (let current: Scope | undefined = scope; current; current = current.parent) { + if (current.bindings.has(name)) return current.bindings.get(name); + } + return undefined; + } + function isRegexReference(node: Node | undefined, scope: Scope): boolean { + if (node?.type !== 'Identifier' || !node.name) return false; + return binding(scope, node.name) ?? node.name === 'RegExp'; + } + function bindPattern(node: Node | undefined, scope: Scope): void { + if (!node) return; + if (node.type === 'Identifier' && node.name) { + scope.bindings.set(node.name, false); + return; + } + for (const child of patternChildren(node)) bindPattern(child, scope); + } + function patternChildren(node: Node): Node[] { + if (node.type === 'Property') return [node.value as Node]; + if (node.type === 'RestElement') return [node.argument as Node]; + if (node.type === 'AssignmentPattern') return [node.left as Node]; + if (node.type !== 'ObjectPattern' && node.type !== 'ArrayPattern') return []; + return Object.values(node).flatMap((child) => (Array.isArray(child) ? (child as Node[]) : [])); + } + function blockScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + for (const statement of node.body ?? []) declareStatement(statement, scope); + for (const statement of node.body ?? []) bindRegexAliases(statement, scope); + return scope; + } + function declareStatement(statement: Node, scope: Scope): void { + if (statement.type === 'VariableDeclaration') { + for (const declaration of statement.declarations ?? []) bindPattern(declaration.id, scope); + } else if (statement.type === 'FunctionDeclaration' || statement.type === 'ClassDeclaration') { + bindPattern(statement.id, scope); + } + } + function bindRegexAliases(statement: Node, scope: Scope): void { + if (statement.type !== 'VariableDeclaration') return; + for (const declaration of statement.declarations ?? []) { + if (declaration.id?.type === 'Identifier' && isRegexReference(declaration.init, scope)) { + scope.bindings.set(declaration.id.name!, true); + } + } + } + function isRegexBypass(node: Node, scope: Scope): boolean { + if (node.type !== 'NewExpression' && node.type !== 'CallExpression') return false; + if (isRegexReference(node.callee, scope)) return true; + return node.type === 'CallExpression' && isIndirectRegexCall(node, scope); + } + function isIndirectRegexCall(node: Node, scope: Scope): boolean { + const name = calledName(node.callee); + if (node.callee?.type !== 'MemberExpression') return false; + if ((name === 'call' || name === 'apply') && isRegexReference(node.callee.object, scope)) { + return true; + } + if (name === 'construct' && node.callee.object?.name === 'Reflect') { + return ( + binding(scope, 'Reflect') === undefined && isRegexReference(node.arguments?.[0], scope) + ); + } + return ( + (name === 'match' || name === 'matchAll' || name === 'search') && + node.arguments?.[0]?.regex === undefined + ); + } + function scopeForNode(node: Node, scope: Scope): Scope { + switch (node.type) { + case 'Program': + case 'BlockStatement': + return blockScope(node, scope); + case 'FunctionDeclaration': + case 'FunctionExpression': + case 'ArrowFunctionExpression': + return functionScope(node, scope); + case 'CatchClause': { + const local: Scope = { parent: scope, bindings: new Map() }; + bindPattern(node.param as Node, local); + return local; + } + case 'ForStatement': + case 'ForOfStatement': + case 'ForInStatement': + return loopScope(node, scope); + default: + return scope; + } + } + function functionScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + bindPattern(node.id, scope); + for (const parameter of node.params ?? []) bindPattern(parameter, scope); + return scope; + } + function loopScope(node: Node, parent: Scope): Scope { + const scope: Scope = { parent, bindings: new Map() }; + const declaration = node.type === 'ForStatement' ? node.init : node.left; + if (declaration?.type === 'VariableDeclaration') { + for (const item of declaration.declarations ?? []) bindPattern(item.id, scope); + } + return scope; + } + function visit(value: unknown, scope: Scope): void { + if (!value || typeof value !== 'object') return; + if (Array.isArray(value)) { + for (const item of value) visit(item, scope); + return; + } + const node = value as Node; + const local = scopeForNode(node, scope); + if (isRegexBypass(node, local)) { + const line = source.slice(0, node.start).split('\n').length; + violations.push(`${path.relative(SOURCE_ROOT, filePath)}:${line}`); + } + for (const child of Object.values(node)) visit(child, local); + } + visit(parsed.program, { bindings: new Map() }); + return violations; +} + +test('Maestro regex construction stays behind the bounded selector owner', () => { + const files = sourceFiles(SOURCE_ROOT).filter((file) => file !== REGEX_OWNER); + assert.ok(files.length > 0, 'guard must scan Maestro production files'); + assert.deepEqual( + files.flatMap((file) => regexBypassViolations(fs.readFileSync(file, 'utf8'), file)), + [], + 'Route authored selector patterns through internal/selector-regex.ts.', + ); +}); + +test('Maestro regex guard catches direct and implicit construction', () => { + const source = [ + 'new RegExp(query)', + 'RegExp(query)', + 'value.match(query)', + 'value.matchAll(query)', + 'value.search(query)', + "value['match'](query)", + 'const R = RegExp; new R(query)', + 'Reflect.construct(RegExp, [query])', + 'RegExp.call(null, query)', + 'RegExp.apply(null, [query])', + ].join(';'); + assert.equal(regexBypassViolations(source, 'fixture.ts').length, 10); + assert.deepEqual(regexBypassViolations('value.matchAll(/fixed/g)', 'fixture.ts'), []); + assert.deepEqual( + regexBypassViolations('const R = RegExp; function use(R) { new R(query) }', 'fixture.ts'), + [], + ); + assert.deepEqual( + regexBypassViolations( + 'function use() { const RegExp = make(); new RegExp(query) }', + 'fixture.ts', + ), + [], + ); + assert.deepEqual( + regexBypassViolations('const R = RegExp; for (const R of values) new R(query)', 'fixture.ts'), + [], + ); +}); From 9aa73821d21e21c5486a2b76ab287d292dfb23e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:42:29 +0100 Subject: [PATCH 03/17] fix(maestro): match ordered wildcard literals with bounded work --- .../internal/__tests__/selector-regex.test.ts | 52 +++++++++--- .../maestro/src/internal/selector-regex.ts | 83 +++++++++++++++++-- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 96baf1aff09..b9c405b8f82 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -28,9 +28,6 @@ test.each([ '(?:(?:a|ab)(?:c|bc))*', 'a*a*', 'a*b*a*', - '.*a.*b', - '.*x.*y.*z', - '.*a.*a.*a.*b', '(a*)(a*)b', '(?:aa)+a+b', 'a{10001}', @@ -60,17 +57,52 @@ test('refuses a nullable separator before matching a maximum-length node value', ); }); -test('refuses overlapping wildcard and grouped repetitions before a long node value runs', () => { +test('refuses overlapping grouped repetitions before a long node value runs', () => { const value = `${'a\n'.repeat(4096)}X`; - for (const pattern of ['.*a.*b', '.*a.*a.*a.*b', '(a*)(a*)b']) { - expect(() => matchesMaestroRegex(value, pattern)).toThrow( - expect.objectContaining({ - details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), - }), - ); + expect(() => matchesMaestroRegex(value, '(a*)(a*)b')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + +test('ordered wildcard literals retain Maestro full and multiline matching', () => { + for (const [value, pattern, expected] of [ + ['xxaYYb', '.*a.*b', true], + ['a\nZZ', '.*a.*b', false], + ['a\nb', '.*a.*b', true], + ['Order\nconfirmed', '.*Order.*confirmed.*', true], + ['xYyZz', '.*x.*y.*z', true], + ['Å\nβ', '.*å.*β', true], + ['a\r\nb', '.*a.*b', true], + ['a\u2028b', '.*a.*b', true], + ['ababa', '.*aba', true], + ['aababa', '.*a.*aba', true], + ['a.b\nc', String.raw`.*a\.b.*c`, true], + ['aX\nbYc', 'a.*b.*c', true], + ['xaX\nbYc', 'a.*b.*c', false], + ['a\nbX', '.*a.*b', false], + ['a'.repeat(8192) + 'b', '.*a.*b', true], + ['a'.repeat(8192) + 'X', '.*a.*b', false], + ] as const) { + expect(matchesMaestroRegex(value, pattern)).toBe(expected); } }); +test('ordered wildcard work exhaustion remains indeterminate', () => { + const pattern = `.*${'a'.repeat(99)}b.*c`; + expect(() => matchesMaestroRegex('a'.repeat(11_000), pattern)).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + expect(() => matchesMaestroRegex('x'.repeat(1_000_001), 'a.*b.*c')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('extracts only patterns that are exact literals', () => { expect(literalFromMaestroRegex('checkout-submit')).toBe('checkout-submit'); expect(literalFromMaestroRegex(String.raw`price\.usd`)).toBe('price.usd'); diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 71dc73873a5..b8f6c9b3329 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -16,10 +16,18 @@ const MAX_CACHED_PATTERNS = 128; const MAX_PATTERN_PATHS = 32; const MAX_MULTILINE_VALUE_LENGTH = 16_384; const MAX_MULTILINE_WORK = 131_072; +const MAX_ORDERED_WORK = 1_000_000; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; -type Matcher = LiteralMatcher | { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; +type Matcher = + | LiteralMatcher + | { runs: RegExp[] } + | { + regex: RegExp; + multilineRegex: RegExp; + canSpanLines: boolean; + }; const matcherCache = new Map(); export function requiresExactMaestroRegexMatch(pattern: string): boolean { @@ -39,6 +47,7 @@ export function matchesMaestroRegex( const matcher = matcherForPattern(pattern); if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; + if ('runs' in matcher) return matchesOrderedRuns(value, pattern, matcher.runs); if (!hasLineTerminator(value)) return matcher.regex.test(value); // A whole-value match has one anchored start. The work budget below limits how many // line-boundary starts the multiline engine may try, not this bounded single start. @@ -121,6 +130,39 @@ function matchesAnyLine(value: string, regex: RegExp): boolean { return regex.test(value.slice(start)); } +function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boolean { + let cursor = 0; + let work = 0; + for (const [index, run] of runs.entries()) { + let start = cursor; + for (; start <= value.length; start += 1) { + if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) indeterminateMaestroRegex(); + if ( + index === 0 && + !pattern.startsWith('.*') && + start > 0 && + !isLineTerminator(value[start - 1]) + ) + continue; + run.lastIndex = start; + if (!run.test(value)) continue; + const end = run.lastIndex; + if ( + index === runs.length - 1 && + !pattern.endsWith('.*') && + end !== value.length && + !isLineTerminator(value[end]) + ) { + continue; + } + cursor = end; + break; + } + if (start > value.length) return false; + } + return true; +} + function matcherForPattern(pattern: string): Matcher { const cached = matcherCache.get(pattern); if (cached) return cached; @@ -136,13 +178,16 @@ function matcherForPattern(pattern: string): Matcher { matcher = { literal, wholeOnly }; } else { if (pattern.length > MAX_PATTERN_LENGTH) unsafeMaestroRegex(); - const canSpanLines = assertBoundedMaestroPattern(pattern); + const bounded = assertBoundedMaestroPattern(pattern); try { - matcher = { - regex: new RegExp(`^(?:${pattern})$`, 'is'), - multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), - canSpanLines, - }; + matcher = + typeof bounded === 'boolean' + ? { + regex: new RegExp(`^(?:${pattern})$`, 'is'), + multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), + canSpanLines: bounded, + } + : { runs: bounded }; } catch { unsafeMaestroRegex(); } @@ -154,7 +199,7 @@ function matcherForPattern(pattern: string): Matcher { return matcher; } -function assertBoundedMaestroPattern(pattern: string): boolean { +function assertBoundedMaestroPattern(pattern: string): boolean | RegExp[] { let parsed: AST.Pattern; try { parsed = parser.parsePattern(pattern); @@ -194,12 +239,34 @@ function assertBoundedMaestroPattern(pattern: string): boolean { }); }, }); + const ordered = orderedLiteralRuns(parsed); + if (ordered) return ordered; for (const alternative of parsed.alternatives) { for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); } return parsed.alternatives.some((alternative) => alternative.elements.some(elementCanSpanLines)); } +function orderedLiteralRuns(pattern: AST.Pattern): RegExp[] | undefined { + if (pattern.alternatives.length !== 1) return undefined; + const elements = pattern.alternatives[0]!.elements; + const wildcard = (element: RegexElement): boolean => + element.type === 'Quantifier' && + element.element.type === 'CharacterSet' && + element.element.kind === 'any' && + element.min === 0 && + element.max === Infinity && + element.greedy; + if (elements.filter(wildcard).length < 2) return undefined; + if (elements.some((element) => element.type !== 'Character' && !wildcard(element))) { + return undefined; + } + return pattern.raw + .split('.*') + .filter(Boolean) + .map((source) => new RegExp(source, 'iy')); +} + function elementCanSpanLines(element: RegexElement): boolean { if (element.type === 'Assertion') return false; if (element.type === 'Quantifier') return elementCanSpanLines(element.element); From 9fb5e1fd8c54d4c498c7556631facf2cf30a7ba4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 08:59:03 +0100 Subject: [PATCH 04/17] docs: clarify bounded Maestro wildcard matching --- website/docs/docs/run-maestro-flows.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index d99dacb17af..5f0e8529b24 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Backreferences, lookahead and lookbehind assertions, overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Ordered literal runs separated by greedy `.*` match with bounded work. Backreferences, lookahead and lookbehind assertions, other overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 38e4c6e8791372c22fb4277e0891e3f5497fa8c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:26:32 +0100 Subject: [PATCH 05/17] refactor(maestro): simplify ordered matcher boundaries --- .../maestro/src/internal/selector-regex.ts | 27 +++++++++---------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b8f6c9b3329..eb1d2c4ef0d 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -134,27 +134,16 @@ function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boo let cursor = 0; let work = 0; for (const [index, run] of runs.entries()) { + const needsLineStart = index === 0 && !pattern.startsWith('.*'); + const needsLineEnd = index === runs.length - 1 && !pattern.endsWith('.*'); let start = cursor; for (; start <= value.length; start += 1) { if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) indeterminateMaestroRegex(); - if ( - index === 0 && - !pattern.startsWith('.*') && - start > 0 && - !isLineTerminator(value[start - 1]) - ) - continue; + if (needsLineStart && !atLineStart(value, start)) continue; run.lastIndex = start; if (!run.test(value)) continue; const end = run.lastIndex; - if ( - index === runs.length - 1 && - !pattern.endsWith('.*') && - end !== value.length && - !isLineTerminator(value[end]) - ) { - continue; - } + if (needsLineEnd && !atLineEnd(value, end)) continue; cursor = end; break; } @@ -163,6 +152,14 @@ function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boo return true; } +function atLineStart(value: string, index: number): boolean { + return index === 0 || isLineTerminator(value[index - 1]); +} + +function atLineEnd(value: string, index: number): boolean { + return index === value.length || isLineTerminator(value[index]); +} + function matcherForPattern(pattern: string): Matcher { const cached = matcherCache.get(pattern); if (cached) return cached; From a8024aaa2ca2a5008520e02ef71faad7fb0f9e1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 09:57:57 +0100 Subject: [PATCH 06/17] fix(maestro): clarify uncertainty and simplify bounded matching --- .../runtime-selector-resolution.test.ts | 6 +++--- .../__tests__/runtime-targets-typed.test.ts | 11 ++++++++-- .../maestro/src/internal/selector-regex.ts | 21 ++++++++++++++----- website/docs/docs/run-maestro-flows.md | 2 +- 4 files changed, 29 insertions(+), 11 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index 7da724862c1..c8ac48ba985 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -104,13 +104,13 @@ test('a confirmed unindexed match wins over uncertainty but an index still refus {}, { confirmedUnindexedExistence: true }, ); - expect(resolver.resolve({ text: '.*Ready.*' }).matches.map((node) => node.index)).toEqual([1, 2]); - expect(() => resolver.resolve({ text: '.*Ready.*', index: 0 })).toThrow( + expect(resolver.resolve({ text: '.*Ready' }).matches.map((node) => node.index)).toEqual([1, 2]); + expect(() => resolver.resolve({ text: '.*Ready', index: 0 })).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), }), ); - expect(() => createMaestroSnapshotResolver(snapshot).resolve({ text: '.*Ready.*' })).toThrow( + expect(() => createMaestroSnapshotResolver(snapshot).resolve({ text: '.*Ready' })).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), }), diff --git a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts index 416df73a4fd..460b6f53490 100644 --- a/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-targets-typed.test.ts @@ -199,7 +199,7 @@ test('a hidden confirmed match cannot hide uncertainty in a visible observation ]); expect(() => - resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: '.*Ready.*' } }, 'android', { + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: '.*Ready' } }, 'android', { confirmedUnindexedExistence: true, }), ).toThrow( @@ -214,10 +214,17 @@ test('a hidden confirmed match cannot hide uncertainty in a visible observation snapshot.nodes[2]!, ]); expect( - resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready.*' } }, 'android', { + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready' } }, 'android', { confirmedUnindexedExistence: true, }), ).toMatchObject({ ok: true, node: { index: 1 } }); + expect(() => + resolveMaestroTargetFromSnapshot(visibleMatch, { selector: { text: '.*Ready' } }, 'android'), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); }); test('keeps Maestro-visible app content matchable while a React Native overlay is present', () => { diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index eb1d2c4ef0d..ec693e59e56 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -139,11 +139,8 @@ function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boo let start = cursor; for (; start <= value.length; start += 1) { if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) indeterminateMaestroRegex(); - if (needsLineStart && !atLineStart(value, start)) continue; - run.lastIndex = start; - if (!run.test(value)) continue; - const end = run.lastIndex; - if (needsLineEnd && !atLineEnd(value, end)) continue; + const end = orderedRunEnd(value, run, start, needsLineStart, needsLineEnd); + if (end === undefined) continue; cursor = end; break; } @@ -152,6 +149,20 @@ function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boo return true; } +function orderedRunEnd( + value: string, + run: RegExp, + start: number, + needsLineStart: boolean, + needsLineEnd: boolean, +): number | undefined { + if (needsLineStart && !atLineStart(value, start)) return undefined; + run.lastIndex = start; + if (!run.test(value)) return undefined; + const end = run.lastIndex; + return needsLineEnd && !atLineEnd(value, end) ? undefined : end; +} + function atLineStart(value: string, index: number): boolean { return index === 0 || isLineTerminator(value[index - 1]); } diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 5f0e8529b24..59ed50632ac 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Ordered literal runs separated by greedy `.*` match with bounded work. Backreferences, lookahead and lookbehind assertions, other overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, the step fails with `maestro_selector_regex_indeterminate` if no confirmed match settles the unindexed selector. +- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Ordered literal runs separated by greedy `.*` match with bounded work. Backreferences, lookahead and lookbehind assertions, other overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, an observation can use a definite unindexed match to confirm existence. An action or indexed selector fails with `maestro_selector_regex_indeterminate` because an undecidable node could change the chosen target. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 37171118dc4c151a80b3b033897fb5f31dbe3dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 10:13:18 +0100 Subject: [PATCH 07/17] docs(maestro): state typed matcher refusals --- packages/maestro/src/internal/selector-regex.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index ec693e59e56..bb8c2403475 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -34,6 +34,10 @@ export function requiresExactMaestroRegexMatch(pattern: string): boolean { return pattern.length > MAX_PATTERN_LENGTH && hasRegexSyntax(pattern); } +/** + * Returns a match or throws AppError with `maestro_selector_regex_unsafe` or + * `maestro_selector_regex_indeterminate`. + */ export function matchesMaestroRegex( value: string, pattern: string, From f511986f84765ad3b8895afaf0d37cc5cc953b4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 11:25:19 +0100 Subject: [PATCH 08/17] fix(maestro): retry indeterminate observation snapshots --- .../daemon-runtime-port-observation.test.ts | 106 ++++++++++++++++++ .../daemon-runtime-port-observation.ts | 44 +++++++- 2 files changed, 145 insertions(+), 5 deletions(-) diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts index 0874714e215..926c87734a8 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts @@ -12,6 +12,7 @@ import { maestroSnapshotSignature, observeTypedMaestroCondition, resolveTypedMaestroTarget, + scrollUntilTypedMaestroTarget, waitForTypedSnapshotStability, } from '../daemon-runtime-port-observation.ts'; import { @@ -223,6 +224,111 @@ test('matches iOS Maestro ids on semantic nodes suppressed from interactive pres ).resolves.toMatchObject({ matched: true, visible: true, candidateCount: 1, ref: 'e2' }); }); +test('retries an indeterminate regex observation until a later snapshot has a confirmed match', async () => { + const clock = { value: 0 }; + let captures = 0; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const ready = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + + const match = await observeTypedMaestroCondition({ + condition: { kind: 'visible', selector: { text: '.*Ready' } }, + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, header, ready]), + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e3' }); + expect(captures).toBe(2); +}); + +test('polls an indeterminate relational selector until its parent appears', async () => { + const clock = { value: 0 }; + let captures = 0; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const parent = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + const row = { + index: 3, + parentIndex: 2, + type: 'Text', + identifier: 'row', + rect: { x: 20, y: 90, width: 120, height: 44 }, + }; + + const match = await observeTypedMaestroCondition({ + condition: { kind: 'visible', selector: { id: 'row', childOf: { text: '.*Ready' } } }, + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, parent, row]), + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e4' }); + expect(captures).toBe(2); +}); + +test('does not report notVisible when the final regex observation is indeterminate', async () => { + await expect( + observeTypedMaestroCondition({ + condition: { kind: 'notVisible', selector: { text: '.*Ready' } }, + timeoutMs: 0, + context: { generation: 0, env: {} }, + snapshot: async () => + makeSnapshot([{ index: 0, type: 'Text', label: 'Header\n'.repeat(10_000) }]), + dependencies: makeDependencies(), + platform: 'android', + }), + ).rejects.toMatchObject({ + details: { reason: 'maestro_selector_regex_indeterminate' }, + }); +}); + +test('recaptures an indeterminate scroll target before scrolling', async () => { + const clock = { value: 0 }; + let captures = 0; + let scrolls = 0; + const root = { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }; + const header = { index: 1, type: 'Text', label: 'Header\n'.repeat(10_000) }; + const ready = { + index: 2, + type: 'Text', + label: 'Ready', + rect: { x: 20, y: 40, width: 120, height: 44 }, + }; + + const match = await scrollUntilTypedMaestroTarget({ + selector: { text: '.*Ready' }, + direction: 'down', + timeoutMs: MAESTRO_OBSERVATION_POLL_MS, + context: { generation: 0, env: {} }, + snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, header, ready]), + scroll: async (_remaining, snapshot) => { + scrolls += 1; + return snapshot; + }, + dependencies: makeDependencies(clock), + platform: 'android', + }); + + expect(match).toMatchObject({ matched: true, visible: true, ref: 'e3' }); + expect(captures).toBe(2); + expect(scrolls).toBe(0); +}); + test('reports iOS Maestro evidence refs in semantic snapshot space after earlier suppression', async () => { const snapshot = makeSnapshot([ { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts index c9d7ed5d8e8..bdcbbfc4dfb 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts @@ -138,6 +138,23 @@ function resolveTargetFromSnapshot(params: { ); } +function resolveObservationTarget(params: Parameters[0]): { + match?: MaestroTargetMatch; + indeterminate?: AppError; +} { + try { + return { match: resolveTargetFromSnapshot(params) }; + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) { + return { indeterminate: error }; + } + throw error; + } +} + export async function observeTypedMaestroCondition(params: { readonly condition: MaestroObservationCondition; readonly timeoutMs: number; @@ -148,20 +165,22 @@ export async function observeTypedMaestroCondition(params: { }): Promise { validateTimeout(params.timeoutMs, 'observation'); let lastMatch: MaestroTargetMatch | undefined; + let lastIndeterminate: AppError | undefined; const conditionDeadline = params.dependencies.now() + params.timeoutMs; while (true) { throwIfAborted(params.context.signal); const snapshot = await captureRetriableMaestroSnapshot(params, conditionDeadline); - const match = resolveTargetFromSnapshot({ + const resolution = resolveObservationTarget({ query: { selector: params.condition.selector }, context: params.context, snapshot, platform: params.platform, mode: 'observe', }); - lastMatch = match; - if (maestroObservationMatches(params.condition, match)) return match; + lastMatch = resolution.match; + lastIndeterminate = resolution.indeterminate; + if (lastMatch && maestroObservationMatches(params.condition, lastMatch)) return lastMatch; if (params.dependencies.now() >= conditionDeadline) break; await sleepWithinDeadline( @@ -173,6 +192,7 @@ export async function observeTypedMaestroCondition(params: { } throwIfAborted(params.context.signal); + if (lastIndeterminate) throw lastIndeterminate; return requireObservationResult(lastMatch); } @@ -189,26 +209,39 @@ export async function scrollUntilTypedMaestroTarget(params: { validateTimeout(params.timeoutMs, 'scrollUntilVisible'); const deadline = params.dependencies.now() + params.timeoutMs; let lastMatch: MaestroTargetMatch | undefined; + let lastIndeterminate: AppError | undefined; let settledSnapshot: SnapshotState | undefined; while (true) { throwIfAborted(params.context.signal); const snapshot = settledSnapshot ?? (await captureRetriableMaestroSnapshot(params, deadline)); settledSnapshot = undefined; - lastMatch = resolveTargetFromSnapshot({ + const resolution = resolveObservationTarget({ query: { selector: params.selector }, context: params.context, snapshot, platform: params.platform, mode: 'observe', }); + lastMatch = resolution.match; + lastIndeterminate = resolution.indeterminate; if ( - lastMatch.visiblePercentage === MAESTRO_RUNTIME_ADAPTER_POLICY.scrollUntilVisiblePercentage + lastMatch?.visiblePercentage === MAESTRO_RUNTIME_ADAPTER_POLICY.scrollUntilVisiblePercentage ) { return lastMatch; } if (params.dependencies.now() >= deadline) break; + if (lastIndeterminate) { + await sleepWithinDeadline( + params.dependencies, + deadline, + MAESTRO_OBSERVATION_POLL_MS, + params.context.signal, + ); + continue; + } + const remaining = deadline - params.dependencies.now(); if (remaining > 0) { settledSnapshot = await params.scroll(remaining, snapshot); @@ -216,6 +249,7 @@ export async function scrollUntilTypedMaestroTarget(params: { } throwIfAborted(params.context.signal); + if (lastIndeterminate) throw lastIndeterminate; return requireObservationResult(lastMatch); } From 3e487227be5d67a8faa726595c62f8978e1b2601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 12:16:38 +0100 Subject: [PATCH 09/17] fix: close Maestro selector review gaps --- .../runtime-selector-resolution.test.ts | 15 +++++++++ .../src/internal/runtime-target-policy.ts | 33 ++++++++++--------- .../maestro/src/internal/selector-regex.ts | 2 +- scripts/check-package.ts | 4 +-- scripts/lib/shipped-imports.ts | 2 +- test/repo-guards/maestro-regex-owner.test.ts | 18 +++++++++- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/run-maestro-flows.md | 6 +++- 8 files changed, 59 insertions(+), 23 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index c8ac48ba985..f080af2aab2 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -93,6 +93,21 @@ test('an exact long selector checks every candidate before refusing regex execut ); }); +test('a long pattern requires one candidate to satisfy every selector field', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: pattern, enabled: false }, + { index: 1, label: `${pattern} extra`, enabled: true }, + ]), + ); + expect(() => resolver.resolve({ text: pattern, enabled: true })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { const snapshot = makeSnapshot([ { index: 0, label: 'Header\n'.repeat(10_000) }, diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index 741aabc14a2..c69c4e71769 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -53,22 +53,23 @@ export function assertLongMaestroSelectorsHaveExactCandidates( selector: MaestroFlatSelector, ): void { const { id, text } = selector; - if ( - id !== undefined && - requiresExactMaestroRegexMatch(id) && - !nodes.some((node) => matchesMaestroRegex(node.identifier ?? '', id, true)) - ) { - matchesMaestroRegex('', id); - } - if ( - text !== undefined && - requiresExactMaestroRegexMatch(text) && - !nodes.some((node) => - visibleTextValues(node).some((value) => matchesMaestroRegex(value, text, true)), - ) - ) { - matchesMaestroRegex('', text); - } + const longPattern = [id, text].find( + (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), + ); + if (!longPattern) return; + const exactCandidate = nodes.some((node) => { + try { + return matchesMaestroTypedSelector(node, selector); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === 'maestro_selector_regex_indeterminate' + ) + return false; + throw error; + } + }); + if (!exactCandidate) matchesMaestroRegex('', longPattern); } export function filterVisibleMaestroMatches(params: { diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index bb8c2403475..b84a36c02d7 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -5,7 +5,7 @@ import { normalizeText } from './shared.ts'; export const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern uses constructs that the bounded matcher cannot safely execute. unsafe: { reason: 'maestro_selector_regex_unsafe' }, - // A multiline value might match across partial lines, so absence cannot be confirmed safely. + // A multiline value might match across partial lines, so neither absence nor the chosen target can be decided safely. indeterminate: { reason: 'maestro_selector_regex_indeterminate' }, } as const satisfies ReasonTable<'maestro selector regex'>; diff --git a/scripts/check-package.ts b/scripts/check-package.ts index 778fa7009df..0e5684313b8 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -291,7 +291,7 @@ try { step(`Verified the dependency closure: ${[...importedBy.keys()].sort().join(', ')}.`); // R11 permits a workspace runtime dependency to be absent from the root manifest only when // tsdown bundles it. The notices plugin attributes only modules rendered into the artifact. - // Check that proof for every such dependency in the installed tarball, not only today's regexpp. + // Check attribution for every bundled external dependency declared in the workspace. const bundled = new Set(bundledDependencyNames); const bundledWorkspaceDependencies = bundledWorkspaceDependencyNames( new Map( @@ -311,7 +311,7 @@ try { importedBy, ); step( - `Confirmed ${bundledWorkspaceDependencies.size} workspace runtime dependencies are bundled.`, + `Confirmed ${bundledWorkspaceDependencies.size} bundled workspace dependencies are attributed.`, ); importEveryExport(manifest); smokeTestBin(installedRoot, manifest); diff --git a/scripts/lib/shipped-imports.ts b/scripts/lib/shipped-imports.ts index 7dd6a08531a..7c59a1fb8a2 100644 --- a/scripts/lib/shipped-imports.ts +++ b/scripts/lib/shipped-imports.ts @@ -79,7 +79,7 @@ export function bundledWorkspaceDependencyNames( return names; } -/** Prove that a workspace runtime dependency omitted from the root manifest is in the packed code. */ +/** Prove that bundled workspace dependencies are attributed in the packed code. */ export function assertBundledWorkspaceDependencies( names: ReadonlySet, attributionLabels: ReadonlySet, diff --git a/test/repo-guards/maestro-regex-owner.test.ts b/test/repo-guards/maestro-regex-owner.test.ts index 5911943cc9a..dcac5bbf322 100644 --- a/test/repo-guards/maestro-regex-owner.test.ts +++ b/test/repo-guards/maestro-regex-owner.test.ts @@ -56,6 +56,14 @@ function regexBypassViolations(source: string, filePath: string): string[] { return undefined; } function isRegexReference(node: Node | undefined, scope: Scope): boolean { + if (node?.type === 'MemberExpression') { + return ( + node.object?.type === 'Identifier' && + node.object.name === 'globalThis' && + binding(scope, 'globalThis') === undefined && + calledName(node) === 'RegExp' + ); + } if (node?.type !== 'Identifier' || !node.name) return false; return binding(scope, node.name) ?? node.name === 'RegExp'; } @@ -149,6 +157,7 @@ function regexBypassViolations(source: string, filePath: string): string[] { const declaration = node.type === 'ForStatement' ? node.init : node.left; if (declaration?.type === 'VariableDeclaration') { for (const item of declaration.declarations ?? []) bindPattern(item.id, scope); + bindRegexAliases(declaration, scope); } return scope; } @@ -192,8 +201,11 @@ test('Maestro regex guard catches direct and implicit construction', () => { 'Reflect.construct(RegExp, [query])', 'RegExp.call(null, query)', 'RegExp.apply(null, [query])', + 'for (const R = RegExp; ; ) new R(query)', + 'globalThis.RegExp(query)', + "new globalThis['RegExp'](query)", ].join(';'); - assert.equal(regexBypassViolations(source, 'fixture.ts').length, 10); + assert.equal(regexBypassViolations(source, 'fixture.ts').length, 13); assert.deepEqual(regexBypassViolations('value.matchAll(/fixed/g)', 'fixture.ts'), []); assert.deepEqual( regexBypassViolations('const R = RegExp; function use(R) { new R(query) }', 'fixture.ts'), @@ -210,4 +222,8 @@ test('Maestro regex guard catches direct and implicit construction', () => { regexBypassViolations('const R = RegExp; for (const R of values) new R(query)', 'fixture.ts'), [], ); + assert.deepEqual( + regexBypassViolations('function use(globalThis) { globalThis.RegExp(query) }', 'fixture.ts'), + [], + ); }); diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 3c30bb75f5d..c5247a36973 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -886,7 +886,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `maestro_selector_regex_unsafe` | The selector pattern uses constructs that the bounded matcher cannot safely execute. | -| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so absence cannot be confirmed safely. | +| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so neither absence nor the chosen target can be decided safely. | ### Metro reload diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 59ed50632ac..08d1d6f6038 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,11 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Selector `id` and `text` match exact text before interpreting a safe pattern as a regular expression. A plain literal also matches one line of a multiline value, while invalid regex syntax uses whole-value literal equality. Regex patterns match complete spans between line boundaries within a bounded value and can use groups, alternatives, character classes, and counted or disjoint repetitions. Ordered literal runs separated by greedy `.*` match with bounded work. Backreferences, lookahead and lookbehind assertions, other overlapping repetitions across literals or groups, quantified groups containing alternatives or repetitions at any depth, excessive ambiguous groups, and counted repetitions over 10,000 fail with `maestro_selector_regex_unsafe`. Regex patterns over 256 characters also fail unless the full selector equals normalized text in a snapshot node, in which case regex is not executed. When a line-spanning pattern exceeds the bounded multiline work budget, an observation can use a definite unindexed match to confirm existence. An action or indexed selector fails with `maestro_selector_regex_indeterminate` because an undecidable node could change the chosen target. +- Selector `id` and `text`: + - Supported matches: exact text, one line of a multiline value for plain literals, and safe regular expressions over complete spans between line boundaries. Safe patterns can use groups, alternatives, character classes, counted or disjoint repetitions, and ordered literal runs separated by greedy `.*`. Invalid regex syntax uses whole-value literal equality. + - Limits: whole-value multiline regex matching is bounded to 16,384 characters; longer values can still match individual lines. Counted repetitions cannot exceed 10,000, and a pattern can contain at most four ambiguous groups. A regex pattern over 256 characters is accepted only when one snapshot node satisfies every selector field, including an exact normalized text match for the long pattern; that regex is never executed. + - Refusals: backreferences, lookahead or lookbehind, overlapping repetitions, and quantified groups containing alternatives or repetitions fail with `maestro_selector_regex_unsafe`. A pattern that exceeds the limits also fails with this reason. + - Selection: an unindexed observation may confirm a definite match despite another node whose line-spanning match cannot be decided within the work budget. An action or indexed selector fails with `maestro_selector_regex_indeterminate` when that node could change the chosen target. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From a98c38c56e0e4c6ae1214c1e9b530fe107fca542 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:33:55 +0100 Subject: [PATCH 10/17] fix(maestro): resolve multiline selectors within the length limit --- .../daemon-runtime-port-observation.test.ts | 15 ++++---- .../daemon-runtime-port-observation.ts | 17 ++-------- .../runtime-selector-resolution.test.ts | 34 +++++++++++++++++++ .../internal/runtime-selector-resolution.ts | 13 ++++--- .../src/internal/runtime-target-policy.ts | 26 +------------- .../maestro/src/internal/selector-regex.ts | 16 +-------- website/docs/docs/run-maestro-flows.md | 2 +- 7 files changed, 56 insertions(+), 67 deletions(-) diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts index 926c87734a8..82144fad3c0 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts @@ -297,7 +297,7 @@ test('does not report notVisible when the final regex observation is indetermina }); }); -test('recaptures an indeterminate scroll target before scrolling', async () => { +test('scrolls past an indeterminate snapshot to a confirmed target', async () => { const clock = { value: 0 }; let captures = 0; let scrolls = 0; @@ -315,18 +315,21 @@ test('recaptures an indeterminate scroll target before scrolling', async () => { direction: 'down', timeoutMs: MAESTRO_OBSERVATION_POLL_MS, context: { generation: 0, env: {} }, - snapshot: async () => makeSnapshot(captures++ === 0 ? [root, header] : [root, header, ready]), - scroll: async (_remaining, snapshot) => { + snapshot: async () => { + captures += 1; + return makeSnapshot([root, header]); + }, + scroll: async () => { scrolls += 1; - return snapshot; + return makeSnapshot([root, header, ready]); }, dependencies: makeDependencies(clock), platform: 'android', }); expect(match).toMatchObject({ matched: true, visible: true, ref: 'e3' }); - expect(captures).toBe(2); - expect(scrolls).toBe(0); + expect(captures).toBe(1); + expect(scrolls).toBe(1); }); test('reports iOS Maestro evidence refs in semantic snapshot space after earlier suppression', async () => { diff --git a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts index bdcbbfc4dfb..812a1b43464 100644 --- a/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts +++ b/packages/maestro/src/daemon-port/daemon-runtime-port-observation.ts @@ -230,22 +230,9 @@ export async function scrollUntilTypedMaestroTarget(params: { ) { return lastMatch; } - if (params.dependencies.now() >= deadline) break; - - if (lastIndeterminate) { - await sleepWithinDeadline( - params.dependencies, - deadline, - MAESTRO_OBSERVATION_POLL_MS, - params.context.signal, - ); - continue; - } - const remaining = deadline - params.dependencies.now(); - if (remaining > 0) { - settledSnapshot = await params.scroll(remaining, snapshot); - } + if (remaining <= 0) break; + settledSnapshot = await params.scroll(remaining, snapshot); } throwIfAborted(params.context.signal); diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index f080af2aab2..3729c4b6f25 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -77,6 +77,19 @@ test('a nonmatching multiline node does not prevent a later confirmed selector m expect(resolver.resolve({ text: '.*Sign in.*' }).matches.map((node) => node.index)).toEqual([1]); }); +test('action resolution ignores an unrelated multiline value within the regex length limit', () => { + const terms = 'Please read the terms and conditions before continuing to checkout.\n'; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: terms.repeat(45) }, + { index: 1, label: 'Sign in' }, + ]), + ); + + const match = resolver.resolve({ text: 'Sign (in|up).*' }); + expect(match.matches.map((node) => node.index)).toEqual([1]); +}); + test('an exact long selector checks every candidate before refusing regex execution', () => { const pattern = `Total: 12.5 ${'x'.repeat(300)}`; const resolver = createMaestroSnapshotResolver( @@ -108,6 +121,27 @@ test('a long pattern requires one candidate to satisfy every selector field', () ); }); +test('a long pattern requires an exact match within the selected parent', () => { + const pattern = `Total: 12.5 ${'x'.repeat(300)}`; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'summary' }, + { index: 1, label: pattern, parentIndex: 0 }, + { index: 2, identifier: 'details' }, + { index: 3, label: `${pattern} extra`, parentIndex: 2 }, + ]), + ); + + expect( + resolver.resolve({ text: pattern, childOf: { id: 'summary' } }).matches.map((node) => node.index), + ).toEqual([1]); + expect(() => resolver.resolve({ text: pattern, childOf: { id: 'details' } })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), + }), + ); +}); + test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { const snapshot = makeSnapshot([ { index: 0, label: 'Header\n'.repeat(10_000) }, diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index 053db632d14..d52c40b800c 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -11,10 +11,8 @@ import { selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { - assertLongMaestroSelectorsHaveExactCandidates, - matchesMaestroTypedSelector, -} from './runtime-target-policy.ts'; +import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { matchesMaestroRegex, requiresExactMaestroRegexMatch } from './selector-regex.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ @@ -184,7 +182,6 @@ function resolveWithoutOwnIndex( let uncertain: AppError | undefined; let matches: SnapshotNode[]; if (hasMaestroLeafSelectorFields(leaf)) { - assertLongMaestroSelectorsHaveExactCandidates(snapshot.nodes, leaf); matches = snapshot.nodes.filter((node) => { try { return matchesMaestroTypedSelector(node, leaf); @@ -228,6 +225,12 @@ function resolveWithoutOwnIndex( const relatedIndexes = resolvePositionIndexes(relation, anchor); matches = matches.filter((node) => relatedIndexes.has(node.index)); } + if (matches.length === 0) { + const longPattern = [leaf.id, leaf.text].find( + (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), + ); + if (longPattern !== undefined) matchesMaestroRegex('', longPattern); + } if (uncertain && (!confirmedUnindexedExistence || matches.length === 0)) throw uncertain; return { matches, ...(uncertain ? { uncertain } : {}) }; } diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index c69c4e71769..6ab4de66dcb 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -2,7 +2,7 @@ import { AppError } from '@agent-device/kernel/errors'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; import type { MaestroLeafSelector, MaestroRelationalSelectorFields } from './program-ir.ts'; -import { matchesMaestroRegex, requiresExactMaestroRegexMatch } from './selector-regex.ts'; +import { matchesMaestroRegex } from './selector-regex.ts'; import { extractNodeText } from './shared.ts'; import { isMaestroNodeVisible } from './snapshot-policy.ts'; @@ -48,30 +48,6 @@ export function matchesMaestroTypedSelector( return true; } -export function assertLongMaestroSelectorsHaveExactCandidates( - nodes: readonly SnapshotNode[], - selector: MaestroFlatSelector, -): void { - const { id, text } = selector; - const longPattern = [id, text].find( - (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), - ); - if (!longPattern) return; - const exactCandidate = nodes.some((node) => { - try { - return matchesMaestroTypedSelector(node, selector); - } catch (error) { - if ( - error instanceof AppError && - error.details?.reason === 'maestro_selector_regex_indeterminate' - ) - return false; - throw error; - } - }); - if (!exactCandidate) matchesMaestroRegex('', longPattern); -} - export function filterVisibleMaestroMatches(params: { visibility: SnapshotVisibility; matches: SnapshotNode[]; diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index b84a36c02d7..511db261c5a 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -15,7 +15,6 @@ const MAX_COUNTED_REPETITION = 10_000; const MAX_CACHED_PATTERNS = 128; const MAX_PATTERN_PATHS = 32; const MAX_MULTILINE_VALUE_LENGTH = 16_384; -const MAX_MULTILINE_WORK = 131_072; const MAX_ORDERED_WORK = 1_000_000; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; @@ -53,10 +52,7 @@ export function matchesMaestroRegex( if (normalizeText(value) === normalizeText(pattern)) return true; if ('runs' in matcher) return matchesOrderedRuns(value, pattern, matcher.runs); if (!hasLineTerminator(value)) return matcher.regex.test(value); - // A whole-value match has one anchored start. The work budget below limits how many - // line-boundary starts the multiline engine may try, not this bounded single start. - if (value.length <= MAX_MULTILINE_VALUE_LENGTH && matcher.regex.test(value)) return true; - if (boundedMultilineWork(value)) return matcher.multilineRegex.test(value); + if (value.length <= MAX_MULTILINE_VALUE_LENGTH) return matcher.multilineRegex.test(value); if (matchesAnyLine(value, matcher.regex)) return true; if (matcher.canSpanLines) indeterminateMaestroRegex(); return false; @@ -114,16 +110,6 @@ function hasLineTerminator(value: string): boolean { return /[\n\r\u2028\u2029]/.test(value); } -function boundedMultilineWork(value: string): boolean { - if (value.length > MAX_MULTILINE_VALUE_LENGTH) return false; - let boundaries = 1; - for (const character of value) { - if (isLineTerminator(character)) boundaries += 1; - if (boundaries * value.length > MAX_MULTILINE_WORK) return false; - } - return true; -} - function matchesAnyLine(value: string, regex: RegExp): boolean { let start = 0; for (let index = 0; index < value.length; index += 1) { diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 08d1d6f6038..6f9a2777ca1 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -34,7 +34,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com - Supported matches: exact text, one line of a multiline value for plain literals, and safe regular expressions over complete spans between line boundaries. Safe patterns can use groups, alternatives, character classes, counted or disjoint repetitions, and ordered literal runs separated by greedy `.*`. Invalid regex syntax uses whole-value literal equality. - Limits: whole-value multiline regex matching is bounded to 16,384 characters; longer values can still match individual lines. Counted repetitions cannot exceed 10,000, and a pattern can contain at most four ambiguous groups. A regex pattern over 256 characters is accepted only when one snapshot node satisfies every selector field, including an exact normalized text match for the long pattern; that regex is never executed. - Refusals: backreferences, lookahead or lookbehind, overlapping repetitions, and quantified groups containing alternatives or repetitions fail with `maestro_selector_regex_unsafe`. A pattern that exceeds the limits also fails with this reason. - - Selection: an unindexed observation may confirm a definite match despite another node whose line-spanning match cannot be decided within the work budget. An action or indexed selector fails with `maestro_selector_regex_indeterminate` when that node could change the chosen target. + - Selection uses a definite match for an unindexed observation even if another node's match is undecidable. An action or indexed selector fails with `maestro_selector_regex_indeterminate` if that node could change the chosen target. `scrollUntilVisible` continues scrolling and reports the error if its last snapshot is still undecidable at the deadline. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 27f2cd628f281522659d70db94743fbaf68167a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 14:40:00 +0100 Subject: [PATCH 11/17] style(maestro): format selector regression test --- .../internal/__tests__/runtime-selector-resolution.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index 3729c4b6f25..b8bdd14cb65 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -133,7 +133,9 @@ test('a long pattern requires an exact match within the selected parent', () => ); expect( - resolver.resolve({ text: pattern, childOf: { id: 'summary' } }).matches.map((node) => node.index), + resolver + .resolve({ text: pattern, childOf: { id: 'summary' } }) + .matches.map((node) => node.index), ).toEqual([1]); expect(() => resolver.resolve({ text: pattern, childOf: { id: 'details' } })).toThrow( expect.objectContaining({ From 79e143b4eec89d247d9250a0e9a1953bbeb72942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 17:42:21 +0100 Subject: [PATCH 12/17] fix(maestro): preserve selector uncertainty through scroll and relations --- ...on-runtime-port-observation-scroll.test.ts | 150 ++++++++++-------- .../daemon-runtime-port-observation.test.ts | 18 ++- .../runtime-selector-resolution.test.ts | 31 ++++ .../internal/__tests__/selector-regex.test.ts | 10 ++ .../maestro/src/internal/facade-execution.ts | 2 +- .../src/internal/runtime-port-geometry.ts | 18 ++- .../internal/runtime-selector-resolution.ts | 54 ++++--- .../src/internal/runtime-target-policy.ts | 25 +-- .../maestro/src/internal/selector-regex.ts | 41 +++-- website/docs/docs/error-reasons.md | 2 +- website/docs/docs/run-maestro-flows.md | 4 +- 11 files changed, 232 insertions(+), 123 deletions(-) diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts index 4d9eb460c61..6bfca5a102a 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation-scroll.test.ts @@ -113,71 +113,95 @@ test('scrolls until the target is fully visible in the screen viewport', async ( expect(result.observation?.identity).toMatch(/^maestro-observation-/); }); -test('uses Maestro swipeFromCenter semantics inside the visible vertical container', async () => { - const requests: MaestroDaemonOperationRequest[] = []; - let snapshots = 0; - const port = createDaemonMaestroRuntimePort({ - ...makeRuntimeEnvelope({ flags: { platform: 'ios', replayBackend: 'maestro' } }), - invoke: async (request) => { - requests.push(request); - if (request.command !== 'snapshot') return { ok: true, data: {} }; - snapshots += 1; - return { - ok: true, - data: { - createdAt: snapshots, - nodes: [ - { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, - { - index: 1, - parentIndex: 0, - type: 'ScrollView', - rect: { x: 0, y: 100, width: 402, height: 650 }, - }, - ...(snapshots < 3 - ? [] - : [ - { - index: 2, - parentIndex: 1, - type: 'Button', - identifier: 'home-open-form', - rect: { x: 20, y: 600, width: 180, height: 44 }, - }, - ]), - ], - }, - }; - }, - dependencies: makeDependencies(), - platform: 'ios', - }); +test.each([ + { name: 'absent target', undecidable: false, findsTarget: true }, + { name: 'undecidable target', undecidable: true, findsTarget: true }, + { name: 'undecidable target through the deadline', undecidable: true, findsTarget: false }, +])( + 'swipes inside the visible vertical container with an $name', + async ({ undecidable, findsTarget }) => { + const requests: MaestroDaemonOperationRequest[] = []; + let scrolled = false; + const port = createDaemonMaestroRuntimePort({ + ...makeRuntimeEnvelope({ flags: { platform: 'ios', replayBackend: 'maestro' } }), + invoke: async (request) => { + requests.push(request); + if (request.command === 'gesture') scrolled = true; + if (request.command !== 'snapshot') return { ok: true, data: {} }; + return { + ok: true, + data: { + createdAt: 0, + nodes: [ + { index: 0, type: 'Application', rect: { x: 0, y: 0, width: 402, height: 874 } }, + { + index: 1, + parentIndex: 0, + type: 'ScrollView', + rect: { x: 0, y: 100, width: 402, height: 650 }, + }, + ...(scrolled && findsTarget + ? [ + { + index: 2, + parentIndex: 1, + type: 'Button', + label: 'Open form', + rect: { x: 20, y: 600, width: 180, height: 44 }, + }, + ] + : undecidable + ? [ + { + index: 2, + parentIndex: 1, + type: 'Text', + label: 'Terms and conditions\n'.repeat(800), + }, + ] + : []), + ], + }, + }; + }, + dependencies: makeDependencies(), + platform: 'ios', + }); - await port.execute({ - command: { - kind: 'scrollUntilVisible', - source: { line: 2 }, - element: { id: 'home-open-form' }, - direction: 'down', - timeout: 2_000, - }, - generation: 0, - env: {}, - invalidateObservation() {}, - }); + const result = port.execute({ + command: { + kind: 'scrollUntilVisible', + source: { line: 2 }, + element: { text: '.*Open form' }, + direction: 'down', + timeout: 2_000, + }, + generation: 0, + env: {}, + invalidateObservation() {}, + }); - const gesture = requests.find(({ command }) => command === 'gesture'); - expect(gesture).toMatchObject({ - input: { - kind: 'pan', - origin: { x: 201, y: 425 }, - delta: { x: 0, y: -260 }, - durationMs: 601, - }, - dispatch: { gestureViewport: { x: 0, y: 100, width: 402, height: 650 } }, - }); - expect(requests.some(({ command }) => command === 'scroll')).toBe(false); -}); + if (findsTarget) { + await expect(result).resolves.toMatchObject({ observation: { matched: true } }); + } else { + await expect(result).rejects.toMatchObject({ + details: { reason: 'maestro_selector_regex_indeterminate' }, + }); + } + + const gesture = requests.find(({ command }) => command === 'gesture'); + expect(gesture).toMatchObject({ + input: { + kind: 'pan', + origin: { x: 201, y: 425 }, + delta: { x: 0, y: -260 }, + durationMs: 601, + }, + dispatch: { gestureViewport: { x: 0, y: 100, width: 402, height: 650 } }, + }); + expect(requests.some(({ command }) => command === 'scroll')).toBe(false); + }, +); test('ignores a larger scroll container that does not intersect the application viewport', async () => { const requests: MaestroDaemonOperationRequest[] = []; diff --git a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts index 82144fad3c0..62f32307f23 100644 --- a/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts +++ b/packages/maestro/src/daemon-port/__tests__/daemon-runtime-port-observation.test.ts @@ -281,14 +281,24 @@ test('polls an indeterminate relational selector until its parent appears', asyn expect(captures).toBe(2); }); -test('does not report notVisible when the final regex observation is indeterminate', async () => { +test.each([ + { + name: 'oversized multiline label', + selector: { text: '.*Ready' }, + node: { index: 0, type: 'Text', label: 'Header\n'.repeat(10_000) }, + }, + { + name: 'clipped field in a complete snapshot', + selector: { text: 'Order is ready' }, + node: { index: 0, type: 'EditText', label: 'Order is', value: 'Order is', textClipped: true }, + }, +])('does not report notVisible with a $name', async ({ selector, node }) => { await expect( observeTypedMaestroCondition({ - condition: { kind: 'notVisible', selector: { text: '.*Ready' } }, + condition: { kind: 'notVisible', selector }, timeoutMs: 0, context: { generation: 0, env: {} }, - snapshot: async () => - makeSnapshot([{ index: 0, type: 'Text', label: 'Header\n'.repeat(10_000) }]), + snapshot: async () => ({ ...makeSnapshot([node]), truncated: false }), dependencies: makeDependencies(), platform: 'android', }), diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index b8bdd14cb65..822a6929adb 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -129,6 +129,7 @@ test('a long pattern requires an exact match within the selected parent', () => { index: 1, label: pattern, parentIndex: 0 }, { index: 2, identifier: 'details' }, { index: 3, label: `${pattern} extra`, parentIndex: 2 }, + { index: 4, identifier: 'empty' }, ]), ); @@ -137,6 +138,7 @@ test('a long pattern requires an exact match within the selected parent', () => .resolve({ text: pattern, childOf: { id: 'summary' } }) .matches.map((node) => node.index), ).toEqual([1]); + expect(resolver.resolve({ text: pattern, childOf: { id: 'empty' } }).matches).toEqual([]); expect(() => resolver.resolve({ text: pattern, childOf: { id: 'details' } })).toThrow( expect.objectContaining({ details: expect.objectContaining({ reason: 'maestro_selector_regex_unsafe' }), @@ -144,6 +146,35 @@ test('a long pattern requires an exact match within the selected parent', () => ); }); +test('clipped field text leaves matching uncertain while complete fields still decide', () => { + const resolver = createMaestroSnapshotResolver({ + ...makeSnapshot([ + { + index: 0, + label: 'Order is', + value: 'Order is', + identifier: 'order-status', + contentDescription: 'Order status', + textClipped: true, + enabled: false, + }, + ]), + truncated: false, + }); + + for (const text of ['Order is ready', 'Order is']) { + expect(() => resolver.resolve({ text })).toThrow( + expect.objectContaining({ + details: { reason: 'maestro_selector_regex_indeterminate', retriable: false }, + }), + ); + } + expect(resolver.resolve({ text: 'Order status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ text: 'order-status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ id: 'order-status' }).matches.map((node) => node.index)).toEqual([0]); + expect(resolver.resolve({ text: 'Order is ready', enabled: true }).matches).toEqual([]); +}); + test('a confirmed unindexed match wins over uncertainty but an index still refuses', () => { const snapshot = makeSnapshot([ { index: 0, label: 'Header\n'.repeat(10_000) }, diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index b9c405b8f82..043fed4150b 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -158,6 +158,16 @@ test('invalid regex syntax uses whole-value literal equality', () => { expect(matchesMaestroRegex('prefix\n[\nsuffix', '[')).toBe(false); }); +test('dense multiline values retain complete-line matches when span search exceeds its work limit', () => { + const entries = 'Log\n'.repeat(1_500); + expect(matchesMaestroRegex(`${entries}Order ready`, 'Order.*ready')).toBe(true); + expect(() => matchesMaestroRegex(`${entries}Order\nready`, 'Order.*ready')).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('CR and LF each provide a multiline anchor boundary', () => { expect(matchesMaestroRegex('one\r\ntwo', '^$')).toBe(true); expect(matchesMaestroRegex('one\rtwo', '^two$')).toBe(true); diff --git a/packages/maestro/src/internal/facade-execution.ts b/packages/maestro/src/internal/facade-execution.ts index 8e318c54290..bdb734a01ad 100644 --- a/packages/maestro/src/internal/facade-execution.ts +++ b/packages/maestro/src/internal/facade-execution.ts @@ -318,7 +318,7 @@ function suggestionBasis( if ( selector.text !== undefined && matchesMaestroTypedSelector( - { ...node, label: undefined, value: undefined }, + { ...node, label: undefined, value: undefined, textClipped: undefined }, { text: selector.text }, ) ) { diff --git a/packages/maestro/src/internal/runtime-port-geometry.ts b/packages/maestro/src/internal/runtime-port-geometry.ts index 59b6edf2b22..76ccdfa6557 100644 --- a/packages/maestro/src/internal/runtime-port-geometry.ts +++ b/packages/maestro/src/internal/runtime-port-geometry.ts @@ -25,6 +25,7 @@ import { } from './runtime-target-policy.ts'; import { createMaestroResolver } from './runtime-target-ranking.ts'; import { resolveMaestroClickability } from './runtime-clickability.ts'; +import { MAESTRO_SELECTOR_REGEX_REASONS } from './selector-regex.ts'; import type { MaestroResolutionProbe } from './runtime-selector-resolution.ts'; import type { MaestroRuntimeOperations, @@ -96,10 +97,19 @@ function selectMaestroScrollableViewport( const candidateByIndex = new Map( candidates.map((candidate) => [candidate.node.index, candidate]), ); - for (const target of resolver.resolve(selector).indexed) { - const container = findScrollContainer(target, visibility.nodeByIndex); - const candidate = container ? candidateByIndex.get(container.index) : undefined; - if (candidate) return candidate.viewport; + try { + for (const target of resolver.resolve(selector).indexed) { + const container = findScrollContainer(target, visibility.nodeByIndex); + const candidate = container ? candidateByIndex.get(container.index) : undefined; + if (candidate) return candidate.viewport; + } + } catch (error) { + if ( + !(error instanceof AppError) || + error.details?.reason !== MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ) { + throw error; + } } return candidates.sort(compareViewportAreaDescending)[0]?.viewport; } diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index d52c40b800c..8b9b14e7d93 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -12,7 +12,11 @@ import { type MaestroPositionRelation, } from './runtime-target-position.ts'; import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; -import { matchesMaestroRegex, requiresExactMaestroRegexMatch } from './selector-regex.ts'; +import { + MAESTRO_SELECTOR_REGEX_REASONS, + matchesMaestroRegex, + requiresExactMaestroRegexMatch, +} from './selector-regex.ts'; export type MaestroSelectorResolution = { /** Relation-composed matches in snapshot order, before this selector's own index. */ @@ -179,30 +183,10 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - let uncertain: AppError | undefined; - let matches: SnapshotNode[]; - if (hasMaestroLeafSelectorFields(leaf)) { - matches = snapshot.nodes.filter((node) => { - try { - return matchesMaestroTypedSelector(node, leaf); - } catch (error) { - if ( - error instanceof AppError && - error.details?.reason === 'maestro_selector_regex_indeterminate' - ) { - uncertain ??= error; - return false; - } - throw error; - } - }); - } else { - matches = [...snapshot.nodes]; - } - + let scope: readonly SnapshotNode[] = snapshot.nodes; if (childOf) { const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); - matches = matches.filter((node) => setsIntersect(ancestorIndexes(node), parentIndexes)); + scope = scope.filter((node) => setsIntersect(ancestorIndexes(node), parentIndexes)); } if (containsChild) { const matchedParentIndexes = new Set( @@ -211,20 +195,38 @@ function resolveWithoutOwnIndex( .filter((node): node is SnapshotNode => node !== undefined) .map((node) => node.index), ); - matches = matches.filter((node) => matchedParentIndexes.has(node.index)); + scope = scope.filter((node) => matchedParentIndexes.has(node.index)); } if (containsDescendants) { const containingAncestorSets = containsDescendants.map((nested) => collectContainingAncestorIndexes(resolve(nested).indexed, ancestorIndexes), ); - matches = matches.filter((node) => + scope = scope.filter((node) => containingAncestorSets.every((indexes) => indexes.has(node.index)), ); } for (const [relation, anchor] of positionalSelectors(selector)) { const relatedIndexes = resolvePositionIndexes(relation, anchor); - matches = matches.filter((node) => relatedIndexes.has(node.index)); + scope = scope.filter((node) => relatedIndexes.has(node.index)); + } + if (scope.length === 0 || !hasMaestroLeafSelectorFields(leaf)) { + return { matches: [...scope] }; } + let uncertain: AppError | undefined; + const matches = scope.filter((node) => { + try { + return matchesMaestroTypedSelector(node, leaf); + } catch (error) { + if ( + error instanceof AppError && + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ) { + uncertain ??= error; + return false; + } + throw error; + } + }); if (matches.length === 0) { const longPattern = [leaf.id, leaf.text].find( (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), diff --git a/packages/maestro/src/internal/runtime-target-policy.ts b/packages/maestro/src/internal/runtime-target-policy.ts index 6ab4de66dcb..87dd8211eef 100644 --- a/packages/maestro/src/internal/runtime-target-policy.ts +++ b/packages/maestro/src/internal/runtime-target-policy.ts @@ -2,7 +2,11 @@ import { AppError } from '@agent-device/kernel/errors'; import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { SnapshotVisibility } from '@agent-device/contracts/snapshot'; import type { MaestroLeafSelector, MaestroRelationalSelectorFields } from './program-ir.ts'; -import { matchesMaestroRegex } from './selector-regex.ts'; +import { + createMaestroSelectorIndeterminateError, + MAESTRO_SELECTOR_REGEX_REASONS, + matchesMaestroRegex, +} from './selector-regex.ts'; import { extractNodeText } from './shared.ts'; import { isMaestroNodeVisible } from './snapshot-policy.ts'; @@ -67,7 +71,7 @@ function tryMatchMaestroSelectorValue( } catch (error) { if ( error instanceof AppError && - error.details?.reason === 'maestro_selector_regex_indeterminate' + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason ) { return error; } @@ -75,18 +79,21 @@ function tryMatchMaestroSelectorValue( } } -function visibleTextValues(node: SnapshotNode): string[] { - return [node.label, extractNodeText(node), node.identifier].filter((value): value is string => - Boolean(value), - ); -} - function matchesMaestroVisibleText(node: SnapshotNode, query: string): boolean | AppError { + const values = node.textClipped + ? [node.contentDescription ?? (node.text === '' ? node.label : undefined), node.identifier] + : [node.label, extractNodeText(node), node.identifier]; let uncertain: AppError | undefined; - for (const value of visibleTextValues(node)) { + for (const value of new Set(values)) { + if (!value) continue; const result = tryMatchMaestroSelectorValue(value, query); if (result === true) return true; if (result instanceof AppError) uncertain ??= result; } + if (node.textClipped) { + // Validate the pattern even when the clipped prefix is the only available text. + matchesMaestroRegex('', query, true); + return uncertain ?? createMaestroSelectorIndeterminateError(); + } return uncertain ?? false; } diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 511db261c5a..8ccdb705dd1 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -5,7 +5,7 @@ import { normalizeText } from './shared.ts'; export const MAESTRO_SELECTOR_REGEX_REASONS = { // The selector pattern uses constructs that the bounded matcher cannot safely execute. unsafe: { reason: 'maestro_selector_regex_unsafe' }, - // A multiline value might match across partial lines, so neither absence nor the chosen target can be decided safely. + // Incomplete snapshot text or the matching work limit prevents a definite selector result. indeterminate: { reason: 'maestro_selector_regex_indeterminate' }, } as const satisfies ReasonTable<'maestro selector regex'>; @@ -15,6 +15,7 @@ const MAX_COUNTED_REPETITION = 10_000; const MAX_CACHED_PATTERNS = 128; const MAX_PATTERN_PATHS = 32; const MAX_MULTILINE_VALUE_LENGTH = 16_384; +const MAX_MULTILINE_WORK = 4_000_000; const MAX_ORDERED_WORK = 1_000_000; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; @@ -52,9 +53,14 @@ export function matchesMaestroRegex( if (normalizeText(value) === normalizeText(pattern)) return true; if ('runs' in matcher) return matchesOrderedRuns(value, pattern, matcher.runs); if (!hasLineTerminator(value)) return matcher.regex.test(value); - if (value.length <= MAX_MULTILINE_VALUE_LENGTH) return matcher.multilineRegex.test(value); + if (value.length <= MAX_MULTILINE_VALUE_LENGTH) { + if (!matcher.canSpanLines || withinMultilineWorkLimit(value)) { + return matcher.multilineRegex.test(value); + } + if (matcher.regex.test(value)) return true; + } if (matchesAnyLine(value, matcher.regex)) return true; - if (matcher.canSpanLines) indeterminateMaestroRegex(); + if (matcher.canSpanLines) throw createMaestroSelectorIndeterminateError(); return false; } @@ -110,6 +116,17 @@ function hasLineTerminator(value: string): boolean { return /[\n\r\u2028\u2029]/.test(value); } +function withinMultilineWorkLimit(value: string): boolean { + // With the multiline start anchor, each line boundary can restart a scan of the remaining suffix. + let work = value.length; + for (let index = 0; index < value.length; index += 1) { + if (!isLineTerminator(value[index])) continue; + work += value.length - index - 1; + if (work > MAX_MULTILINE_WORK) return false; + } + return true; +} + function matchesAnyLine(value: string, regex: RegExp): boolean { let start = 0; for (let index = 0; index < value.length; index += 1) { @@ -128,7 +145,9 @@ function matchesOrderedRuns(value: string, pattern: string, runs: RegExp[]): boo const needsLineEnd = index === runs.length - 1 && !pattern.endsWith('.*'); let start = cursor; for (; start <= value.length; start += 1) { - if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) indeterminateMaestroRegex(); + if ((work += 1 + run.source.length) > MAX_ORDERED_WORK) { + throw createMaestroSelectorIndeterminateError(); + } const end = orderedRunEnd(value, run, start, needsLineStart, needsLineEnd); if (end === undefined) continue; cursor = end; @@ -373,15 +392,11 @@ function unsafeMaestroRegex(): never { }); } -function indeterminateMaestroRegex(): never { - throw new AppError( - 'UNSUPPORTED_OPERATION', - 'Maestro selector cannot safely decide a multiline match.', - { - reason: MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason, - retriable: false, - }, - ); +export function createMaestroSelectorIndeterminateError(): AppError { + return new AppError('UNSUPPORTED_OPERATION', 'Maestro could not decide the selector match.', { + reason: MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason, + retriable: false, + }); } export function literalFromMaestroRegex(pattern: string): string | undefined { diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c5247a36973..c3986928c93 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -886,7 +886,7 @@ These reasons can come from more than one command. | Reason | Meaning | | --- | --- | | `maestro_selector_regex_unsafe` | The selector pattern uses constructs that the bounded matcher cannot safely execute. | -| `maestro_selector_regex_indeterminate` | A multiline value might match across partial lines, so neither absence nor the chosen target can be decided safely. | +| `maestro_selector_regex_indeterminate` | Incomplete snapshot text or the matching work limit prevents a definite selector result. | ### Metro reload diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 6f9a2777ca1..0407be9d5bd 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -32,9 +32,9 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com - Selector `id` and `text`: - Supported matches: exact text, one line of a multiline value for plain literals, and safe regular expressions over complete spans between line boundaries. Safe patterns can use groups, alternatives, character classes, counted or disjoint repetitions, and ordered literal runs separated by greedy `.*`. Invalid regex syntax uses whole-value literal equality. - - Limits: whole-value multiline regex matching is bounded to 16,384 characters; longer values can still match individual lines. Counted repetitions cannot exceed 10,000, and a pattern can contain at most four ambiguous groups. A regex pattern over 256 characters is accepted only when one snapshot node satisfies every selector field, including an exact normalized text match for the long pattern; that regex is never executed. + - Multiline regex matching has a work limit and scans values up to 16,384 characters for spans across lines. Individual lines can still match. Counted repetitions cannot exceed 10,000, and a pattern can contain at most four ambiguous groups. When there are candidates to check, a regex pattern over 256 characters requires one node to satisfy every selector field, including an exact normalized text match for that pattern. - Refusals: backreferences, lookahead or lookbehind, overlapping repetitions, and quantified groups containing alternatives or repetitions fail with `maestro_selector_regex_unsafe`. A pattern that exceeds the limits also fails with this reason. - - Selection uses a definite match for an unindexed observation even if another node's match is undecidable. An action or indexed selector fails with `maestro_selector_regex_indeterminate` if that node could change the chosen target. `scrollUntilVisible` continues scrolling and reports the error if its last snapshot is still undecidable at the deadline. + - Selection uses a definite match for an unindexed observation even if another node's match is undecidable. A clipped Android field can leave a text match undecidable even when the snapshot tree is complete. An action or indexed selector fails with `maestro_selector_regex_indeterminate` if an undecidable match could change the chosen target. `scrollUntilVisible` continues scrolling and reports the error if its last snapshot is still undecidable at the deadline. - Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS simulators, `grant`, `deny`, or `reset` on `notifications` returns `ios-notification-permission-unsupported`. Answer the notification prompt with the CLI command `alert accept` or `alert dismiss`, which this Maestro subset does not include. For `all`, `simctl privacy` determines which services the runtime can change, and current runtimes leave notifications untouched. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. From 49623c481d2b8a6567c3fd82aabf65cdfb7b7a06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 1 Dec 2026 17:49:04 +0100 Subject: [PATCH 13/17] refactor(maestro): separate generic regex matching from dispatch --- packages/maestro/src/internal/selector-regex.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 8ccdb705dd1..085a73673c0 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -20,14 +20,8 @@ const MAX_ORDERED_WORK = 1_000_000; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; -type Matcher = - | LiteralMatcher - | { runs: RegExp[] } - | { - regex: RegExp; - multilineRegex: RegExp; - canSpanLines: boolean; - }; +type GenericMatcher = { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; +type Matcher = LiteralMatcher | { runs: RegExp[] } | GenericMatcher; const matcherCache = new Map(); export function requiresExactMaestroRegexMatch(pattern: string): boolean { @@ -52,6 +46,10 @@ export function matchesMaestroRegex( if ('literal' in matcher) return matchesLiteral(value, matcher); if (normalizeText(value) === normalizeText(pattern)) return true; if ('runs' in matcher) return matchesOrderedRuns(value, pattern, matcher.runs); + return matchesGenericRegex(value, matcher); +} + +function matchesGenericRegex(value: string, matcher: GenericMatcher): boolean { if (!hasLineTerminator(value)) return matcher.regex.test(value); if (value.length <= MAX_MULTILINE_VALUE_LENGTH) { if (!matcher.canSpanLines || withinMultilineWorkLimit(value)) { From d14c09bf106b95f214699c1f7f67545de5119d31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:46:20 +0100 Subject: [PATCH 14/17] fix(maestro): preserve definite selector outcomes --- .../runtime-selector-resolution.test.ts | 26 +++++++ .../internal/__tests__/selector-regex.test.ts | 8 +- .../internal/runtime-selector-resolution.ts | 77 +++++++++++-------- .../maestro/src/internal/selector-regex.ts | 39 +++++++--- 4 files changed, 108 insertions(+), 42 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index 822a6929adb..26c8b346862 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -146,6 +146,32 @@ test('a long pattern requires an exact match within the selected parent', () => ); }); +test('an empty relation scope skips later relations with uncertain matches', () => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'empty' }, + { index: 1, identifier: 'orders' }, + { index: 2, label: 'Order pending', textClipped: true, parentIndex: 1 }, + ]), + ); + const uncertain = { text: 'Order.*ready' }; + + expect(resolver.resolve({ childOf: { id: 'empty' }, containsChild: uncertain }).matches).toEqual( + [], + ); + expect(resolver.resolve({ containsDescendants: [{ id: 'missing' }, uncertain] }).matches).toEqual( + [], + ); + expect(resolver.resolve({ containsDescendants: [uncertain, { id: 'missing' }] }).matches).toEqual( + [], + ); + expect(() => resolver.resolve({ containsChild: uncertain })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('clipped field text leaves matching uncertain while complete fields still decide', () => { const resolver = createMaestroSnapshotResolver({ ...makeSnapshot([ diff --git a/packages/maestro/src/internal/__tests__/selector-regex.test.ts b/packages/maestro/src/internal/__tests__/selector-regex.test.ts index 043fed4150b..b9cb0cc53c1 100644 --- a/packages/maestro/src/internal/__tests__/selector-regex.test.ts +++ b/packages/maestro/src/internal/__tests__/selector-regex.test.ts @@ -158,8 +158,14 @@ test('invalid regex syntax uses whole-value literal equality', () => { expect(matchesMaestroRegex('prefix\n[\nsuffix', '[')).toBe(false); }); -test('dense multiline values retain complete-line matches when span search exceeds its work limit', () => { +test('dense multiline values skip starts that cannot match the leading literal', () => { const entries = 'Log\n'.repeat(1_500); + expect(matchesMaestroRegex(`${entries}order\nready`, 'Order.*ready')).toBe(true); + expect(matchesMaestroRegex(`${entries}Log\nclosed`, 'Order.*ready')).toBe(false); +}); + +test('dense multiline values retain complete-line matches when span search exceeds its work limit', () => { + const entries = `Log\n${'Order pending\n'.repeat(900)}`; expect(matchesMaestroRegex(`${entries}Order ready`, 'Order.*ready')).toBe(true); expect(() => matchesMaestroRegex(`${entries}Order\nready`, 'Order.*ready')).toThrow( expect.objectContaining({ diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index 8b9b14e7d93..df809e4d2ff 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -183,48 +183,58 @@ function resolveWithoutOwnIndex( containsDescendants, ...leaf } = selector; - let scope: readonly SnapshotNode[] = snapshot.nodes; + let narrowed: SnapshotNode[] | undefined; + let relationUncertainty: AppError | undefined; + const narrow = (resolveFilter: () => (node: SnapshotNode) => boolean): void => { + if (narrowed?.length === 0) return; + try { + narrowed = (narrowed ?? snapshot.nodes).filter(resolveFilter()); + } catch (error) { + if (!isIndeterminateRegexError(error)) throw error; + relationUncertainty ??= error; + } + }; if (childOf) { - const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); - scope = scope.filter((node) => setsIntersect(ancestorIndexes(node), parentIndexes)); + narrow(() => { + const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); + return (node) => setsIntersect(ancestorIndexes(node), parentIndexes); + }); } if (containsChild) { - const matchedParentIndexes = new Set( - resolve(containsChild) - .indexed.map(parentOf) - .filter((node): node is SnapshotNode => node !== undefined) - .map((node) => node.index), - ); - scope = scope.filter((node) => matchedParentIndexes.has(node.index)); + narrow(() => { + const matchedParentIndexes = new Set( + resolve(containsChild) + .indexed.map(parentOf) + .filter((node): node is SnapshotNode => node !== undefined) + .map((node) => node.index), + ); + return (node) => matchedParentIndexes.has(node.index); + }); } - if (containsDescendants) { - const containingAncestorSets = containsDescendants.map((nested) => - collectContainingAncestorIndexes(resolve(nested).indexed, ancestorIndexes), - ); - scope = scope.filter((node) => - containingAncestorSets.every((indexes) => indexes.has(node.index)), - ); + for (const nested of containsDescendants ?? []) { + narrow(() => { + const indexes = collectContainingAncestorIndexes(resolve(nested).indexed, ancestorIndexes); + return (node) => indexes.has(node.index); + }); } for (const [relation, anchor] of positionalSelectors(selector)) { - const relatedIndexes = resolvePositionIndexes(relation, anchor); - scope = scope.filter((node) => relatedIndexes.has(node.index)); - } - if (scope.length === 0 || !hasMaestroLeafSelectorFields(leaf)) { - return { matches: [...scope] }; + narrow(() => { + const relatedIndexes = resolvePositionIndexes(relation, anchor); + return (node) => relatedIndexes.has(node.index); + }); } + const scope = narrowed ?? snapshot.nodes; + if (scope.length === 0) return { matches: [] }; + if (relationUncertainty) throw relationUncertainty; + if (!hasMaestroLeafSelectorFields(leaf)) return { matches: [...scope] }; let uncertain: AppError | undefined; const matches = scope.filter((node) => { try { return matchesMaestroTypedSelector(node, leaf); } catch (error) { - if ( - error instanceof AppError && - error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason - ) { - uncertain ??= error; - return false; - } - throw error; + if (!isIndeterminateRegexError(error)) throw error; + uncertain ??= error; + return false; } }); if (matches.length === 0) { @@ -237,6 +247,13 @@ function resolveWithoutOwnIndex( return { matches, ...(uncertain ? { uncertain } : {}) }; } +function isIndeterminateRegexError(error: unknown): error is AppError { + return ( + error instanceof AppError && + error.details?.reason === MAESTRO_SELECTOR_REGEX_REASONS.indeterminate.reason + ); +} + function collectContainingAncestorIndexes( nodes: readonly SnapshotNode[], ancestorIndexes: (node: SnapshotNode) => ReadonlySet, diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 085a73673c0..404ef08501c 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -20,7 +20,12 @@ const MAX_ORDERED_WORK = 1_000_000; const parser = new RegExpParser(); type RegexElement = AST.Alternative['elements'][number]; type LiteralMatcher = { literal: string; wholeOnly: boolean; lineRegex?: RegExp }; -type GenericMatcher = { regex: RegExp; multilineRegex: RegExp; canSpanLines: boolean }; +type GenericMatcher = { + regex: RegExp; + multilineRegex: RegExp; + canSpanLines: boolean; + initialLiteral?: RegExp; +}; type Matcher = LiteralMatcher | { runs: RegExp[] } | GenericMatcher; const matcherCache = new Map(); @@ -52,7 +57,7 @@ export function matchesMaestroRegex( function matchesGenericRegex(value: string, matcher: GenericMatcher): boolean { if (!hasLineTerminator(value)) return matcher.regex.test(value); if (value.length <= MAX_MULTILINE_VALUE_LENGTH) { - if (!matcher.canSpanLines || withinMultilineWorkLimit(value)) { + if (!matcher.canSpanLines || withinMultilineWorkLimit(value, matcher.initialLiteral)) { return matcher.multilineRegex.test(value); } if (matcher.regex.test(value)) return true; @@ -114,11 +119,15 @@ function hasLineTerminator(value: string): boolean { return /[\n\r\u2028\u2029]/.test(value); } -function withinMultilineWorkLimit(value: string): boolean { +function withinMultilineWorkLimit(value: string, initialLiteral?: RegExp): boolean { // With the multiline start anchor, each line boundary can restart a scan of the remaining suffix. let work = value.length; for (let index = 0; index < value.length; index += 1) { if (!isLineTerminator(value[index])) continue; + if (initialLiteral) { + initialLiteral.lastIndex = index + 1; + if (!initialLiteral.test(value)) continue; + } work += value.length - index - 1; if (work > MAX_MULTILINE_WORK) return false; } @@ -196,13 +205,13 @@ function matcherForPattern(pattern: string): Matcher { const bounded = assertBoundedMaestroPattern(pattern); try { matcher = - typeof bounded === 'boolean' - ? { + 'runs' in bounded + ? bounded + : { regex: new RegExp(`^(?:${pattern})$`, 'is'), multilineRegex: new RegExp(`^(?:${pattern})$`, 'ims'), - canSpanLines: bounded, - } - : { runs: bounded }; + ...bounded, + }; } catch { unsafeMaestroRegex(); } @@ -214,7 +223,9 @@ function matcherForPattern(pattern: string): Matcher { return matcher; } -function assertBoundedMaestroPattern(pattern: string): boolean | RegExp[] { +function assertBoundedMaestroPattern( + pattern: string, +): Pick | { runs: RegExp[] } { let parsed: AST.Pattern; try { parsed = parser.parsePattern(pattern); @@ -255,11 +266,17 @@ function assertBoundedMaestroPattern(pattern: string): boolean | RegExp[] { }, }); const ordered = orderedLiteralRuns(parsed); - if (ordered) return ordered; + if (ordered) return { runs: ordered }; for (const alternative of parsed.alternatives) { for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); } - return parsed.alternatives.some((alternative) => alternative.elements.some(elementCanSpanLines)); + const first = parsed.alternatives.length === 1 ? parsed.alternatives[0]?.elements[0] : undefined; + return { + canSpanLines: parsed.alternatives.some((alternative) => + alternative.elements.some(elementCanSpanLines), + ), + ...(first?.type === 'Character' ? { initialLiteral: new RegExp(first.raw, 'iy') } : {}), + }; } function orderedLiteralRuns(pattern: AST.Pattern): RegExp[] | undefined { From 6a0c0520ee62f95ec0d418af9f5e5efdf488eee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 10:52:13 +0100 Subject: [PATCH 15/17] refactor(maestro): separate leaf matching from relation resolution --- .../src/internal/runtime-selector-resolution.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index df809e4d2ff..33328d6a611 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -11,7 +11,7 @@ import { selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; -import { matchesMaestroTypedSelector } from './runtime-target-policy.ts'; +import { matchesMaestroTypedSelector, type MaestroFlatSelector } from './runtime-target-policy.ts'; import { MAESTRO_SELECTOR_REGEX_REASONS, matchesMaestroRegex, @@ -226,6 +226,14 @@ function resolveWithoutOwnIndex( const scope = narrowed ?? snapshot.nodes; if (scope.length === 0) return { matches: [] }; if (relationUncertainty) throw relationUncertainty; + return resolveLeafMatches(scope, leaf, confirmedUnindexedExistence); +} + +function resolveLeafMatches( + scope: readonly SnapshotNode[], + leaf: MaestroFlatSelector, + confirmedUnindexedExistence: boolean, +): { matches: SnapshotNode[]; uncertain?: AppError } { if (!hasMaestroLeafSelectorFields(leaf)) return { matches: [...scope] }; let uncertain: AppError | undefined; const matches = scope.filter((node) => { From 9fba66b4440146808fe7fa4abf8dacb01cd4b1b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:13:41 +0100 Subject: [PATCH 16/17] fix(maestro): scope indeterminate selector matches --- .../runtime-selector-resolution.test.ts | 125 +++++++++ .../internal/runtime-selector-resolution.ts | 254 ++++++++++++------ .../src/internal/runtime-target-position.ts | 13 + .../src/internal/runtime-target-ranking.ts | 4 +- .../maestro/src/internal/selector-regex.ts | 10 +- 5 files changed, 317 insertions(+), 89 deletions(-) diff --git a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts index 26c8b346862..e51a1837636 100644 --- a/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts +++ b/packages/maestro/src/internal/__tests__/runtime-selector-resolution.test.ts @@ -3,6 +3,8 @@ import type { SnapshotNode } from '@agent-device/kernel/snapshot'; import type { MaestroSelector } from '../program-ir.ts'; import { createMaestroSnapshotResolver } from '../runtime-selector-resolution.ts'; import type { MaestroPositionRelation } from '../runtime-target-position.ts'; +import { matchMaestroCandidatesWithResolver } from '../runtime-target-ranking.ts'; +import { resolveMaestroTargetFromSnapshot } from '../runtime-targets.ts'; import { makeSnapshot } from './runtime-target-fixtures.ts'; test('computes recursive selector sets once per snapshot instead of once per candidate', () => { @@ -90,6 +92,17 @@ test('action resolution ignores an unrelated multiline value within the regex le expect(match.matches.map((node) => node.index)).toEqual([1]); }); +test('action resolution skips line starts that share only the first literal character', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Shipping info\n'.repeat(800) }, + { index: 1, label: 'Sign in', rect: { x: 0, y: 0, width: 40, height: 20 } }, + ]); + + expect( + resolveMaestroTargetFromSnapshot(snapshot, { selector: { text: 'Sign (in|up).*' } }, 'android'), + ).toMatchObject({ ok: true, node: { index: 1 } }); +}); + test('an exact long selector checks every candidate before refusing regex execution', () => { const pattern = `Total: 12.5 ${'x'.repeat(300)}`; const resolver = createMaestroSnapshotResolver( @@ -172,6 +185,118 @@ test('an empty relation scope skips later relations with uncertain matches', () ); }); +test('ranking reuses the parent result after a definite relation miss', () => { + const childOf = { text: 'Summary' }; + const computed: MaestroSelector[] = []; + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true }, + { index: 1, identifier: 'row', parentIndex: 0 }, + ]), + { onSelectorComputed: (selector) => computed.push(selector) }, + ); + + expect( + matchMaestroCandidatesWithResolver({ childOf, containsChild: { id: 'missing' } }, resolver) + .matches, + ).toEqual([]); + expect(computed.filter((selector) => selector === childOf)).toHaveLength(1); +}); + +test('a definite leaf ID miss discards uncertainty from an otherwise viable relation', () => { + const snapshot = makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true }, + { index: 1, identifier: 'row', parentIndex: 0 }, + ]); + const childOf = { text: 'Summary' }; + + expect( + resolveMaestroTargetFromSnapshot(snapshot, { selector: { id: 'missing', childOf } }, 'android'), + ).toMatchObject({ + ok: false, + failureReason: 'selector-did-not-match', + evidence: { matched: false }, + }); + expect(() => + resolveMaestroTargetFromSnapshot(snapshot, { selector: { id: 'row', childOf } }, 'android'), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test.each(['containsChild', 'containsDescendants'] as const)( + '%s only retains uncertainty in the subtree with the clipped source', + (relation) => { + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, identifier: 'summary' }, + { index: 1, label: 'Ready', parentIndex: 0 }, + { index: 2, identifier: 'archive' }, + { index: 3, label: 'Rea', textClipped: true, parentIndex: 2 }, + ]), + ); + const nested = { text: 'Ready' }; + const scope = + relation === 'containsChild' ? { containsChild: nested } : { containsDescendants: [nested] }; + + expect(resolver.resolve({ id: 'summary', ...scope }).matches.map((node) => node.index)).toEqual( + [0], + ); + expect(() => resolver.resolve({ id: 'archive', ...scope })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); + }, +); + +test('nested indexed relations retain only possible selections in their scope', () => { + const rect = (y: number) => ({ x: 0, y, width: 40, height: 20 }); + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summary', rect: rect(0) }, + { index: 1, identifier: 'confirmed', parentIndex: 0, rect: rect(20) }, + { index: 2, label: 'Summ', textClipped: true, rect: rect(100) }, + { index: 3, identifier: 'possible', parentIndex: 2, rect: rect(120) }, + ]), + ); + + expect( + resolver.resolve({ childOf: { text: 'Summary', index: 0 } }).matches.map((node) => node.index), + ).toEqual([1]); + expect( + resolver.resolve({ id: 'confirmed', childOf: { text: 'Summary', index: 1 } }).matches, + ).toEqual([]); + expect(() => + resolver.resolve({ id: 'possible', childOf: { text: 'Summary', index: 1 } }), + ).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + +test('positional uncertainty only reaches candidates on the applicable side', () => { + const rect = (y: number) => ({ x: 0, y, width: 40, height: 20 }); + const resolver = createMaestroSnapshotResolver( + makeSnapshot([ + { index: 0, label: 'Summ', textClipped: true, rect: rect(100) }, + { index: 1, identifier: 'above', rect: rect(20) }, + { index: 2, identifier: 'below', rect: rect(150) }, + ]), + ); + const below = { text: 'Summary' }; + + expect(resolver.resolve({ id: 'above', below }).matches).toEqual([]); + expect(() => resolver.resolve({ id: 'below', below })).toThrow( + expect.objectContaining({ + details: expect.objectContaining({ reason: 'maestro_selector_regex_indeterminate' }), + }), + ); +}); + test('clipped field text leaves matching uncertain while complete fields still decide', () => { const resolver = createMaestroSnapshotResolver({ ...makeSnapshot([ diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index 33328d6a611..ae7193511c0 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -8,11 +8,13 @@ import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import type { MaestroSelector } from './program-ir.ts'; import { hasMaestroLeafSelectorFields } from './selector-relations.ts'; import { + createMaestroPositionUncertainty, selectMaestroPositionMatches, type MaestroPositionRelation, } from './runtime-target-position.ts'; import { matchesMaestroTypedSelector, type MaestroFlatSelector } from './runtime-target-policy.ts'; import { + createMaestroSelectorIndeterminateError, MAESTRO_SELECTOR_REGEX_REASONS, matchesMaestroRegex, requiresExactMaestroRegexMatch, @@ -23,6 +25,7 @@ export type MaestroSelectorResolution = { readonly matches: SnapshotNode[]; /** Matches after applying this selector's own index or no-index ordering policy. */ readonly indexed: SnapshotNode[]; + readonly parentMatched: boolean; readonly uncertain?: AppError; }; @@ -46,9 +49,18 @@ export type MaestroSnapshotResolver = { resolvePosition(relation: MaestroPositionRelation, anchor: MaestroSelector): SnapshotNode[]; }; +type UncertainNodes = ReadonlySet; +type CandidateMatch = boolean | 'uncertain'; +type RelationMatch = (node: SnapshotNode) => CandidateMatch; +type SelectorEntry = Omit & { + uncertainNodes?: UncertainNodes; + uncertainIndexed?: UncertainNodes; +}; + type MaestroPositionResolution = { ordered: SnapshotNode[]; - candidateIndexes: ReadonlySet; + match: RelationMatch; + uncertain: boolean; }; /** Resolve a recursive selector graph once for one immutable snapshot. */ @@ -59,9 +71,8 @@ export function createMaestroSnapshotResolver( ): MaestroSnapshotResolver { const visibility = createSnapshotVisibility(snapshot.nodes, probe); probe.onVisibilityContextCreated?.(); - const selectorCache = new WeakMap(); + const selectorCache = new WeakMap(); const resolving = new WeakSet(); - let resolutionDepth = 0; const ancestorIndexesByNode = new WeakMap>(); const positionCaches = new Map< MaestroPositionRelation, @@ -99,10 +110,16 @@ export function createMaestroSnapshotResolver( const cached = cache.get(anchor); if (cached) return cached; probe.onPositionComputed?.(relation, anchor); - const ordered = selectMaestroPositionMatches(snapshot.nodes, relation, resolve(anchor).indexed); - const resolution = { + const { indexed, uncertainIndexed } = resolveEntry(anchor); + const ordered = selectMaestroPositionMatches(snapshot.nodes, relation, indexed); + const candidateIndexes = new Set(ordered.map((node) => node.index)); + const uncertainAtPosition = + uncertainIndexed && createMaestroPositionUncertainty(relation, uncertainIndexed); + const resolution: MaestroPositionResolution = { ordered, - candidateIndexes: new Set(ordered.map((node) => node.index)), + match: (node) => + candidateIndexes.has(node.index) || (uncertainAtPosition?.(node) ? 'uncertain' : false), + uncertain: uncertainIndexed !== undefined, }; cache.set(anchor, resolution); return resolution; @@ -111,67 +128,75 @@ export function createMaestroSnapshotResolver( const resolvePosition = ( relation: MaestroPositionRelation, anchor: MaestroSelector, - ): SnapshotNode[] => resolvePositionEntry(relation, anchor).ordered; - - const resolvePositionIndexes = ( - relation: MaestroPositionRelation, - anchor: MaestroSelector, - ): ReadonlySet => resolvePositionEntry(relation, anchor).candidateIndexes; + ): SnapshotNode[] => { + const { ordered, uncertain } = resolvePositionEntry(relation, anchor); + if (uncertain) throw createMaestroSelectorIndeterminateError(); + return ordered; + }; - const resolve = (selector: MaestroSelector): MaestroSelectorResolution => { + const resolveEntry = (selector: MaestroSelector): SelectorEntry => { const cached = selectorCache.get(selector); if (cached) return cached; if (resolving.has(selector)) { throw new AppError('INVALID_ARGS', 'Maestro selector relations cannot contain cycles.'); } resolving.add(selector); - const confirmedUnindexedExistence = - resolutionDepth === 0 && - options.confirmedUnindexedExistence === true && - selector.index === undefined; - resolutionDepth += 1; try { probe.onSelectorComputed?.(selector); - const { matches, uncertain } = resolveWithoutOwnIndex( + const { matches, possible, uncertainNodes, parentMatched } = resolveWithoutOwnIndex( snapshot, selector, parentOf, ancestorIndexes, - resolve, - resolvePositionIndexes, - confirmedUnindexedExistence, + resolveEntry, + resolvePositionEntry, ); - const resolution = { - matches, - indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), - ...(uncertain ? { uncertain } : {}), - }; - selectorCache.set(selector, resolution); - return resolution; + const selection = + possible && uncertainNodes && selector.index !== undefined + ? selectPossiblyIndexedMatches(possible, uncertainNodes, selector.index) + : { + indexed: selectMaestroIndexedMatches(matches, selector.index, options.orderUnindexed), + uncertainIndexed: uncertainNodes, + }; + const entry = { matches, uncertainNodes, parentMatched, ...selection }; + selectorCache.set(selector, entry); + return entry; } finally { - resolutionDepth -= 1; resolving.delete(selector); } }; + const resolve = (selector: MaestroSelector): MaestroSelectorResolution => { + const { matches, indexed, parentMatched, uncertainNodes } = resolveEntry(selector); + const uncertain = uncertainNodes && createMaestroSelectorIndeterminateError(); + if ( + uncertain && + (!options.confirmedUnindexedExistence || selector.index !== undefined || !matches.length) + ) { + throw uncertain; + } + return { matches, indexed, parentMatched, ...(uncertain ? { uncertain } : {}) }; + }; + return { visibility, resolve, resolvePosition }; } -type ResolveSelector = (selector: MaestroSelector) => MaestroSelectorResolution; -type ResolvePositionIndexes = ( - relation: MaestroPositionRelation, - anchor: MaestroSelector, -) => ReadonlySet; - function resolveWithoutOwnIndex( snapshot: SnapshotState, selector: MaestroSelector, parentOf: (node: SnapshotNode) => SnapshotNode | undefined, ancestorIndexes: (node: SnapshotNode) => ReadonlySet, - resolve: ResolveSelector, - resolvePositionIndexes: ResolvePositionIndexes, - confirmedUnindexedExistence: boolean, -): { matches: SnapshotNode[]; uncertain?: AppError } { + resolve: (selector: MaestroSelector) => SelectorEntry, + resolvePosition: ( + relation: MaestroPositionRelation, + anchor: MaestroSelector, + ) => MaestroPositionResolution, +): { + matches: SnapshotNode[]; + possible?: SnapshotNode[]; + uncertainNodes?: UncertainNodes; + parentMatched: boolean; +} { const { index: _index, childOf, @@ -184,75 +209,111 @@ function resolveWithoutOwnIndex( ...leaf } = selector; let narrowed: SnapshotNode[] | undefined; - let relationUncertainty: AppError | undefined; - const narrow = (resolveFilter: () => (node: SnapshotNode) => boolean): void => { + let uncertainNodes: Set | undefined; + let parentMatched = true; + const narrow = (resolveFilter: () => RelationMatch): void => { if (narrowed?.length === 0) return; - try { - narrowed = (narrowed ?? snapshot.nodes).filter(resolveFilter()); - } catch (error) { - if (!isIndeterminateRegexError(error)) throw error; - relationUncertainty ??= error; - } + const match = resolveFilter(); + narrowed = (narrowed ?? snapshot.nodes).filter((node) => { + const result = match(node); + if (result === false) uncertainNodes?.delete(node); + if (result === 'uncertain') (uncertainNodes ??= new Set()).add(node); + return result !== false; + }); }; if (childOf) { narrow(() => { - const parentIndexes = new Set(resolve(childOf).indexed.map((node) => node.index)); - return (node) => setsIntersect(ancestorIndexes(node), parentIndexes); + const { indexed, uncertainIndexed } = resolve(childOf); + parentMatched = indexed.length > 0 || uncertainIndexed !== undefined; + const parentIndexes = new Set(indexed.map((node) => node.index)); + const possibleParents = new Set(); + for (const node of uncertainIndexed ?? []) possibleParents.add(node.index); + return (node) => { + const ancestors = ancestorIndexes(node); + return ( + setsIntersect(ancestors, parentIndexes) || + (setsIntersect(ancestors, possibleParents) ? 'uncertain' : false) + ); + }; }); } if (containsChild) { narrow(() => { - const matchedParentIndexes = new Set( - resolve(containsChild) - .indexed.map(parentOf) - .filter((node): node is SnapshotNode => node !== undefined) - .map((node) => node.index), - ); - return (node) => matchedParentIndexes.has(node.index); + const { indexed, uncertainIndexed } = resolve(containsChild); + const parents = new Set(indexed.map((node) => parentOf(node)?.index)); + const possibleParents = new Set(); + for (const node of uncertainIndexed ?? []) possibleParents.add(parentOf(node)?.index); + return (node) => + parents.has(node.index) || (possibleParents.has(node.index) ? 'uncertain' : false); }); } for (const nested of containsDescendants ?? []) { narrow(() => { - const indexes = collectContainingAncestorIndexes(resolve(nested).indexed, ancestorIndexes); - return (node) => indexes.has(node.index); + const { indexed, uncertainIndexed } = resolve(nested); + const indexes = collectContainingAncestorIndexes(indexed, ancestorIndexes); + const possibleAncestors = collectContainingAncestorIndexes( + uncertainIndexed ?? [], + ancestorIndexes, + ); + return (node) => + indexes.has(node.index) || (possibleAncestors.has(node.index) ? 'uncertain' : false); }); } for (const [relation, anchor] of positionalSelectors(selector)) { - narrow(() => { - const relatedIndexes = resolvePositionIndexes(relation, anchor); - return (node) => relatedIndexes.has(node.index); - }); + narrow(() => resolvePosition(relation, anchor).match); } - const scope = narrowed ?? snapshot.nodes; - if (scope.length === 0) return { matches: [] }; - if (relationUncertainty) throw relationUncertainty; - return resolveLeafMatches(scope, leaf, confirmedUnindexedExistence); + return { + ...resolveLeafMatches(narrowed ?? snapshot.nodes, leaf, selector.index, uncertainNodes), + parentMatched, + }; } function resolveLeafMatches( scope: readonly SnapshotNode[], leaf: MaestroFlatSelector, - confirmedUnindexedExistence: boolean, -): { matches: SnapshotNode[]; uncertain?: AppError } { - if (!hasMaestroLeafSelectorFields(leaf)) return { matches: [...scope] }; - let uncertain: AppError | undefined; - const matches = scope.filter((node) => { - try { - return matchesMaestroTypedSelector(node, leaf); - } catch (error) { - if (!isIndeterminateRegexError(error)) throw error; - uncertain ??= error; - return false; + index: MaestroSelector['index'], + uncertainNodes: Set | undefined, +): Omit, 'parentMatched'> { + if (scope.length === 0) return { matches: [] }; + const hasLeaf = hasMaestroLeafSelectorFields(leaf); + const matches: SnapshotNode[] = []; + let possible: SnapshotNode[] | undefined; + let leafMatched = false; + for (const node of scope) { + const result = hasLeaf ? matchLeaf(node, leaf) : true; + if (result === false) { + uncertainNodes?.delete(node); + continue; } - }); - if (matches.length === 0) { + if (result === true) leafMatched = true; + if (result === 'uncertain') (uncertainNodes ??= new Set()).add(node); + if (uncertainNodes?.has(node)) { + if (index !== undefined) (possible ??= [...matches]).push(node); + } else { + matches.push(node); + possible?.push(node); + } + } + if (!leafMatched) { const longPattern = [leaf.id, leaf.text].find( (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), ); if (longPattern !== undefined) matchesMaestroRegex('', longPattern); } - if (uncertain && (!confirmedUnindexedExistence || matches.length === 0)) throw uncertain; - return { matches, ...(uncertain ? { uncertain } : {}) }; + return { + matches, + possible, + uncertainNodes: uncertainNodes?.size ? uncertainNodes : undefined, + }; +} + +function matchLeaf(node: SnapshotNode, leaf: MaestroFlatSelector): CandidateMatch { + try { + return matchesMaestroTypedSelector(node, leaf); + } catch (error) { + if (!isIndeterminateRegexError(error)) throw error; + return 'uncertain'; + } } function isIndeterminateRegexError(error: unknown): error is AppError { @@ -263,7 +324,7 @@ function isIndeterminateRegexError(error: unknown): error is AppError { } function collectContainingAncestorIndexes( - nodes: readonly SnapshotNode[], + nodes: Iterable, ancestorIndexes: (node: SnapshotNode) => ReadonlySet, ): Set { const containingIndexes = new Set(); @@ -274,7 +335,9 @@ function collectContainingAncestorIndexes( } function setsIntersect(left: ReadonlySet, right: ReadonlySet): boolean { - for (const value of left) if (right.has(value)) return true; + if (right.size) { + for (const value of left) if (right.has(value)) return true; + } return false; } @@ -299,6 +362,29 @@ function selectMaestroIndexedMatches( return selected ? [selected] : []; } +function selectPossiblyIndexedMatches( + nodes: readonly SnapshotNode[], + uncertain: UncertainNodes, + index: number | string, +): Pick { + const desiredIndex = resolveMaestroSelectorIndex(index); + const possible = new Set(); + let definiteBefore = 0; + let uncertainBefore = 0; + const ordered = sortMaestroMatchesForIndex(nodes); + for (const node of ordered) { + if (definiteBefore > desiredIndex) break; + const isUncertain = uncertain.has(node); + if (definiteBefore + uncertainBefore >= desiredIndex) { + if (!isUncertain && uncertainBefore === 0) return { indexed: [node] }; + possible.add(node); + } + if (isUncertain) uncertainBefore += 1; + else definiteBefore += 1; + } + return { indexed: [], ...(possible.size ? { uncertainIndexed: possible } : {}) }; +} + export function selectMaestroIndexedNode( matches: readonly SnapshotNode[], index: number | string | undefined, diff --git a/packages/maestro/src/internal/runtime-target-position.ts b/packages/maestro/src/internal/runtime-target-position.ts index 478d9717d82..99092ae3ee6 100644 --- a/packages/maestro/src/internal/runtime-target-position.ts +++ b/packages/maestro/src/internal/runtime-target-position.ts @@ -69,3 +69,16 @@ function isFiniteRect(rect: Rect | undefined): rect is Rect { function centerCoordinate(origin: number, size: number): number { return origin + Math.trunc(size / 2); } + +export function createMaestroPositionUncertainty( + relation: MaestroPositionRelation, + anchors: Iterable, +): ((node: SnapshotNode) => boolean) | undefined { + let extreme: Rect | undefined; + for (const { rect } of anchors) { + if (isFiniteRect(rect) && (!extreme || qualifies(relation, extreme, rect))) extreme = rect; + } + if (!extreme) return undefined; + const anchor = extreme; + return (node) => isFiniteRect(node.rect) && qualifies(relation, node.rect, anchor); +} diff --git a/packages/maestro/src/internal/runtime-target-ranking.ts b/packages/maestro/src/internal/runtime-target-ranking.ts index 5326b0f3fb3..5edc0f63124 100644 --- a/packages/maestro/src/internal/runtime-target-ranking.ts +++ b/packages/maestro/src/internal/runtime-target-ranking.ts @@ -74,9 +74,7 @@ export function matchMaestroCandidatesWithResolver( selector: MaestroSelector, resolver: MaestroSnapshotResolver, ): MaestroCandidateMatches { - const { matches, uncertain } = resolver.resolve(selector); - const parentMatched = - selector.childOf === undefined || resolver.resolve(selector.childOf).indexed.length > 0; + const { matches, parentMatched, uncertain } = resolver.resolve(selector); return { matches, parentMatched, ...(uncertain ? { uncertain } : {}) }; } diff --git a/packages/maestro/src/internal/selector-regex.ts b/packages/maestro/src/internal/selector-regex.ts index 404ef08501c..ed20aa4e919 100644 --- a/packages/maestro/src/internal/selector-regex.ts +++ b/packages/maestro/src/internal/selector-regex.ts @@ -270,12 +270,18 @@ function assertBoundedMaestroPattern( for (const alternative of parsed.alternatives) { for (const path of expandedPaths(alternative.elements)) assertDisjointQuantifiers(path); } - const first = parsed.alternatives.length === 1 ? parsed.alternatives[0]?.elements[0] : undefined; + let initialLiteral = ''; + if (parsed.alternatives.length === 1) { + for (const element of parsed.alternatives[0]!.elements) { + if (element.type !== 'Character') break; + initialLiteral += element.raw; + } + } return { canSpanLines: parsed.alternatives.some((alternative) => alternative.elements.some(elementCanSpanLines), ), - ...(first?.type === 'Character' ? { initialLiteral: new RegExp(first.raw, 'iy') } : {}), + ...(initialLiteral ? { initialLiteral: new RegExp(initialLiteral, 'iy') } : {}), }; } From 395d8a137c4bcefe64c0f9a544afac5a1ec66426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 2 Dec 2026 17:23:09 +0100 Subject: [PATCH 17/17] fix(maestro): simplify leaf candidate collection --- .../internal/runtime-selector-resolution.ts | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/packages/maestro/src/internal/runtime-selector-resolution.ts b/packages/maestro/src/internal/runtime-selector-resolution.ts index ae7193511c0..9c6d63182de 100644 --- a/packages/maestro/src/internal/runtime-selector-resolution.ts +++ b/packages/maestro/src/internal/runtime-selector-resolution.ts @@ -263,7 +263,7 @@ function resolveWithoutOwnIndex( narrow(() => resolvePosition(relation, anchor).match); } return { - ...resolveLeafMatches(narrowed ?? snapshot.nodes, leaf, selector.index, uncertainNodes), + ...resolveLeafMatches(narrowed ?? snapshot.nodes, leaf, uncertainNodes), parentMatched, }; } @@ -271,39 +271,33 @@ function resolveWithoutOwnIndex( function resolveLeafMatches( scope: readonly SnapshotNode[], leaf: MaestroFlatSelector, - index: MaestroSelector['index'], uncertainNodes: Set | undefined, ): Omit, 'parentMatched'> { if (scope.length === 0) return { matches: [] }; const hasLeaf = hasMaestroLeafSelectorFields(leaf); - const matches: SnapshotNode[] = []; - let possible: SnapshotNode[] | undefined; let leafMatched = false; - for (const node of scope) { + const possible = scope.filter((node) => { const result = hasLeaf ? matchLeaf(node, leaf) : true; if (result === false) { uncertainNodes?.delete(node); - continue; + return false; } if (result === true) leafMatched = true; if (result === 'uncertain') (uncertainNodes ??= new Set()).add(node); - if (uncertainNodes?.has(node)) { - if (index !== undefined) (possible ??= [...matches]).push(node); - } else { - matches.push(node); - possible?.push(node); - } - } + return true; + }); if (!leafMatched) { const longPattern = [leaf.id, leaf.text].find( (pattern) => pattern !== undefined && requiresExactMaestroRegexMatch(pattern), ); if (longPattern !== undefined) matchesMaestroRegex('', longPattern); } + const unresolved = uncertainNodes; + if (!unresolved?.size) return { matches: possible }; return { - matches, + matches: possible.filter((node) => !unresolved.has(node)), possible, - uncertainNodes: uncertainNodes?.size ? uncertainNodes : undefined, + uncertainNodes: unresolved, }; }