Skip to content

Commit bc95d7f

Browse files
committed
refactor(snapshot): give the Wave 4 policies neutral host seams (#1983)
#2005 established the presentation ownership boundary and moved the iOS presentation policies out of `src/daemon/`. It left the three remaining Wave 4 policies behind their existing daemon adapters. This closes that gap, so `src/snapshot/` owns host-side snapshot policy generally rather than presentation alone. Freshness recovery: the window vocabulary, the Android staleness classification and its thresholds, and the retry loop move to `src/snapshot/snapshot-freshness/`. The loop is parameterized by a classifier and a retry schedule, so how long a backend may lag behind a real transition is a policy input rather than a constant the loop owns. `src/daemon/session-snapshot-freshness.ts` keeps only what needs a session — reading and retiring the window on store-owned `SessionState`, and choosing the comparison baseline from snapshot lineage — and remains the declared R7 owner of `androidSnapshotFreshness`. The two call sites #1739 named as the Wave 5 blockers, `selector-capture-runtime.ts` and `deferred-interaction-outcome.ts`, now reach freshness through the seam. Timeout evidence: whether a failure is the accessibility-timeout shape becomes a policy in `src/snapshot/snapshot-timeout-policy.ts`. The published `details.androidSnapshotTimeoutScreenshot` payload becomes vocabulary in `@agent-device/contracts/snapshot-timeout-evidence`, built through constructors so an assembly site cannot publish a fifth, undeclared arm. It gets its own subpath rather than riding the shared capture facade, which keeps it out of the CLI cold-start closure. Typed details, diagnostics and screenshot evidence are unchanged. Screenshot-overlay policy: which Android nodes earn an overlay ref, and what rectangle an overlay covers, move to `src/snapshot/screenshot-overlay/`. The daemon keeps approved artifact and ref assembly only — ranking, projection to screenshot pixels, drawing and PNG IO. The boundary test generalizes from the presentation subtree to the whole facet: nothing under `src/snapshot/` may import `src/daemon/`. It gains a positive control, because a filter that stopped matching would look identical to a boundary being obeyed. The residual call sites #1983 also named are audited and deliberately left in place. `direct-ios-selector.ts` carries no presentation policy; its two pure exports are selector derivation and ADR 0011 delegation-on-error, whose owner would be the selector pipeline governed by R19, not this facet. ADR 0004 records the finding so it does not have to be re-derived. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01GLYhmt5ZNHQATG8T8ZFo7R
1 parent 50f460c commit bc95d7f

35 files changed

Lines changed: 1037 additions & 495 deletions

‎CONTEXT.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,8 @@ alone.
196196
**Presentation options**:
197197
The policy input controlling how one snapshot acquisition becomes a public projection.
198198

199-
**Snapshot presentation facet**:
200-
The host-side owner of the neutral acquisition-to-presentation contract and TypeScript policies.
199+
**Snapshot policy facet**:
200+
The host-side owner of neutral snapshot policy: presentation, freshness, timeout and overlay.
201201
Platform acquisition supplies raw facts and a fold policy; runner-side Swift presentation remains
202202
separate across the process boundary.
203203

‎docs/adr/0004-ios-snapshot-backend-strategy.md‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,46 @@ capture-plan tier before the process boundary. The contract fixture under
7878
`contracts/fixtures/snapshot-presentation-conformance.json` is the shared proof between those
7979
runtimes; it does not imply that Swift and TypeScript share an implementation.
8080

81-
This is the first ownership slice of the Wave 4 debt tracked by #1983. Freshness recovery,
82-
timeout evidence, and screenshot-overlay policy retain their existing daemon adapters until their
83-
neutral host seams are extracted; new consumers must use the facet rather than add another daemon
84-
presentation path.
81+
The same split now holds for the three remaining Wave 4 policies tracked by #1983, so
82+
`src/snapshot/` is the host-side owner of snapshot policy generally rather than of presentation
83+
alone:
84+
85+
- **Freshness recovery.** The freshness window, the Android staleness classification and its
86+
thresholds, and the retry loop live in `src/snapshot/snapshot-freshness/`. The loop is
87+
parameterized by a classifier and a retry schedule, so "how long may a backend lag behind a real
88+
transition" is a policy input rather than a constant the loop owns.
89+
`src/daemon/session-snapshot-freshness.ts` keeps only what needs a session: reading and retiring
90+
the window on store-owned `SessionState`, and choosing the comparison baseline from snapshot
91+
lineage. It remains the declared R7 owner of `androidSnapshotFreshness`.
92+
- **Timeout evidence.** Whether a failure is the accessibility-timeout shape is a policy in
93+
`src/snapshot/snapshot-timeout-policy.ts`; the published `details.androidSnapshotTimeoutScreenshot`
94+
payload is vocabulary in `@agent-device/contracts/snapshot-timeout-evidence`, built through
95+
constructors so an assembly site cannot publish an undeclared arm. The daemon keeps the ordering
96+
that genuinely needs it — resolving a bound screenshot runtime, writing the artifact, annotating
97+
it from the stored observation, and emitting the diagnostics. Typed details, logs and screenshot
98+
evidence are unchanged.
99+
- **Screenshot-overlay policy.** Which Android nodes earn an overlay ref, and what rectangle an
100+
overlay for one of them covers, live in `src/snapshot/screenshot-overlay/`. The daemon keeps
101+
approved artifact and ref assembly only: ranking, projection to screenshot pixels, drawing, and
102+
PNG IO.
103+
104+
`scripts/layering/snapshot-presentation-boundary.test.ts` enforces the direction for the whole
105+
facet: nothing under `src/snapshot/` may import `src/daemon/`. It carries a positive control,
106+
because a filter that stopped matching would look identical to a boundary being obeyed.
107+
108+
The residual call sites #1983 also named are audited and deliberately left in place.
109+
`src/daemon/direct-ios-selector.ts` carries no presentation policy: `isLocalIosRunnerSession` and
110+
`readSimpleIosSelectorTarget` are session routing (device family, provider ownership, the
111+
stabilization window), while `deriveDirectIosNodeSelector` and `isDirectIosSelectorFallbackError`
112+
are selector derivation and ADR 0011 delegation-on-error. The latter two are pure and
113+
daemon-independent, but their owner would be the selector pipeline governed by R19, not this
114+
facet; moving them under ADR 0004 would widen it to a boundary it does not decide. The
115+
observation and interaction consumers — `selector-capture-runtime.ts`,
116+
`deferred-interaction-outcome.ts`, `snapshot-capture.ts` and
117+
`interaction-touch-android-freshness.ts` — now reach freshness only through the facet or its
118+
session binding.
119+
120+
New consumers must use the facet rather than add another daemon presentation path.
85121

86122
## Regression Notes
87123

‎fallow-baselines/health.json‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -112,11 +112,6 @@
112112
"count": 1
113113
}
114114
},
115-
"src/daemon/android-snapshot-freshness.ts": {
116-
"crap_moderate": {
117-
"count": 1
118-
}
119-
},
120115
"src/daemon/client/daemon-client-lifecycle.ts": {
121116
"complexity_high": {
122117
"count": 1
@@ -575,7 +570,6 @@
575570
"src/daemon/handlers/session.ts:complexity",
576571
"src/replay/script-utils.ts:high impact",
577572
"packages/selectors/src/internal/predicates.ts:high impact",
578-
"src/daemon/android-snapshot-freshness.ts:high impact",
579573
"src/platforms/boot-diagnostics.ts:complexity",
580574
"src/compat/maestro/support.ts:high impact",
581575
"src/daemon/session-routing.ts:high impact",

‎packages/contracts/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,10 @@
307307
"types": "./src/snapshot-runtime.ts",
308308
"default": "./src/snapshot-runtime.ts"
309309
},
310+
"./snapshot-timeout-evidence": {
311+
"types": "./src/snapshot-timeout-evidence.ts",
312+
"default": "./src/snapshot-timeout-evidence.ts"
313+
},
310314
"./startup-recovery-fence": {
311315
"types": "./src/startup-recovery-fence.ts",
312316
"default": "./src/startup-recovery-fence.ts"
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import type { ScreenshotOverlayRef } from '@agent-device/kernel/snapshot';
4+
import {
5+
snapshotTimeoutCaptureFailed,
6+
snapshotTimeoutEvidenceOverlayCounts,
7+
snapshotTimeoutEvidenceOverlayFailed,
8+
snapshotTimeoutEvidenceWithOverlayRefs,
9+
snapshotTimeoutEvidenceWithoutOverlaySource,
10+
} from './snapshot-timeout-evidence.ts';
11+
12+
function overlayRef(ref: string): ScreenshotOverlayRef {
13+
return {
14+
ref,
15+
label: ref,
16+
rect: { x: 0, y: 0, width: 10, height: 10 },
17+
overlayRect: { x: 0, y: 0, width: 10, height: 10 },
18+
center: { x: 5, y: 5 },
19+
};
20+
}
21+
22+
test('a failed capture publishes no path and no overlay claim', () => {
23+
const evidence = snapshotTimeoutCaptureFailed('adb screencap exited 1');
24+
assert.deepEqual(evidence, { captureFailed: true, error: 'adb screencap exited 1' });
25+
assert.deepEqual(snapshotTimeoutEvidenceOverlayCounts(evidence), {
26+
overlayRefCount: undefined,
27+
overlayRefsAnnotated: undefined,
28+
});
29+
});
30+
31+
test('a capture with no stored observation still discloses that refs were requested', () => {
32+
const evidence = snapshotTimeoutEvidenceWithoutOverlaySource('/tmp/shot.png');
33+
assert.deepEqual(evidence, {
34+
path: '/tmp/shot.png',
35+
overlayRefsRequested: true,
36+
overlayRefsAnnotated: false,
37+
overlayRefSource: 'unavailable',
38+
overlayRefCount: 0,
39+
});
40+
});
41+
42+
test('an empty ref list is a capture that was not annotated, not an annotated one', () => {
43+
const none = snapshotTimeoutEvidenceWithOverlayRefs('/tmp/shot.png', []);
44+
const some = snapshotTimeoutEvidenceWithOverlayRefs('/tmp/shot.png', [overlayRef('e1')]);
45+
assert.deepEqual(snapshotTimeoutEvidenceOverlayCounts(none), {
46+
overlayRefCount: 0,
47+
overlayRefsAnnotated: false,
48+
});
49+
assert.deepEqual(snapshotTimeoutEvidenceOverlayCounts(some), {
50+
overlayRefCount: 1,
51+
overlayRefsAnnotated: true,
52+
});
53+
});
54+
55+
test('a failed annotation keeps the screenshot and names why the refs are missing', () => {
56+
const evidence = snapshotTimeoutEvidenceOverlayFailed('/tmp/shot.png', 'png decode failed');
57+
assert.deepEqual(evidence, {
58+
path: '/tmp/shot.png',
59+
overlayRefsRequested: true,
60+
overlayRefsAnnotated: false,
61+
overlayRefSource: 'session-snapshot',
62+
overlayRefCount: 0,
63+
overlayAnnotationError: 'png decode failed',
64+
});
65+
});
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import type { ScreenshotOverlayRef } from '@agent-device/kernel/snapshot';
2+
3+
/**
4+
* The typed `details.androidSnapshotTimeoutScreenshot` payload published when an accessibility
5+
* snapshot times out and the daemon falls back to a screenshot (#1983).
6+
*
7+
* The shape is a discriminated union rather than a bag of optional fields because each arm is a
8+
* different claim about what evidence exists: no capture at all, a capture with no snapshot to
9+
* annotate from, a capture annotated with overlay refs, or a capture whose annotation failed.
10+
* Callers construct it through the builders below so an assembly site cannot publish a fifth,
11+
* undeclared arm.
12+
*/
13+
type CapturedSnapshotTimeoutEvidenceBase = {
14+
path: string;
15+
overlayRefsRequested: true;
16+
};
17+
18+
export type SnapshotTimeoutEvidence =
19+
| {
20+
captureFailed: true;
21+
error: string;
22+
}
23+
| (CapturedSnapshotTimeoutEvidenceBase & {
24+
overlayRefSource: 'unavailable';
25+
overlayRefsAnnotated: false;
26+
overlayRefCount: 0;
27+
})
28+
| (CapturedSnapshotTimeoutEvidenceBase & {
29+
overlayRefSource: 'session-snapshot';
30+
overlayRefsAnnotated: boolean;
31+
overlayRefCount: number;
32+
overlayRefs: ScreenshotOverlayRef[];
33+
})
34+
| (CapturedSnapshotTimeoutEvidenceBase & {
35+
overlayRefSource: 'session-snapshot';
36+
overlayRefsAnnotated: false;
37+
overlayRefCount: 0;
38+
overlayAnnotationError: string;
39+
});
40+
41+
/** No screenshot was taken: the evidence path itself failed. */
42+
export function snapshotTimeoutCaptureFailed(error: string): SnapshotTimeoutEvidence {
43+
return { captureFailed: true, error };
44+
}
45+
46+
/** A screenshot exists, but no stored observation was available to derive overlay refs from. */
47+
export function snapshotTimeoutEvidenceWithoutOverlaySource(path: string): SnapshotTimeoutEvidence {
48+
return {
49+
path,
50+
overlayRefsRequested: true,
51+
overlayRefsAnnotated: false,
52+
overlayRefSource: 'unavailable',
53+
overlayRefCount: 0,
54+
};
55+
}
56+
57+
/** A screenshot annotated from the stored observation. An empty ref list is not an annotation. */
58+
export function snapshotTimeoutEvidenceWithOverlayRefs(
59+
path: string,
60+
overlayRefs: ScreenshotOverlayRef[],
61+
): SnapshotTimeoutEvidence {
62+
return {
63+
path,
64+
overlayRefsRequested: true,
65+
overlayRefsAnnotated: overlayRefs.length > 0,
66+
overlayRefCount: overlayRefs.length,
67+
overlayRefSource: 'session-snapshot',
68+
overlayRefs,
69+
};
70+
}
71+
72+
/** A screenshot exists and a stored observation existed, but annotating it threw. */
73+
export function snapshotTimeoutEvidenceOverlayFailed(
74+
path: string,
75+
overlayAnnotationError: string,
76+
): SnapshotTimeoutEvidence {
77+
return {
78+
path,
79+
overlayRefsRequested: true,
80+
overlayRefsAnnotated: false,
81+
overlayRefSource: 'session-snapshot',
82+
overlayRefCount: 0,
83+
overlayAnnotationError,
84+
};
85+
}
86+
87+
/**
88+
* The overlay counts a diagnostic may report, narrowed off the union so a log site does not
89+
* re-derive the arm discrimination with `in` checks.
90+
*/
91+
export function snapshotTimeoutEvidenceOverlayCounts(evidence: SnapshotTimeoutEvidence): {
92+
overlayRefCount: number | undefined;
93+
overlayRefsAnnotated: boolean | undefined;
94+
} {
95+
return 'captureFailed' in evidence
96+
? { overlayRefCount: undefined, overlayRefsAnnotated: undefined }
97+
: {
98+
overlayRefCount: evidence.overlayRefCount,
99+
overlayRefsAnnotated: evidence.overlayRefsAnnotated,
100+
};
101+
}

‎scripts/layering/package-boundaries.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ const CONTRACT_EXPORTS = [
121121
'@agent-device/contracts/snapshot',
122122
'@agent-device/contracts/snapshot-presentation',
123123
'@agent-device/contracts/snapshot-runtime',
124+
'@agent-device/contracts/snapshot-timeout-evidence',
124125
'@agent-device/contracts/startup-recovery-fence',
125126
'@agent-device/contracts/touch-runtime',
126127
'@agent-device/contracts/tv-remote',
@@ -703,6 +704,14 @@ test('Node resolution enforces the exports map at runtime', () => {
703704
contractsReactNativeOverlayResolved.endsWith('packages/contracts/src/react-native-overlay.ts'),
704705
contractsReactNativeOverlayResolved,
705706
);
707+
const contractsSnapshotTimeoutEvidenceResolved = import.meta
708+
.resolve('@agent-device/contracts/snapshot-timeout-evidence');
709+
assert.ok(
710+
contractsSnapshotTimeoutEvidenceResolved.endsWith(
711+
'packages/contracts/src/snapshot-timeout-evidence.ts',
712+
),
713+
contractsSnapshotTimeoutEvidenceResolved,
714+
);
706715
const providerWebDriverResolved = import.meta.resolve('@agent-device/provider-webdriver');
707716
assert.ok(
708717
providerWebDriverResolved.endsWith('packages/provider-webdriver/src/index.ts'),

‎scripts/layering/session-state.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export const SESSION_STATE_FIELD_OWNERS: Readonly<Record<string, readonly string
4747
snapshot: ['src/daemon/session-snapshot.ts'],
4848
snapshotGeneration: ['src/daemon/session-snapshot.ts'],
4949
lastComparisonSafeSnapshot: ['src/daemon/session-snapshot.ts'],
50-
androidSnapshotFreshness: ['src/daemon/android-snapshot-freshness.ts'],
50+
androidSnapshotFreshness: ['src/daemon/session-snapshot-freshness.ts'],
5151
// One-shot deferred-warning latch (#1587 follow-up): the transition function is the only
5252
// writer, so the latch's window semantics live in a single module.
5353
recoveredSnapshotWarningLatch: ['src/daemon/snapshot-quality-latch.ts'],

‎scripts/layering/snapshot-presentation-boundary.test.ts‎

Lines changed: 36 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,48 @@ import { listTrackedTypeScriptFiles } from './tracked-sources.ts';
88

99
const repoRoot = path.resolve(import.meta.dirname, '../..');
1010

11-
test('snapshot presentation cannot import daemon assembly', () => {
11+
/**
12+
* The host-side snapshot facet (`src/snapshot/`) owns presentation, freshness, timeout and
13+
* overlay policy; `src/daemon/` owns the assembly that orders them (#1983, ADR 0004). The
14+
* dependency runs one way only, so a policy stays testable without standing up a session.
15+
*
16+
* The real tree is clean, which is exactly why the positive control below exists: a filter that
17+
* stopped matching would look identical to a boundary being obeyed.
18+
*/
19+
function daemonImportsFromSnapshotFacet(
20+
sources: ReadonlyMap<string, string>,
21+
workspaceTargets?: ReadonlyMap<string, string>,
22+
): string[] {
23+
return resolveImportEdges(sources, workspaceTargets)
24+
.filter(
25+
(edge) => edge.file.startsWith('src/snapshot/') && edge.target.startsWith('src/daemon/'),
26+
)
27+
.map((edge) => `${edge.file}:${edge.line} -> ${edge.target}`);
28+
}
29+
30+
test('the snapshot facet cannot import daemon assembly', () => {
1231
const files = listTrackedTypeScriptFiles(repoRoot);
1332
const sources = new Map(
1433
files.map((file) => [file, fs.readFileSync(path.join(repoRoot, file), 'utf8')]),
1534
);
16-
const violations = resolveImportEdges(sources, workspaceSpecifierTargets(repoRoot)).filter(
17-
(edge) =>
18-
edge.file.startsWith('src/snapshot/snapshot-presentation/') &&
19-
edge.target.startsWith('src/daemon/'),
20-
);
2135

2236
assert.deepEqual(
23-
violations.map((edge) => `${edge.file}:${edge.line} -> ${edge.target}`),
37+
daemonImportsFromSnapshotFacet(sources, workspaceSpecifierTargets(repoRoot)),
2438
[],
25-
'the snapshot presentation facet must not depend on daemon assembly',
39+
'the host-side snapshot facet must not depend on daemon assembly',
2640
);
2741
});
42+
43+
test('the boundary reports a facet module that reaches back into the daemon', () => {
44+
const sources = new Map([
45+
['src/daemon/types.ts', 'export type SessionState = { id: string };\n'],
46+
[
47+
'src/snapshot/snapshot-freshness/android.ts',
48+
"import type { SessionState } from '../../daemon/types.ts';\nexport type X = SessionState;\n",
49+
],
50+
]);
51+
52+
assert.deepEqual(daemonImportsFromSnapshotFacet(sources), [
53+
'src/snapshot/snapshot-freshness/android.ts:1 -> src/daemon/types.ts',
54+
]);
55+
});

‎src/__tests__/eager-closure-budgets.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ export const FACADE_BUDGETS: Readonly<Record<string, number>> = Object.freeze({
182182
'packages/contracts/src/settings.ts': 3,
183183
'packages/contracts/src/snapshot-presentation.ts': 2,
184184
'packages/contracts/src/snapshot-runtime.ts': 3,
185+
'packages/contracts/src/snapshot-timeout-evidence.ts': 1,
185186
'packages/contracts/src/startup-recovery-fence.ts': 1,
186187
'packages/contracts/src/tv-remote.ts': 3,
187188
'packages/contracts/src/type-text-runtime.ts': 4,

0 commit comments

Comments
 (0)