Skip to content

Commit 99b256c

Browse files
committed
fix: per-ref MCP pin provenance and seeded generations
Review findings on the first cut: 1. The MCP layer kept ONE refsGeneration per session, so after snapshot(s12) -> find(s13) a plain @e37 from the pre-find snapshot got pinned ~s13 and read as current — recreating the find-blessing hole at the pinning layer. Replace it with per-ref provenance: Map<pinScope, Map<refBody, generation>>, scoped by state dir + session name (stateDir is a per-call MCP config field, so one server process can face multiple daemons). Merge-only updates: refs present in a ref-issuing response (snapshot nodes, digest refs, the find ref) move to its generation; absent refs KEEP their older pins — an old pin on a replaced tree is what makes the daemon warn. Never-issued refs pass through unpinned; an issuing response without refsGeneration clears the scope; memory bounded to the ~1000 most recently issued pins. 2. Generations were per-lifetime counters from 1, so a reopened session's ~s1 collided silently with the previous lifetime's. Seed the first bump at a random 6-digit base (crypto randomInt): cross-lifetime collisions become ~1e-6 — probabilistic (seeded), not identity-based, documented on the field. Pin format unchanged; within-lifetime comparisons stay exact. Tests: the MCP blessing scenario (pre-find ref stays pinned to ITS generation), the daemon half in the provider scenario (find must not bless a pre-find pin), reopen/reseed at unit + handler level, state-dir scope isolation, digest-ref merging; generation fixtures made seed-agnostic (relative bumps, echo the observed seed). Refs #1076
1 parent 21644af commit 99b256c

9 files changed

Lines changed: 343 additions & 88 deletions

File tree

‎src/daemon/__tests__/session-snapshot.test.ts‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,43 @@ test('setSessionSnapshot advances the generation on every tree replacement (#107
2626

2727
const first = makeSnapshot();
2828
setSessionSnapshot(session, first);
29-
expect(session.snapshotGeneration).toBe(1);
29+
// First bump of a lifetime is SEEDED at a random 6-digit base (see
30+
// nextSnapshotGeneration) — assert the range, not a literal.
31+
const seeded = session.snapshotGeneration!;
32+
expect(seeded).toBeGreaterThanOrEqual(100_000);
33+
expect(seeded).toBeLessThan(1_000_000);
3034
expect(session.snapshotRefsStale).toBe(true);
3135

3236
// Storing the SAME snapshot object again is not a replacement.
3337
setSessionSnapshot(session, first);
34-
expect(session.snapshotGeneration).toBe(1);
38+
expect(session.snapshotGeneration).toBe(seeded);
3539

40+
// Within a lifetime the counter is strictly monotonic.
3641
setSessionSnapshot(session, makeSnapshot());
37-
expect(session.snapshotGeneration).toBe(2);
42+
expect(session.snapshotGeneration).toBe(seeded + 1);
43+
});
44+
45+
test('a reopened session reseeds so pins from a previous lifetime do not silently collide', () => {
46+
const firstLifetime = makeSession();
47+
setSessionSnapshot(firstLifetime, makeSnapshot());
48+
const oldGeneration = firstLifetime.snapshotGeneration!;
49+
50+
// Reopen: a fresh session object restarts the counter with a NEW seed.
51+
const secondLifetime = makeSession();
52+
setSessionSnapshot(secondLifetime, makeSnapshot());
53+
secondLifetime.snapshotRefsStale = false;
54+
55+
// Probabilistic, not identity-based: the seeds collide with ~1/900000
56+
// probability (an accepted residual risk, documented on the field).
57+
expect(secondLifetime.snapshotGeneration).not.toBe(oldGeneration);
58+
// A pin minted in the previous lifetime warns instead of reading as current.
59+
expect(
60+
resolveRefStalenessWarning({
61+
session: secondLifetime,
62+
ref: '@e1',
63+
mintedGeneration: oldGeneration,
64+
}),
65+
).toContain(`minted from snapshot s${oldGeneration}`);
3866
});
3967

