Skip to content

Commit 4f9aded

Browse files
thymikeeclaude
andauthored
fix(record): make an aborted authoring recording terminal by construction (callstack#1712)
* fix(record): make an aborted authoring recording terminal by construction A second successful `open` on an `open --save-script` session aborts the recording: the aggregate goes to `authoring{aborted}`, `recordSession` is cleared, and the caller is warned. `close --save-script` then refuses it with "Retry with plain close; it will tear down the session without writing." That promise was not kept. When the second `open` itself carried `--save-script`, the recorder's shared flag ingress re-armed `recordSession` while leaving the status terminal, and a bare `close` published the full session log — the writer gated only on `recordSession` and the repair variant, so nothing on the ordinary authoring path refused an aborted lifecycle. The abort is now terminal by construction rather than inert by ordering: - `isAuthoringAborted` gives the pure aggregate one home for the question. - `applyRecordedSaveScriptFlags` takes no branch for an aborted lifecycle: it neither re-arms recording nor retargets the output path. - `SessionScriptWriter` asks one `isPublicationWriteBlocked` question covering all three reasons to publish nothing, so every path reaching the writer (bare `close`, teardown, idle-reap, active publication) refuses it. Armed recordings, published recordings, and every repair transaction are unaffected; the control tests for those stay green against the pre-fix code while the five new regressions go red. Closes callstack#1533 * docs: record the callstack#1533 resolution in ADR 0016 and fix a stale symbol reference The ADR 0016 close-time amendment still described callstack#1533 as unresolved, and the session-close.ts note named `isAuthoringAbortedWriteBlocked` — a private helper that was folded into `isPublicationWriteBlocked` when the writer's three sequential guards collapsed into one predicate, so the symbol names nothing in the tree. * fix(record): arm recording through the publication lifecycle, not around it `recordSession` is an evidence-capture flag, but three surfaces set it directly without consulting the publication aggregate, so it could contradict a terminal ABORTED authoring status. The callstack#1533 fix closed the recorded-action ingress and made the writer refuse an ABORTED lifecycle, then documented the remaining contradiction as acceptable — the writer's own comment noted that "something can re-arm that boolean behind the terminal status". That something was live: `buildNextOpenSession` re-armed recording for any `open --save-script`, and `applyOrdinaryScriptRecordingOpenOutcome` only aborts a lifecycle that is still ARMED. A third `open --save-script` on an already-ABORTED session therefore left `recordSession` true behind the terminal status. The writer gate hid the publication symptom, but the session kept paying recording-time costs for a recording that can never publish: `recordSession` disables the direct iOS selector fast paths for click and get, forcing every interaction onto the snapshot route. Route the flag through one rule owned by the publication projection (`recordSessionAfterSaveScriptFlag`), which answers "not recording" for an ABORTED lifecycle on every surface that handles it — the re-open builder, the close finalizer, and the recorded-action ingress. The writer's gate is unchanged and still correct; it now stands on the aggregate alone rather than as a net under a known drift, so the comments defending the drift are replaced by statements of the rule. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PFW9gJqz1wEHoowkdd1nFW * docs: describe the full callstack#1533 surface in the changelog entry Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PFW9gJqz1wEHoowkdd1nFW --------- Co-authored-by: Claude <[email protected]>
1 parent f569b91 commit 4f9aded

12 files changed

Lines changed: 315 additions & 13 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
## Unreleased
44

5+
- Fixed: a script recording aborted by a second `open` is no longer published by a later bare `close` (#1533). `open <app> --save-script` followed by a second successful `open` terminates the recording and warns "Script publication was aborted…", and `close --save-script` correctly refuses it with "Retry with plain close; it will tear down the session without writing." But when that second `open` itself carried `--save-script`, the flag re-armed recording behind the terminal status, and a bare `close` then wrote the full session log to disk — publishing a recording the caller had been told was aborted, and breaking the promise the refusal makes. An aborted authoring lifecycle is now terminal by construction: `--save-script` arms nothing on any surface that handles it — the re-open builder, the close finalizer, and the recorded-action ingress — and the script writer refuses the lifecycle from every path that reaches it (bare `close`, teardown, idle-reap, active publication). This also stops an aborted session from paying recording-time costs it can never publish: a re-opened aborted recording no longer keeps the direct iOS selector fast paths for `click` and `get` disabled. Armed recordings, published recordings, and every repair transaction are unaffected.
56
- `agent-device mcp` now serves the stateless MCP `2026-07-28` revision alongside the handshake-based revisions it already spoke, as the spec's "dual-era server". Modern clients probe `server/discover`, which advertises the supported revisions, the tools capability, and server identity; their requests declare a protocol version in `_meta`, and their results carry `resultType: "complete"` plus `_meta["io.modelcontextprotocol/serverInfo"]`. `tools/list` and `server/discover` now return the `ttlMs`/`cacheScope` cache hints, so a client can cache the 55-tool, ~223KB tool list for an hour instead of re-fetching it on every start; the list was already emitted in a deterministic (sorted) order, which is the other half of what makes it cacheable. Each revision is answered on its own wire contract: a request declaring `2025-11-25` or `2025-06-18` through modern framing still gets the legacy result shape, and `initialize` never agrees to `2026-07-28`, which has no handshake to establish. A declared revision this server does not implement is rejected with `UnsupportedProtocolVersionError` (`-32022`) naming the ones it does, rather than being served under a version the client did not ask for, and modern framing that omits its required `protocolVersion`/`clientCapabilities` metadata — or supplies a `clientInfo` that is not a valid `Implementation` — is rejected as invalid params. `initialize` and `ping` were removed in `2026-07-28`, so a modern-framed call to either is answered `-32601` rather than served inside a `resultType: "complete"` envelope. Responses to legacy clients are unchanged byte-for-byte — `initialize` and `ping` are still served, and no cache, `resultType`, or `_meta` field is added to their results. Nothing here affects the CLI, Node, or daemon surfaces: the stdio transport, the tool set, and every tool's input/output schema are untouched.
67
- Fixed: the MCP `initialize` handshake now answers with the protocol revision the client requested when it is one this server implements, instead of always answering `2025-11-25`. A client pinned to `2025-06-18` was told to speak a revision it had not asked for, which the lifecycle contract answers by disconnecting.
78
- `agent-device help workflow` is now a compact ~8KB card instead of a ~41KB dump; the same depth still exists, split into `help scripting` (save-script, secret-safe fills, batch JSON, replay divergence/repair, recording) and `help gestures` (multi-touch shapes and platform quirks), plus a few paragraphs folded into the topics that already owned the subject (`help debugging`, `help physical-device`, `help validate`). Every `help <topic>` first line is now `agent-device <version> — <topic>` so an agent can read the installed version from its mandatory first help read instead of a separate `agent-device --version` call.

‎docs/adr/0016-active-session-script-publication.md‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,28 @@ fresh session is the only re-arming boundary.
108108
> without writing. This is distinct from
109109
> [#1533](https://github.com/callstack/agent-device/issues/1533), which is about an
110110
> already-ARMED-then-ABORTED session whose flag ingress re-enables `recordSession` and lets a
111-
> *bare* `close` (no `--save-script` on the close itself) publish; that case is unresolved here.
111+
> *bare* `close` (no `--save-script` on the close itself) publish; that case is resolved by the
112+
> amendment below.
113+
114+
> **Amendment (#1533, shipped).** ABORTED terminality above was enforced only by
115+
> `abortAuthoringOnSecondOpen` clearing `session.recordSession` — inert by ordering, not by
116+
> construction. `recordSession` is an evidence-capture flag that several surfaces set directly, so
117+
> a later `--save-script` re-armed it while the status stayed ABORTED, and a *bare* `close` then
118+
> published the full session log through a writer that only knew how to refuse repair
119+
> transactions. The refusal this ADR specifies for `close --save-script` in ABORTED promises the
120+
> caller that plain `close` "tears down without writing", so the gap also made an existing error
121+
> message untrue.
122+
>
123+
> ABORTED is now terminal by construction. `--save-script` arms recording through one rule owned by
124+
> the publication projection (`recordSessionAfterSaveScriptFlag`), which answers "not recording"
125+
> for an ABORTED lifecycle on every surface that handles the flag — the re-open builder, the close
126+
> finalizer, and the recorded-action ingress — so the flag can no longer contradict the status.
127+
> Publication authorization is likewise the aggregate's to answer: the writer asks one
128+
> publication-blocked question covering not-recording, an uncommittable or committed repair, and an
129+
> ABORTED authoring lifecycle alike, so every path that reaches it (bare `close`, teardown,
130+
> idle-reap, active publication) refuses. ARMED and PUBLISHED lifecycles and every repair
131+
> transaction are unchanged; no state name, transition, or entry point in the lifecycle above is
132+
> added or altered.
112133
113134
This lifecycle is distinct from ADR 0012's repair transaction. `session save-script` rejects a session
114135
with `saveScriptBoundary` set and directs the caller to finish or abort the repair through its existing

‎src/daemon/__tests__/session-action-recorder.test.ts‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@
77
*/
88
import { test, expect } from 'vitest';
99
import { recordActionEntry } from '../session-action-recorder.ts';
10-
import { makeIosSession } from '../../__tests__/test-utils/session-factories.ts';
10+
import {
11+
authoringPublication,
12+
makeIosSession,
13+
} from '../../__tests__/test-utils/session-factories.ts';
1114

1215
test('an observation-only action is excluded while repair-armed and no --record is given', () => {
1316
const session = makeIosSession('default', {
@@ -261,3 +264,58 @@ test('whitespace-only fills collapse ambiguous recorder output and keys', () =>
261264
});
262265
expect(JSON.stringify(session.actions)).not.toContain(whitespace);
263266
});
267+
268+
test('#1533: the --save-script ingress does not re-arm an aborted authoring lifecycle', () => {
269+
const session = makeIosSession('s', {
270+
// What `abortAuthoringOnSecondOpen` leaves behind: terminal status, recording off.
271+
recordSession: false,
272+
scriptPublication: authoringPublication('aborted'),
273+
});
274+
275+
// The second `open --save-script` records its own action, carrying the flag
276+
// that caused the abort into the recorder's shared ingress.
277+
recordActionEntry(session, {
278+
command: 'open',
279+
positionals: ['com.example.other'],
280+
flags: { saveScript: true },
281+
});
282+
283+
expect(session.recordSession).toBe(false);
284+
expect(session.scriptPublication).toEqual(authoringPublication('aborted'));
285+
});
286+
287+
test('#1533: an aborted lifecycle cannot be retargeted by a later --save-script=<path> either', () => {
288+
const session = makeIosSession('s', {
289+
recordSession: false,
290+
scriptPublication: authoringPublication('aborted', { path: '/tmp/original.ad' }),
291+
});
292+
293+
recordActionEntry(session, {
294+
command: 'open',
295+
positionals: ['com.example.other'],
296+
flags: { saveScript: '/tmp/hijacked.ad', force: true },
297+
});
298+
299+
expect(session.recordSession).toBe(false);
300+
expect(session.scriptPublication).toEqual(
301+
authoringPublication('aborted', { path: '/tmp/original.ad' }),
302+
);
303+
});
304+
305+
test('#1533: an ARMED authoring lifecycle still takes the ingress (retarget + force unchanged)', () => {
306+
const session = makeIosSession('s', {
307+
recordSession: true,
308+
scriptPublication: authoringPublication('armed'),
309+
});
310+
311+
recordActionEntry(session, {
312+
command: 'close',
313+
positionals: [],
314+
flags: { saveScript: '/tmp/out.ad', force: true },
315+
});
316+
317+
expect(session.recordSession).toBe(true);
318+
expect(session.scriptPublication).toEqual(
319+
authoringPublication('armed', { path: '/tmp/out.ad', force: true }),
320+
);
321+
});

‎src/daemon/__tests__/session-script-writer.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -680,3 +680,49 @@ test('write() publishes atomically: no stray temp file survives a successful rep
680680
expect(fs.readdirSync(path.dirname(outPath))).toEqual([path.basename(outPath)]);
681681
expect(fs.readFileSync(outPath, 'utf8')).toContain(HEAL_COMPLETE_SENTINEL);
682682
});
683+
684+
// --- #1533: an ABORTED ordinary authoring recording publishes nothing, and the
685+
// lifecycle alone decides that — a session handed to the writer still recording
686+
// is refused on the strength of its terminal status ---
687+
688+
test('#1533: write() publishes nothing for an aborted authoring lifecycle that is still recording', () => {
689+
const root = mkdtempForTestSync('agent-device-script-writer-authoring-aborted-');
690+
const sessionsDir = path.join(root, 'sessions');
691+
const writer = new SessionScriptWriter(sessionsDir);
692+
// The production shape after `open --save-script` -> `open --save-script`:
693+
// the second open aborted the lifecycle AND cleared recording, then its own
694+
// recorded action's `--save-script` ingress set the boolean back to true.
695+
const session = makeAuthoringSession('default', {
696+
scriptPublication: authoringPublication('aborted'),
697+
actions: [action({ command: 'click', positionals: ['id="save"'] })],
698+
});
699+
700+
expect(writer.write(session)).toEqual({ written: false });
701+
expect(fs.existsSync(sessionsDir)).toBe(false);
702+
});
703+
704+
test('#1533: the abort is terminal per-target too — an explicit --save-script path is not written either', () => {
705+
const root = mkdtempForTestSync('agent-device-script-writer-authoring-aborted-explicit-');
706+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
707+
const outPath = path.join(root, 'flows', 'aborted.ad');
708+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
709+
const session = makeAuthoringSession('default', {
710+
scriptPublication: authoringPublication('aborted', { path: outPath }),
711+
actions: [action({ command: 'click', positionals: ['id="save"'] })],
712+
});
713+
714+
expect(writer.write(session, { force: true })).toEqual({ written: false });
715+
expect(fs.readdirSync(path.dirname(outPath))).toEqual([]);
716+
});
717+
718+
test('#1533: an ARMED authoring recording is untouched by the abort gate', () => {
719+
const root = mkdtempForTestSync('agent-device-script-writer-authoring-armed-');
720+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
721+
const session = makeAuthoringSession('default', {
722+
scriptPublication: authoringPublication('armed'),
723+
actions: [action({ command: 'click', positionals: ['id="save"'] })],
724+
});
725+
726+
const { parsed } = writeAndParse(writer, session);
727+
expect(parsed.actions.map((a) => a.command)).toEqual(['click']);
728+
});

‎src/daemon/handlers/__tests__/session-close-script.test.ts‎

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from 'node:path';
33
import { afterEach, expect, test, vi } from 'vitest';
44
import { AppError } from '@agent-device/kernel/errors';
55
import {
6+
authoringPublication,
67
makeIosSession,
78
makeRepairCompleteSession,
89
} from '../../../__tests__/test-utils/session-factories.ts';
@@ -25,7 +26,8 @@ afterEach(() => {
2526
function setup(name: string, session = makeIosSession(name, { appBundleId: 'com.example.app' })) {
2627
const root = mkdtempForTestSync('agent-device-session-close-script-');
2728
roots.push(root);
28-
const sessionStore = new SessionStore(path.join(root, 'sessions'));
29+
const sessionsDir = path.join(root, 'sessions');
30+
const sessionStore = new SessionStore(sessionsDir);
2931
sessionStore.set(name, session);
3032
const req: DaemonRequest = {
3133
token: 'token',
@@ -34,7 +36,7 @@ function setup(name: string, session = makeIosSession(name, { appBundleId: 'com.
3436
positionals: [],
3537
flags: {},
3638
};
37-
return { req, session, sessionStore };
39+
return { req, session, sessionStore, sessionsDir };
3840
}
3941

4042
test('failed repair publication removes only its synthetic close before retry', () => {
@@ -110,3 +112,58 @@ test('ordinary publication failure retains its close action after making the err
110112
},
111113
});
112114
});
115+
116+
// --- #1533: a bare `close` after an aborted --save-script re-arm publishes nothing ---
117+
//
118+
// `close --save-script` on this session is refused by `assertTerminalRecordingCloseAllowed`
119+
// with "Retry with plain close; it will tear down the session without writing." These pin
120+
// that promise: the plain-close teardown path must write nothing.
121+
122+
test('#1533: bare close on an aborted authoring session writes no script', () => {
123+
const { req, session, sessionStore, sessionsDir } = setup(
124+
'aborted',
125+
makeIosSession('aborted', {
126+
appBundleId: 'com.example.app',
127+
// Post-`abortAuthoringOnSecondOpen`, then re-armed by the second open's own
128+
// `--save-script` flag ingress.
129+
recordSession: true,
130+
scriptPublication: authoringPublication('aborted'),
131+
actions: [{ ts: 1, command: 'click', positionals: ['id="save"'], flags: {} }],
132+
}),
133+
);
134+
135+
expect(
136+
finalizeOrdinaryCloseScript({
137+
req,
138+
session,
139+
sessionStore,
140+
platformCloseError: undefined,
141+
}),
142+
).toBeUndefined();
143+
144+
expect(sessionStore.get('aborted')?.scriptPublication).toEqual(authoringPublication('aborted'));
145+
expect(fs.existsSync(sessionsDir) ? fs.readdirSync(sessionsDir) : []).toEqual([]);
146+
});
147+
148+
test('#1533: an ordinary armed authoring session still publishes on bare close', () => {
149+
const { req, session, sessionStore, sessionsDir } = setup(
150+
'armed',
151+
makeIosSession('armed', {
152+
appBundleId: 'com.example.app',
153+
recordSession: true,
154+
scriptPublication: authoringPublication('armed'),
155+
actions: [{ ts: 1, command: 'click', positionals: ['id="save"'], flags: {} }],
156+
}),
157+
);
158+
159+
expect(
160+
finalizeOrdinaryCloseScript({
161+
req,
162+
session,
163+
sessionStore,
164+
platformCloseError: undefined,
165+
}),
166+
).toBeUndefined();
167+
168+
expect(fs.readdirSync(sessionsDir)).toHaveLength(1);
169+
});

‎src/daemon/handlers/__tests__/session-open-surface.test.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,16 @@
11
import assert from 'node:assert/strict';
22
import { test } from 'vitest';
33
import { AppError } from '@agent-device/kernel/errors';
4-
import { buildOpenResult, resolveRequestedOpenSurface } from '../session-open-surface.ts';
4+
import {
5+
buildNextOpenSession,
6+
buildOpenResult,
7+
resolveRequestedOpenSurface,
8+
} from '../session-open-surface.ts';
9+
import {
10+
authoringPublication,
11+
makeIosSession,
12+
} from '../../../__tests__/test-utils/session-factories.ts';
13+
import { IOS_SIMULATOR } from '../../../__tests__/test-utils/device-fixtures.ts';
514

615
test('resolveRequestedOpenSurface rejects surface flag on iOS', () => {
716
assert.throws(
@@ -48,3 +57,54 @@ test('buildOpenResult exposes the Vega serial without leaking an internal platfo
4857
assert.equal(result.serial, 'amazon-vvd');
4958
assert.equal(result.target, 'tv');
5059
});
60+
61+
// --- #1533: `--save-script` arms recording through the publication lifecycle, not around it ---
62+
//
63+
// A re-open is the surface that used to set `recordSession` on its own. An ABORTED authoring
64+
// lifecycle is terminal, so the flag must arm nothing here either — otherwise the session keeps
65+
// paying recording-time costs (the direct-selector fast paths stay disabled) for a recording that
66+
// can never publish, and the writer is the only thing standing between it and a stray script.
67+
68+
function reopen(existingSession: ReturnType<typeof makeIosSession>, saveScript: boolean) {
69+
return buildNextOpenSession({
70+
existingSession,
71+
sessionName: existingSession.name,
72+
device: IOS_SIMULATOR,
73+
surface: 'app',
74+
appBundleId: 'com.example.other',
75+
saveScript,
76+
});
77+
}
78+
79+
test('#1533: re-opening an aborted authoring session with --save-script does not re-arm recording', () => {
80+
const aborted = makeIosSession('s', {
81+
recordSession: false,
82+
scriptPublication: authoringPublication('aborted'),
83+
});
84+
85+
assert.equal(reopen(aborted, true).recordSession, false);
86+
});
87+
88+
test('#1533: an aborted lifecycle that is already recording is corrected, not carried forward', () => {
89+
const drifted = makeIosSession('s', {
90+
recordSession: true,
91+
scriptPublication: authoringPublication('aborted'),
92+
});
93+
94+
assert.equal(reopen(drifted, true).recordSession, false);
95+
});
96+
97+
test('a re-open with --save-script still arms recording for a session with no publication yet', () => {
98+
const plain = makeIosSession('s', { recordSession: false });
99+
100+
assert.equal(reopen(plain, true).recordSession, true);
101+
});
102+
103+
test('a re-open without --save-script leaves an armed authoring session recording', () => {
104+
const armed = makeIosSession('s', {
105+
recordSession: true,
106+
scriptPublication: authoringPublication('armed'),
107+
});
108+
109+
assert.equal(reopen(armed, false).recordSession, true);
110+
});

‎src/daemon/handlers/session-close-script.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
effectiveWriteForce,
99
isSessionScriptPublished,
1010
markCloseGeneratedPublicationDone,
11+
recordSessionAfterSaveScriptFlag,
1112
} from '../session-script-publication-capability.ts';
1213
import { abortRepairTransaction, isRepairArmedSession } from '../session-replay-transaction.ts';
1314

@@ -80,7 +81,9 @@ export function finalizeOrdinaryCloseScript(params: {
8081
// The recorded close action already armed target/force through the recorder's flag ingress.
8182
// On a platform-close failure that action was never recorded; the log still publishes, but —
8283
// as before this migration — to the session default, not the request's explicit path.
83-
if (req.flags?.saveScript) session.recordSession = true;
84+
if (req.flags?.saveScript) {
85+
session.recordSession = recordSessionAfterSaveScriptFlag(session, true);
86+
}
8487

8588
try {
8689
const result = sessionStore.writeSessionLog(session, {

‎src/daemon/handlers/session-close.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,9 +291,12 @@ async function stopOrRetainAppleRunnerAfterClose(
291291
// fallback chains but no `target-v1` recording-time evidence — degraded replay verification with
292292
// no signal to the caller. Recording-time evidence can only be captured from action zero
293293
// (`armAuthoringOnOpen`), so an unarmed session has nothing to retroactively arm; the only
294-
// correct response is refusal, before any teardown or publication work runs. This intentionally
295-
// does not resolve #1533 (aborted-mid-recording close --save-script); that is a distinct,
296-
// already-armed case with its own resolution.
294+
// correct response is refusal, before any teardown or publication work runs.
295+
//
296+
// #1533 (aborted-mid-recording) is the adjacent already-armed case: this refusal promises "plain
297+
// close tears down without writing", and an ABORTED authoring lifecycle keeps that promise —
298+
// `--save-script` re-arms nothing on any surface (`recordSessionAfterSaveScriptFlag`) and the
299+
// writer refuses to publish the lifecycle from every path that reaches it.
297300
function assertTerminalRecordingCloseAllowed(req: DaemonRequest, session: SessionState): void {
298301
if (!req.flags?.saveScript) return;
299302
if (isAuthoringArmedSession(session)) return;

0 commit comments

Comments
 (0)