Skip to content

Commit 233a34d

Browse files
thymikeeclaude
andauthored
refactor(daemon): extract the session event journal into a workspace package (#2361)
* refactor(daemon): extract the session event journal into a workspace package `src/daemon/session-event-*.ts` (6 modules) and `src/core/keyboard-actions.ts` move as git renames into a new private package `@agent-device/session-journal`. One subpath per moved module points straight at the moved file; no `index.ts`, no re-export at any old path. Every consumer switches to the owning specifier. The journal's request-shaped inputs now name `DaemonRequest`/`DaemonResponse`/ `DaemonResponseData` from `@agent-device/kernel/contracts` instead of the daemon's own `daemon-request.ts`, which the package may not reach (R11) and which carries `internal` with its `SessionState` callbacks and admitted `DeviceLease`. The response types were already re-exports of the kernel ones, so no shape changes; the request type narrows to the four fields the journal reads. A type-level test reads every request-shaped parameter off the real signatures and asserts the reachable type graph declares no `internal` key, holds nothing shaped like a live session record or a `DeviceLease`, and carries no callback. The daemon reaches the journal only by workspace specifier now, so the code-signature walk gets the same pin the descriptor registry got: a walk stopping at the package boundary would report an unchanged signature after an entry-shape or retention-window edit, and a client would keep reusing a daemon writing the superseded journal. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XUhCzFDpMU92EM8o3tjRhy * chore(gates): rank the session-journal package on the layering spine R6's drift guard requires every production zone to be a deliberate ranked-or-unranked decision. `session-journal` is vocabulary the daemon reads a dispatched request through, so it takes rank 1 beside `command-registry` and `contracts` rather than the unranked kit treatment: its only ranked edges are to same-rank zones, which is not a back-edge. No `APPROVED_OVER_CEILING` row and no fallow baseline edit: rename detection carries all seven moved entries' merge-base closures, so each falls under the no-growth rule, and no baseline entry was keyed on the old paths. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01XUhCzFDpMU92EM8o3tjRhy --------- Co-authored-by: Claude Opus 5 <[email protected]>
1 parent 51ed621 commit 233a34d

30 files changed

Lines changed: 287 additions & 19 deletions

‎docs/adr/0018-unified-event-journal.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ redaction discipline, and sink (inventoried 2026-07-24):
5959
`phaseCounts` tally, and debug-mode live streaming to the per-request ndjson file (after
6060
`createRequestExecutionScope` rebinds `logPath`), `daemon.log`, or stderr. The
6161
`traceLogPath` scope option is dead: no call site ever sets it.
62-
2. **Session event log** (`src/daemon/session-event-log.ts`). Append-only per-session
62+
2. **Session event log** (`@agent-device/session-journal/session-event-log`). Append-only per-session
6363
`events.ndjson` with kinds `request.started`/`request.finished`/`action.recorded`, written from
6464
three request-lifecycle points plus `SessionStore.recordAction`, read only by the public
6565
`events` command. `action.recorded` is already a projection of `session.actions` pushes — the

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@
167167
"check:unit": "pnpm test:unit && pnpm check:tmpdir-leaks && pnpm test:smoke",
168168
"check": "pnpm check:tooling && pnpm check:fallow && pnpm check:unit",
169169
"prepack": "pnpm check:mcp-metadata && pnpm package:npm",
170-
"typecheck": "tsc -b packages/xml packages/kernel packages/contracts packages/host-kit packages/capture-kit packages/managed-allocation packages/provision-kit packages/platform-apple packages/platform-android packages/platform-harmonyos packages/platform-vega packages/platform-linux packages/platform-web packages/ad-script packages/selectors packages/command-registry packages/ad-replay packages/maestro packages/replay-test packages/provider-webdriver packages/provider-limrun && tsc -p tsconfig.json && tsc -p examples/sdk/tsconfig.json",
170+
"typecheck": "tsc -b packages/xml packages/kernel packages/contracts packages/host-kit packages/capture-kit packages/managed-allocation packages/provision-kit packages/platform-apple packages/platform-android packages/platform-harmonyos packages/platform-vega packages/platform-linux packages/platform-web packages/ad-script packages/selectors packages/command-registry packages/session-journal packages/ad-replay packages/maestro packages/replay-test packages/provider-webdriver packages/provider-limrun && tsc -p tsconfig.json && tsc -p examples/sdk/tsconfig.json",
171171
"test-app:install": "pnpm install --dir examples/test-app",
172172
"test-app:start": "pnpm --dir examples/test-app start",
173173
"test-app:ios": "pnpm --dir examples/test-app ios",
@@ -294,6 +294,7 @@
294294
"@agent-device/provision-kit": "workspace:*",
295295
"@agent-device/replay-test": "workspace:*",
296296
"@agent-device/selectors": "workspace:*",
297+
"@agent-device/session-journal": "workspace:*",
297298
"@agent-device/xml": "workspace:*",
298299
"@arethetypeswrong/cli": "^0.18.5",
299300
"@chenglou/freerange": "^0.0.4",

‎packages/host-kit/src/code-signature.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,26 @@ test('the daemon source graph stamps the command descriptor registry package', (
134134
assert.ok(labels.includes(owned), `${owned} is missing from the daemon code graph`);
135135
}
136136
});
137+
138+
/**
139+
* The same claim for the ADR 0018 event journal (#2341). The daemon writes and reads
140+
* `events.ndjson` only through this package's workspace subpaths, so a walk that stopped at the
141+
* package boundary would report an unchanged signature after an entry-shape or retention-window
142+
* edit, and a client would keep reusing a daemon writing the superseded journal. The manifest is
143+
* asserted beside the sources because its `exports` map is what chose them.
144+
*/
145+
test('the daemon source graph stamps the session event journal package', () => {
146+
const repoRoot = path.resolve(import.meta.dirname, '..', '..', '..');
147+
const entryPath = path.join(repoRoot, 'src', 'daemon.ts');
148+
if (!fs.existsSync(entryPath)) return;
149+
150+
const labels = labelsOf(entryPath, repoRoot);
151+
for (const owned of [
152+
'packages/session-journal/src/session-event-log.ts',
153+
'packages/session-journal/src/session-event-log-window.ts',
154+
'packages/session-journal/src/session-event-action.ts',
155+
'packages/session-journal/package.json',
156+
]) {
157+
assert.ok(labels.includes(owned), `${owned} is missing from the daemon code graph`);
158+
}
159+
});
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
{
2+
"name": "@agent-device/session-journal",
3+
"version": "0.0.0",
4+
"private": true,
5+
"sideEffects": false,
6+
"type": "module",
7+
"description": "The ADR 0018 unified request event journal: the append-only per-session event log, its rotation window and line scanner, and the presentation projections that turn a dispatched request or action into a journal entry.",
8+
"dependencies": {
9+
"@agent-device/command-registry": "workspace:*",
10+
"@agent-device/contracts": "workspace:*",
11+
"@agent-device/host-kit": "workspace:*",
12+
"@agent-device/kernel": "workspace:*"
13+
},
14+
"exports": {
15+
"./session-event-log": {
16+
"types": "./src/session-event-log.ts",
17+
"default": "./src/session-event-log.ts"
18+
},
19+
"./session-event-log-lines": {
20+
"types": "./src/session-event-log-lines.ts",
21+
"default": "./src/session-event-log-lines.ts"
22+
},
23+
"./session-event-log-window": {
24+
"types": "./src/session-event-log-window.ts",
25+
"default": "./src/session-event-log-window.ts"
26+
},
27+
"./session-event-request": {
28+
"types": "./src/session-event-request.ts",
29+
"default": "./src/session-event-request.ts"
30+
},
31+
"./session-event-action": {
32+
"types": "./src/session-event-action.ts",
33+
"default": "./src/session-event-action.ts"
34+
},
35+
"./session-event-action-presentation": {
36+
"types": "./src/session-event-action-presentation.ts",
37+
"default": "./src/session-event-action-presentation.ts"
38+
},
39+
"./keyboard-actions": {
40+
"types": "./src/keyboard-actions.ts",
41+
"default": "./src/keyboard-actions.ts"
42+
}
43+
}
44+
}
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import type { DeviceInfo } from '@agent-device/kernel/device';
2+
import type { DeviceLease } from '@agent-device/contracts/device';
3+
import { expectTypeOf, test } from 'vitest';
4+
import { buildActionEventResult } from '../session-event-action-presentation.ts';
5+
import {
6+
buildRequestFinishedEvent,
7+
buildRequestStartedEvent,
8+
shouldRecordEventForRequest,
9+
} from '../session-event-log.ts';
10+
import {
11+
buildRequestSuccessEventPresentation,
12+
readRequestedScreenshotFileName,
13+
} from '../session-event-request.ts';
14+
15+
/**
16+
* Every request-shaped parameter this package accepts, read off the real signatures rather than
17+
* restated. Widening any one of them back to the daemon's own `DaemonRequest` — the type that
18+
* carries `internal` with its `SessionState` callbacks and admitted `DeviceLease` — changes this
19+
* union, and the assertions below stop holding.
20+
*/
21+
type JournalRequestInput =
22+
| Parameters<typeof buildRequestStartedEvent>[0]['req']
23+
| Parameters<typeof buildRequestFinishedEvent>[0]['req']
24+
| Parameters<typeof shouldRecordEventForRequest>[0]
25+
| Parameters<typeof buildRequestSuccessEventPresentation>[0]
26+
| Parameters<typeof readRequestedScreenshotFileName>[0]
27+
| Parameters<typeof buildActionEventResult>[0];
28+
29+
type Primitive = string | number | boolean | bigint | symbol | null | undefined;
30+
31+
/**
32+
* Recursion budget. Six is not asserted to be deep enough by inspection: the last assertion in
33+
* this file walks again at twelve and requires the two answers to be identical, so a budget that
34+
* stopped short of some path would show up as a type the deeper walk found and this one did not.
35+
*/
36+
type Budget = [0, 0, 0, 0, 0, 0];
37+
38+
/** Twice the budget, for the saturation check. */
39+
type DoubleBudget = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
40+
41+
/**
42+
* `T`'s own declared keys, with index signatures dropped. Keeping `string` would silently absorb
43+
* every literal beside it in a union (`string | 'internal'` reduces to `string`), which would make
44+
* the assertion below vacuous the moment a `Record<string, unknown>` appears on a path — and one
45+
* does, at `flags`. A record that could hold an `internal` property is not a declared route to
46+
* session state; a declared `internal` key is.
47+
*/
48+
type DeclaredKeys<T> = keyof { [K in keyof T as string extends K ? never : K]: 0 };
49+
50+
/** Every declared property NAME reachable from `T`, arrays entered through their element type. */
51+
type ReachableKeys<
52+
T,
53+
Cap extends readonly unknown[],
54+
Depth extends readonly unknown[] = [],
55+
> = Depth['length'] extends Cap['length']
56+
? never
57+
: [T] extends [Primitive]
58+
? never
59+
: [T] extends [(...args: never[]) => unknown]
60+
? never
61+
: T extends readonly (infer Element)[]
62+
? ReachableKeys<Element, Cap, [...Depth, 0]>
63+
: T extends object
64+
?
65+
| DeclaredKeys<T>
66+
| { [K in keyof T]-?: ReachableKeys<NonNullable<T[K]>, Cap, [...Depth, 0]> }[keyof T]
67+
: never;
68+
69+
/**
70+
* Every property TYPE reachable from `T`. Arrays are entered through their element type, and a
71+
* function through its PARAMETERS: that is how the daemon's `internal` actually hands out a live
72+
* session record (`beforeDispatch?: (session: SessionState) => …`), so a walk that treated a
73+
* callback as a leaf would never see the very route this file exists to reject.
74+
*/
75+
type ReachableTypes<
76+
T,
77+
Cap extends readonly unknown[],
78+
Depth extends readonly unknown[] = [],
79+
> = Depth['length'] extends Cap['length']
80+
? never
81+
: [T] extends [Primitive]
82+
? never
83+
: [T] extends [(...args: never[]) => unknown]
84+
? ReachableTypes<Parameters<T>, Cap, [...Depth, 0]>
85+
: T extends readonly (infer Element)[]
86+
? Element | ReachableTypes<Element, Cap, [...Depth, 0]>
87+
: T extends object
88+
? {
89+
[K in keyof T]-?:
90+
| NonNullable<T[K]>
91+
| ReachableTypes<NonNullable<T[K]>, Cap, [...Depth, 0]>;
92+
}[keyof T]
93+
: never;
94+
95+
/**
96+
* The structural minimum of `src/daemon/session-state.ts`'s `SessionState`. The package may not
97+
* import that module (R11), so the live session record is named by the three required fields no
98+
* other shape in the public request vocabulary carries together. Anything typed as `SessionState`
99+
* is assignable to this, which is what `Extract` needs.
100+
*/
101+
type LiveSessionRecord = { name: string; device: DeviceInfo; createdAt: number };
102+
103+
/** A callback of any arity — the form `SessionState` takes when it reaches a request. */
104+
type AnyCallback = (...args: never[]) => unknown;
105+
106+
test('the journal reads a request shape with no route to daemon-private session state', () => {
107+
// ADR 0018's journal is durable and rendered outside the daemon. Its input is the public
108+
// request vocabulary of `@agent-device/kernel/contracts`: `command`, `flags`, `meta.requestId`
109+
// and `meta.clientArtifactPaths`. The daemon's own request type adds `internal`, whose members
110+
// hand out `SessionState` and an admitted `DeviceLease`; taking it here would put a live
111+
// session record on a path the journal could serialize.
112+
expectTypeOf<
113+
Extract<ReachableKeys<JournalRequestInput, Budget>, 'internal'>
114+
>().toEqualTypeOf<never>();
115+
expectTypeOf<
116+
Extract<ReachableTypes<JournalRequestInput, Budget>, LiveSessionRecord>
117+
>().toEqualTypeOf<never>();
118+
expectTypeOf<
119+
Extract<ReachableTypes<JournalRequestInput, Budget>, DeviceLease>
120+
>().toEqualTypeOf<never>();
121+
expectTypeOf<
122+
Extract<ReachableTypes<JournalRequestInput, Budget>, AnyCallback>
123+
>().toEqualTypeOf<never>();
124+
});
125+
126+
/**
127+
* The budget is a fixed point, not a guess. Walking again at twice the depth must reveal no key
128+
* and no type the six-deep walk missed; if the public request vocabulary ever grows a path deeper
129+
* than the budget, this fails here rather than quietly narrowing the assertions above.
130+
*
131+
* What the walk deliberately does not see: a route through an index signature. `flags` and `input`
132+
* are `Record<string, unknown>`, so a value stashed under a record key is invisible to a type-level
133+
* walk by construction — `DeclaredKeys` drops index signatures precisely so their `string` cannot
134+
* absorb the literal keys beside it. The claim is about DECLARED routes, which is what a type can
135+
* carry; a record that could hold anything is not one.
136+
*/
137+
test('the six-deep walk is saturated: twice the budget finds nothing more', () => {
138+
expectTypeOf<
139+
Exclude<
140+
ReachableKeys<JournalRequestInput, DoubleBudget>,
141+
ReachableKeys<JournalRequestInput, Budget>
142+
>
143+
>().toEqualTypeOf<never>();
144+
expectTypeOf<
145+
Exclude<
146+
ReachableTypes<JournalRequestInput, DoubleBudget>,
147+
ReachableTypes<JournalRequestInput, Budget>
148+
>
149+
>().toEqualTypeOf<never>();
150+
});

