Skip to content

Commit 3b71fee

Browse files
thymikeeclaude
andauthored
refactor(layering): rank every root module so R5 sees through (root) (#3288)
* refactor(remote): read the remote temp artifact path from the daemon HTTP contract The macos-app lease recognized a remote client's temp artifact path by value-importing src/remote/daemon-artifacts.ts, while src/remote/ imports the daemon's session artifact paths: remote and daemon-server formed a zone-level cycle. The path format (builder and recognizer) is client/daemon wire vocabulary, so it moves verbatim into @agent-device/contracts/daemon-http, which both sides already load; the daemon no longer loads the remote upload client to check a path shape. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * fix(contracts): read the remote temp artifact extension the way the builder writes it buildRemoteTempArtifactPath dotted a bare extension ('png' -> '.png') but isRemoteTempArtifactPath stripped and re-appended the extension as given, so a path the builder produced for 'png' failed the check for 'png'. Both now go through one dottedExtension helper. Every production caller passes '.png' today, so no admitted path changes. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * chore(gates): rank every root module and reject zone-level value cycles (#3280) R5 could not see through the unranked (root) zone: nine zones formed one value cycle through it, and src/sdk/index.ts and src/ai-sdk/index.ts (rank 4) reached daemon-client (rank 5) through src/agent-device-client.ts. - scripts/layering/root-module-zones.ts declares the zone of every src/*.ts module, and targetDagZone reads it. (root) ranks above the spine (9) and holds only bin.ts, cli.ts and daemon.ts, so a ranked import of any undeclared root module is an R5 back-edge. New zones: daemon-contracts (2), command-runtime (3), platform-runtime (4, now including its private src/platform-runtime/ submodule) and platform-runtime-host (8: every spine zone reaches it only through loadHost's import(), so a static import of the lazy host is a back-edge from any of them; its facets read daemon session artifacts). core takes the two root modules it imports; daemon-client takes agent-device-client.ts. - With that declaration and the old ranks, the gate reports exactly the two known inversions (sdk -> daemon-client, ai-sdk -> daemon-client). The published SDK entries must export a client that reaches the daemon with no injected transport, so no code change removes that dependency: sdk and ai-sdk move to rank 6 above daemon-client, cli to 7. - R80 zone-value-dag projects static value imports onto zones and rejects any cycle, which catches same-rank pairs R5 cannot order. - Dynamic imports stay out of R5 and R80; the reason is recorded at R5 in check.ts. R6 now measures seven type-only inversions the unranked root hid (commands -> daemon-client, core -> platform-runtime, core -> platform-runtime-host, plugins -> sdk, and three platform-runtime -> platform-runtime-host types of lazily loaded host modules), ratcheted equally at the merge-base. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 8ccec5b commit 3b71fee

12 files changed

Lines changed: 509 additions & 66 deletions

‎docs/dependency-graph-findings.md‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@ type-only inversions, R7 pins SessionState field ownership, and the shared selec
7474
(`daemon/interaction/internal/interaction-common.ts`, step 3) and the recorder boundary
7575
(`session-action-recorder.ts`, step 4). The two-pass structure is two call sites, not a scattered
7676
concern.
77-
- Still outside every rule: **dynamic** import direction (0 inversions today, nothing watching),
78-
and anything inside a zone.
77+
- Still outside every rule: **dynamic** import direction, out of scope by decision with the reason
78+
recorded at R5 in `scripts/layering/check.ts` (#3280), and anything inside a zone.
7979

8080
## 0. Where the inversions ended up (and why 5 is the floor for now)
8181

@@ -263,6 +263,16 @@ moving `DaemonRequest` is most of what §1's second cluster needs.
263263

264264
## 3. `(root)`: what is left is there for a reason
265265

266+
> **Status after #3280:** the section below is historical. Every root module now declares its zone
267+
> in `scripts/layering/root-module-zones.ts`, `(root)` ranks above the spine and holds only
268+
> `bin.ts`, `cli.ts` and `daemon.ts`, and R80 asserts that the zone graph of static value imports is
269+
> acyclic. That reduces `(root)` in the logical graph only: the modules still live directly under
270+
> `src/`, and the declaration is a bridge whose rows go as groups move into zone folders or
271+
> packages. The physical moves remain outstanding, starting with #3294. Ranking the composition roots did not weaken R2: it still rejects a direct `daemon/` ->
272+
> `commands/` import, and the daemon reaches the command surface through the ranked
273+
> `command-runtime` zone, which the zone graph now shows instead of hiding. The SDK entries rank
274+
> above `daemon-client`, because the typed client they publish reaches the daemon through it.
275+
266276
13 files: 11 published `package.json` entrypoints, the three executables (`bin.ts`, `cli.ts`,
267277
`daemon.ts`), and the composition roots — `runtime.ts`, `agent-device-client.ts`,
268278
`provider-device-runtime.ts`, `command-catalog.ts`.

‎packages/contracts/src/daemon-http.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@ import {
66
buildDaemonHttpBaseUrl,
77
buildDaemonHttpTenantHeaders,
88
buildDaemonHttpUrl,
9+
buildRemoteTempArtifactDirPath,
10+
buildRemoteTempArtifactPath,
911
DAEMON_RPC_PROTOCOL_VERSION,
12+
isRemoteTempArtifactPath,
1013
} from './daemon-http.ts';
1114

1215
test('buildDaemonHttpBaseUrl appends the public agent-device base path', () => {
@@ -64,3 +67,33 @@ test('buildDaemonHealthPayload takes the version from its caller and keeps the p
6467
},
6568
);
6669
});
70+
71+
test('the daemon recognizes every temp path a remote client names, however the extension is spelled', () => {
72+
for (const built of ['png', '.png']) {
73+
for (const checked of ['png', '.png']) {
74+
assert.equal(
75+
isRemoteTempArtifactPath(
76+
buildRemoteTempArtifactPath('screenshot', built),
77+
'screenshot',
78+
checked,
79+
),
80+
true,
81+
`built with '${built}', checked with '${checked}'`,
82+
);
83+
}
84+
}
85+
});
86+
87+
test('a temp path of another prefix, a directory, or an escape is not a remote temp artifact', () => {
88+
const screenshot = buildRemoteTempArtifactPath('screenshot', '.png');
89+
assert.equal(isRemoteTempArtifactPath(screenshot, 'recording', '.png'), false);
90+
assert.equal(
91+
isRemoteTempArtifactPath(buildRemoteTempArtifactDirPath('screenshot'), 'screenshot', '.png'),
92+
false,
93+
);
94+
assert.equal(isRemoteTempArtifactPath(`${screenshot}/../x.png`, 'screenshot', '.png'), false);
95+
assert.equal(
96+
isRemoteTempArtifactPath('/Users/me/agent-device-screenshot-1-a.png', 'screenshot', '.png'),
97+
false,
98+
);
99+
});

‎packages/contracts/src/daemon-http.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
import path from 'node:path';
2+
13
// The daemon HTTP wire vocabulary shared by the daemon server, the remote
24
// proxy, and every client that talks to them: the base path, the tenant and
3-
// network-access header names, the URL/auth/tenant header builders, and the
4-
// /health payload. Client and server must agree on all of it, so neither side
5+
// network-access header names, the URL/auth/tenant header builders, the
6+
// /health payload, and the temp artifact paths a remote client names on the
7+
// daemon host. Client and server must agree on all of it, so neither side
58
// owns it (ADR 0006).
69
export const DAEMON_HTTP_BASE_PATH = '/agent-device';
710
export const DAEMON_HTTP_TENANT_HEADER = 'x-agent-device-tenant';
@@ -83,3 +86,43 @@ export function buildDaemonHealthPayload(
8386
...(options.upstream !== undefined ? { upstream: options.upstream } : {}),
8487
};
8588
}
89+
90+
// A remote client names a daemon-host temp path for each artifact it downloads afterwards, and the
91+
// daemon accepts exactly that shape where it otherwise refuses host paths.
92+
const REMOTE_TEMP_DIR = '/tmp';
93+
94+
/** The daemon-host temp path a remote client names for an artifact it downloads afterwards. */
95+
export function buildRemoteTempArtifactPath(prefix: string, extension: string): string {
96+
return path.posix.join(
97+
REMOTE_TEMP_DIR,
98+
`${remoteTempArtifactStem(prefix)}${dottedExtension(extension)}`,
99+
);
100+
}
101+
102+
/** A directory temp path — unlike `buildRemoteTempArtifactPath`, no extension is ever appended. */
103+
export function buildRemoteTempArtifactDirPath(prefix: string): string {
104+
return path.posix.join(REMOTE_TEMP_DIR, remoteTempArtifactStem(prefix));
105+
}
106+
107+
/** Whether `value` has the shape `buildRemoteTempArtifactPath(prefix, extension)` returns. */
108+
export function isRemoteTempArtifactPath(
109+
value: string,
110+
prefix: string,
111+
extension: string,
112+
): boolean {
113+
const dotted = dottedExtension(extension);
114+
const stem = path.posix.basename(value, dotted);
115+
return (
116+
value === path.posix.join(REMOTE_TEMP_DIR, `${stem}${dotted}`) &&
117+
stem.startsWith(`agent-device-${prefix}-`) &&
118+
/^\d+-[a-z0-9]+$/.test(stem.slice(`agent-device-${prefix}-`.length))
119+
);
120+
}
121+
122+
function dottedExtension(extension: string): string {
123+
return extension.startsWith('.') ? extension : `.${extension}`;
124+
}
125+
126+
function remoteTempArtifactStem(prefix: string): string {
127+
return `agent-device-${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
128+
}

‎scripts/layering/check.ts‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
//
44
// Ranked target spine, as rank groups lowest to highest. `A ◄ B` means B may not
55
// be outranked by A (the back-edge order the gate rejects), NOT that every displayed import exists:
6-
// { contracts, request, selectors } ◄ core ◄ commands
7-
// ◄ { client, daemon-server } ◄ daemon-client ◄ cli
8-
// (authoritative ranks: `TARGET_DAG_RANK` in model.ts. The former rank-0 kernel
9-
// zone lives in packages/kernel since #1490 W0; R11 owns its boundary.)
6+
// { contracts, selectors, ... } ◄ { core, daemon-contracts } ◄ { commands, command-runtime }
7+
// ◄ { client, daemon-server, platform-runtime, ... } ◄ daemon-client ◄ { sdk, ai-sdk }
8+
// ◄ cli ◄ platform-runtime-host ◄ (root)
9+
// (authoritative ranks: `TARGET_DAG_RANK` in model.ts; root modules declare their zone in
10+
// root-module-zones.ts. The former rank-0 kernel zone lives in packages/kernel since #1490 W0;
11+
// R11 owns its boundary.)
1012
// `commands/schema/` renders the rest of commands/'s facets and reads them; commands never
1113
// imports it back (#2543). It shares the commands zone (#2679 folded the standalone
1214
// cli-schema zone into it), so the ranked spine and the R2 zone-policy table cannot see the
@@ -22,6 +24,8 @@
2224
// - Over the RANKED SPINE only: rejection of every spine back-edge (R5), i.e.
2325
// an import whose source zone outranks its target zone, plus a ratchet on the
2426
// same inversion measured over TYPE-ONLY edges (R6).
27+
// - Over the ZONE GRAPH: static value imports between zones form no cycle (R80), which R5
28+
// cannot see between two zones of the same rank.
2529
// - Over the DAEMON and its capture-admission adapters: SessionState field ownership (R7), because the session
2630
// record is store-owned mutable state that any daemon module can write; and the terminal
2731
// concrete-platform boundary (R65), which rejects every import form into the retired
@@ -52,9 +56,9 @@
5256
// R6, R9, and the R10 R7 counts are ratchets with no written-down reference: each is the same
5357
// measurement taken over the merge-base with origin/main (`ratchet-reference.ts`), so growth
5458
// fails, a shrink needs no edit, and no change can bank headroom.
55-
// `(root)` holds entrypoints and composition roots. The retired `src/utils` zone is deliberately
56-
// outside the spine and is rejected separately by R14; extracted workspace package zones are
57-
// classified separately and held behind R11 instead of the src folder spine.
59+
// `(root)` holds the executables and ranks above the spine. The retired `src/utils` zone is
60+
// deliberately outside the spine and is rejected separately by R14; extracted workspace package
61+
// zones are classified separately and held behind R11 instead of the src folder spine.
5862

5963
import { execFileSync } from 'node:child_process';
6064
import fs from 'node:fs';
@@ -79,6 +83,7 @@ import {
7983
type ResolvedImportEdge,
8084
} from './model.ts';
8185
import { checkTypeInversions } from './type-inversion-ratchet.ts';
86+
import { checkZoneValueDag } from './zone-value-dag.ts';
8287
import {
8388
measureRatchets,
8489
mergeBaseRatchets,
@@ -237,6 +242,15 @@ function checkRecordRuntimeOwnership(sources: ReadonlyMap<string, string>): Laye
237242
* import direction no longer matters. Splitting zones into packages would not replace it: the
238243
* A4 spike found an undeclared workspace package still resolves through root node_modules and
239244
* a relative tunnel into another package's src still compiles.
245+
* Scope: static value imports. Dynamic imports are out of scope for R5 and R80 by decision
246+
* (#3280). An `import()` target never joins the importer's eager closure, so a lazy edge cannot
247+
* cost what a value back-edge costs, and the code places lazy seams exactly where a module
248+
* defers one ranked above it or one that depends back on it: `cli/process-entry.ts` loads
249+
* `cli.ts`, the MCP tools load the typed client, the daemon's provider registry loads the
250+
* Limrun runtime from `src/sdk/`, and the platform runtime loads its operation host
251+
* (`loadHost`), which reads daemon session artifacts. Ranking them would reject that pattern
252+
* rather than a mistake; what a lazy edge may load is owned by R13's laziness policy and the
253+
* eager-closure budgets.
240254
*/
241255
function checkBackEdges(edges: readonly ResolvedImportEdge[]): LayeringViolation[] {
242256
const seen = new Set<string>();
@@ -398,7 +412,8 @@ function report(
398412
process.stdout.write(
399413
`Layering guard: OK — ${files.length} source files satisfy R2 and contain no ` +
400414
`value-import cycles (both checked globally); the ranked target spine contains no ` +
401-
`back-edges; the ranked spine's type-only inversions hold at or under the merge-base ` +
415+
`back-edges and the zone graph no value-import cycle (R80); the ranked spine's ` +
416+
`type-only inversions hold at or under the merge-base ` +
402417
`${reference.ref.slice(0, 10)} per zone pair (R6, ${inversions} remaining); ` +
403418
`${RETIRED_PATH_RULES.R14.rule} permits no tracked paths under retired src/utils; ` +
404419
`all ${sessionStateFieldCount()} SessionState fields are classified and every write is ` +
@@ -473,6 +488,7 @@ export const LAYERING_RULE_IDS = [
473488
'substrate-domain-shape',
474489
'selector-pipeline-ownership',
475490
'back-edges',
491+
'zone-value-dag',
476492
'type-spine-inversions',
477493
'session-state-ownership',
478494
'daemon-modularity-ratchets',
@@ -514,6 +530,7 @@ export const LAYERING_RULES: Readonly<Record<LayeringRuleId, LayeringRule>> = {
514530
'selector-pipeline-ownership': (context) =>
515531
selectorPipelineOwnershipViolations(context.edges, workspaceSpecifierTargets(repoRoot)),
516532
'back-edges': (context) => checkBackEdges(context.edges),
533+
'zone-value-dag': (context) => checkZoneValueDag(context.edges),
517534
'type-spine-inversions': (context) =>
518535
checkTypeInversions(context.edges, context.reference.typeInversions),
519536
'session-state-ownership': (context) => checkSessionStateOwnership(context.sources),

‎scripts/layering/model.test.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -285,12 +285,11 @@ test('ranked and unranked zones are disjoint and both non-empty', () => {
285285
test('classifyZone separates the ranked spine from intentionally-unranked zones', () => {
286286
assert.equal(classifyZone('contracts'), 'ranked');
287287
assert.equal(classifyZone('daemon-server'), 'ranked');
288-
assert.equal(classifyZone('(root)'), 'unranked');
289-
assert.equal(classifyZone('platform-runtime'), 'unranked');
290288
assert.equal(classifyZone('platforms'), 'unclassified');
291289
assert.equal(classifyZone('utils'), 'unclassified');
292-
// Every satellite zone joined the spine; only the composition root stays out, because R2
293-
// forbids daemon/ from importing commands/ so the files that wire them cannot be ranked.
290+
// Every src/ zone is on the spine, `(root)` and the zones root modules declare included.
291+
assert.equal(classifyZone('(root)'), 'ranked');
292+
assert.equal(classifyZone('platform-runtime'), 'ranked');
294293
assert.equal(classifyZone('mcp'), 'ranked');
295294
assert.equal(classifyZone('screenshot-diff'), 'ranked');
296295
// A zone that is neither ranked nor listed peripheral must be flagged, never
@@ -302,7 +301,7 @@ test('every production zone is deliberately classified as ranked or unranked', (
302301
// Drift guard: a new src/<folder>/ (or a daemon-client/server split) forces a
303302
// deliberate ranked-vs-peripheral decision here instead of silently escaping
304303
// spine back-edge detection. If this fails, add the new zone to TARGET_DAG_RANK
305-
// (ranked spine) or UNRANKED_ZONES (root/peripheral) in model.ts.
304+
// (ranked spine) or UNRANKED_ZONES (peripheral) in model.ts.
306305
const productionFiles = listSourceFiles();
307306
assert.deepEqual(unclassifiedZones(productionFiles), []);
308307

‎scripts/layering/model.ts‎

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from 'node:path';
22
import { PLATFORMS } from '@agent-device/kernel/device';
33
import { parseSync } from 'oxc-parser';
44
import { destructuredDynamicImportBindings, visitAst } from './layering-ast.ts';
5+
import { declaredRootModuleZone } from './root-module-zones.ts';
56

67
export type ImportEdge = {
78
spec: string;
@@ -56,17 +57,24 @@ const TARGET_DAG_RANK = new Map([
5657
['selectors', 1],
5758
['session-journal', 1],
5859
['core', 2],
60+
['daemon-contracts', 2],
61+
['command-runtime', 3],
5962
['commands', 3],
6063
['mcp', 3],
61-
['ai-sdk', 4],
6264
['client', 4],
6365
['daemon-server', 4],
6466
['metro', 4],
67+
['platform-runtime', 4],
6568
['remote', 4],
66-
['sdk', 4],
6769
['plugins', 4],
6870
['daemon-client', 5],
69-
['cli', 6],
71+
// The SDK entries publish the typed client, which reaches the daemon through daemon-client.
72+
['ai-sdk', 6],
73+
['sdk', 6],
74+
['cli', 7],
75+
// Reached only through `loadHost`'s import(), so every spine zone ranks below it.
76+
['platform-runtime-host', 8],
77+
['(root)', 9],
7078
]);
7179

7280
export const RANKED_ZONES: ReadonlySet<string> = new Set(TARGET_DAG_RANK.keys());
@@ -81,25 +89,19 @@ export function zoneRank(zone: string): number | null {
8189
}
8290

8391
// Zones deliberately left OUT of the src folder spine. They are NOT unenforced:
84-
// every file remains under the global value-cycle rule (R4). `(root)` composes
85-
// the spine from above; extracted package zones are held by R11 package exports
86-
// and the no-root-back-import rule instead of their former src folder rank.
92+
// every file remains under the global value-cycle rule (R4) and the zone-level value DAG
93+
// (R80). Extracted package zones are held by R11 package exports and the no-root-back-import
94+
// rule instead of a src folder rank.
8795
//
88-
// The satellite zones used to be listed here too, on the grounds that ranking them would
89-
// invent an order the architecture had not committed to. Once `(root)` was emptied of shared
90-
// contracts, every one of them turned out to have a consistent rank already — so the order was
91-
// there, just unasserted. The former `utils` zone was retired into owning modules and packages.
92-
// Extracted workspace packages are not src/ zones: R11 owns their physical seams, and their zone
93-
// names only appear in workspace-aware graphs. The platform packages additionally carry R13's
96+
// Every other src/ zone is ranked, `(root)` included: root modules declare their zone in
97+
// `root-module-zones.ts`, and `(root)` ranks above the spine. Extracted workspace packages are
98+
// not src/ zones: R11 owns their physical seams, and their zone names only appear in
99+
// workspace-aware graphs. The platform packages additionally carry R13's
94100
// exact-family/composition/laziness policy.
95101
export const UNRANKED_ZONES: ReadonlySet<string> = new Set([
96-
'(root)',
97102
// Stand-ins the bundler resolves in place of a dependency it deliberately omits. Nothing in
98103
// the production graph imports them, so ranking them would claim an edge the alias replaces.
99104
'vendor',
100-
// Private implementation submodules of the canonical root composition. R13 owns their exact
101-
// importer and concrete-platform authority; giving them a spine rank would duplicate that seam.
102-
'platform-runtime',
103105
'kernel',
104106
'host-kit',
105107
'capture-kit',
@@ -294,7 +296,7 @@ export function targetDagZone(file: string): string {
294296
// #2342 relocated the daemon client to its own `src/daemon-client/` folder, so the
295297
// client zone now falls out of the folder itself; `src/daemon/` is server-only.
296298
if (file.startsWith('src/daemon/')) return 'daemon-server';
297-
return topFolder(file);
299+
return declaredRootModuleZone(file) ?? topFolder(file);
298300
}
299301

300302
// The set of zones every production file resolves into. A zone that is neither ranked

0 commit comments

Comments
 (0)