Skip to content

Commit 93c3462

Browse files
committed
feat: add --force/--overwrite for --save-script, arm-time EEXIST preflight
#1235 made healed-script publication refuse-on-exist. #1258 adds an escape hatch: --force (alias --overwrite) on open/close/replay makes publishHealedScriptAtomically atomically REPLACE an existing target (renameSync) instead of refusing. The flag threads CLI -> daemon request -> SessionState.saveScriptForce (persisted at arm time, like saveScriptPath, so a later close/auto-commit that doesn't repeat the flag still honors it) -> the publish primitive. Default (flag absent) is unchanged: refuse-on-exist. Second half: an arm-time EEXIST preflight in session-replay-runtime.ts now fails a repair-armed replay --save-script BEFORE any step dispatches when its target already exists and --force is not set, instead of only failing at publish time after the whole repair run (and its corrective steps) has already executed against the device.
1 parent 54977f3 commit 93c3462

12 files changed

Lines changed: 348 additions & 33 deletions

‎src/client/client-types.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,8 @@ export type AppOpenOptions = AgentDeviceRequestOverrides &
292292
launchArgs?: string[];
293293
relaunch?: boolean;
294294
saveScript?: boolean | string;
295+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
296+
force?: boolean;
295297
deviceHub?: boolean;
296298
testIme?: boolean;
297299
noRecord?: boolean;
@@ -316,6 +318,9 @@ export type AppOpenResult = {
316318
export type AppCloseOptions = AgentDeviceRequestOverrides & {
317319
app?: string;
318320
shutdown?: boolean;
321+
saveScript?: boolean | string;
322+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
323+
force?: boolean;
319324
};
320325

321326
export type AppCloseResult = {
@@ -866,6 +871,8 @@ export type ReplayRunOptions = AgentDeviceRequestOverrides &
866871
* `<stem>.healed.ad` when the repair ends with `close --save-script`.
867872
*/
868873
saveScript?: boolean | string;
874+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
875+
force?: boolean;
869876
};
870877

871878
export type ReplayTestOptions = AgentDeviceRequestOverrides &
@@ -1072,6 +1079,8 @@ export type InternalRequestOptions = AgentDeviceClientConfig &
10721079
relaunch?: boolean;
10731080
shutdown?: boolean;
10741081
saveScript?: boolean | string;
1082+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
1083+
force?: boolean;
10751084
deviceHub?: boolean;
10761085
testIme?: boolean;
10771086
noRecord?: boolean;
@@ -1110,7 +1119,12 @@ export type AgentDeviceClient = {
11101119
options?: AgentDeviceRequestOverrides & Pick<AgentDeviceClientConfig, 'stateDir'>,
11111120
) => Promise<string>;
11121121
close: (
1113-
options?: AgentDeviceRequestOverrides & { shutdown?: boolean },
1122+
options?: AgentDeviceRequestOverrides & {
1123+
shutdown?: boolean;
1124+
saveScript?: boolean | string;
1125+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
1126+
force?: boolean;
1127+
},
11141128
) => Promise<SessionCloseResult>;
11151129
artifacts: (options?: CloudArtifactsOptions) => Promise<AgentArtifactsResult>;
11161130
};

