Skip to content

Commit 66e02f0

Browse files
committed
fix: tighten replay capability boundaries
1 parent e04bef9 commit 66e02f0

34 files changed

Lines changed: 549 additions & 267 deletions

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ const PINNED_TEST_FILE_LINES: Readonly<Record<string, number>> = Object.freeze({
5151
'src/daemon/handlers/__tests__/find.test.ts': 1199,
5252
'packages/platform-apple/src/core/__tests__/perf.test.ts': 1222,
5353
'src/mcp/__tests__/command-tools.test.ts': 1216,
54-
'src/daemon/replay/internal/__tests__/session-replay-divergence.test.ts': 1136,
54+
'src/daemon/replay/internal/__tests__/session-replay-divergence.test.ts': 1100,
5555
'packages/platform-apple/src/core/__tests__/apps.test.ts': 1146,
5656
'src/daemon/replay/internal/__tests__/session-replay-repair-transaction.test.ts': 1202,
5757
'src/daemon/replay/internal/__tests__/session-replay-target-verification-runtime.test.ts': 1182,

‎scripts/layering/model.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,22 @@ test('parseImports distinguishes value, type-only, dynamic, and value re-export
5252
);
5353
});
5454

55+
test('parseImports detects multiline dynamic imports', () => {
56+
const edges = parseImports(['void import(', " '../multiline.ts'", ');'].join('\n'));
57+
58+
assert.deepEqual(edges, [
59+
{ spec: '../multiline.ts', dynamic: true, typeOnly: false, line: 1, symbols: [] },
60+
]);
61+
});
62+
63+
test('parseImports resolves constant-template dynamic imports', () => {
64+
const edges = parseImports('void import(`../template.ts`);');
65+
66+
assert.deepEqual(edges, [
67+
{ spec: '../template.ts', dynamic: true, typeOnly: false, line: 1, symbols: [] },
68+
]);
69+
});
70+
5571
test('parseImports retains named source symbols without changing edge-kind detection', () => {
5672
const edges = parseImports(
5773
[

‎scripts/layering/model.ts‎

Lines changed: 63 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import path from 'node:path';
22
import { PLATFORMS } from '@agent-device/kernel/device';
3+
import { parseSync } from 'oxc-parser';
4+
import { visitAst } from './layering-ast.ts';
35

46
export type ImportEdge = {
57
spec: string;
@@ -105,13 +107,60 @@ export function classifyZone(zone: string): ZoneClassification {
105107
return 'unclassified';
106108
}
107109

108-
function scanDynamicImports(line: string, lineNo: number): ImportEdge[] {
109-
const edges: ImportEdge[] = [];
110-
const re = /import\s*\(\s*['"]([^'"]+)['"]/g;
111-
let match: RegExpExecArray | null;
112-
while ((match = re.exec(line))) {
113-
edges.push({ spec: match[1]!, dynamic: true, typeOnly: false, line: lineNo, symbols: [] });
110+
function sourceLine(source: string, offset: number | null | undefined): number {
111+
const start = typeof offset === 'number' && offset >= 0 ? offset : 0;
112+
return source.slice(0, start).split('\n').length;
113+
}
114+
115+
function literalSpecifier(node: unknown): string | undefined {
116+
if (node === null || typeof node !== 'object') return undefined;
117+
const record = node as Record<string, unknown>;
118+
if (record.type === 'Literal' && typeof record.value === 'string') return record.value;
119+
if (record.type === 'TemplateLiteral') {
120+
const expressions = record.expressions;
121+
const quasis = record.quasis;
122+
if (!Array.isArray(expressions) || expressions.length > 0 || !Array.isArray(quasis)) {
123+
return undefined;
124+
}
125+
const quasi = quasis[0];
126+
if (quasi === null || typeof quasi !== 'object') return undefined;
127+
const value = (quasi as Record<string, unknown>).value;
128+
if (value === null || typeof value !== 'object') return undefined;
129+
const cooked = (value as Record<string, unknown>).cooked;
130+
return typeof cooked === 'string' ? cooked : undefined;
131+
}
132+
if (
133+
record.type === 'ParenthesizedExpression' ||
134+
record.type === 'TSAsExpression' ||
135+
record.type === 'TSTypeAssertion' ||
136+
record.type === 'TSSatisfiesExpression' ||
137+
record.type === 'TSNonNullExpression'
138+
) {
139+
return literalSpecifier(record.expression);
114140
}
141+
if (record.type === 'BinaryExpression' && record.operator === '+') {
142+
const left = literalSpecifier(record.left);
143+
const right = literalSpecifier(record.right);
144+
return left === undefined || right === undefined ? undefined : left + right;
145+
}
146+
return undefined;
147+
}
148+
149+
function scanDynamicImports(source: string): ImportEdge[] {
150+
const edges: ImportEdge[] = [];
151+
const parsed = parseSync('layering-imports.ts', source);
152+
visitAst(parsed.program, (node) => {
153+
if (node.type !== 'ImportExpression') return;
154+
const spec = literalSpecifier(node.source);
155+
if (spec === undefined) return;
156+
edges.push({
157+
spec,
158+
dynamic: true,
159+
typeOnly: false,
160+
line: sourceLine(source, node.start as number | undefined),
161+
symbols: [],
162+
});
163+
});
115164
return edges;
116165
}
117166

@@ -187,9 +236,16 @@ function scanFromImport(lines: string[], index: number): ImportEdge | null {
187236

188237
export function parseImports(source: string): ImportEdge[] {
189238
const lines = source.split('\n');
239+
const dynamicImports = scanDynamicImports(source);
240+
const dynamicImportsByLine = new Map<number, ImportEdge[]>();
241+
for (const edge of dynamicImports) {
242+
const lineEdges = dynamicImportsByLine.get(edge.line) ?? [];
243+
lineEdges.push(edge);
244+
dynamicImportsByLine.set(edge.line, lineEdges);
245+
}
190246
const edges: ImportEdge[] = [];
191247
for (let index = 0; index < lines.length; index++) {
192-
edges.push(...scanDynamicImports(lines[index]!, index + 1));
248+
edges.push(...(dynamicImportsByLine.get(index + 1) ?? []));
193249
const sideEffect = scanSideEffectImport(lines[index]!, index + 1);
194250
if (sideEffect) {
195251
edges.push(sideEffect);

‎src/daemon/__tests__/internal-observation.test.ts‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -35,26 +35,36 @@ function scenario() {
3535
markSessionPartialRefsIssued(session, ['e1']);
3636
sessionStore.set(sessionName, session);
3737
const captured = snapshot('e2', 'Internal capture');
38-
const authority = bindInternalObservationAuthority({
39-
sessionStore,
40-
sessionName,
41-
});
38+
const authority = bindAuthority(sessionStore, sessionName);
4239
const stored = authority.store(captured);
4340
return { sessionStore, sessionName, session, prior, captured, authority, ...stored };
4441
}
4542

4643
function publishCurrent(input: ReturnType<typeof scenario>, signal?: AbortSignal) {
47-
const authority = bindInternalObservationAuthority({
48-
sessionStore: input.sessionStore,
49-
sessionName: input.sessionName,
50-
...(signal ? { signal } : {}),
51-
});
44+
const authority = bindAuthority(input.sessionStore, input.sessionName, signal);
5245
return authority.finalize(input.evidence, {
5346
refsGeneration: input.refsGeneration,
5447
refs: ['@e2'],
5548
});
5649
}
5750

51+
function bindAuthority(sessionStore: SessionStore, sessionName: string, signal?: AbortSignal) {
52+
return bindInternalObservationAuthority({
53+
sessionStore: {
54+
get: () => sessionStore.get(sessionName),
55+
update: (mutate) => {
56+
const session = sessionStore.get(sessionName);
57+
if (!session) return false;
58+
mutate(session);
59+
sessionStore.set(sessionName, session);
60+
return true;
61+
},
62+
},
63+
sessionName,
64+
...(signal ? { signal } : {}),
65+
});
66+
}
67+
5868
test('publishes exactly the validated outward refs from a current internal capture', () => {
5969
const input = scenario();
6070

‎src/daemon/__tests__/replay-coordinator-ownership.test.ts‎

Lines changed: 111 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ const DIVERGENCE_CHAIN_FILES = [
4141

4242
type ImportSite = {
4343
file: string;
44+
kind: 'import' | 'dynamic-import' | 'named-reexport' | 'all-reexport';
4445
/** Repo-root-relative path the specifier resolves to, or `null` for an unresolved/external specifier. */
4546
target: string | null;
4647
/** A named import binding at this site: its exported name and whether IT is type-only. */
@@ -92,6 +93,7 @@ function collectImportSites(
9293
}));
9394
sites.push({
9495
file,
96+
kind: 'import',
9597
target,
9698
bindings,
9799
declarationTypeOnly: node.importKind === 'type',
@@ -101,6 +103,7 @@ function collectImportSites(
101103
if (node.type === 'ImportExpression') {
102104
sites.push({
103105
file,
106+
kind: 'dynamic-import',
104107
target: importSourceTarget(file, node.source),
105108
bindings: [],
106109
declarationTypeOnly: false,
@@ -120,6 +123,7 @@ function collectImportSites(
120123
: [];
121124
sites.push({
122125
file,
126+
kind: node.type === 'ExportNamedDeclaration' ? 'named-reexport' : 'all-reexport',
123127
target: importSourceTarget(file, node.source),
124128
bindings,
125129
declarationTypeOnly: node.exportKind === 'type',
@@ -129,9 +133,54 @@ function collectImportSites(
129133
}
130134

131135
function importSourceTarget(file: string, source: unknown): string | null {
132-
if (!source || typeof source !== 'object') return null;
133-
const value = (source as { value?: unknown }).value;
134-
return typeof value === 'string' ? resolveRelativeTarget(file, value) : null;
136+
const value = constantSpecifier(source);
137+
return value === undefined ? null : resolveRelativeTarget(file, value);
138+
}
139+
140+
function objectRecord(value: unknown): Record<string, unknown> | undefined {
141+
return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;
142+
}
143+
144+
function templateSpecifier(node: Record<string, unknown>): string | undefined {
145+
const expressions = node.expressions;
146+
const quasis = node.quasis;
147+
if (!Array.isArray(expressions) || expressions.length !== 0 || !Array.isArray(quasis)) {
148+
return undefined;
149+
}
150+
const quasi = objectRecord(quasis[0]);
151+
const value = quasi ? objectRecord(quasi.value) : undefined;
152+
return value && typeof value.cooked === 'string' ? value.cooked : undefined;
153+
}
154+
155+
function wrappedSpecifier(node: Record<string, unknown>): string | undefined {
156+
return constantSpecifier(node.expression);
157+
}
158+
159+
function binarySpecifier(node: Record<string, unknown>): string | undefined {
160+
if (node.operator !== '+') return undefined;
161+
const left = constantSpecifier(node.left);
162+
const right = constantSpecifier(node.right);
163+
return left !== undefined && right !== undefined ? left + right : undefined;
164+
}
165+
166+
function literalSpecifier(node: Record<string, unknown>): string | undefined {
167+
return typeof node.value === 'string' ? node.value : undefined;
168+
}
169+
170+
const SPECIFIER_READERS: Record<string, (node: Record<string, unknown>) => string | undefined> = {
171+
Literal: literalSpecifier,
172+
TemplateLiteral: templateSpecifier,
173+
TSAsExpression: wrappedSpecifier,
174+
TSTypeAssertion: wrappedSpecifier,
175+
ChainExpression: wrappedSpecifier,
176+
ParenthesizedExpression: wrappedSpecifier,
177+
BinaryExpression: binarySpecifier,
178+
};
179+
180+
function constantSpecifier(value: unknown): string | undefined {
181+
const node = objectRecord(value);
182+
if (!node) return undefined;
183+
return SPECIFIER_READERS[String(node.type)]?.(node);
135184
}
136185

137186
function importsValueBinding(site: ImportSite, name: string): boolean {
@@ -196,9 +245,7 @@ function coordinatorImportBindings(
196245
const namespace = new Set<string>();
197246
for (const node of body) {
198247
if (node.type !== 'ImportDeclaration') continue;
199-
const source = node.source as { value?: unknown };
200-
if (typeof source.value !== 'string') continue;
201-
if (resolveRelativeTarget(file, source.value) !== COORDINATOR_MODULE) continue;
248+
if (importSourceTarget(file, node.source) !== COORDINATOR_MODULE) continue;
202249
if (node.importKind === 'type') continue;
203250
for (const specifier of node.specifiers as readonly Record<string, unknown>[]) {
204251
addCoordinatorImportBinding(specifier, direct, namespace);
@@ -268,17 +315,36 @@ function dynamicCoordinatorImportSite(
268315
file: string,
269316
node: Record<string, unknown>,
270317
): CoordinatorConstructionSite | undefined {
271-
const sourceNode = node.source as { type?: unknown; value?: unknown } | undefined;
272-
if (
273-
sourceNode?.type !== 'Literal' ||
274-
typeof sourceNode.value !== 'string' ||
275-
resolveRelativeTarget(file, sourceNode.value) !== COORDINATOR_MODULE
276-
) {
318+
if (importSourceTarget(file, node.source) !== COORDINATOR_MODULE) {
277319
return undefined;
278320
}
279321
return { file, kind: 'dynamic-import', start: Number(node.start) };
280322
}
281323

324+
function coordinatorReexportSites(
325+
files: readonly string[],
326+
sourceOverrides: ReadonlyMap<string, string> = new Map(),
327+
): ImportSite[] {
328+
return files.flatMap((file) =>
329+
collectImportSites(file, sourceOverrides.get(file)).filter(
330+
(site) =>
331+
(site.kind === 'named-reexport' || site.kind === 'all-reexport') &&
332+
site.target === COORDINATOR_MODULE,
333+
),
334+
);
335+
}
336+
337+
function unresolvedDynamicImportSites(
338+
files: readonly string[],
339+
sourceOverrides: ReadonlyMap<string, string> = new Map(),
340+
): ImportSite[] {
341+
return files.flatMap((file) =>
342+
collectImportSites(file, sourceOverrides.get(file)).filter(
343+
(site) => site.kind === 'dynamic-import' && site.target === null,
344+
),
345+
);
346+
}
347+
282348
const PRODUCTION_FILES = listProductionSourceFiles();
283349

284350
test('createReplayCoordinator has exactly one production call site', () => {
@@ -292,6 +358,31 @@ test('createReplayCoordinator has exactly one production call site', () => {
292358
sites.map(({ file, kind }) => `${file} (${kind})`).join(', ') || '(none)'
293359
}`,
294360
);
361+
assert.deepEqual(
362+
coordinatorReexportSites(PRODUCTION_FILES),
363+
[],
364+
'createReplayCoordinator must not be re-exported from a production module',
365+
);
366+
});
367+
368+
test('coordinator ownership scanning catches re-exports and unresolved dynamic imports', () => {
369+
const probe = 'src/daemon/replay/internal/probe.ts';
370+
const source = `
371+
export { createReplayCoordinator } from '../../session-replay-coordinator.ts';
372+
export * from '../../session-replay-coordinator.ts';
373+
const target = '../../session-replay-coordinator.ts';
374+
void import(target);
375+
void import(
376+
\`../../session-replay-coordinator.ts\`
377+
);
378+
`;
379+
const overrides = new Map([[probe, source]]);
380+
assert.equal(coordinatorReexportSites([probe], overrides).length, 2);
381+
assert.equal(unresolvedDynamicImportSites([probe], overrides).length, 1);
382+
assert.deepEqual(
383+
coordinatorConstructionSites(probe, source).map(({ kind }) => kind),
384+
['dynamic-import'],
385+
);
295386
});
296387

297388
test('coordinator ownership scanning catches aliases, namespaces, and dynamic imports', () => {
@@ -365,6 +456,14 @@ test('the divergence-report chain never imports SessionStore', () => {
365456
}
366457
});
367458

459+
test('the divergence-report chain rejects unresolved dynamic imports', () => {
460+
assert.deepEqual(
461+
unresolvedDynamicImportSites(DIVERGENCE_CHAIN_FILES),
462+
[],
463+
'protected replay imports must resolve their dynamic specifier or fail closed',
464+
);
465+
});
466+
368467
test('SessionStore ownership scanning catches dynamic imports and re-exports', () => {
369468
const sites = collectImportSites(
370469
'src/daemon/replay/internal/probe.ts',

0 commit comments

Comments
 (0)