Skip to content

Commit 83d189f

Browse files
committed
fix: match arm-time preflight force to per-target retarget contract
Re-review ordering-mismatch fix. The preflight computed effective force as `req.flags?.force || preRunSession.saveScriptForce`, accepting persisted force regardless of whether THIS request retargets. So a `--from` continuation with explicit `--save-script=b.ad` (no live force) on a session forced for a.ad would PASS the preflight, run every step, then have `applySaveScriptRetarget` clear the force for b.ad, and finally refuse the existing b.ad at publish time — defeating the arm-time-preflight point and mutating the session mid-run. Now the effective-force decision is computed inside `preflightSaveScriptTarget` against the target THIS request resolves to (the same one the armer will set), matching `applySaveScriptRetarget`'s per-target contract: live force always bypasses; persisted force bypasses ONLY when `targetPath === existingSaveScriptPath` (same target). A retarget to a different path without live force is now refused BEFORE any step dispatches. The preflight stays read-only (runs before the armer; never mutates the session). Regression: a --from continuation retargeting to an existing b.ad without live force fails at the preflight, dispatches zero steps, and leaves saveScriptPath/ saveScriptForce unchanged. Verified it fails (leg passes preflight, runs) when the fix is reverted. Same-target continuation and live-force retarget stay correct.
1 parent 7d632b1 commit 83d189f

2 files changed

Lines changed: 107 additions & 11 deletions

File tree

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

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,86 @@ test('#1258 preflight honors PERSISTED force: a --from continuation without --fo
682682
expect(sessionStore.get(sessionName)?.saveScriptForce).toBe(true);
683683
});
684684