‎src/commands/cli-grammar/flag-definitions-connection.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,11 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
195195
},
196196
{
197197
key: 'force',
198-
names: ['--force'],
198+
names: ['--force', '--overwrite'],
199199
type: 'boolean',
200-
usageLabel: '--force',
201-
usageDescription: 'Force connection state replacement when reconnecting',
200+
usageLabel: '--force, --overwrite',
201+
usageDescription:
202+
'Force replacement of existing state (connect: replace an active connection; --save-script: overwrite an existing target instead of refusing)',
202203
},
203204
{
204205
key: 'noLogin',

‎src/commands/management/app.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ const openCommandMetadata = defineFieldCommandMetadata(
4040
),
4141
relaunch: booleanField('Force relaunch.'),
4242
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
43+
force: booleanField(
44+
'Overwrite an existing --save-script target instead of refusing (alias: --overwrite).',
45+
),
4346
deviceHub: booleanField('Use Xcode Device Hub when surfacing Apple simulators.'),
4447
testIme: booleanField(
4548
'Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).',
@@ -65,6 +68,9 @@ const closeCommandMetadata = defineFieldCommandMetadata(
6568
app: stringField('Optional app to close.'),
6669
shutdown: booleanField('Shutdown the session/device where supported.'),
6770
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
71+
force: booleanField(
72+
'Overwrite an existing --save-script target instead of refusing (alias: --overwrite).',
73+
),
6874
},
6975
);
7076

@@ -131,6 +137,7 @@ const openCliSchema = {
131137
'deviceHub',
132138
'testIme',
133139
'saveScript',
140+
'force',
134141
'noRecord',
135142
'relaunch',
136143
'surface',
@@ -143,7 +150,7 @@ const openCliSchema = {
143150

144151
const closeCliSchema = {
145152
positionalArgs: ['app?'],
146-
allowedFlags: ['saveScript', 'shutdown'],
153+
allowedFlags: ['saveScript', 'force', 'shutdown'],
147154
} as const satisfies CommandSchemaOverride;
148155

149156
const appsCliReader: CliReader = (_positionals, flags) => ({
@@ -161,6 +168,7 @@ const openCliReader: CliReader = (positionals, flags) => ({
161168
launchArgs: flags.launchArgs,
162169
relaunch: flags.relaunch,
163170
saveScript: flags.saveScript,
171+
force: flags.force,
164172
deviceHub: flags.deviceHub,
165173
testIme: flags.testIme,
166174
noRecord: flags.noRecord,
@@ -175,6 +183,7 @@ const closeCliReader: CliReader = (positionals, flags) => ({
175183
app: positionals[0],
176184
shutdown: flags.shutdown,
177185
saveScript: flags.saveScript,
186+
force: flags.force,
178187
});
179188

180189
const appsDaemonWriter: DaemonWriter = direct(PUBLIC_COMMANDS.apps);

‎src/commands/replay/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ export const replayCommandMetadata = defineFieldCommandMetadata(
4949
// from the first replay attempt; optional string value is the healed
5050
// script's output path.
5151
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
52+
// #1258: overwrite an existing --save-script target (arm-time preflight +
53+
// publish) instead of refusing. Alias: --overwrite.
54+
force: booleanField(),
5255
},
5356
);
5457

@@ -96,6 +99,7 @@ const replayCliSchema = {
9699
'timeoutMs',
97100
'out',
98101
'saveScript',
102+
'force',
99103
],
100104
} as const satisfies CommandSchemaOverride;
101105

@@ -130,6 +134,7 @@ export const replayCliReader: CliReader = (positionals, flags) => ({
130134
resumeFrom: flags.replayFrom,
131135
resumePlanDigest: flags.replayPlanDigest,
132136
saveScript: flags.saveScript,
137+
force: flags.force,
133138
});
134139

135140
export const testCliReader: CliReader = (positionals, flags) => ({

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,77 @@ test('write() now refuses to clobber a stale PARTIAL (non-sentinel) .healed.ad a
283283
expect(fs.readFileSync(healedPath, 'utf8')).toBe(before);
284284
});
285285

286+
// --- #1258: `--force`/`--overwrite` opts into replacing an existing target
287+
// atomically instead of refusing. ---
288+
289+
test('write(session, { force: true }) overwrites an existing COMPLETE target atomically', () => {
290+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-'));
291+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
292+
const healedPath = path.join(root, 'flows', 'login.healed.ad');
293+
fs.mkdirSync(path.dirname(healedPath), { recursive: true });
294+
fs.writeFileSync(
295+
healedPath,
296+
`context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`,
297+
);
298+
299+
const session = makeIosSession('default', {
300+
recordSession: true,
301+
saveScriptBoundary: 0,
302+
saveScriptComplete: true,
303+
saveScriptPath: healedPath,
304+
saveScriptDefaultedHealedPath: true,
305+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
306+
});
307+
308+
const result = writer.write(session, { force: true });
309+
expect(result.written).toBe(true);
310+
expect(result.written && result.path).toBe(healedPath);
311+
const parsed = parseReplayScriptDetailed(fs.readFileSync(healedPath, 'utf8'));
312+
expect(parsed.actions.map((a) => a.positionals[0])).toEqual(['id="new"']);
313+
// The overwrite is atomic (rename-replace): only the published target
314+
// remains in the directory, no stray temp file left behind.
315+
expect(fs.readdirSync(path.dirname(healedPath))).toEqual([path.basename(healedPath)]);
316+
});
317+
318+
test('write(session, { force: true }) overwrites an existing target for ORDINARY (non-repair) recording too', () => {
319+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-ordinary-'));
320+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
321+
const outPath = path.join(root, 'flows', 'existing.ad');
322+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
323+
fs.writeFileSync(outPath, 'context platform=ios device="x"\nclick id="old"\n');
324+
325+
const session = makeIosSession('default', {
326+
recordSession: true,
327+
// No saveScriptBoundary: ordinary open/close --save-script, not a repair.
328+
saveScriptPath: outPath,
329+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
330+
});
331+
332+
const result = writer.write(session, { force: true });
333+
expect(result.written).toBe(true);
334+
const parsed = parseReplayScriptDetailed(fs.readFileSync(outPath, 'utf8'));
335+
expect(parsed.actions.map((a) => a.positionals[0])).toEqual(['id="new"']);
336+
});
337+
338+
test('write(session) without { force: true } still refuses, even when a prior write in the same test used force', () => {
339+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-default-'));
340+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
341+
const outPath = path.join(root, 'flows', 'existing.ad');
342+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
343+
fs.writeFileSync(outPath, 'context platform=ios device="x"\nclick id="old"\n');
344+
const before = fs.readFileSync(outPath, 'utf8');
345+
346+
const session = makeIosSession('default', {
347+
recordSession: true,
348+
saveScriptPath: outPath,
349+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
350+
});
351+
352+
// Default (no options / force omitted): refuse-on-exist, unchanged.
353+
expect(() => writer.write(session)).toThrow(/already exists/);
354+
expect(fs.readFileSync(outPath, 'utf8')).toBe(before);
355+
});
356+
286357
// The lock/lease machinery previously here (acquireLease/releaseLease/
287358
// stealExpiredLease/the three-writer interleaving) is gone: the publish
288359
// primitive is now a single exclusive `linkSync`, which already decides a

‎src/daemon/handlers/__tests__/session-replay-repair-transaction.test.ts‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ import { AppError } from '../../../kernel/errors.ts';
6565
import { makeIosSession } from '../../../__tests__/test-utils/session-factories.ts';
6666
import { HEAL_COMPLETE_SENTINEL } from '../../session-script-writer.ts';
6767
import { parseReplayScriptDetailed } from '../../../replay/script.ts';
68+
import type { DaemonRequest } from '../../types.ts';
6869
import {
6970
baseReplayRequest as baseReq,
7071
writeReplayFile,
@@ -512,6 +513,108 @@ test('BLOCKER 2b/2c: a close whose commit FAILS (no-clobber) keeps the session f
512513
expect(promoted.actions.filter((a) => a.command === 'close')).toHaveLength(1);
513514
});
514515

516+
// --- #1258: `--force`/`--overwrite` on `--save-script`. ---
517+
518+
test('#1258: close --save-script --force overwrites an existing COMPLETE healed .ad instead of refusing', async () => {
519+
const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup(
520+
'agent-device-repair-transaction-force-overwrite-',
521+
);
522+
makeCompleteRepairSession(sessionStore, sessionName, root);
523+
// A prior COMPLETE (sentinel-marked) healed artifact already sits at the
524+
// default path — `--force` must overwrite it instead of refusing.
525+
fs.writeFileSync(
526+
path.join(root, 'flow.healed.ad'),
527+
`context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`,
528+
);
529+
530+
const closeResponse = await handleCloseCommand({
531+
req: {
532+
token: 't',
533+
session: sessionName,
534+
command: 'close',
535+
positionals: [],
536+
flags: { force: true },
537+
},
538+
sessionName,
539+
logPath,
540+
sessionStore,
541+
leaseRegistry,
542+
});
543+
544+
expect(closeResponse.ok).toBe(true);
545+
expect(sessionStore.get(sessionName)).toBeUndefined();
546+
const healedPath = path.join(root, 'flow.healed.ad');
547+
if (closeResponse.ok) expect(closeResponse.data?.savedScript).toBe(healedPath);
548+
const script = fs.readFileSync(healedPath, 'utf8');
549+
expect(script).toContain(HEAL_COMPLETE_SENTINEL);
550+
const parsed = parseReplayScriptDetailed(script);
551+
// The new repair's own actions replaced the stale prior artifact — the old
552+
// content is gone, never merged/appended.
553+
expect(parsed.actions.some((a) => a.positionals[0] === 'id="old"')).toBe(false);
554+
expect(parsed.actions.map((a) => a.command)).toEqual(['open', 'press', 'close']);
555+
});
556+
557+
test('#1258 arm-time preflight: an existing --save-script target rejects BEFORE any step runs', async () => {
558+
const { root, sessionStore, sessionName, logPath } = setup(
559+
'agent-device-repair-transaction-arm-preflight-',
560+
);
561+
const filePath = writeReplayFile(root, ['open "Demo" --relaunch', 'close']);
562+
// The default healed sibling already exists — a prior repair, or an
563+
// unrelated stale file sitting at that path.
564+
fs.writeFileSync(path.join(root, 'flow.healed.ad'), 'context platform=ios device="x"\n');
565+
566+
const spy: DaemonRequest[] = [];
567+
const invoke = makeRecordingReplayInvoke({ sessionStore, sessionName, spy });
568+
569+
const result = await runReplayScriptFile({
570+
req: baseReq({ positionals: [filePath], flags: { saveScript: true } }),
571+
sessionName,
572+
logPath,
573+
sessionStore,
574+
invoke,
575+
});
576+
577+
expect(result.ok).toBe(false);
578+
if (!result.ok) {
579+
expect(result.error.code).toBe('COMMAND_FAILED');
580+
expect(result.error.message).toMatch(/already exists/);
581+
}
582+
// Not a single step dispatched — the preflight fired BEFORE the loop, not
583+
// merely at the end (publish time). Even `open` never ran.
584+
expect(spy).toHaveLength(0);
585+
// The session was never armed (no boundary stamped) either — the whole
586+
// repair-arm side effect is skipped, not just the dispatch.
587+
expect(sessionStore.get(sessionName)?.saveScriptBoundary).toBeUndefined();
588+
});
589+
590+
test('#1258: --force skips the arm-time preflight and the replay proceeds despite the existing target', async () => {
591+
const { root, sessionStore, sessionName, logPath } = setup(
592+
'agent-device-repair-transaction-arm-preflight-force-',
593+
);
594+
const filePath = writeReplayFile(root, ['open "Demo" --relaunch', 'close']);
595+
fs.writeFileSync(path.join(root, 'flow.healed.ad'), 'context platform=ios device="x"\n');
596+
597+
const spy: DaemonRequest[] = [];
598+
const invoke = makeRecordingReplayInvoke({ sessionStore, sessionName, spy });
599+
600+
const result = await runReplayScriptFile({
601+
req: baseReq({ positionals: [filePath], flags: { saveScript: true, force: true } }),
602+
sessionName,
603+
logPath,
604+
sessionStore,
605+
invoke,
606+
});
607+
608+
expect(result.ok).toBe(true);
609+
// `open` dispatched — the preflight did not block it. The terminal `close`
610+
// is skipped while repair-armed (existing, unrelated behavior), so `open`
611+
// is the only step this minimal script actually dispatches.
612+
expect(spy.map((r) => r.command)).toEqual(['open']);
613+
// `force` is persisted on the session from arm time, so a LATER commit
614+
// (e.g. a bare `close`, or teardown) still honors the overwrite.
615+
expect(sessionStore.get(sessionName)?.saveScriptForce).toBe(true);
616+
});
617+
515618
test('BLOCKER 2 (new): a repair close whose PLATFORM close fails never commits a healed .ad claiming a successful close', async () => {
516619
const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup(
517620
'agent-device-repair-transaction-platform-close-fail-',

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

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,17 @@ async function maybeShutdownSessionTarget(params: {
4848
return await shutdownDeviceTarget(device);
4949
}
5050

51+
/**
52+
* #1258: the effective `--force`/`--overwrite` decision for a `close`-time
53+
* publish — this close request's own flag OR'd with whatever was persisted
54+
* on the session at an earlier arm (`open --save-script --force`, or a
55+
* repair's first `replay --save-script --force`). Either source authorizes
56+
* overwriting; neither being set keeps the default refuse-on-exist.
57+
*/
58+
function resolveEffectiveSaveScriptForce(req: DaemonRequest, session: SessionState): boolean {
59+
return Boolean(req.flags?.force || session.saveScriptForce);
60+
}
61+
5162
function shouldRetainAppleRunnerAfterClose(req: DaemonRequest, session: SessionState): boolean {
5263
return (
5364
isIosSimulator(session.device) &&
@@ -91,7 +102,9 @@ function commitRepairBeforeClose(
91102
session: session.name,
92103
...successText(`Closed: ${session.name}`),
93104
});
94-
const result = sessionStore.writeSessionLog(session);
105+
const result = sessionStore.writeSessionLog(session, {
106+
force: resolveEffectiveSaveScriptForce(req, session),
107+
});
95108
if (result.written) return { kind: 'committed', path: result.path };
96109
if (result.error) {
97110
// The session is kept for retry (BLOCKER 2b): roll back the just-recorded
@@ -207,7 +220,7 @@ async function runSessionCloseTeardown(params: {
207220
if (req.flags?.saveScript) {
208221
session.recordSession = true;
209222
}
210-
sessionStore.writeSessionLog(session);
223+
sessionStore.writeSessionLog(session, { force: resolveEffectiveSaveScriptForce(req, session) });
211224
}
212225
await attemptCleanup('materialized_paths', () =>
213226
cleanupRetainedMaterializedPathsForSession(sessionName),

0 commit comments

Comments
 (0)