Skip to content

Commit d79f822

Browse files
committed
fix(layering): make R7 exhaustive, and follow session records through aliases
Review finding: `SESSION_STATE_FIELD_OWNERS` covered 27 of `SessionState`'s 42 fields and nothing asserted parity, so a new field could be added and pass the gate by being invisible to it. R7's advertised claim — "every SessionState write is inside its declared owner" — was broader than what it checked. Investigating that turned up a second, larger gap the finding did not name: the scan only recognized a binding literally named `session`. The daemon names these records by role, so `nextSession`, `provisionalSession`, `completedSession`, `preRunSession` and `preEntrySession` were all invisible — and three of those writes were genuine violations R7 existed to catch: src/daemon/snapshot-runtime.ts:256 nextSession.snapshotScopeSource src/daemon/snapshot-runtime.ts:265 nextSession.snapshotGeneration src/daemon/handlers/session-replay-runtime.ts:707 preEntrySession.pendingRecordAndHeal The first two are the #1076 versioned-ref invariant: the generation advances exactly when the stored tree is replaced. That rule lived in `setSessionSnapshot` and had acquired a second statement of itself in snapshot-runtime.ts, whose own comment admitted the bypass. It now goes through `setSnapshotLineage` in the owning module. The third clears a watermark stamped by session-replay-resume.ts; `clearPendingRecordAndHealWatermark` puts the clear beside the stamp. Gate changes: - Binding detection accepts aliases, paired with the existing declared-field filter so an unrelated `…Session` local only registers if it also writes a field SessionState owns — where the remedy is the same anyway. - `fieldClassificationDrift` asserts parity in all three directions: unclassified, in-both, and naming a field SessionState no longer declares. - `STORE_OWNED_SESSION_STATE_FIELDS` classifies the 11 fields the store establishes at construction. It is a positive claim, so a direct write to one fails and names both remedies. - Four fields the widened scan made visible (`lease`, `deviceClaim`, `appName`, `saveScriptComplete`) got real owners. `nextSnapshotGeneration` is now module-private: replacing its only external call site orphaned the export, which `pnpm check` caught via Fallow. Verified against three injected regressions: a new SessionState field with no direct write (the reviewer's exact scenario), a foreign write through an alias binding, and a direct write to a store-established field. All three rejected. `pnpm check` green, 4486 unit tests. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01Bfu8HofkhybiAm5LECfqur
1 parent e53f083 commit d79f822

8 files changed

Lines changed: 255 additions & 25 deletions

File tree

‎CONTEXT.md‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -274,10 +274,21 @@ The perfect-shape refactor is complete and merged. Its end-state:
274274
workable while each field has an owner that keeps its invariants, so
275275
`SESSION_STATE_FIELD_OWNERS` (`scripts/layering/session-state.ts`) records them and the gate
276276
stops the set from growing quietly: a new field must declare an owner, a foreign write fails
277-
with the owner to call instead, and an owner that stops writing must be removed. Field names are
278-
read out of the `SessionState` declaration, so a daemon module with an unrelated local named
279-
`session` cannot trip it. ADR 0014's ref frame is the worked example — its four fields moved
280-
together across two modules until `activateRefFrame` took the transition.
277+
with the owner to call instead, and an owner that stops writing must be removed. The
278+
classification is **exhaustive** — every field is either in that table or in
279+
`STORE_OWNED_SESSION_STATE_FIELDS`, the positive claim "the store establishes this and nothing
280+
mutates it later". Without that parity a new field with no direct write would satisfy the gate by
281+
being invisible to it, and R7 would silently stop covering part of the type it covers. A direct
282+
write to a store-established field fails, naming both remedies. Detection follows session
283+
records through **aliased bindings** (`nextSession`, `provisionalSession`, `completedSession`),
284+
not just a local named `session`: matching the literal name is what let three genuine foreign
285+
writes sit unreported. Since there is no type information in the gate, the binding test is a name
286+
test paired with the declared-field filter — a provider or runner session only registers if it
287+
also writes a field `SessionState` owns, and the remedy is then the same. ADR 0014's ref frame
288+
and the snapshot lineage are the worked examples: the frame's four fields moved together across
289+
two modules until `activateRefFrame` took the transition, and `snapshotScopeSource` +
290+
`snapshotGeneration` were assigned in `snapshot-runtime.ts` until `setSnapshotLineage` took
291+
theirs.
281292
- Zero-dep CI jobs (R8). Some jobs run scripts straight from a checkout with `install-deps: false`,
282293
so they have no `node_modules`. Nothing local can feel that constraint — every dev machine has
283294
`node_modules` sitting right there — so a script grows a package import, passes locally, and fails

