Skip to content

Commit 3ce8ac0

Browse files
thymikeeclaude
andcommitted
chore(gates): ban the CLI process from reaching daemon modules (R78)
R78 walks static and dynamic edges from src/bin.ts and src/cli.ts and fails on any reached module outside the client-side roots that imports the daemon package, naming the chain. R82 and R78 share one walker, process-reach.ts. The client-side policy in LOGICAL_MODULE_POLICIES now covers the CLI, typed client, remote transports and daemon client. The two moved entries that carry the durable-capture machinery and the claim fixtures entry are approved over the new-entry ceiling, and the ADRs say what the rules do now. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent e91435f commit 3ce8ac0

11 files changed

Lines changed: 285 additions & 69 deletions

‎docs/adr/0032-layering-graph-engine.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ finding. Clean tree: custom 0, depcruise 10 (3 R6 survivors, 7 recorded R78 edge
8585
| R14 non-TS file under `src/utils` | flag | ✓ | ✗ | ✗ |
8686
| R71 file under `src/replay` | flag | ✓ | ✓ | ✓ generic |
8787

88+
_R78 no longer records edges: the client's direct imports are a flat ban in `LOGICAL_MODULE_POLICIES` (R10), and R78 now walks reachability from the CLI entries, so the "unrecorded" and "stale" rows describe the spike at its date, not the rules as shipped._
89+
8890
Custom prints `file:line`, rule id and hint (`report()` in `scripts/layering/check.ts`); depcruise
8991
the rule name and an authored comment, without a line. "Generic" means a fallow zone pair
9092
(`core → cli`) and a docs link, with no rule id or hint; R14 and R71 surface as "matches no zone".

‎docs/adr/0033-collocation-decision-table.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ already owns the operations behind the vocabulary.
7979
| `src/diagnostics.ts` | keep | The diagnostics seam every zone imports (AGENTS.md mandates it); highest fan-in in the repo is what a substrate looks like, not misplacement. |
8080
| `src/internal/request-cancel.ts` | keep | Request-cancellation mechanics AGENTS.md routes to `host-kit/request`; internal beside its facade is already the collocation. |
8181
| `src/request.ts` | keep | Cross-layer request contracts AGENTS.md names as a host-kit seam; consumers span every zone. |
82-
| `src/session-paths.ts` | keep | Session-artifact path grammar the daemon, cli, and platforms all resolve; AGENTS.md keeps the path *policy* in `packages/daemon/src/core/session-artifact-paths.ts`, which consumes this. |
82+
| `src/session-paths.ts` | keep | Session-artifact path grammar the daemon, cli, and platforms all resolve; AGENTS.md keeps the path *policy* in `packages/daemon-contracts/src/session-artifact-paths.ts`, which consumes this. |
8383

8484
### kernel
8585

@@ -118,7 +118,7 @@ already owns the operations behind the vocabulary.
118118

119119
| File | Decision | Reason |
120120
| --- | --- | --- |
121-
| `src/cli/commands/device-release.ts` | keep | Command surface belongs in `cli` by the folder spine; the daemon device-claim modules it reuses are already extracted, so what remains is thin daemonless-CLI composition. |
121+
| `src/cli/commands/device-release.ts` | moved | Now `src/platform-runtime-claim-recovery.ts`: the daemonless stale release composes the shared reconciler with the root gateway, and the CLI process may reach no daemon module (R78), so it sits beside the claim-recovery gateway in the platform-runtime composition. |
122122

123123
### (root)
124124

@@ -133,8 +133,9 @@ the whole `daemon-contracts` zone has moved into `packages/daemon-contracts` —
133133
package derive the zone, so every moved file's `ROOT_MODULE_ZONES` row is gone.
134134
The daemon ⇄ client shared files that remain here (`provider-credential-fingerprint.ts`) trace
135135
to #2559, which relocated the shared contracts **to the process root** so the client stops
136-
importing `packages/daemon/src/` at all; the `daemon-client` logical-module policy bans every edge from `src/daemon-client/` into
137-
`packages/daemon/src/`, and #3288's `daemon-contracts`
136+
importing `packages/daemon/src/` at all; the `client-side` logical-module policy bans every edge from the CLI, typed client, remote transports and
137+
`src/daemon-client/` into `packages/daemon/src/`, R78 bans the hop through any root module the CLI
138+
process reaches, and #3288's `daemon-contracts`
138139
zone was the declaration of that shared-below-both ownership — the extraction makes it
139140
physical, with R11 and the package's dependency edges holding the same boundary. Rows on
140141
path-keyed evidence alone (the `platform-runtime-*` seams) say "retain for this batch": a guard's
@@ -144,6 +145,7 @@ optimal.
144145
| File | Decision | Reason |
145146
| --- | --- | --- |
146147
| `src/daemon-diagnostics-scope.ts` | moved → `packages/daemon-contracts/src/daemon-diagnostics-scope.ts` ([#3297](https://github.com/callstack/agent-device/pull/3297) into `src/daemon-contracts/`, then the package extraction) | The whole `daemon-contracts` zone now lives as `packages/daemon-contracts`, so the package directory derives the zone and the per-file `ROOT_MODULE_ZONES` row stays deleted; an internal rename needs no ownership-table edit. |
148+
| `packages/daemon-contracts/src/device-claim-recovery.ts` | keep (shared-below-both) | The owner-scoped claim reconciler runs durable-resource recovery for a dead owner's state dir; the daemon runs it at `open` and startup and the daemonless `device release --stale` runs it too, so it lives below both. Runtime recovery may live in `daemon-contracts` only when both sides run it and root composition supplies just the gateway (ADR 0019 section 1); the package depends on `capture-kit`, which cannot depend back on it (a project-reference cycle through `selectors`). |
147149
| `src/daemon-policy-file.ts` | moved → `packages/daemon-contracts/src/daemon-policy-file.ts` | Daemon ⇄ client shared contract from #2559, declared `daemon-contracts` by #3288 — the shared-below-both ownership the spine needs, since daemon-client (rank 5) dynamically imports it. The extraction makes that placement physical: the package sits below both sides and its manifest exports own the boundary. |
148150
| `src/daemon.ts` | keep | Entry point (`internal/daemon` bundle entry); composition roots stay in root by umbrella §4. |
149151
| `src/platform-runtime-apple-runner-owner.ts` | retain for this batch | `platform-runtime-*` composition seam: R13's exact-importer rule and the ADR 0022 R76 inventory key on its path, so relocation requires coordinated ownership changes to both declarations — the rules constrain the move, they do not independently prove the placement. |

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,26 @@ export const NEW_ENTRY_CEILINGS: Readonly<Record<EntryCategory, number>> = Objec
132132
*/
133133
export const APPROVED_OVER_CEILING: Readonly<
134134
Record<string, { issue: string; reason: string; owner: string }>
135-
> = Object.freeze({});
135+
> = Object.freeze({
136+
'packages/capture-kit/src/capture-admission/app-log-durable-resource.ts': {
137+
issue: '#3616',
138+
reason:
139+
'Moved verbatim out of the daemon app-log session resource so the claim reconciler no longer imports the daemon; the closure is the durable-capture machinery every capture resource carries, and no consumer gains modules.',
140+
owner: 'daemon single-entry stack (L1b)',
141+
},
142+
'packages/daemon-contracts/src/device-claims.fixtures.ts': {
143+
issue: '#3616',
144+
reason:
145+
'Test-only entry for daemon tests that drive the claim reconciler directly; it loads the same closure as device-claim-recovery.ts and no production module imports it.',
146+
owner: 'daemon single-entry stack (L1b)',
147+
},
148+
'packages/daemon-contracts/src/device-claim-recovery.ts': {
149+
issue: '#3616',
150+
reason:
151+
'Moved verbatim out of the daemon so the CLI release path and the daemon share one reconciler without the CLI importing the daemon; only the daemon and the lazily loaded stale-release path import it.',
152+
owner: 'daemon single-entry stack (L1b)',
153+
},
154+
});
136155

137156
/** The category is a function of the path, never a hand-written column. */
138157
export function entryCategoryOf(entryFile: string): EntryCategory {

‎scripts/layering/architecture-ownership.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,10 +111,13 @@ export const SNAPSHOT_EXECUTION_RETIRED_HANDLER_PATHS = [
111111
'packages/daemon/src/handlers/snapshot-session.ts',
112112
] as const;
113113

114+
/** The CLI, typed client, remote transports and daemon client: code that reaches the daemon over the network. */
115+
export const CLIENT_SIDE_POLICY_NAME = 'client-side';
116+
114117
export const LOGICAL_MODULE_POLICIES = [
115118
{
116-
name: 'daemon-client',
117-
roots: ['src/daemon-client/'],
119+
name: CLIENT_SIDE_POLICY_NAME,
120+
roots: ['src/cli.ts', 'src/cli/', 'src/client/', 'src/remote/', 'src/daemon-client/'],
118121
forbiddenTargetRoots: [DAEMON_SOURCE_ROOT],
119122
},
120123
{

‎scripts/layering/check.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,7 @@ import { recordRuntimeRegistryJoinViolations } from './record-runtime-registry-p
132132
import { recordRuntimeDaemonMechanicsViolations } from './record-runtime-mechanics-policy.ts';
133133
import { checkDaemonPlatformBoundary } from './daemon-platform-boundary.ts';
134134
import { checkDaemonPlatformRuntimeInventory } from './daemon-platform-runtime-inventory.ts';
135+
import { checkDaemonClientEntry } from './daemon-client-entry.ts';
135136
import { checkDaemonProcessReach } from './daemon-process-reach.ts';
136137
import { checkDaemonLayers, DAEMON_ROOT } from './daemon-layers.ts';
137138
import { checkSessionAuthorityOverlay, handlerOwnedOverlay } from './session-authority-overlay.ts';
@@ -518,6 +519,7 @@ export const LAYERING_RULE_IDS = [
518519
'snapshot-assembly-presentation-neutrality',
519520
'daemon-platform-runtime-inventory',
520521
'daemon-process-reach',
522+
'daemon-client-entry',
521523
'session-authority-overlay',
522524
'daemon-layers',
523525
] as const;
@@ -582,6 +584,7 @@ export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
582584
'daemon-platform-runtime-inventory': (context) =>
583585
checkDaemonPlatformRuntimeInventory(context.edges),
584586
'daemon-process-reach': (context) => checkDaemonProcessReach(context.sourceFiles, context.edges),
587+
'daemon-client-entry': (context) => checkDaemonClientEntry(context.sourceFiles, context.edges),
585588
'session-authority-overlay': (context) =>
586589
checkSessionAuthorityOverlay(
587590
context.ratchets.sessionAuthority,
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
import {
4+
checkDaemonClientEntry,
5+
CLI_PROCESS_ENTRIES,
6+
DAEMON_CLIENT_ENTRY_RULE,
7+
} from './daemon-client-entry.ts';
8+
import { resolveImportEdges } from './model.ts';
9+
10+
const DAEMON_MODULE = 'packages/daemon/src/server/platform-request-scope.ts';
11+
12+
/** The CLI entries and a daemon module exist as stubs, so a case fails only on what it plants. */
13+
function check(sources: Record<string, string>) {
14+
const tree = new Map<string, string>([
15+
...CLI_PROCESS_ENTRIES.map((entry) => [entry, 'export {};\n'] as const),
16+
[DAEMON_MODULE, 'export const scope = 1;\n'],
17+
...Object.entries(sources),
18+
]);
19+
return checkDaemonClientEntry([...tree.keys()], resolveImportEdges(tree));
20+
}
21+
22+
test('a daemon import from a module the CLI never reaches is not CLI reach', () => {
23+
assert.deepEqual(check({ 'src/daemon-composition.ts': `import '../${DAEMON_MODULE}';\n` }), []);
24+
});
25+
26+
test('a root module the CLI lazy-loads cannot launder a daemon import', () => {
27+
const violations = check({
28+
'src/cli.ts': "export const run = () => import('./cli/commands/device.ts');\n",
29+
'src/cli/commands/device.ts':
30+
"export const release = () => import('../../platform-runtime-claim-recovery.ts');\n",
31+
'src/platform-runtime-claim-recovery.ts': `import '../${DAEMON_MODULE}';\n`,
32+
});
33+
assert.equal(violations.length, 1);
34+
assert.equal(violations[0]!.rule, DAEMON_CLIENT_ENTRY_RULE);
35+
assert.equal(violations[0]!.file, 'src/platform-runtime-claim-recovery.ts');
36+
assert.ok(
37+
violations[0]!.message.includes(
38+
`Chain: src/cli.ts -> src/cli/commands/device.ts -> src/platform-runtime-claim-recovery.ts -> ${DAEMON_MODULE}.`,
39+
),
40+
violations[0]!.message,
41+
);
42+
});
43+
44+
test('a daemon import inside a client-side root is left to the client-side policy', () => {
45+
assert.deepEqual(check({ 'src/cli.ts': `import '../${DAEMON_MODULE}';\n` }), []);
46+
});
47+
48+
test('a type-only import by a reached root module is not a load', () => {
49+
assert.deepEqual(
50+
check({
51+
'src/cli.ts': "import './platform-runtime-types.ts';\n",
52+
'src/platform-runtime-types.ts': `import type { scope } from '../${DAEMON_MODULE}';\n`,
53+
}),
54+
[],
55+
);
56+
});
57+
58+
test('a missing CLI entry fails as stale instead of passing silently', () => {
59+
const violations = checkDaemonClientEntry(['src/cli.ts'], []);
60+
assert.equal(violations.length, 1);
61+
assert.match(violations[0]!.message, /stale module: src\/bin\.ts/);
62+
});
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import {
2+
CLIENT_SIDE_POLICY_NAME,
3+
LOGICAL_MODULE_POLICIES,
4+
matchesDeclaredRoot,
5+
} from './architecture-ownership.ts';
6+
import type { LayeringViolation, ResolvedImportEdge } from './model.ts';
7+
import { staleReachModules, walkProcessReach } from './process-reach.ts';
8+
import { DAEMON_SOURCE_ROOT } from './tracked-sources.ts';
9+
10+
export const DAEMON_CLIENT_ENTRY_RULE = 'R78 daemon-client-entry';
11+
12+
/** The modules a CLI process starts from. */
13+
export const CLI_PROCESS_ENTRIES: readonly string[] = ['src/bin.ts', 'src/cli.ts'];
14+
15+
/**
16+
* Catches: any module the CLI process can load — over static and dynamic edges, so a root module
17+
* the CLI lazy-loads counts — importing the daemon package. The folder ban on the client-side
18+
* roots lives in `LOGICAL_MODULE_POLICIES` (R10) and covers direct edges, type-only included;
19+
* this rule covers the hop outside those roots, where a root platform-runtime module could
20+
* launder a daemon import into the CLI process. The violation names the chain from the entry.
21+
* What the client shares with the daemon lives below both: `packages/daemon-contracts`,
22+
* `DaemonWireRequest` in `@agent-device/contracts/command`, `DaemonResponse` in kernel.
23+
* Evidence: the folder ban alone left `device release --stale` loading the daemon reconciler
24+
* through a root module one hop away.
25+
* Cost: one breadth-first walk over the resolved edges, inside check:layering.
26+
* Kill criterion: a maintainer decision that the CLI process may load daemon internals directly.
27+
*/
28+
export function checkDaemonClientEntry(
29+
sourceFiles: readonly string[],
30+
edges: readonly ResolvedImportEdge[],
31+
entries: readonly string[] = CLI_PROCESS_ENTRIES,
32+
): LayeringViolation[] {
33+
const stale = staleReachModules(
34+
DAEMON_CLIENT_ENTRY_RULE,
35+
'scripts/layering/daemon-client-entry.ts',
36+
entries,
37+
sourceFiles,
38+
'CLI_PROCESS_ENTRIES',
39+
);
40+
if (stale.length > 0) return stale;
41+
const policy = LOGICAL_MODULE_POLICIES.find(({ name }) => name === CLIENT_SIDE_POLICY_NAME);
42+
const isPolicyCovered = (file: string) =>
43+
policy?.roots.some((root) => matchesDeclaredRoot(file, root)) ?? false;
44+
const walk = walkProcessReach(
45+
entries,
46+
edges.filter((edge) => !edge.file.startsWith(DAEMON_SOURCE_ROOT)),
47+
(edge) => edge.target.startsWith(DAEMON_SOURCE_ROOT),
48+
);
49+
return walk.stopped
50+
.filter((edge) => !isPolicyCovered(edge.file))
51+
.map((edge) => ({
52+
rule: DAEMON_CLIENT_ENTRY_RULE,
53+
file: edge.file,
54+
line: edge.line,
55+
message:
56+
`the CLI process reaches daemon internals: ${edge.file} imports ${edge.target}. ` +
57+
`Chain: ${[...walk.chainTo(edge.file), edge.target].join(' -> ')}.`,
58+
}));
59+
}

‎scripts/layering/daemon-modularity.test.ts‎

Lines changed: 34 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ test('a production import of the daemon request/session-state modules outside th
8888
const edges = resolveImportEdges(
8989
new Map([
9090
[
91-
'src/remote/daemon-artifacts.ts',
91+
'src/commands/new-importer.ts',
9292
"import type { SessionState } from '../../packages/daemon/src/core/session-state.ts';",
9393
],
9494
['packages/daemon/src/core/session-state.ts', 'export type SessionState = { name: string };'],
@@ -97,10 +97,7 @@ test('a production import of the daemon request/session-state modules outside th
9797

9898
const violations = checkDaemonModularityRatchets(edges, REFERENCE, REFERENCE);
9999
assert.equal(violations.length, 1);
100-
assert.match(
101-
violations[0]!.message,
102-
/src\/remote\/daemon-artifacts\.ts imports a daemon request/,
103-
);
100+
assert.match(violations[0]!.message, /src\/commands\/new-importer\.ts imports a daemon request/);
104101
});
105102

106103
test('logical modules reject forbidden imports', () => {
@@ -656,28 +653,36 @@ test('R9 banks a shrink with no edit anywhere', () => {
656653
);
657654
});
658655

659-
for (const [kind, source] of [
660-
[
661-
'type-only',
662-
"import type { DaemonRequest } from '../../packages/daemon/src/core/daemon-request.ts';",
663-
],
664-
['value', "import { handle } from '../../packages/daemon/src/server/daemon-stop.ts';"],
665-
[
666-
'dynamic',
667-
"export const load = () => import('../../packages/daemon/src/server/daemon-stop.ts');",
668-
],
669-
] as const) {
670-
test(`the daemon client importing the daemon package is red (${kind})`, () => {
671-
const edges = resolveImportEdges(
672-
new Map([
673-
['src/daemon-client/daemon-client.ts', source],
674-
['packages/daemon/src/core/daemon-request.ts', 'export type DaemonRequest = object;'],
675-
['packages/daemon/src/server/daemon-stop.ts', 'export const handle = 1;'],
676-
]),
677-
);
678-
679-
const violations = checkDaemonModularityRatchets(edges, REFERENCE, REFERENCE);
680-
assert.equal(violations.length, 1);
681-
assert.match(violations[0]!.message, /daemon-client must not import packages\/daemon\/src/);
682-
});
656+
for (const file of [
657+
'src/cli.ts',
658+
'src/cli/commands/daemon.ts',
659+
'src/client/client-normalizers.ts',
660+
'src/remote/daemon-artifacts.ts',
661+
'src/daemon-client/daemon-client.ts',
662+
]) {
663+
for (const [kind, source] of [
664+
[
665+
'type-only',
666+
"import type { DaemonRequest } from '../packages/daemon/src/core/daemon-request.ts';",
667+
],
668+
['value', "import { handle } from '../packages/daemon/src/server/daemon-stop.ts';"],
669+
[
670+
'dynamic',
671+
"export const load = () => import('../packages/daemon/src/server/daemon-stop.ts');",
672+
],
673+
] as const) {
674+
test(`client-side ${file} importing the daemon package is red (${kind})`, () => {
675+
const edges = resolveImportEdges(
676+
new Map([
677+
[file, source.replaceAll('../', '../'.repeat(file.split('/').length - 1))],
678+
['packages/daemon/src/core/daemon-request.ts', 'export type DaemonRequest = object;'],
679+
['packages/daemon/src/server/daemon-stop.ts', 'export const handle = 1;'],
680+
]),
681+
);
682+
683+
const violations = checkDaemonModularityRatchets(edges, REFERENCE, REFERENCE);
684+
assert.equal(violations.length, 1);
685+
assert.match(violations[0]!.message, /client-side must not import packages\/daemon\/src/);
686+
});
687+
}
683688
}

0 commit comments

Comments
 (0)