Skip to content

Commit 97a0ad2

Browse files
thymikeeclaude
andcommitted
chore(gates): forbid process globals outside declared entry points (#3753)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent bece3e4 commit 97a0ad2

3 files changed

Lines changed: 231 additions & 1 deletion

File tree

‎scripts/layering/check.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ import { recordRuntimeDaemonMechanicsViolations } from './record-runtime-mechani
139139
import { checkDaemonPlatformBoundary } from './daemon-platform-boundary.ts';
140140
import { checkDaemonPlatformRuntimeInventory } from './daemon-platform-runtime-inventory.ts';
141141
import { checkDaemonClientEntry } from './daemon-client-entry.ts';
142+
import { processGlobalsViolations } from './process-globals-policy.ts';
142143
import { checkDaemonProcessReach } from './daemon-process-reach.ts';
143144
import {
144145
checkPackageExportSurface,
@@ -453,7 +454,8 @@ function report(
453454
`concrete platform imports in every executable and type-only form; ` +
454455
`no production daemon file reaches the root platform-runtime family or a hub that ` +
455456
`does (R76); the daemon process reaches no caller-side replay source module over ` +
456-
`static or dynamic edges (R82); ` +
457+
`static or dynamic edges (R82); process globals stay at declared entries and ` +
458+
`command-host reads stay at command-execution/spawn boundaries (R86); ` +
457459
`${packageExportSurfaceSummary(ratchets.testOnlyExports, reference.testOnlyExports)}; ` +
458460
`${testColocationSummary(ratchets.unmatchedTests, reference.unmatchedTests)}; and ` +
459461
`the handler-owned SessionState/SessionStore ` +
@@ -539,6 +541,7 @@ export const LAYERING_RULE_IDS = [
539541
'provider-snapshot-presentation-ownership',
540542
'snapshot-assembly-presentation-neutrality',
541543
'daemon-platform-runtime-inventory',
544+
'process-globals',
542545
'daemon-process-reach',
543546
'daemon-client-entry',
544547
'session-authority-overlay',
@@ -607,6 +610,7 @@ export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
607610
snapshotAssemblyPresentationViolations(context.sources, context.edges),
608611
'daemon-platform-runtime-inventory': (context) =>
609612
checkDaemonPlatformRuntimeInventory(context.edges),
613+
'process-globals': (context) => processGlobalsViolations(context.allTypeScriptSources),
610614
'daemon-process-reach': (context) => checkDaemonProcessReach(context.sourceFiles, context.edges),
611615
'daemon-client-entry': (context) => checkDaemonClientEntry(context.sourceFiles, context.edges),
612616
'session-authority-overlay': (context) =>
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
import { LAYERING_RULES } from './check.ts';
4+
import { PROCESS_GLOBALS_RULE, processGlobalsViolations } from './process-globals-policy.ts';
5+
6+
function check(source: string, file = 'src/commands/example.ts') {
7+
return processGlobalsViolations(new Map([[file, source]]));
8+
}
9+
10+
test('the registered gate rejects process configuration and command-host scope in non-entry sources', () => {
11+
const allTypeScriptSources = new Map([
12+
['src/commands/example.ts', 'const env = process.env;\ncommandHostEnvironment();'],
13+
]);
14+
const violations = LAYERING_RULES['process-globals']({ allTypeScriptSources } as Parameters<
15+
(typeof LAYERING_RULES)['process-globals']
16+
>[0]);
17+
assert.deepEqual(
18+
violations.map(({ rule, file, line }) => ({ rule, file, line })),
19+
[1, 2].map((line) => ({ rule: PROCESS_GLOBALS_RULE, file: 'src/commands/example.ts', line })),
20+
);
21+
});
22+
23+
test('all six process globals fail, including bracketed and imported process members', () => {
24+
for (const member of ['env', 'cwd', 'on', 'once', 'exit', 'emitWarning']) {
25+
for (const expression of [
26+
`process.${member}`,
27+
`process['${member}']`,
28+
`globalThis.process.${member}`,
29+
]) {
30+
assert.equal(check(`${expression};`).length, 1, expression);
31+
}
32+
assert.equal(check(`import p from 'node:process'; p.${member};`).length, 1);
33+
assert.equal(check(`import { ${member} as local } from 'process';`).length, 1);
34+
assert.equal(check(`const { ${member}: local } = process;`).length, 1);
35+
}
36+
});
37+
38+
test('entry declarations permit process reads but do not permit ambient command-host calls', () => {
39+
for (const file of [
40+
'src/bin.ts',
41+
'src/cli.ts',
42+
'src/cli/commands/example.ts',
43+
'src/daemon.ts',
44+
'src/agent-device-client.ts',
45+
'packages/capture-kit/src/png-worker.ts',
46+
'packages/maestro/src/daemon-port/run-script-http-child.ts',
47+
'packages/react-native/src/companion/client-companion-tunnel-worker.ts',
48+
'packages/platform-apple/src/os/macos/helper.ts',
49+
'packages/platform-apple/src/runner/runner-process-launch.ts',
50+
]) {
51+
assert.deepEqual(check('process.env; process.on("SIGINT", stop);', file), [], file);
52+
assert.equal(check('commandHostEnvironment();', file).length, 1, file);
53+
}
54+
});
55+
56+
test('command spawn boundaries permit the scoped host but still reject raw process configuration', () => {
57+
for (const file of [
58+
'packages/host-kit/src/internal/exec.ts',
59+
'packages/platform-apple/src/core/tool-provider.ts',
60+
'packages/platform-linux/src/tool-provider.ts',
61+
'src/platform-runtime-android-adb-host.ts',
62+
]) {
63+
assert.deepEqual(check('commandHostEnvironment();', file), [], file);
64+
assert.equal(check('process.env;', file).length, 1, file);
65+
}
66+
});
67+
68+
test('renamed and namespace command-host calls cannot bypass the boundary', () => {
69+
assert.equal(
70+
check(
71+
"import { commandHostEnvironment as host } from '@agent-device/host-kit/command'; host();",
72+
).length,
73+
1,
74+
);
75+
assert.equal(check('commands.commandHostEnvironment();').length, 1);
76+
});
77+
78+
test('test support and scripts are outside the production rule', () => {
79+
for (const file of [
80+
'src/example.test.ts',
81+
'packages/test-kit/src/example.ts',
82+
'src/example.fixtures.ts',
83+
'packages/maestro/test/example.ts',
84+
'scripts/example.ts',
85+
]) {
86+
assert.deepEqual(check('process.env; commandHostEnvironment();', file), [], file);
87+
}
88+
assert.equal(check('process.env;', 'packages/example/src/module.ts').length, 1);
89+
});
90+
91+
test('comments, strings and explicit host values are not process reads', () => {
92+
assert.deepEqual(check('// process.env\nconst text = "process.cwd()"; host.env; host.cwd;'), []);
93+
});
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
import { parseSync } from 'oxc-parser';
2+
import { asNode, memberName, nodeList, propertyName, visitAst } from './layering-ast.ts';
3+
import type { LayeringViolation } from './model.ts';
4+
import { isProductionSourceFile } from './tracked-sources.ts';
5+
6+
export const PROCESS_GLOBALS_RULE = 'R86 process-globals';
7+
8+
/** Process capture and lifecycle belong to these executable or released factory boundaries. */
9+
const PROCESS_ENTRIES = new Set([
10+
'src/bin.ts',
11+
'src/cli.ts',
12+
'src/daemon.ts',
13+
'src/agent-device-client.ts',
14+
'packages/capture-kit/src/png-worker.ts',
15+
'packages/react-native/src/companion/companion-tunnel.ts',
16+
'packages/react-native/src/companion/client-companion-tunnel-worker.ts',
17+
'packages/maestro/src/daemon-port/run-script-http-child.ts',
18+
'packages/platform-apple/src/os/macos/helper.ts',
19+
'packages/platform-apple/src/runner/runner-process-launch.ts',
20+
]);
21+
// src/cli/** and scripts/** are entry trees. Apple native helper executables live outside the
22+
// TypeScript source trees. Reserve agent-device/host's entry here when #3757 supplies its path.
23+
24+
/** Only command execution and spawn adapters may consult the ambient command-host scope. */
25+
const COMMAND_HOST_BOUNDARIES = new Set([
26+
'packages/host-kit/src/internal/exec.ts',
27+
'packages/platform-apple/src/core/tool-provider.ts',
28+
'packages/platform-linux/src/tool-provider.ts',
29+
'src/platform-runtime-android-adb-host.ts',
30+
]);
31+
const PROCESS_MEMBERS = new Set(['env', 'cwd', 'on', 'once', 'exit', 'emitWarning']);
32+
33+
/**
34+
* Catches ambient configuration and process lifecycle in reusable modules, plus command-host
35+
* scope reads outside spawn adapters. Uses the existing OXC layering parser; no debt baseline.
36+
* Test support, including packages/test-kit, uses the shared production-source classification.
37+
* Workers and children receive serializable configuration at their declared entry boundary.
38+
* Kill criterion: retire only if reusable sources may own process configuration and lifecycle.
39+
*/
40+
export function processGlobalsViolations(
41+
sources: ReadonlyMap<string, string>,
42+
): LayeringViolation[] {
43+
const violations: LayeringViolation[] = [];
44+
for (const [file, source] of sources) {
45+
if (!isProductionSourceFile(file)) continue;
46+
const processEntry = PROCESS_ENTRIES.has(file) || file.startsWith('src/cli/');
47+
const commandBoundary = COMMAND_HOST_BOUNDARIES.has(file);
48+
if (processEntry && commandBoundary) continue;
49+
const program = parseSync(file, source).program;
50+
const processNames = new Set(['process']);
51+
const commandHostNames = new Set(['commandHostEnvironment']);
52+
const processExports = new Set<string>();
53+
visitAst(program, (node) => {
54+
if (node.type !== 'ImportDeclaration') return;
55+
const specifier = asNode(node.source)?.value;
56+
for (const value of nodeList(node.specifiers)) {
57+
const binding = asNode(value);
58+
const local = asNode(binding?.local)?.name;
59+
if (typeof local !== 'string') continue;
60+
if (specifier === 'node:process' || specifier === 'process') {
61+
if (binding?.type !== 'ImportSpecifier') processNames.add(local);
62+
else if (PROCESS_MEMBERS.has(propertyName(binding.imported) ?? '')) {
63+
processExports.add(local);
64+
}
65+
}
66+
if (propertyName(binding?.imported) === 'commandHostEnvironment') {
67+
commandHostNames.add(local);
68+
}
69+
}
70+
});
71+
const isProcess = (value: unknown): boolean => {
72+
const node = asNode(value);
73+
if (node?.type === 'Identifier') return processNames.has(String(node.name));
74+
return (
75+
node?.type === 'MemberExpression' &&
76+
asNode(node.object)?.type === 'Identifier' &&
77+
['globalThis', 'global'].includes(String(asNode(node.object)?.name)) &&
78+
memberName(node) === 'process'
79+
);
80+
};
81+
visitAst(program, (node) => {
82+
let message: string | undefined;
83+
if (!processEntry) {
84+
if (
85+
node.type === 'MemberExpression' &&
86+
isProcess(node.object) &&
87+
PROCESS_MEMBERS.has(memberName(node) ?? '')
88+
) {
89+
message = `process.${memberName(node)} belongs at a declared process entry; pass the owning host explicitly`;
90+
} else if (node.type === 'VariableDeclarator' && isProcess(node.init)) {
91+
const pattern = asNode(node.id);
92+
if (
93+
pattern?.type === 'ObjectPattern' &&
94+
nodeList(pattern.properties).some((value) =>
95+
PROCESS_MEMBERS.has(propertyName(asNode(value)?.key) ?? ''),
96+
)
97+
) {
98+
message =
99+
'process configuration and lifecycle destructuring belongs at a declared process entry';
100+
}
101+
} else if (node.type === 'ImportDeclaration') {
102+
if (
103+
nodeList(node.specifiers).some((value) =>
104+
processExports.has(String(asNode(asNode(value)?.local)?.name)),
105+
)
106+
) {
107+
message =
108+
'process configuration and lifecycle imports belong at a declared process entry';
109+
}
110+
}
111+
}
112+
if (!commandBoundary && node.type === 'CallExpression') {
113+
const callee = asNode(node.callee);
114+
if (
115+
(callee?.type === 'Identifier' && commandHostNames.has(String(callee.name))) ||
116+
(callee?.type === 'MemberExpression' && memberName(callee) === 'commandHostEnvironment')
117+
) {
118+
message =
119+
'commandHostEnvironment() belongs at the command-execution/spawn boundary; pass the owning host explicitly';
120+
}
121+
}
122+
if (message) {
123+
violations.push({
124+
rule: PROCESS_GLOBALS_RULE,
125+
file,
126+
line: source.slice(0, Number(node.start ?? 0)).split('\n').length,
127+
message,
128+
});
129+
}
130+
});
131+
}
132+
return violations;
133+
}

0 commit comments

Comments
 (0)