src/daemon/__tests__/session-event-action.test.ts renamed to packages/session-journal/src/__tests__/session-event-action.test.ts

File renamed without changes.

src/daemon/__tests__/session-event-log-window.test.ts renamed to packages/session-journal/src/__tests__/session-event-log-window.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
33
import fs from 'node:fs';
44
import path from 'node:path';
55
import { AppError } from '@agent-device/kernel/errors';
6-
import { mkdtempForTestSync } from '../../__tests__/test-utils/tmp-dir.ts';
6+
import { mkdtempForTestSync } from './test-utils/tmp-dir.ts';
77
import {
88
appendSessionEvent,
99
flushSessionEventLogWrites,

src/daemon/__tests__/session-event-request.test.ts renamed to packages/session-journal/src/__tests__/session-event-request.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import assert from 'node:assert/strict';
22
import { test } from 'vitest';
33
import { buildRequestFinishedEvent, buildRequestStartedEvent } from '../session-event-log.ts';
4-
import type { DaemonRequest, DaemonResponseData } from '../daemon-request.ts';
4+
import type { DaemonRequest, DaemonResponseData } from '@agent-device/kernel/contracts';
55

66
function buildSuccessEvent(
77
command: string,
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import fs from 'node:fs';
2+
import os from 'node:os';
3+
import path from 'node:path';
4+
5+
/**
6+
* Creates a fresh scratch directory for one test. Cleanup is automatic: the
7+
* unit suite redirects TMPDIR to a per-run directory (scripts/vitest-tmpdir-global-setup.ts)
8+
* that gets removed in one recursive rm after every worker finishes, so
9+
* individual tests never need their own afterEach/afterAll for this.
10+
*/
11+
export function mkdtempForTestSync(prefix: string): string {
12+
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
13+
}
File renamed without changes.

0 commit comments

Comments
 (0)