685+
test('#1258 preflight is per-target: a --from continuation RETARGETING to an existing <b> WITHOUT live force is refused BEFORE dispatch and leaves the session target unmutated', async () => {
686+
const { root, sessionStore, sessionName, logPath } = setup(
687+
'agent-device-repair-transaction-preflight-retarget-',
688+
);
689+
const filePath = writeReplayFile(root, [
690+
'open "Demo" --relaunch',
691+
SAVE_ANNOTATION,
692+
'click id="save"',
693+
'click id="confirm"',
694+
'close',
695+
]);
696+
const targetA = path.join(root, 'a.ad');
697+
const targetB = path.join(root, 'b.ad');
698+
// <b> already exists (nobody opted to overwrite it); <a> does not, so leg 1
699+
// arms/forces <a> cleanly.
700+
fs.writeFileSync(targetB, 'context platform=ios device="x"\nclick id="unrelated"\n');
701+
const beforeB = fs.readFileSync(targetB, 'utf8');
702+
const spy: DaemonRequest[] = [];
703+
const invoke = makeRecordingReplayInvoke({
704+
sessionStore,
705+
sessionName,
706+
spy,
707+
evidence: (req) => (req.command === 'click' ? freshEvidence('confirm', 'Confirm') : undefined),
708+
});
709+
710+
// Leg 1: `--save-script=<a> --force` — arms + PERSISTS force for <a>, then
711+
// diverges (nothing published).
712+
const leg1 = await runReplayScriptFile({
713+
req: baseReq({ positionals: [filePath], flags: { saveScript: targetA, force: true } }),
714+
sessionName,
715+
logPath,
716+
sessionStore,
717+
invoke,
718+
});
719+
expect(leg1.ok).toBe(false);
720+
if (leg1.ok) return;
721+
const divergence = leg1.error.details?.divergence as { resume: { planDigest: string } };
722+
const session = sessionStore.get(sessionName)!;
723+
expect(session.saveScriptPath).toBe(targetA);
724+
expect(session.saveScriptForce).toBe(true);
725+
// The agent's corrective press.
726+
sessionStore.recordAction(session, {
727+
command: 'press',
728+
positionals: ['@e7'],
729+
flags: {},
730+
result: { selectorChain: ['id="save-v2"'] },
731+
targetEvidence: freshEvidence('save-v2', 'Save V2'),
732+
});
733+
const dispatchesBeforeLeg2 = spy.length;
734+
735+
// Leg 2: `--from N --save-script=<b>` (explicit RETARGET, NO live force) — <b>
736+
// exists. The persisted force was granted for <a>, and
737+
// `applySaveScriptRetarget` WOULD clear it for <b>; the preflight must MATCH
738+
// that per-target contract and REFUSE here, before any step dispatches,
739+
// instead of executing the leg and only refusing at publish time.
740+
const leg2 = await runReplayScriptFile({
741+
req: baseReq({
742+
positionals: [filePath],
743+
flags: { saveScript: targetB, replayFrom: 3, replayPlanDigest: divergence.resume.planDigest },
744+
}),
745+
sessionName,
746+
logPath,
747+
sessionStore,
748+
invoke,
749+
});
750+
expect(leg2.ok).toBe(false);
751+
if (!leg2.ok) {
752+
expect(leg2.error.code).toBe('COMMAND_FAILED');
753+
expect(leg2.error.message).toMatch(/already exists/);
754+
}
755+
// Not a single step of leg 2 dispatched — refused BEFORE the loop.
756+
expect(spy.length).toBe(dispatchesBeforeLeg2);
757+
// READ-ONLY: the rejected request left the session target untouched — still
758+
// armed/forced for <a>, never retargeted to <b>.
759+
expect(sessionStore.get(sessionName)?.saveScriptPath).toBe(targetA);
760+
expect(sessionStore.get(sessionName)?.saveScriptForce).toBe(true);
761+
// <b> is byte-for-byte untouched.
762+
expect(fs.readFileSync(targetB, 'utf8')).toBe(beforeB);
763+
});
764+
685765
test('#1258 force is per-target: re-arming --save-script=<b> WITHOUT --force drops force persisted for <a>, so <b> is NOT overwritten', async () => {
686766
const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup(
687767
'agent-device-repair-transaction-retarget-clears-force-',

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

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -257,13 +257,14 @@ export async function runReplayScriptFile(params: {
257257
// refuse-on-exist at publish time (`publishHealedScriptAtomically`, at
258258
// `close`/completion). Computes the SAME target `armReplaySaveScriptStep`
259259
// below would resolve, without needing the session to exist yet, and
260-
// honors the SAME effective force decision publication uses — the live
261-
// `--force`/`--overwrite` OR the one persisted at arm time
262-
// (`saveScriptForce`), so a `--from` continuation that does not repeat the
263-
// flag is not rejected on a target a prior `--force` leg already authorized.
260+
// honors the SAME effective force decision publication uses — read-only:
261+
// it never mutates the session (it runs BEFORE `applySaveScriptRetarget`),
262+
// so `liveForce`/`persistedForce` are passed separately for it to apply the
263+
// per-target rule against the target it computes.
264264
const saveScriptPreflight = preflightSaveScriptTarget({
265265
saveScript: req.flags?.saveScript,
266-
force: Boolean(req.flags?.force || preRunSession?.saveScriptForce),
266+
liveForce: req.flags?.force,
267+
persistedForce: preRunSession?.saveScriptForce,
267268
sourcePath: resolved,
268269
existingSaveScriptPath: preRunSession?.saveScriptPath,
269270
});
@@ -532,22 +533,37 @@ function preflightReplayAgainstActiveRepair(params: {
532533
* wins; otherwise an already-armed session's existing path if this is a
533534
* `--from` continuation leg reusing it, else the default `<stem>.healed.ad`
534535
* sibling) WITHOUT needing the session to exist yet, so it runs before step 1
535-
* dispatches even when that step is the `open` that creates the session. A
536-
* no-op when `--save-script` was not passed this invocation, or when `force`
537-
* was — the caller explicitly opted into overwriting.
536+
* dispatches even when that step is the `open` that creates the session.
537+
* READ-ONLY: it never mutates the session (it runs before
538+
* `applySaveScriptRetarget`).
539+
*
540+
* The effective-force decision MATCHES `applySaveScriptRetarget`'s per-target
541+
* contract, computed against the target THIS request resolves to: a live
542+
* `--force`/`--overwrite` always bypasses; a PERSISTED `saveScriptForce`
543+
* bypasses ONLY when this request writes to the SAME target it was granted for
544+
* (`targetPath === existingSaveScriptPath`). An explicit RETARGET to a
545+
* different path without a live force does NOT bypass here — because
546+
* `applySaveScriptRetarget` will CLEAR that persisted force for the new target
547+
* before publication anyway, so letting the run execute (mutating the session
548+
* mid-flight) only to refuse the existing target at the end is exactly what
549+
* this preflight exists to prevent. A no-op when `--save-script` was not passed.
538550
*/
539551
function preflightSaveScriptTarget(params: {
540552
saveScript: boolean | string | undefined;
541-
force: boolean | undefined;
553+
liveForce: boolean | undefined;
554+
persistedForce: boolean | undefined;
542555
sourcePath: string;
543556
existingSaveScriptPath: string | undefined;
544557
}): DaemonResponse | undefined {
545-
const { saveScript, force, sourcePath, existingSaveScriptPath } = params;
546-
if (!saveScript || force) return undefined;
558+
const { saveScript, liveForce, persistedForce, sourcePath, existingSaveScriptPath } = params;
559+
if (!saveScript) return undefined;
547560
const targetPath =
548561
typeof saveScript === 'string'
549562
? expandSessionPath(saveScript)
550563
: (existingSaveScriptPath ?? healedScriptSiblingPath(sourcePath));
564+
const effectiveForce =
565+
Boolean(liveForce) || (Boolean(persistedForce) && targetPath === existingSaveScriptPath);
566+
if (effectiveForce) return undefined;
551567
if (!fs.existsSync(targetPath)) return undefined;
552568
return errorResponse(
553569
'COMMAND_FAILED',

0 commit comments

Comments
 (0)