Skip to content

Commit a41a147

Browse files
committed
chore: enforce the terminal daemon platform boundary
1 parent 20b67ab commit a41a147

48 files changed

Lines changed: 1279 additions & 248 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎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/platform-runtime-operations.ts",
308308
"default": "./src/platform-runtime-operations.ts"
309309
},
310+
"./platform-resource-cleanup": {
311+
"types": "./src/platform-resource-cleanup.ts",
312+
"default": "./src/platform-resource-cleanup.ts"
313+
},
310314
"./platform-runtime-unavailable": {
311315
"types": "./src/platform-runtime-unavailable.ts",
312316
"default": "./src/platform-runtime-unavailable.ts"
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import type { DeviceInfo } from '@agent-device/kernel/device';
2+
3+
/** Platform-owned resource finalization invoked by neutral daemon orchestration. */
4+
export type PlatformResourceCleanup = Readonly<{
5+
stopSnapshotHelper(device: DeviceInfo): Promise<void>;
6+
closeManagedBrowser(
7+
params: Readonly<{
8+
device: DeviceInfo;
9+
sessionName: string;
10+
stateDir: string;
11+
openSessionNames: () => readonly string[];
12+
}>,
13+
): Promise<void>;
14+
cleanupSessionlessExecutionHost(device: DeviceInfo): Promise<void>;
15+
retainExecutionHostAfterClose(params: {
16+
device: DeviceInfo;
17+
shutdownRequested: boolean;
18+
hasScreenRecording: boolean;
19+
hasLease: boolean;
20+
}): boolean;
21+
}>;

‎packages/platform-android/src/observation.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,33 @@ test('owns touch rounding and screen-size parsing behind raw host commands', asy
6868
allowFailure: true,
6969
});
7070
});
71+
72+
test('a transient empty dump never demotes a variant that previously answered', async () => {
73+
const calls: string[] = [];
74+
let primaryReads = 0;
75+
const host: AndroidObservationHost = {
76+
...hostFor(new Map()),
77+
runAdb: vi.fn(async (_device, args) => {
78+
const key = args.join(' ');
79+
calls.push(key);
80+
if (key === 'shell dumpsys window windows') primaryReads += 1;
81+
return {
82+
exitCode: 0,
83+
stdout:
84+
primaryReads === 2 && key === 'shell dumpsys window windows'
85+
? ''
86+
: 'mCurrentFocus=Window{1 u0 com.example.app/.MainActivity}',
87+
stderr: '',
88+
};
89+
}),
90+
};
91+
const observer = createAndroidObservationAdapter(host);
92+
const transientDevice = { ...device, id: 'emulator-transient' };
93+
94+
await observer.readAppState(transientDevice);
95+
await observer.readAppState(transientDevice);
96+
const thirdReadStart = calls.length;
97+
await observer.readAppState(transientDevice);
98+
99+
expect(calls[thirdReadStart]).toBe('shell dumpsys window windows');
100+
});

‎packages/platform-android/src/observation.ts‎

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,6 @@ export function createAndroidObservationAdapter(
7373
});
7474
}
7575

