Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/daemon/src/core/__tests__/ref-frame.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
activateCompleteRefFrame,
activatePartialRefFrame,
admitRefMutation,
admitRefRead,
expireRefFrame,
refFrame,
refFrameEpoch,
Expand Down Expand Up @@ -162,3 +163,12 @@ test('a frame cannot be constructed, edited, or derived outside ref-frame-slot.t
];
assert.equal(rejectedByTsc.length, 4);
});

test('a read is admitted for every ref under a complete frame and only for issued refs under a partial one', () => {
const complete = session();
activateCompleteRefFrame(complete);
assert.equal(reason(admitRefRead(complete, 'e9')), undefined);
const partial = partialSession(7, new Set(['e4']));
assert.equal(reason(admitRefRead(partial, 'e4')), undefined);
assert.equal(reason(admitRefRead(partial, 'e9')), 'ref_not_issued');
});
12 changes: 12 additions & 0 deletions packages/daemon/src/core/ref-frame.ts
Original file line number Diff line number Diff line change
Expand Up @@ -244,3 +244,15 @@ export function admitRefMutation(params: {

return { admitted: true };
}

/**
* ADR 0014 read evidence: a partial frame retains its source tree only as evidence for the refs it
* issued. Any other ref body, plain or pinned, was minted from a tree that frame superseded, so
* resolving it there would bind whatever node now holds that number (#1076, #4686). Reads stay
* fail-open with a warning everywhere else; only this case has no evidence to read.
*/
export function admitRefRead(session: SessionState, refBody: string): RefFrameAdmission {
const scope = refFrameScope(session);
if (scope !== 'all' && !scope.has(refBody)) return { admitted: false, reason: 'ref_not_issued' };
return { admitted: true };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { test, expect, vi, beforeEach } from 'vitest';
import {
legacyDispatchCapture,
resetLegacySnapshotCapture,
} from '../__tests__/support/legacy-snapshot-capture-fixture.ts';
import { attachRefs } from '@agent-device/kernel/snapshot';
import { makeSessionStore } from '../__tests__/support/store-factory.ts';
import { activateCompleteRefFrame } from '../core/ref-frame.ts';
import {
installInteractorSnapshotResolution,
mockInteractorSnapshot,
} from '../__tests__/support/interactor-resolution-fixture.ts';
import {
createTouchCommandSurface,
touchCreateCommandSurface,
} from '../__tests__/support/touch-command-surface-fake.ts';
import { captureAndStoreSnapshot } from '../__tests__/support/command-surface-override-fake.ts';
import type { DaemonFindOptions } from '@agent-device/contracts/daemon-command-surface';
import { handleInteractionCommands } from './interaction/index.ts';
import {
contextFromFlags,
makeSession,
} from './interaction/internal/__tests__/interaction-touch-fixtures.ts';
import { invokeFindHandler } from './interaction/internal/__tests__/find-handler-fixture.ts';
import {
getRuntimeBindings,
resetGetRuntimeFixture,
} from './__tests__/interaction-get-runtime-fixture.ts';

// #4686 / ADR 0014 "Partial issuance": a read-only `find` that prints a ref activates a partial
// frame over its own capture. A ref from the earlier `snapshot -i` was minted from a different
// tree, so a read of it must refuse instead of binding whatever node now holds that number.

const { mockRunAppleRunnerCommand } = vi.hoisted(() => ({
mockRunAppleRunnerCommand: vi.fn(),
}));

vi.mock('@agent-device/platform-apple/runner/operations', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@agent-device/platform-apple/runner/operations')>();
return { ...actual, runAppleRunnerCommand: mockRunAppleRunnerCommand };
});

beforeEach(() => {
installInteractorSnapshotResolution();
resetLegacySnapshotCapture(mockInteractorSnapshot);
mockRunAppleRunnerCommand.mockReset();
mockRunAppleRunnerCommand.mockResolvedValue({});
resetGetRuntimeFixture();
});

/** The `snapshot -i` tree the caller holds refs for: `@e2` is the item counter. */
function interactiveTree() {
return attachRefs([
{ index: 0, depth: 0, type: 'Application', label: 'MultiTodo' },
{ index: 1, depth: 1, parentIndex: 0, type: 'StaticText', label: '4 items' },
{ index: 2, depth: 1, parentIndex: 0, type: 'Cell', label: 'Speakers (4)' },
]);
}

/** The full capture find reads: `e2` is now a keyboard key, not the counter. */
function fullCapture() {
return {
nodes: [
{ index: 0, depth: 0, type: 'Application', label: 'MultiTodo' },
{ index: 1, depth: 1, parentIndex: 0, type: 'Key', label: 'Q' },
{ index: 2, depth: 1, parentIndex: 0, type: 'StaticText', label: '4 items' },
{ index: 3, depth: 1, parentIndex: 0, type: 'Cell', label: 'Speakers (4)' },
],
backend: 'xctest',
producer: 'apple-runner',
};
}

/**
* Read-only `find get text` as the command family answers it: one capture stored as the session
* snapshot, and the matched node's ref minted from that capture. Text and selector queries both
* name the "Speakers (4)" cell here; the daemon's issuance is what these cases pin.
*/
const findSurface = createTouchCommandSurface({
members: (config) => ({
selectors: {
find: async (options: DaemonFindOptions) => {
const snapshot = await captureAndStoreSnapshot(config, options);
const node = snapshot.nodes.find((candidate) => candidate.label === 'Speakers (4)')!;
return { kind: 'text' as const, ref: `@${node.ref}`, text: node.label!, node };
},
},
}),
});

async function getText(
sessionStore: ReturnType<typeof makeSessionStore>,
sessionName: string,
ref: string,
) {
return await handleInteractionCommands({
createCommandSurface: touchCreateCommandSurface,
req: {
token: 't',
session: sessionName,
command: 'get',
positionals: ['text', ref],
flags: {},
},
sessionName,
sessionStore,
contextFromFlags,
...getRuntimeBindings(),
});
}

for (const query of [
['Speakers', 'get', 'text'],
['label="Speakers (4)"', 'get', 'text'],
]) {
test(`a ref from the earlier snapshot is refused, not misread, after find ${query[0]} get text`, async () => {
const sessionStore = makeSessionStore();
const sessionName = `partial-frame-${query[0]}`;
const session = makeSession(sessionName);
session.snapshot = {
nodes: interactiveTree(),
createdAt: Date.now(),
backend: 'xctest',
producer: 'apple-runner',
};
activateCompleteRefFrame(session);
sessionStore.publish(sessionName, session);
legacyDispatchCapture.mockResolvedValue(fullCapture());

const found = await invokeFindHandler({
createCommandSurface: findSurface,
sessionName,
sessionStore,
positionals: query,
invoke: async () => ({ ok: true, data: {} }),
});
expect(found?.ok).toBe(true);
const printed = found?.ok ? (found.data?.ref as string) : undefined;
expect(printed).toBe('@e4');

// `@e2` was the counter in the caller's snapshot; the find's tree has a key there.
const stale = await getText(sessionStore, sessionName, '@e2');
expect(stale?.ok).toBe(false);
if (!stale || stale.ok) throw new Error('expected the unissued-ref refusal');
expect(stale.error.details?.reason).toBe('ref_not_issued');

// The ref the find printed still reads the node it read.
const issued = await getText(sessionStore, sessionName, printed!);
expect(issued?.ok).toBe(true);
if (issued?.ok) expect(issued.data?.text).toBe('Speakers (4)');
});
}
6 changes: 6 additions & 0 deletions packages/daemon/src/execution/selector-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
markSessionPartialRefsIssued,
publishAmbiguousMatchCandidateRefs,
resolveRefStalenessWarning,
unissuedRefReadError,
} from './session-snapshot.ts';
import {
checkElementTargetArgs,
Expand Down Expand Up @@ -135,6 +136,11 @@ export async function dispatchGetViaRuntime(
if (target.target.kind === 'ref') {
const invalidRefFlagsResponse = refSnapshotFlagGuardResponse('get', req.flags);
if (invalidRefFlagsResponse) return invalidRefFlagsResponse;
const unissued = unissuedRefReadError(
params.sessionStore.get(params.sessionName),
target.target.ref,
);
if (unissued) return errorResponse(unissued.code, unissued.message, unissued.details);
}
// ADR 0012 step 4: a guarded replay dispatch must resolve through the
// snapshot path so the post-resolution identity guard runs.
Expand Down
31 changes: 30 additions & 1 deletion packages/daemon/src/execution/session-snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@ import { randomInt } from 'node:crypto';
import type { SettleObservation } from '@agent-device/contracts/interaction';
import { readElementMatchCandidateRefs, AppError } from '@agent-device/kernel/errors';
import type { SnapshotState } from '@agent-device/contracts/snapshot-model';
import { activatePartialRefFrame, refFrameEpoch, refFrameState } from '../core/ref-frame.ts';
import {
activatePartialRefFrame,
admitRefRead,
refFrameEpoch,
refFrameScope,
refFrameState,
} from '../core/ref-frame.ts';
import type { SessionRef, SessionState } from '../core/session-state.ts';
import type { SessionStore } from '../core/session-store.ts';

Expand Down Expand Up @@ -249,6 +255,29 @@ function buildPinnedStaleRefWarning(params: {
return `Ref @${plainRef} was minted from snapshot s${params.mintedGeneration} but the session's ref frame is now s${params.currentFrameEpoch} — re-run snapshot -i.`;
}

/**
* The refusal for an `@ref` read the current frame holds no evidence for (`admitRefRead`): a
* partial publication — a read-only `find`, a settled diff, a replay divergence screen — replaced
* the frame that minted it. Returns undefined when the read may proceed.
*/
export function unissuedRefReadError(
session: SessionState | undefined,
ref: string,
): AppError | undefined {
if (!session) return undefined;
const refBody = normalizeRefBody(ref);
if (admitRefRead(session, refBody).admitted) return undefined;
const scope = refFrameScope(session);
const currentGeneration = refFrameEpoch(session);
return new AppError('COMMAND_FAILED', `Ref @${refBody} was not issued by the current ref frame`, {
reason: 'ref_not_issued',
ref: `@${refBody}`,
...(currentGeneration !== undefined ? { currentGeneration } : {}),
scope: scope === 'all' ? 'all' : Array.from(scope),
hint: 'A find, settled diff, or replay divergence published new refs after this one was issued, so it no longer resolves. Use a ref that response printed, or run snapshot -i for fresh refs.',
});
}

/**
* Staleness warning for a command consuming an `@ref` argument (ADR 0014).
* Frame expiry is checked FIRST, matching the admission order (evidence #17): an
Expand Down
4 changes: 3 additions & 1 deletion packages/daemon/src/execution/wait-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { absenceCaptureOptionError } from '@agent-device/selectors/absence-obser
import { absenceCaptureOptionRefusal } from '@agent-device/selectors/absence-observation';
import { createPlatformRequestScope } from '../core/platform-request-scope.ts';
import { parseVersionedRefPositional } from './ref-positionals.ts';
import { resolveRefStalenessWarning } from './session-snapshot.ts';
import { resolveRefStalenessWarning, unissuedRefReadError } from './session-snapshot.ts';
import {
resolveSessionAtAddress,
resolveSessionDevice,
Expand Down Expand Up @@ -145,6 +145,8 @@ function normalizeWaitPositionals(
if (parsed.kind !== 'ref') return { waitParsed: parsed };
const versionedRef = parseVersionedRefPositional(parsed.rawRef);
if (!versionedRef.ok) return versionedRef.response;
const unissued = unissuedRefReadError(session, versionedRef.ref);
if (unissued) return errorResponse(unissued.code, unissued.message, unissued.details);
return {
waitParsed: { ...parsed, rawRef: versionedRef.ref },
staleRefsWarning: resolveRefStalenessWarning({
Expand Down
2 changes: 1 addition & 1 deletion src/commands/schema/cli-help.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Bootstrap:
Snapshots and refs:
snapshot reads visible state; snapshot -i gets current interactive refs only -- fast path before interaction. Default text is token-efficient; --raw/--json for full provider tree.
Legend: @e12 [button] label="Add to cart" enabled hittable -> press @e12. [off-screen below] -> scroll down --until (a hint, not a ref).
Refs stay valid until you press/click/fill/type/scroll/back/wait-for-async-UI, or otherwise change app state; open/--relaunch clears the stored snapshot outright.
Refs stay valid until you press/click/fill/type/scroll/back/wait-for-async-UI, change app state, or find/diff print refs; open/--relaunch clears the stored snapshot outright.
Prefer --settle and its diff when it shows next target; refresh with snapshot -i only when you did not settle, it reported not settled, or output lacks what you need. A known selector/label after a mutation is often enough, since interaction commands refresh state internally.
Truncated preview: snapshot -s @e12 (the current concrete ref), not get text. Missing target: scroll <dir> --until <selector>. TV/D-pad focus: help tv.

Expand Down
5 changes: 5 additions & 0 deletions website/docs/docs/selectors.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ position instead.
agent-device find "Follow" click --first
```

A read-only `find` that prints a ref (`get text`, `get attrs`, `list`) publishes only the refs it
returns, so it ends the earlier snapshot's refs. A later `get` or `wait` on one of those older refs
fails with `error.details.reason: ref_not_issued` instead of reading whichever element now has that
number. Use a ref the `find` printed, or run `snapshot -i` again.

Tips:

- `find role <value>` and the `role=` selector key use the same role names that snapshots show. See
Expand Down
Loading