4068
test('resolveRefStalenessWarning: pinned-current clean, pinned-stale precise, plain coarse', () => {

‎src/daemon/handlers/__tests__/interaction.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3534,3 +3534,30 @@ test('a malformed generation suffix is INVALID_ARGS with the ref grammar hint',
35343534
}
35353535
}
35363536
});
3537+
3538+
test('after a session reopen, a pin from the previous lifetime warns (reseeded generations)', async () => {
3539+
const sessionStore = makeSessionStore();
3540+
const sessionName = 'reopened-pin-warns';
3541+
// Previous lifetime: a seeded generation minted the client's pin.
3542+
const previous = makeStaleRefSession(sessionName);
3543+
setSessionSnapshot(previous, { ...previous.snapshot! });
3544+
const oldGeneration = previous.snapshotGeneration!;
3545+
3546+
// Reopen: fresh session object, same name — the counter reseeds, so the
3547+
// old pin cannot silently read as current even though both lifetimes are
3548+
// one replacement deep (a per-lifetime count from 1 would collide here).
3549+
const reopened = makeStaleRefSession(sessionName);
3550+
setSessionSnapshot(reopened, { ...reopened.snapshot! });
3551+
reopened.snapshotRefsStale = false;
3552+
sessionStore.set(sessionName, reopened);
3553+
// Probabilistic (~1/900000 collision) — accepted residual risk.
3554+
expect(reopened.snapshotGeneration).not.toBe(oldGeneration);
3555+
3556+
const response = await runInteraction(sessionStore, sessionName, 'press', [
3557+
`@e1~s${oldGeneration}`,
3558+
]);
3559+
expect(response?.ok).toBe(true);
3560+
if (response?.ok) {
3561+
expect(String(response.data?.warning)).toContain(`minted from snapshot s${oldGeneration}`);
3562+
}
3563+
});

‎src/daemon/handlers/__tests__/snapshot-handler.test.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -489,12 +489,15 @@ test('snapshot responses carry refsGeneration and advance it per capture (#1076
489489

490490
const first = await runVersionedRefsCommand({ sessionStore, sessionName, command: 'snapshot' });
491491
// Ref-issuing response reports the generation ONCE; the node tree itself
492-
// stays plain `e1` refs (token economy).
493-
expect(first?.refsGeneration).toBe(1);
494-
expect(sessionStore.get(sessionName)?.snapshotGeneration).toBe(1);
492+
// stays plain `e1` refs (token economy). The first generation of a session
493+
// lifetime is SEEDED (random 6-digit base), so assert relative bumps and
494+
// echo the observed seed instead of literals.
495+
const seed = first?.refsGeneration;
496+
expect(typeof seed).toBe('number');
497+
expect(sessionStore.get(sessionName)?.snapshotGeneration).toBe(seed);
495498

496499
const second = await runVersionedRefsCommand({ sessionStore, sessionName, command: 'snapshot' });
497-
expect(second?.refsGeneration).toBe(2);
500+
expect(second?.refsGeneration).toBe((seed as number) + 1);
498501
});
499502