‎scripts/layering/check.ts‎

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,11 @@ import fs from 'node:fs';
2828
import path from 'node:path';
2929
import { pathToFileURL } from 'node:url';
3030
import {
31+
fieldClassificationDrift,
3132
findSessionStateWrites,
3233
sessionStateFields,
3334
SESSION_STATE_FIELD_OWNERS,
35+
STORE_OWNED_SESSION_STATE_FIELDS,
3436
} from './session-state.ts';
3537
import { uninstallableImports, zeroDepJobs } from './zero-dep-jobs.ts';
3638
import {
@@ -291,6 +293,30 @@ function checkSessionStateOwnership(sources: ReadonlyMap<string, string>): Viola
291293
const violations: Violation[] = [];
292294
const seenOwners = new Map<string, Set<string>>();
293295

296+
// Parity first: the rule is only exhaustive if every declared field is classified. A field
297+
// that is in neither table would otherwise pass by being invisible to the scan, and R7 would
298+
// quietly stop covering part of the type it claims to cover.
299+
const DRIFT_MESSAGE: Readonly<Record<string, string>> = {
300+
unclassified:
301+
'is declared by SessionState but classified nowhere. Name its owning module in ' +
302+
'SESSION_STATE_FIELD_OWNERS, or — if the store establishes it at construction and nothing ' +
303+
'mutates it later — add it to STORE_OWNED_SESSION_STATE_FIELDS.',
304+
both:
305+
'is in both SESSION_STATE_FIELD_OWNERS and STORE_OWNED_SESSION_STATE_FIELDS. A field is ' +
306+
'either store-established or owned by a writer, not both.',
307+
'not-a-field':
308+
'is classified but is no longer declared by SessionState — remove it from the table it ' +
309+
'still appears in.',
310+
};
311+
for (const { field, problem } of fieldClassificationDrift(fields)) {
312+
violations.push({
313+
rule: 'R7 session-state-ownership',
314+
file: 'scripts/layering/session-state.ts',
315+
line: 1,
316+
message: `session.${field} ${DRIFT_MESSAGE[problem]}`,
317+
});
318+
}
319+
294320
for (const write of writes) {
295321
const owners = SESSION_STATE_FIELD_OWNERS[write.field];
296322
const seen = seenOwners.get(write.field) ?? new Set<string>();
@@ -309,14 +335,19 @@ function checkSessionStateOwnership(sources: ReadonlyMap<string, string>): Viola
309335
continue;
310336
}
311337
if (owners === undefined) {
338+
const storeOwned = STORE_OWNED_SESSION_STATE_FIELDS.has(write.field);
312339
violations.push({
313340
rule: 'R7 session-state-ownership',
314341
file: write.file,
315342
line: write.line,
316-
message:
317-
`session.${write.field} has no declared owner. SessionStore hands out the live ` +
318-
`record, so this write is durable: name the owning module in ` +
319-
`SESSION_STATE_FIELD_OWNERS (scripts/layering/session-state.ts).`,
343+
message: storeOwned
344+
? `session.${write.field} is classified store-established ` +
345+
`(STORE_OWNED_SESSION_STATE_FIELDS), meaning nothing mutates it after construction — ` +
346+
`but this is a direct write. Route it through the store, or move the field into ` +
347+
`SESSION_STATE_FIELD_OWNERS with this module as its owner.`
348+
: `session.${write.field} has no declared owner. SessionStore hands out the live ` +
349+
`record, so this write is durable: name the owning module in ` +
350+
`SESSION_STATE_FIELD_OWNERS (scripts/layering/session-state.ts).`,
320351
});
321352
continue;
322353
}
@@ -392,15 +423,22 @@ function checkZeroDepJobs(): Violation[] {
392423
return violations;
393424
}
394425

426+
function sessionStateFieldCount(): number {
427+
return (
428+
Object.keys(SESSION_STATE_FIELD_OWNERS).length + STORE_OWNED_SESSION_STATE_FIELDS.size
429+
);
430+
}
431+
395432
function report(files: readonly string[], violations: readonly Violation[]): number {
396433
if (violations.length === 0) {
397434
process.stdout.write(
398435
`Layering guard: OK — ${files.length} source files satisfy R1-R3 and contain no ` +
399436
`value-import cycles (both checked globally); the ranked target spine contains no ` +
400437
`back-edges (only the composition root is unranked), and its type-only ` +
401438
`inversions match the R6 ratchet (${Object.values(TYPE_INVERSION_BASELINE).reduce((sum, count) => sum + count, 0)} remaining); ` +
402-
`every SessionState write is inside its declared owner (R7); and every zero-dep CI ` +
403-
`job resolves without node_modules (R8).\n`,
439+
`all ${sessionStateFieldCount()} SessionState fields are classified and every write is ` +
440+
`inside its declared owner (R7); and every zero-dep CI job resolves without ` +
441+
`node_modules (R8).\n`,
404442
);
405443
return 0;
406444
}

‎scripts/layering/model.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ import path from 'node:path';
44
import { test } from 'node:test';
55
import { listSourceFiles } from './check.ts';
66
import {
7+
fieldClassificationDrift,
78
findSessionStateWrites,
89
sessionStateFields,
910
SESSION_STATE_FIELD_OWNERS,
11+
STORE_OWNED_SESSION_STATE_FIELDS,
1012
} from './session-state.ts';
1113
import { uninstallableImports, zeroDepJobs } from './zero-dep-jobs.ts';
1214
import {
@@ -399,3 +401,69 @@ test("the repo's own zero-dep jobs resolve without node_modules", () => {
399401
assert.deepEqual(uninstallableImports(job, read, exists), [], `${job.job} must reach no package`);
400402
}
401403
});
404+
405+
test('a session write counts through an aliased binding, not only one named `session`', () => {
406+
// The daemon names these records by role: nextSession, provisionalSession, completedSession,
407+
// preRunSession, preEntrySession, activeSession. Matching only the literal name `session` hid
408+
// three real foreign writes — nextSession.snapshotGeneration in snapshot-runtime.ts among them
409+
// — while the gate reported that every write was inside its owner.
410+
const writes = findSessionStateWrites(
411+
new Map([
412+
[
413+
'src/daemon/probe.ts',
414+
[
415+
'nextSession.snapshotGeneration = 3;',
416+
'preEntrySession.refFrameState = "active";',
417+
'completedSession.saveScriptComplete = true;',
418+
// Not a session binding, and not a session write.
419+
'result.snapshotGeneration = 9;',
420+
'flags.refFrameState = "x";',
421+
].join('\n'),
422+
],
423+
]),
424+
['snapshotGeneration', 'refFrameState', 'saveScriptComplete'],
425+
);
426+
assert.deepEqual(
427+
writes.map(({ field, line }) => `${line}:${field}`),
428+
['1:snapshotGeneration', '2:refFrameState', '3:saveScriptComplete'],
429+
);
430+
});
431+
432+
test('every SessionState field is classified exactly once', () => {
433+
// Exhaustiveness is the point: without this, a new field with no direct write would satisfy
434+
// R7 by being invisible to the scan, and the rule would silently stop covering part of the
435+
// type it claims to cover.
436+
const fields = sessionStateFields(
437+
readFileSync(path.resolve(import.meta.dirname, '../../src/daemon/types.ts'), 'utf8'),
438+
);
439+
assert.deepEqual(fieldClassificationDrift(fields), []);
440+
assert.equal(
441+
Object.keys(SESSION_STATE_FIELD_OWNERS).length + STORE_OWNED_SESSION_STATE_FIELDS.size,
442+
fields.length,
443+
);
444+
});
445+
446+
test('classification drift is reported in all three directions', () => {
447+
const declared = sessionStateFields(
448+
readFileSync(path.resolve(import.meta.dirname, '../../src/daemon/types.ts'), 'utf8'),
449+
);
450+
451+
// Unclassified: a field added to SessionState and to neither table. This is the case the
452+
// reviewer's finding was about — before parity, such a field passed the gate unnoticed.
453+
assert.deepEqual(fieldClassificationDrift([...declared, 'brandNewField']), [
454+
{ field: 'brandNewField', problem: 'unclassified' },
455+
]);
456+
457+
// Stale: a table names a field SessionState no longer declares. Dropping one declared field
458+
// makes exactly that name stale.
459+
assert.deepEqual(fieldClassificationDrift(declared.filter((field) => field !== 'trace')), [
460+
{ field: 'trace', problem: 'not-a-field' },
461+
]);
462+
463+
// Contradictory: a field cannot be both store-established and owned by a writer. The real
464+
// tables must never overlap, which is what makes the `both` branch unreachable in practice.
465+
const inBoth = [...STORE_OWNED_SESSION_STATE_FIELDS].filter(
466+
(field) => field in SESSION_STATE_FIELD_OWNERS,
467+
);
468+
assert.deepEqual(inBoth, [], 'the real tables must not overlap');
469+
});

‎scripts/layering/session-state.ts‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,70 @@ export const SESSION_STATE_FIELD_OWNERS: Readonly<Record<string, readonly string
9191
audioProbe: ['src/daemon/audio-probe.ts'],
9292
pendingInteractionOutcome: ['src/daemon/interaction-outcome-policy.ts'],
9393
postGestureStabilization: ['src/daemon/post-gesture-stabilization.ts'],
94+
95+
// Snapshot lineage on a freshly BUILT record. snapshot-runtime.ts constructs a new
96+
// SessionState rather than mutating the stored one, so it cannot call setSessionSnapshot —
97+
// but the rule is the same, so the two-field transition lives in session-snapshot.ts.
98+
appName: ['src/daemon/snapshot-runtime.ts'],
99+
lease: ['src/daemon/handlers/session-open.ts'],
100+
deviceClaim: ['src/daemon/handlers/session-open.ts'],
101+
saveScriptComplete: ['src/daemon/handlers/session-replay-runtime.ts'],
102+
};
103+
104+
/**
105+
* Fields no daemon module writes through a session binding: they are set when the record is
106+
* constructed (an object literal, not a field assignment) or inside `session-store.ts`, which
107+
* owns the record and is excluded from the scan.
108+
*
109+
* This list exists so the classification is EXHAUSTIVE. Without it, a new `SessionState` field
110+
* that happened to have no direct write would satisfy the gate by being invisible to it, and R7
111+
* would silently stop covering part of the type it claims to cover. Being here is a positive
112+
* claim — "the store establishes this, nothing mutates it later" — so acquiring a direct write
113+
* fails the gate until the field is moved into `SESSION_STATE_FIELD_OWNERS` with a real owner.
114+
*/
115+
export const STORE_OWNED_SESSION_STATE_FIELDS: ReadonlySet<string> = new Set([
116+
'actions',
117+
'appBundleId',
118+
'appLog',
119+
'appLogFailure',
120+
'createdAt',
121+
'device',
122+
'name',
123+
'recordOnlySession',
124+
'sessionScope',
125+
'snapshotDiagnostics',
126+
'surface',
127+
]);
128+
129+
export type FieldClassificationDrift = {
130+
field: string;
131+
problem: 'unclassified' | 'both' | 'not-a-field';
94132
};
95133

134+
/**
135+
* Where the two ownership tables disagree with `SessionState` itself. Empty means every declared
136+
* field is classified exactly once and neither table names a field that no longer exists.
137+
*/
138+
export function fieldClassificationDrift(
139+
fields: readonly string[],
140+
): FieldClassificationDrift[] {
141+
const declared = new Set(fields);
142+
const owned = new Set(Object.keys(SESSION_STATE_FIELD_OWNERS));
143+
const drift: FieldClassificationDrift[] = [];
144+
145+
for (const field of fields) {
146+
const inOwners = owned.has(field);
147+
const inStore = STORE_OWNED_SESSION_STATE_FIELDS.has(field);
148+
if (inOwners && inStore) drift.push({ field, problem: 'both' });
149+
else if (!inOwners && !inStore) drift.push({ field, problem: 'unclassified' });
150+
}
151+
for (const field of [...owned, ...STORE_OWNED_SESSION_STATE_FIELDS]) {
152+
if (!declared.has(field)) drift.push({ field, problem: 'not-a-field' });
153+
}
154+
155+
return drift.sort((left, right) => left.field.localeCompare(right.field));
156+
}
157+
96158
/**
97159
* Field names declared by `SessionState` itself, so the scan cannot be fooled by a daemon
98160
* module with an unrelated local named `session` (a provider session, a runner session).
@@ -105,6 +167,23 @@ export function sessionStateFields(typesSource: string): string[] {
105167
);
106168
}
107169

170+
/**
171+
* Whether a binding holds a `SessionState`. The daemon names these records by role, not always
172+
* `session`: `nextSession`, `provisionalSession`, `completedSession`, `preRunSession`,
173+
* `preEntrySession`, `activeSession`. Matching only the literal name `session` is what let three
174+
* genuine foreign writes sit unreported — `nextSession.snapshotGeneration` in snapshot-runtime.ts
175+
* among them — while the gate claimed every write was inside its owner.
176+
*
177+
* There is no type information here, so this is a name test, and it is deliberately paired with
178+
* the declared-field filter in `findSessionStateWrites`: a binding must look like a session AND
179+
* the field must be one `SessionState` declares. A provider or runner session that happens to be
180+
* named `…Session` only registers if it also writes a field name `SessionState` owns, and the
181+
* remedy then is to declare the owner — the same remedy as for a real write.
182+
*/
183+
function isSessionBinding(name: string): boolean {
184+
return /session/i.test(name);
185+
}
186+
108187
/** A member expression being assigned to, or updated with `++`/`--`. */
109188
type WriteTarget = {
110189
object: string | undefined;
@@ -171,7 +250,7 @@ export function findSessionStateWrites(
171250
}
172251
const record = node as Record<string, unknown>;
173252
const target = writeTarget(record);
174-
if (target && target.object === 'session') {
253+
if (target && target.object !== undefined && isSessionBinding(target.object)) {
175254
if (target.computed) {
176255
writes.push({ file, line: lineOf(source, target.offset), field: '[computed]' });
177256
} else if (target.field !== undefined && declared.has(target.field)) {

‎src/daemon/handlers/session-replay-resume.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,15 @@ export function stampPendingRecordAndHealWatermark(params: {
175175
});
176176
}
177177

178+
/**
179+
* Retire the watermark once the resume it was stamped for has actually been entered. The clear
180+
* belongs beside the stamp: both are statements about when the field is meaningful, and the
181+
* caller that enters the resume knows only that it matched, not what the field means.
182+
*/
183+
export function clearPendingRecordAndHealWatermark(session: SessionState): void {
184+
session.pendingRecordAndHeal = undefined;
185+
}
186+
178187
function computeRecordAndHealWatermark(params: {
179188
resume: ReplayDivergenceResume;
180189
repairHint: ReplayRepairHint;

‎src/daemon/handlers/session-replay-runtime.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
type ReplayTestProgressEvent,
1616
} from '../../request/progress.ts';
1717
import { SessionStore } from '../session-store.ts';
18+
import { clearPendingRecordAndHealWatermark } from './session-replay-resume.ts';
1819
import { expandSessionPath } from '../session-paths.ts';
1920
import { applySaveScriptRetarget } from '../session-action-recorder.ts';
2021
import { computeReplayPlanDigest } from '../../replay/plan-digest.ts';
@@ -704,7 +705,7 @@ function consumeReplayResumeState(params: {
704705
preEntrySession &&
705706
preEntrySession.pendingRecordAndHeal?.expectedFrom === req.flags?.replayFrom
706707
) {
707-
preEntrySession.pendingRecordAndHeal = undefined;
708+
clearPendingRecordAndHealWatermark(preEntrySession);
708709
sessionStore.set(sessionName, preEntrySession);
709710
}
710711
if (req.flags?.saveScript) sessionStore.clearRepairTombstone(sessionName);

‎src/daemon/session-snapshot.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,33 @@ export function setSessionSnapshot(session: SessionState, snapshot: SnapshotStat
3737
}
3838
}
3939

40+
/**
41+
* The same lineage rule, applied to a freshly BUILT record instead of the stored one.
42+
* `snapshot-runtime.ts` constructs a new `SessionState` rather than mutating the one in the
43+
* store, so it cannot go through `setSessionSnapshot` — but the invariant it has to honour is
44+
* identical, and it is the invariant that matters: #1076 versioned refs require the generation
45+
* to advance exactly when the stored tree is replaced (snapshot AND diff — diff's summary
46+
* response leaves client refs pinned to the previous generation, which is what the pinned
47+
* warning diagnoses), and the scope source must describe the tree that actually ended up there.
48+
*
49+
* Both fields therefore move together, here, next to the writer they have to agree with. They
50+
* used to be assigned at the call site, which is how the rule came to have two statements of
51+
* itself in two modules.
52+
*/
53+
export function setSnapshotLineage(
54+
session: SessionState,
55+
params: {
56+
scopeSource: SnapshotState | undefined;
57+
keptCurrentSnapshot: boolean;
58+
previousGeneration: number | undefined;
59+
},
60+
): void {
61+
session.snapshotScopeSource = params.scopeSource;
62+
session.snapshotGeneration = params.keptCurrentSnapshot
63+
? params.previousGeneration
64+
: nextSnapshotGeneration(params.previousGeneration);
65+
}
66+
4067
/**
4168
* Advance `snapshotGeneration` (#1076 versioned refs). The FIRST bump of a
4269
* session lifetime seeds at a random 6-digit base instead of 1: a reopened
@@ -47,7 +74,7 @@ export function setSessionSnapshot(session: SessionState, snapshot: SnapshotStat
4774
* Within a lifetime the counter stays strictly monotonic (+1 per replacement),
4875
* so pinned-vs-current comparisons remain exact.
4976
*/
50-
export function nextSnapshotGeneration(current: number | undefined): number {
77+
function nextSnapshotGeneration(current: number | undefined): number {
5178
return current === undefined ? randomInt(100_000, 1_000_000) : current + 1;
5279
}
5380

0 commit comments

Comments
 (0)