76-
export function resetAndroidObservationMemoForTests(): void {
77-
everAnswered.clear();
78-
}
79-
8076
function createDumpReader(host: AndroidObservationHost, device: DeviceInfo): DumpReader {
8177
const dumps = new Map<string, Promise<string>>();
8278
return (args) => {
@@ -134,11 +130,19 @@ function orderedDumps(device: DeviceInfo, question: Question): readonly (readonl
134130
function recordSections(device: DeviceInfo, key: string, text: string): void {
135131
if (!text) return;
136132
const memo = everAnswered.get(device.id) ?? new Map<string, boolean>();
137-
memo.set(`foreground ${key}`, markerPattern(FOCUS_MARKERS).test(text));
138-
memo.set(`blockingDialog ${key}`, markerPattern([FOCUSED_WINDOW_MARKER]).test(text));
133+
preservePositiveMemo(memo, `foreground ${key}`, markerPattern(FOCUS_MARKERS).test(text));
134+
preservePositiveMemo(
135+
memo,
136+
`blockingDialog ${key}`,
137+
markerPattern([FOCUSED_WINDOW_MARKER]).test(text),
138+
);
139139
everAnswered.set(device.id, memo);
140140
}
141141

142+
function preservePositiveMemo(memo: Map<string, boolean>, key: string, answered: boolean): void {
143+
if (memo.get(key) !== true) memo.set(key, answered);
144+
}
145+
142146
function parseForeground(text: string): AppStateRuntimeResult | null {
143147
for (const match of text.matchAll(FOCUS_LINE)) {
144148
const component = match[1]?.match(
@@ -154,8 +158,9 @@ function parseBlockingDialog(text: string): {
154158
focus: AndroidBlockingDialogFocus | null;
155159
} {
156160
let focusObserved = false;
161+
const lines = text.split('\n');
157162
for (const marker of FOCUS_MARKERS) {
158-
for (const line of text.split('\n')) {
163+
for (const line of lines) {
159164
const index = line.indexOf(marker);
160165
if (index === -1) continue;
161166
if (marker === FOCUSED_WINDOW_MARKER) focusObserved = true;
@@ -165,30 +170,32 @@ function parseBlockingDialog(text: string): {
165170
.slice(index + marker.length)
166171
.split('}')[0]
167172
?.trim() ?? '';
168-
const anr = ANR_TITLE.exec(segment);
169-
if (anr?.[1]) {
170-
return {
171-
focusObserved,
172-
focus: { package: anr[1], focusedWindow: `Application Not Responding: ${anr[1]}`, raw },
173-
};
174-
}
175-
const responding = RESPONDING_TITLE.exec(segment)?.[1]?.trim().replace(/\s+/g, ' ');
176-
if (responding) {
177-
const packageName = PACKAGE_NAME.exec(responding)?.[1];
178-
return {
179-
focusObserved,
180-
focus: {
181-
...(packageName ? { package: packageName } : {}),
182-
focusedWindow: responding,
183-
raw,
184-
},
185-
};
186-
}
173+
const focus = parseDialogFocus(segment, raw);
174+
if (focus) return { focusObserved, focus };
187175
}
188176
}
189177
return { focusObserved, focus: null };
190178
}
191179

180+
function parseDialogFocus(segment: string, raw: string): AndroidBlockingDialogFocus | null {
181+
const anrPackage = ANR_TITLE.exec(segment)?.[1];
182+
if (anrPackage) {
183+
return {
184+
package: anrPackage,
185+
focusedWindow: `Application Not Responding: ${anrPackage}`,
186+
raw,
187+
};
188+
}
189+
const responding = RESPONDING_TITLE.exec(segment)?.[1]?.trim().replace(/\s+/g, ' ');
190+
if (!responding) return null;
191+
const packageName = PACKAGE_NAME.exec(responding)?.[1];
192+
return {
193+
...(packageName ? { package: packageName } : {}),
194+
focusedWindow: responding,
195+
raw,
196+
};
197+
}
198+
192199
function markerPattern(markers: readonly string[]): RegExp {
193200
return new RegExp(markers.map(escapeRegExp).join('|'));
194201
}

‎scripts/__tests__/test-file-size-ratchet.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ const TRIPWIRE_LINES = 1_000;
3434
// Exact current lengths. Lower a pin when its file shrinks; never raise one — extract instead.
3535
const PINNED_TEST_FILE_LINES: Readonly<Record<string, number>> = Object.freeze({
3636
'src/__tests__/remote-connection.test.ts': 2973,
37-
'src/daemon/handlers/__tests__/snapshot-handler.test.ts': 2284,
37+
'src/daemon/handlers/__tests__/snapshot-handler.test.ts': 2242,
3838
'src/commands/interaction/runtime/settle.test.ts': 2359,
3939
'src/daemon/handlers/__tests__/session-replay-runtime-maestro.test.ts': 1963,
4040
'packages/platform-apple/src/runner/__tests__/runner-session.test.ts': 1957,

‎scripts/layering/check.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
// an import whose source zone outranks its target zone, plus a ratchet on the
2020
// same inversion measured over TYPE-ONLY edges (R6).
2121
// - Over the DAEMON only: SessionState field ownership (R7), because the session
22-
// record is store-owned mutable state that any daemon module can write.
22+
// record is store-owned mutable state that any daemon module can write; and the terminal
23+
// concrete-platform boundary (R65), which rejects every import form into src/platforms or a
24+
// platform package.
2325
// - Over the TYPE GRAPH: the largest type-level import cycle is pinned by
2426
// equality (R9). R4 keeps the value graph acyclic, so these cycles are free at
2527
// runtime but bound what can be read in isolation; growth fails, and so does a
@@ -98,6 +100,7 @@ import { policyLead, policyViolation, ZONE_POLICIES } from './zone-policy.ts';
98100
import { contractsImplementationAuthorityViolations } from './contracts-implementation-policy.ts';
99101
import { selectorPipelineOwnershipViolations } from './selector-pipeline-ownership.ts';
100102
import { recordRuntimeRegistryJoinViolations } from './record-runtime-registry-policy.ts';
103+
import { checkDaemonPlatformBoundary } from './daemon-platform-boundary.ts';
101104
import { listTrackedProductionSources, listTrackedTypeScriptFiles } from './tracked-sources.ts';
102105

103106
const repoRoot = execFileSync('git', ['rev-parse', '--show-toplevel'], {
@@ -485,7 +488,9 @@ function report(
485488
`inside its declared owner (R7); the largest type-level cycle is ${typeCycle} files ` +
486489
`(R9); ${daemonModularitySummary()}; ` +
487490
`${packageBoundariesSummary(repoRoot)}; ${platformPackagePolicySummary()}; ` +
488-
`${runtimeCommandCutoverSummary()}; and bin.ts imports normalizeCliCommandAlias, ` +
491+
`${runtimeCommandCutoverSummary()}; R65 keeps production src/daemon free of concrete ` +
492+
`platform imports in every executable and type-only form; and bin.ts imports ` +
493+
`normalizeCliCommandAlias, ` +
489494
`actually passes it into buildCommandUsageText, and holds no local alias literals ` +
490495
`(R12).\n`,
491496
);
@@ -543,6 +548,7 @@ export const LAYERING_RULE_IDS = [
543548
'type-spine-inversions',
544549
'session-state-ownership',
545550
'daemon-modularity-ratchets',
551+
'daemon-platform-boundary',
546552
'bin-alias-fast-path',
547553
'package-boundaries',
548554
'platform-package-policy',
@@ -564,6 +570,8 @@ export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
564570
'session-state-ownership': (context) => checkSessionStateOwnership(context.sources),
565571
'daemon-modularity-ratchets': (context) =>
566572
checkDaemonModularityRatchets(context.edges, context.typeCycleMembers),
573+
'daemon-platform-boundary': (context) =>
574+
checkDaemonPlatformBoundary([...context.sources].map(([path, source]) => ({ path, source }))),
567575
'bin-alias-fast-path': (context) => checkBinAliasFastPath(context.sources),
568576
'package-boundaries': () => checkPackageBoundaries(repoRoot),
569577
'platform-package-policy': (context) =>

0 commit comments

Comments
 (0)