Files
Michał Pierzchała dcd8b65d4c refactor(daemon): split src/daemon/types.ts into request types and session state (#2346)
* refactor(daemon): split daemon/types.ts into request and session-state modules

`src/daemon/types.ts` served two audiences from one file: the dispatch request
shape and the daemon's live session record. It also sat in the only daemon type
cycle — it imported `RefFrame` from `ref-frame.ts`, which imported `SessionState`
back — so neither file could be read in isolation.

Three modules replace it, each importing only downward:

- `daemon-request-wire.ts` declares `DaemonWireRequest`: a dispatched request
  with no `internal` key and no property path to `SessionState` or `DeviceLease`,
  so a consumer can read a request's command, flags and public metadata without
  depending on the session record.
- `daemon-request.ts` adds the daemon-only half (`DaemonRequestInternal`, which
  stays unexported) plus the response vocabulary.
- `session-state.ts` owns `SessionState` and the shapes only it holds.

The cycle is cut by `ref-frame-slot.ts`, declared below both `ref-frame.ts` and
`session-state.ts`: it owns the frame VALUE (the class stays unexported, so the
type remains nominal and unconstructible from outside), while `ref-frame.ts`
keeps every lifetime transition and every `session.refFrame` write.

No behavior change: every importer moves to the module owning the symbol it
uses, with no re-export shim at the old path. `client-normalizers.ts` takes
`SessionRuntimeHints` from `@agent-device/kernel/contracts`, which declares it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ujrc8LYmvM249WY8921J1Y

* test(daemon): assert the wire request shape cannot reach session state

A type-level walk over `DaemonWireRequest` fails `tsc` if the shape regains an
`internal` key or grows a property path back to `SessionState` or `DeviceLease`.
Positive controls over `DaemonRequest` prove the walk finds both when they are
there, so a walk that never matches anything cannot pass by accident.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ujrc8LYmvM249WY8921J1Y

* test(daemon): keep the three over-budget test files at their base length

Splitting `daemon/types.ts` turns one combined import into two in every file
that used both halves. Three of those test files are already over the 1,000-line
tripwire, where the size ratchet allows no growth, so each sheds one line that
was carrying nothing:

- `snapshot-handler.test.ts` and `find.test.ts` each drop a `toHaveLength`
  assertion an adjacent `toEqual` on an explicit array literal already makes.
- `session-replay-repair-transaction.test.ts` names the filtered close actions
  instead of wrapping the expression across three lines inside `expect`.

No assertion is weakened and no test content is removed. Splitting these files
along the modules they mirror is the standing remedy, but none of those modules
split here, so it stays out of this change and is tracked in #2353.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ujrc8LYmvM249WY8921J1Y

* chore(gates): point the daemon modularity and wire-compat gates at the split modules

R7 now locates the `SessionState` declaration by the declaration itself rather
than by a recorded path: `sessionStateWritePressure` measures the merge-base
tree too, and that tree still declares it in `daemon/types.ts` — a path constant
would measure it as zero pressure and bank the headroom.

R10's external-importer ratchet covers all three modules that replaced
`daemon/types.ts`, so moving a symbol between them cannot reopen the boundary to
a new outside zone. The recorded membership is unchanged: `client-normalizers.ts`
and `remote/daemon-artifacts.ts` both import `daemon-request.ts` only.

The daemon RPC closure gate waives `DaemonRequest`, `DaemonResponse` and
`DaemonArtifact` by path, so those three keys follow the declarations to
`daemon-request.ts`. `DaemonRequest`'s rationale now says what it is — the
server-side narrowing of the kernel declaration that fixes the wire shape —
rather than calling it a re-export alias.

The `live-state-shape` and session-resource declaration sites move with
`SessionState`; the depgraph lookalike fixture takes a new plausible path now
that `daemon/session-state.ts` is the real root.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ujrc8LYmvM249WY8921J1Y

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-06 12:36:54 +02:00

75 lines
3.1 KiB
TypeScript

// Catches: a session resource field (appLog, appLogFailure, audioProbe, perfCapture) written
// from outside its declared owner module — R7's session-state-ownership shape applied to the
// narrower set of per-resource fields these session-scoped runtimes carry, where the same
// aliasing hazard (get()/set() hand back and re-put the live reference) applies.
// Evidence: 7b48531d3b (#2081) retired ADR-0019 cutover scaffolding this policy protected during
// the runtime-command migration; 4454aef139 (#2092) removed what it retired.
// Cost: 115 LOC (57 rule + 58 test).
// Kill criterion: none enforced today; retire only by maintainer decision that per-owner write
// authority over appLog/appLogFailure/audioProbe/perfCapture no longer matters. The fields
// are plain mutable properties on the shared session record, so an outside write type-checks.
import { parseSync } from 'oxc-parser';
import { propertyName, visitAst } from './layering-ast.ts';
import type { LayeringViolation } from './model.ts';
type AstNode = Record<string, unknown>;
export const SESSION_RESOURCE_OWNERSHIP_RULE = 'R68 session-resource-ownership';
const RESOURCE_OWNERS: Readonly<Record<string, ReadonlySet<string>>> = {
appLog: new Set(['src/daemon/app-log-session-resource.ts', 'src/daemon/session-state.ts']),
appLogFailure: new Set(['src/daemon/app-log-session-resource.ts', 'src/daemon/session-state.ts']),
audioProbe: new Set([
'src/daemon/audio-probe-session-resource.ts',
'src/daemon/session-state.ts',
]),
perfCapture: new Set([
'src/daemon/perf-capture-session-resource.ts',
'src/daemon/session-state.ts',
]),
};
/** Durable session-resource records have one whole-record construction owner per domain. */
export function sessionResourceOwnershipViolations(
sources: ReadonlyMap<string, string>,
): LayeringViolation[] {
const violations: LayeringViolation[] = [];
for (const [file, source] of sources) {
if (!file.startsWith('src/daemon/')) continue;
const program = parseSync(file, source).program as AstNode;
visitAst(program, (node) => {
if (node['type'] !== 'Property' || node['kind'] !== 'init' || node['computed'] === true) {
return;
}
const field = propertyName(node['key']);
if (field === undefined) return;
const owners = RESOURCE_OWNERS[field];
if (
owners === undefined ||
owners.has(file) ||
isTeardownDiscriminant(field, node['value'])
) {
return;
}
const offset = typeof node['start'] === 'number' ? node['start'] : 0;
violations.push({
rule: SESSION_RESOURCE_OWNERSHIP_RULE,
file,
line: source.slice(0, offset).split('\n').length,
message: `session ${field} record constructed outside its owner`,
});
});
}
return violations;
}
function isTeardownDiscriminant(field: string, valueNode: unknown): boolean {
if (field !== 'appLog' || valueNode === null || typeof valueNode !== 'object') return false;
const value = valueNode as AstNode;
return (
value['type'] === 'Literal' &&
(value['value'] === 'run' || value['value'] === 'already-settled')
);
}