500503
test('diff advances the generation without issuing refsGeneration (#1076 versioned refs)', async () => {
@@ -503,12 +506,14 @@ test('diff advances the generation without issuing refsGeneration (#1076 version
503506

504507
await runVersionedRefsCommand({ sessionStore, sessionName, command: 'snapshot' });
505508

509+
const seed = sessionStore.get(sessionName)?.snapshotGeneration as number;
510+
506511
// diff replaces the stored tree too — the generation advances even though
507-
// the summary response issues no refs, which is exactly what a pinned
508-
// `@e1~s1` ref would then warn about.
512+
// the summary response issues no refs, which is exactly what a ref pinned
513+
// to the snapshot generation would then warn about.
509514
const diffData = await runVersionedRefsCommand({ sessionStore, sessionName, command: 'diff' });
510515
expect(diffData?.refsGeneration).toBeUndefined();
511-
expect(sessionStore.get(sessionName)?.snapshotGeneration).toBe(2);
516+
expect(sessionStore.get(sessionName)?.snapshotGeneration).toBe(seed + 1);
512517
});
513518

514519
test('snapshot surfaces filtered-to-zero Android guidance for interactive snapshots', async () => {

‎src/daemon/session-snapshot.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { randomInt } from 'node:crypto';
12
import type { SnapshotState } from '../kernel/snapshot.ts';
23
import type { SessionState } from './types.ts';
34

@@ -41,7 +42,7 @@ export function setSessionSnapshot(session: SessionState, snapshot: SnapshotStat
4142
// #1076 versioned refs: every tree replacement advances the session's
4243
// snapshot generation, so refs pinned to an earlier generation
4344
// (`@e12~s3`) can be diagnosed precisely.
44-
session.snapshotGeneration = (session.snapshotGeneration ?? 0) + 1;
45+
session.snapshotGeneration = nextSnapshotGeneration(session.snapshotGeneration);
4546
}
4647
session.snapshot = snapshot;
4748
session.snapshotScopeSource = undefined;
@@ -50,6 +51,20 @@ export function setSessionSnapshot(session: SessionState, snapshot: SnapshotStat
5051
}
5152
}
5253

54+
/**
55+
* Advance `snapshotGeneration` (#1076 versioned refs). The FIRST bump of a
56+
* session lifetime seeds at a random 6-digit base instead of 1: a reopened
57+
* session restarts its counter, so a per-lifetime count starting at 1 would
58+
* let a stale `@e1~s1` pin from the previous lifetime silently read as
59+
* current. With a seeded base, cross-lifetime collisions are ~1e-6 instead of
60+
* common — the protection is probabilistic (seeded), NOT identity-based.
61+
* Within a lifetime the counter stays strictly monotonic (+1 per replacement),
62+
* so pinned-vs-current comparisons remain exact.
63+
*/
64+
export function nextSnapshotGeneration(current: number | undefined): number {
65+
return current === undefined ? randomInt(100_000, 1_000_000) : current + 1;
66+
}
67+
5368
/** The response being returned hands the stored snapshot's refs to the client. */
5469
export function markSessionSnapshotRefsIssued(session: SessionState): void {
5570
session.snapshotRefsStale = false;

‎src/daemon/snapshot-runtime.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { createDaemonRuntimePolicy } from './runtime-policy.ts';
1818
import { createDaemonRuntimeSessionStore } from './runtime-session.ts';
1919
import { maybeBuildAndroidSnapshotTimeoutFailure } from './android-snapshot-timeout-evidence.ts';
2020
import { summarizeSnapshotDiagnostics } from '../snapshot-diagnostics.ts';
21+
import { nextSnapshotGeneration } from './session-snapshot.ts';
2122

2223
export async function dispatchSnapshotViaRuntime(params: {
2324
req: DaemonRequest;
@@ -262,7 +263,7 @@ function buildNextSnapshotSession(params: {
262263
// generation, which is exactly what the pinned warning diagnoses).
263264
nextSession.snapshotGeneration = keepCurrentSnapshot
264265
? current?.snapshotGeneration
265-
: (current?.snapshotGeneration ?? 0) + 1;
266+
: nextSnapshotGeneration(current?.snapshotGeneration);
266267
if (record.appName) nextSession.appName = record.appName;
267268
return nextSession;
268269
}

‎src/daemon/types.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,11 @@ export type SessionState = {
268268
* ref outputs) report it once as the additive `refsGeneration` field;
269269
* consumers may pin refs as `@e12~s3` and get a precise staleness warning
270270
* when the pinned generation no longer matches the stored tree. Plain number
271-
* with per-session lifetime — no persistence, no overflow/reset handling.
271+
* with per-session lifetime — no persistence. The first bump of a lifetime
272+
* seeds at a random 6-digit base (`nextSnapshotGeneration`), so a pin from a
273+
* previous lifetime of a reopened same-named session collides only with
274+
* ~1e-6 probability instead of commonly: cross-lifetime protection is
275+
* probabilistic (seeded), NOT identity-based.
272276
*/
273277
snapshotGeneration?: number;
274278
/** Source snapshot used to resolve repeated `snapshot -s @ref` after scoped output replaces refs. */

‎src/mcp/__tests__/command-tools.test.ts‎

Lines changed: 99 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -327,66 +327,143 @@ function createPinningExecutor(runCalls: Array<{ name: string; input: unknown }>
327327
runCommand: async (_client, name, input) => {
328328
runCalls.push({ name, input });
329329
if (name === 'snapshot') {
330-
return { nodes: [], truncated: false, refsGeneration: 12 };
330+
// Issues refs e2 and e37 at generation 500012.
331+
return {
332+
nodes: [{ ref: 'e2' }, { ref: 'e37' }],
333+
truncated: false,
334+
refsGeneration: 500012,
335+
};
331336
}
332337
if (name === 'find') {
333-
return { ref: '@e3', refsGeneration: 13 };
338+
// A later find capture replaced the tree and issued ONLY e5 at 500013.
339+
return { ref: '@e5', refsGeneration: 500013 };
334340
}
335341
return { message: `Ran ${name}` };
336342
},
337343
});
338344
}
339345

340-
test('MCP auto-pins a plain @ref after a snapshot response reported refsGeneration', async () => {
346+
test('MCP keeps per-ref provenance: a pre-find snapshot ref stays pinned to ITS generation', async () => {
347+
// THE find-blessing scenario (#1076): snapshot issues e37 at G1, a later
348+
// find issues e5 at G2. A plain @e37 must forward pinned to G1 — pinning it
349+
// to G2 would make the daemon read it as current and silently re-bless it.
350+
// (The daemon side of this flow — precise warning for the G1 pin after the
351+
// find capture replaced the tree — is covered in the provider scenario.)
341352
const runCalls: Array<{ name: string; input: unknown }> = [];
342353
const executor = createPinningExecutor(runCalls);
343354

344355
await executor.execute('snapshot', { session: 'demo' });
345-
await executor.execute('press', { session: 'demo', target: { kind: 'ref', ref: '@e2' } });
356+
await executor.execute('find', { session: 'demo', query: 'Continue' });
357+
await executor.execute('press', { session: 'demo', target: { kind: 'ref', ref: '@e37' } });
346358

347-
assert.deepEqual(runCalls[1], {
359+
assert.deepEqual(runCalls[2], {
348360
name: 'press',
349-
input: { session: 'demo', target: { kind: 'ref', ref: '@e2~s12' } },
361+
input: { session: 'demo', target: { kind: 'ref', ref: '@e37~s500012' } },
350362
});
351363
});
352364

353-
test('MCP auto-pins wait refs and get targets, and tracks find-issued generations', async () => {
365+
test('MCP pins the find-issued ref to the find generation', async () => {
354366
const runCalls: Array<{ name: string; input: unknown }> = [];
355367
const executor = createPinningExecutor(runCalls);
356368

369+
await executor.execute('snapshot', { session: 'demo' });
357370
await executor.execute('find', { session: 'demo', query: 'Continue' });
358-
await executor.execute('wait', { session: 'demo', ref: '@e3' });
371+
await executor.execute('press', { session: 'demo', target: { kind: 'ref', ref: '@e5' } });
372+
373+
assert.deepEqual(runCalls[2], {
374+
name: 'press',
375+
input: { session: 'demo', target: { kind: 'ref', ref: '@e5~s500013' } },
376+
});
377+
});
378+
379+
test('MCP auto-pins wait refs and get targets from the per-ref map', async () => {
380+
const runCalls: Array<{ name: string; input: unknown }> = [];
381+
const executor = createPinningExecutor(runCalls);
382+
383+
await executor.execute('snapshot', { session: 'demo' });
384+
await executor.execute('wait', { session: 'demo', ref: '@e2' });
359385
await executor.execute('get', {
360386
session: 'demo',
361387
format: 'text',
362-
target: { kind: 'ref', ref: '@e3' },
388+
target: { kind: 'ref', ref: '@e37' },
363389
});
364390

365391
assert.deepEqual(runCalls[1], {
366392
name: 'wait',
367-
input: { session: 'demo', ref: '@e3~s13' },
393+
input: { session: 'demo', ref: '@e2~s500012' },
368394
});
369395
assert.deepEqual(runCalls[2], {
370396
name: 'get',
371-
input: { session: 'demo', format: 'text', target: { kind: 'ref', ref: '@e3~s13' } },
397+
input: { session: 'demo', format: 'text', target: { kind: 'ref', ref: '@e37~s500012' } },
398+
});
399+
});
400+
401+
test('MCP merges digest-level snapshot refs too', async () => {
402+
const runCalls: Array<{ name: string; input: unknown }> = [];
403+
const executor = createCommandToolExecutor({
404+
createClient: () => ({}) as AgentDeviceClient,
405+
runCommand: async (_client, name, input) => {
406+
runCalls.push({ name, input });
407+
return name === 'snapshot'
408+
? { nodeCount: 1, refs: [{ ref: 'e9', label: 'Continue' }], refsGeneration: 41 }
409+
: {};
410+
},
372411
});
412+
413+
await executor.execute('snapshot', { responseLevel: 'digest' });
414+
await executor.execute('press', { target: { kind: 'ref', ref: '@e9' } });
415+
416+
assert.deepEqual(runCalls[1]?.input, { target: { kind: 'ref', ref: '@e9~s41' } });
417+
});
418+
419+
test('MCP passes never-issued refs through unpinned (coarse floor, never guess)', async () => {
420+
const runCalls: Array<{ name: string; input: unknown }> = [];
421+
const executor = createPinningExecutor(runCalls);
422+
423+
await executor.execute('snapshot', { session: 'demo' });
424+
// e99 was never present in any issuing response for this scope.
425+
await executor.execute('press', { session: 'demo', target: { kind: 'ref', ref: '@e99' } });
426+
427+
assert.deepEqual(runCalls[1]?.input, { session: 'demo', target: { kind: 'ref', ref: '@e99' } });
373428
});
374429

375-
test('MCP passes refs through unpinned when no generation is known for the session', async () => {
430+
test('MCP passes refs through unpinned when the pin scope has no history', async () => {
376431
const runCalls: Array<{ name: string; input: unknown }> = [];
377432
const executor = createPinningExecutor(runCalls);
378433

379-
// No snapshot/find ran for THIS session name — never guess.
434+
// Only OTHER session names have history.
380435
await executor.execute('snapshot', { session: 'other' });
381436
await executor.execute('press', { session: 'demo', target: { kind: 'ref', ref: '@e2' } });
382437

383-
assert.deepEqual(runCalls[1], {
384-
name: 'press',
385-
input: { session: 'demo', target: { kind: 'ref', ref: '@e2' } },
438+
assert.deepEqual(runCalls[1]?.input, { session: 'demo', target: { kind: 'ref', ref: '@e2' } });
439+
});
440+
441+
test('MCP pin scopes include the state dir: same-named sessions never cross-pollinate', async () => {
442+
const runCalls: Array<{ name: string; input: unknown }> = [];
443+
const executor = createPinningExecutor(runCalls);
444+
445+
await executor.execute('snapshot', { session: 'demo', stateDir: '/state/a' });
446+
// Same session name against a DIFFERENT daemon state dir: no history there.
447+
await executor.execute('press', {
448+
session: 'demo',
449+
stateDir: '/state/b',
450+
target: { kind: 'ref', ref: '@e2' },
451+
});
452+
// The original scope still pins.
453+
await executor.execute('press', {
454+
session: 'demo',
455+
stateDir: '/state/a',
456+
target: { kind: 'ref', ref: '@e2' },
457+
});
458+
459+
assert.deepEqual(runCalls[1]?.input, { session: 'demo', target: { kind: 'ref', ref: '@e2' } });
460+
assert.deepEqual(runCalls[2]?.input, {
461+
session: 'demo',
462+
target: { kind: 'ref', ref: '@e2~s500012' },
386463
});
387464
});
388465

389-
test('MCP forgets the generation when a ref-issuing response stops carrying one', async () => {
466+
test('MCP clears the whole scope when a ref-issuing response stops carrying a generation', async () => {
390467
const runCalls: Array<{ name: string; input: unknown }> = [];
391468
let issueGeneration = true;
392469
const executor = createCommandToolExecutor({
@@ -395,17 +472,17 @@ test('MCP forgets the generation when a ref-issuing response stops carrying one'
395472
runCalls.push({ name, input });
396473
if (name === 'snapshot') {
397474
return issueGeneration
398-
? { nodes: [], truncated: false, refsGeneration: 4 }
399-
: { nodes: [], truncated: false };
475+
? { nodes: [{ ref: 'e2' }], truncated: false, refsGeneration: 4 }
476+
: { nodes: [{ ref: 'e2' }], truncated: false };
400477
}
401478
return {};
402479
},
403480
});
404481

405482
await executor.execute('snapshot', {});
406483
issueGeneration = false;
407-
// An older daemon (or a response view) without refsGeneration: the stale
408-
// remembered generation must not leak onto new refs.
484+
// An older daemon without refsGeneration: the remembered pins must not
485+
// leak onto refs the response did not vouch for.
409486
await executor.execute('snapshot', {});
410487
await executor.execute('press', { target: { kind: 'ref', ref: '@e2' } });
411488

@@ -432,7 +509,7 @@ test('MCP renders tool text from the unpinned input so the model never sees suff
432509
createClient: () => ({}) as AgentDeviceClient,
433510
runCommand: async (_client, name) =>
434511
name === 'snapshot'
435-
? { nodes: [], truncated: false, refsGeneration: 9 }
512+
? { nodes: [{ ref: 'e2' }], truncated: false, refsGeneration: 9 }
436513
: { message: 'Tapped @e2 (10, 20)' },
437514
});
438515

0 commit comments

Comments
 (0)