Skip to content

Commit 1244334

Browse files
thymikeeclaude
andauthored
fix(replay): escape recorded interpolation, run scripts off the event loop, harden Maestro and test flows (#4363)
* fix(replay): escape recorded literal ${...} text in written scripts Replay interpolates every written positional, flag and runtime string, so recorded text such as `type "cost ${amount}"` replayed as an unresolved or substituted variable. The session script writer now emits the `\${` escape the resolver already honours, keeping exact `--record-as` fill placeholders live. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): run runScript in a child process and enforce the 8 MiB HTTP cap runScript ran `vm.runInNewContext` and a `spawnSync` per `http.post` inline in the daemon, blocking every session for up to 30 s per call and ignoring request cancellation. It now runs in a dedicated `run-script-child` process that the daemon awaits with the request signal; the synchronous script semantics stay inside that child. The HTTP child's response travelled over `spawnSync` stdout with Node's 1 MiB default buffer, so bodies above ~1 MiB failed generically while the declared cap was 8 MiB, and the trusted local path had no cap or timeout. Both paths now apply the cap and the 30 s budget, the buffer is sized for the escaped cap, and the child reports the typed AppError. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): prefix map-form launch argument keys like Maestro Maestro 2.5.1 `IOSLaunchArguments.toIOSLaunchArguments` passes a non-boolean map key as `-key value`, the form `UserDefaults` and `ProcessInfo` parsing read; boolean values keep their key. The `launchApp.arguments` map passed bare `key value` pairs instead. The compatibility help now also states runScript's child-process execution, budgets, and response cap. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): cap eraseText at 10000 characters `eraseText` and `eraseText.charactersToErase` accepted any safe integer, and the daemon built `'\b'.repeat(count)`: a large literal or `${VAR}` value allocated a huge string or threw a raw RangeError. Numeric field constraints gain a `max`, enforced at parse time and after variable resolution with the existing INVALID_ARGS diagnostics. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): accept Maestro variable names from -e and AD_VAR_* Maestro flows look up `${[A-Za-z_][A-Za-z0-9_.]*}` names, but the Maestro backend parsed `-e` with the `.ad` UPPER_SNAKE grammar, so `-e username=x` failed and `AD_VAR_username` was silently dropped. The override parsers now take the replay format and apply that format's key grammar; `AD_*` stays reserved for both. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): export wait forms through the shared wait grammar `replay export` handled only `wait <ms>`, `absent`, and `text <q>`, then passed any other first positional to the selector projection, which returns plain words unchanged: `wait stable` exported as a wait for the on-screen text "stable", `wait @e3` as text "@e3", and a bare `wait text` as text "text". The exporter now parses with `parseWaitPositionals`: `stable` exports as waitForAnimationToEnd with a warning, `@ref` and empty text waits are unsupported, and text and selector waits keep their parsed timeout. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): keep divergence suggestion refs inside the published scope The daemon authorizes exactly the projected `screen.refs`, which are ranked, filtered, and capped per response level. Suggestions and target-binding candidates took refs from the full capture, so a returned ref could be outside the authorized scope, and an empty screen published nothing while still returning suggestion refs. The response and overflow artifact now drop any suggestion or candidate ref that is not in the published scope. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): classify test infrastructure failures by typed details only `test` tagged a failure as infrastructure when its code or message contained text such as "device offline" or "runner did not accept connection". The divergence message embeds the action label, so a step like `wait text "Device offline"` was tagged and skipped its remaining retries. The message patterns are removed. Runner connect and early-exit failures already carry a typed boot-failure `reason`; adb refusals now classify through their typed `adbFailure` family, which the replay divergence response keeps as a safe cause detail. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(react-native): serialize companion tunnel ensure and stop with a state lock `ensureCompanionTunnel` read the state file, decided to spawn, and wrote the new state without exclusion. Two callers for one profile could both spawn; the later write won and the earlier companion was never tracked or stopped. Ensure and stop now run under a host-kit process lock per companion kind, so a second caller waits, reads the first caller's state, and joins it as a consumer. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(replay): use a declared target-binding kind in the divergence scope case Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * refactor(replay): remove the never-produced actionSourcePaths plumbing `actionSourcePaths` was declared for Maestro actions inlined from a `runFlow` include, but the Maestro engine no longer compiles to `SessionAction[]` and no parser sets it. The field and every `?.[index] ?? resolved` fallback are removed across ad-script, ad-replay, and replay-port. The plan digest keeps hashing `source.path: null`, pinned by a test, so saved resume digests stay valid. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * style: format replay remediation changes Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(layering): record the maestro dependency on command-registry The exporter now parses waits with `@agent-device/command-registry`'s wait grammar, so the declared maestro workspace dependencies include it. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * refactor(maestro): share the numeric constraint check and declare the runScript child entry The parser and runtime resolution repeated the same numeric-field checks; both now call `satisfiesNumericConstraints`. Fallow learns that `run-script-child.ts` is a process entry, like the other build-entry children. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): keep runScript and wait-export edges off the eager closure The runScript child resolver moves into `run-script-execution.ts`, so the daemon port no longer loads the `vm` and HTTP modules that only the child process runs. The wait exporter names the `stable`, `@ref`, and bare `text` keyword forms itself instead of importing the command-registry wait grammar, which removes the maestro dependency on command-registry again. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): address review findings on the replay remediation - Script writer: keep `${NAME}` live only in the text of the fill that `--record-as` parameterized, tracked per action through a new `SessionAction.recordedInputVariable`; every other `${` is escaped. - Maestro launch arguments: the `-key` prefix applies to iOS only. - runScript: the child process gets an outer timeout bounded by the vm budget plus one in-flight `http.post`, beside the cancel signal. - `test` infrastructure: classify runner launches that never accepted a connection through the typed `runner_process_exited` reason and `runnerConnectFailureReason` detail, which divergences now keep. - Client replay/test writers validate `-e` keys with the grammar of each resolved replay format. - Maestro variable keys reject `__proto__`. - `wait stable` with non-numeric or extra arguments is not exported. - The companion concurrency test drops its real sleep and manual cleanup. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(maestro): export multi-token waits whole and test runScript in process - The wait exporter keeps the whole selector or text before an optional trailing timeout: `wait text Sign in 2000` exports "Sign in", and a multi-term selector reaches the Maestro projection as one expression. - The runScript and HTTP child entries are thin shims over `runScriptChildOutput` and `runScriptHttpChildOutput`, which the unit tests now run in process; the installed-package test runs the packaged child, which proves both child entries resolve from the bundled layout. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * test(maestro): fail fast on a dead fixture server and pin runScript error codes Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): escape recorded flag and runtime strings at every depth replay resolves The script writer escaped only top-level strings and arrays in flags and runtime hints, while `resolveReplayAction` interpolates strings at any depth. `escapeReplayStringValues` now mirrors that recursion beside the resolver. Target annotations stay verbatim: replay never interpolates them, which a writer test now pins. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): keep recorded ref labels verbatim in written scripts The ref label parses back into `result.refLabel`, which replay compares literally and never interpolates. Escaping it wrote `Pay \${amount}` and broke ref matching. The writer now leaves it as is; the scoped snapshot flag built from the same label stays escaped because replay does interpolate flags. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): keep every recorder-inserted placeholder live in written scripts Session echo protection (ADR 0017) rewrites later echoes of a `--record-as` literal to `${NAME}` on purpose, but the writer kept a placeholder live only as the whole text of its own record-as fill, so a confirm-field fill or an echoed label replayed the literal placeholder. The recorder now lists, per action, every placeholder name it inserted (`SessionAction.livePlaceholders`, replacing `recordedInputVariable`), and ad-script owns `escapeReplayAction`, the inverse of `resolveReplayAction` over the fields replay interpolates. The writer calls it with the action's live set; the scoped snapshot built from a label carries the same set. The runScript child also runs in its own process group so a cancel or timeout reaps its HTTP child, and the cancel test asserts the typed canceled reason. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 * fix(replay): mark only substituted echo placeholders live and split complex helpers Echo protection now reports the placeholders it actually wrote into the result (occurrence counts before and after), so a registered `foo` beside `foobar` no longer marks `${FOO}` live when only `${FOOBAR}` was inserted, and a literal `${FOO}` in the same action stays escaped. `recordActionEntry`, `parseInterpolation`, and `resolveReplayString` are split into named helpers at their decision steps, below the complexity thresholds. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4 --------- Co-authored-by: Claude <[email protected]>
1 parent 7997dc2 commit 1244334

61 files changed

Lines changed: 1687 additions & 535 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.fallowrc.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
"packages/react-native/src/companion/companion-tunnel.ts",
3636
"src/daemon.ts",
3737
"packages/capture-kit/src/png-worker.ts",
38+
"packages/maestro/src/daemon-port/run-script-child.ts",
39+
"packages/maestro/src/daemon-port/run-script-http-child.ts",
3840
"scripts/patch-xcuitest-runner-icon.ts",
3941
"scripts/write-xcuitest-cache-metadata.ts",
4042
"scripts/xcuitest-build-settings.ts",

‎docs/adr/0017-parameterized-recorded-inputs.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ The map gets one entry for each parameterized fill, added only after the entry o
139139
The map is never serialized: not to the script, the session event log, or diagnostics.
140140
The map has no read API beyond the recorder that owns it.
141141
The map disappears with the session.
142+
A placeholder that echo protection writes into a recorded result is a live script placeholder: the recorder lists its name in `SessionAction.livePlaceholders`, and the script writer escapes every other recorded `${`.
142143

143144
This is not a reversal of the "no secret-to-name table" rule in the Mapping contract above.
144145
That rule rejects the retention of state to influence a *naming* decision.

‎packages/ad-replay/src/internal/__tests__/plan-digest.test.ts‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ function digestFor(
2020
return computeReplayPlanDigest({
2121
actions,
2222
actionLines: actions.map((_, i) => i + 1),
23-
actionSourcePaths: undefined,
2423
metadata: {},
2524
...overrides,
2625
});
@@ -31,6 +30,15 @@ test('computeReplayPlanDigest is a 64-char lowercase hex SHA-256', () => {
3130
assert.match(digest, /^[0-9a-f]{64}$/);
3231
});
3332

33+
test('computeReplayPlanDigest keeps the published digest for an unchanged plan', () => {
34+
const digest = computeReplayPlanDigest({
35+
actions: [action({ command: 'open', positionals: ['Demo'] }), action()],
36+
actionLines: [2, 3],
37+
metadata: { platform: 'ios' },
38+
});
39+
assert.equal(digest, '0641236777b11822d90d446022965629ec99ac2ba1af2d5c637f06dd684fe695');
40+
});
41+
3442
test('computeReplayPlanDigest is stable across repeated computation of the same plan', () => {
3543
const actions = [action(), action({ command: 'open', positionals: ['Demo'] })];
3644
assert.equal(digestFor(actions), digestFor(actions));
@@ -54,15 +62,11 @@ test('computeReplayPlanDigest changes when the command changes', () => {
5462
assert.notEqual(original, edited);
5563
});
5664

57-
test('computeReplayPlanDigest changes when source provenance (path/line) changes', () => {
65+
test('computeReplayPlanDigest changes when the source line changes', () => {
5866
const actions = [action()];
5967
const original = digestFor(actions, { actionLines: [1] });
6068
const movedLine = digestFor(actions, { actionLines: [5] });
6169
assert.notEqual(original, movedLine);
62-
63-
const noSourcePath = digestFor(actions, { actionSourcePaths: undefined });
64-
const withSourcePath = digestFor(actions, { actionSourcePaths: ['/tmp/include.ad'] });
65-
assert.notEqual(noSourcePath, withSourcePath);
6670
});
6771

6872
test('computeReplayPlanDigest changes when platform-conditioned metadata changes', () => {

‎packages/ad-replay/src/internal/__tests__/step-loop.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ function runRequest(
4141
entryIndex: overrides.entryIndex ?? 0,
4242
keepSession: overrides.keepSession,
4343
actionLines: actions.map(() => 1),
44-
actionSourcePaths: undefined,
4544
resolvedPath: 'fixture.ad',
4645
varSources: {},
4746
};

‎packages/ad-replay/src/internal/inspect.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import { resolveReplayEntryIndex, type PendingRecordAndHeal } from './resume.ts'
3232
export type AdReplayManifest = Readonly<{
3333
actions: SessionAction[];
3434
actionLines: number[];
35-
actionSourcePaths: (string | undefined)[] | undefined;
3635
metadata: ReplayScriptMetadata;
3736
/** SHA-256 digest of the canonical plan (`digestFlags` binds the same platform/target the replay invokes with). */
3837
planDigest: string;
@@ -83,7 +82,6 @@ export function inspectAdReplay(
8382
const planDigest = computeReplayPlanDigest({
8483
actions: parsed.actions,
8584
actionLines: parsed.actionLines,
86-
actionSourcePaths: parsed.actionSourcePaths,
8785
metadata: {
8886
platform:
8987
digestFlags?.platform ?? resolveDeclaredScriptPlatform(parsed.actions) ?? metadata.platform,
@@ -94,7 +92,6 @@ export function inspectAdReplay(
9492
return {
9593
actions: parsed.actions,
9694
actionLines: parsed.actionLines,
97-
actionSourcePaths: parsed.actionSourcePaths,
9895
metadata,
9996
planDigest,
10097
resolveEntryIndex: (params) => resolveReplayEntryIndex(params, actionCount, planDigest),

‎packages/ad-replay/src/internal/plan-digest.ts‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ export type ReplayPlanDigestMetadata = {
2424
export function computeReplayPlanDigest(params: {
2525
actions: SessionAction[];
2626
actionLines: number[];
27-
actionSourcePaths?: (string | undefined)[];
2827
metadata: ReplayPlanDigestMetadata;
2928
}): string {
3029
const canonical = buildCanonicalPlan(params);
@@ -35,31 +34,25 @@ export function computeReplayPlanDigest(params: {
3534
function buildCanonicalPlan(params: {
3635
actions: SessionAction[];
3736
actionLines: number[];
38-
actionSourcePaths?: (string | undefined)[];
3937
metadata: ReplayPlanDigestMetadata;
4038
}): unknown {
41-
const { actions, actionLines, actionSourcePaths, metadata } = params;
39+
const { actions, actionLines, metadata } = params;
4240
return {
4341
platform: metadata.platform ?? null,
4442
target: metadata.target ?? null,
45-
steps: actions.map((action, index) =>
46-
canonicalizeAction(action, actionLines[index] ?? null, actionSourcePaths?.[index] ?? null),
47-
),
43+
steps: actions.map((action, index) => canonicalizeAction(action, actionLines[index] ?? null)),
4844
};
4945
}
5046

51-
function canonicalizeAction(
52-
action: SessionAction,
53-
line: number | null,
54-
sourcePath: string | null,
55-
): unknown {
47+
function canonicalizeAction(action: SessionAction, line: number | null): unknown {
5648
return {
5749
command: action.command,
5850
positionals: action.positionals ?? [],
5951
flags: action.flags ?? {},
6052
runtime: action.runtime ?? null,
6153
targetEvidence: action.targetEvidence ?? null,
6254
targetEvidences: action.targetEvidences ?? null,
63-
source: { path: sourcePath, line },
55+
// Published digests hash `path: null`; dropping the key would invalidate every saved resume digest.
56+
source: { path: null, line },
6457
};
6558
}

‎packages/ad-replay/src/internal/runtime-port-types.ts‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -348,9 +348,7 @@ export type AdReplayRunRequest = Readonly<{
348348
* `loc`).
349349
*/
350350
readonly actionLines: readonly number[];
351-
/** Per-action resolved source path when it differs from `resolvedPath` (a `runFlow` include's own file), parallel to `actions`. */
352-
readonly actionSourcePaths: readonly (string | undefined)[] | undefined;
353-
/** The resolved `.ad` file path — the interpolation-location fallback when an action's own `actionSourcePaths` entry is absent. */
351+
/** The resolved `.ad` file path every step's interpolation-error location names. */
354352
readonly resolvedPath: string;
355353
/**
356354
* `${VAR}` scope inputs — plain data the daemon reads from the request/

‎packages/ad-replay/src/internal/step-loop.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,13 @@ function mergeArtifactPaths(
208208
return [...new Set([...ledger, ...failureArtifactPaths])];
209209
}
210210

211-
/** `resolveReplayAction`'s `loc` for one step — `actionSourcePaths[index]` when the step came from a `runFlow` include, else the top-level plan's own resolved path. */
211+
/** `resolveReplayAction`'s `loc` for one step of the `.ad` plan. */
212212
function resolveActionLoc(
213213
request: AdReplayRunRequest,
214214
index: number,
215215
): { file: string; line: number } {
216216
return {
217-
file: request.actionSourcePaths?.[index] ?? request.resolvedPath,
217+
file: request.resolvedPath,
218218
line: request.actionLines[index] ?? 1,
219219
};
220220
}

‎packages/ad-script/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ export {
5353
buildReplayVarScope,
5454
collectReplayScrubbableVarValues,
5555
collectReplayShellEnv,
56+
escapeReplayAction,
5657
parseReplayCliEnvEntries,
5758
readReplayCliEnvEntries,
5859
readReplayShellEnvSource,
@@ -66,6 +67,7 @@ export {
6667
resolveReplayFormat,
6768
unsupportedReplayBackendMessage,
6869
type ReplayBackendId,
70+
type ReplayFormat,
6971
} from './internal/format.ts';
7072

7173
export {

‎packages/ad-script/src/internal/__tests__/vars.test.ts‎

Lines changed: 75 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { AppError } from '@agent-device/kernel/errors';
44
import {
55
buildReplayVarScope,
66
collectReplayShellEnv,
7+
escapeReplayAction,
78
parseReplayCliEnvEntries,
89
resolveReplayAction,
910
resolveReplayString,
@@ -98,14 +99,17 @@ test('buildReplayVarScope precedence: cli > shell > file > builtin', () => {
9899
});
99100

100101
test('collectReplayShellEnv strips AD_VAR_ prefix and ignores other vars', () => {
101-
const result = collectReplayShellEnv({
102-
AD_VAR_APP_ID: 'settings',
103-
PATH: '/bin',
104-
AD_VAR_123: 'x',
105-
AD_VAR_: 'empty',
106-
OTHER_VAR: 'y',
107-
AD_APP_ID: 'no-legacy-prefix',
108-
});
102+
const result = collectReplayShellEnv(
103+
{
104+
AD_VAR_APP_ID: 'settings',
105+
PATH: '/bin',
106+
AD_VAR_123: 'x',
107+
AD_VAR_: 'empty',
108+
OTHER_VAR: 'y',
109+
AD_APP_ID: 'no-legacy-prefix',
110+
},
111+
'ad',
112+
);
109113
assert.equal(result.APP_ID, 'settings');
110114
assert.equal(result.PATH, undefined);
111115
assert.equal(result['123'], undefined);
@@ -115,22 +119,50 @@ test('collectReplayShellEnv strips AD_VAR_ prefix and ignores other vars', () =>
115119
});
116120

117121
test('collectReplayShellEnv skips keys that land in reserved AD_* namespace after strip', () => {
118-
const result = collectReplayShellEnv({
119-
AD_VAR_AD_SESSION: 'evil',
120-
AD_VAR_AD_FOO: 'evil',
121-
});
122+
const result = collectReplayShellEnv(
123+
{
124+
AD_VAR_AD_SESSION: 'evil',
125+
AD_VAR_AD_FOO: 'evil',
126+
},
127+
'ad',
128+
);
122129
assert.equal(Object.prototype.hasOwnProperty.call(result, 'AD_SESSION'), false);
123130
assert.equal(Object.prototype.hasOwnProperty.call(result, 'AD_FOO'), false);
124131
});
125132

126133
test('parseReplayCliEnvEntries splits KEY=VALUE and rejects invalid keys', () => {
127-
assert.deepEqual(parseReplayCliEnvEntries(['APP=settings', 'FOO=bar=baz']), {
134+
assert.deepEqual(parseReplayCliEnvEntries(['APP=settings', 'FOO=bar=baz'], 'ad'), {
128135
APP: 'settings',
129136
FOO: 'bar=baz',
130137
});
131-
assert.throws(() => parseReplayCliEnvEntries(['NOEQUAL']), AppError);
132-
assert.throws(() => parseReplayCliEnvEntries(['lower=x']), AppError);
133-
assert.throws(() => parseReplayCliEnvEntries(['=value']), AppError);
138+
assert.throws(() => parseReplayCliEnvEntries(['NOEQUAL'], 'ad'), AppError);
139+
assert.throws(() => parseReplayCliEnvEntries(['lower=x'], 'ad'), AppError);
140+
assert.throws(() => parseReplayCliEnvEntries(['=value'], 'ad'), AppError);
141+
});
142+
143+
test('Maestro -e and AD_VAR_ keys accept the mixed-case and dotted names Maestro flows look up', () => {
144+
assert.deepEqual(parseReplayCliEnvEntries(['username=x', 'api.url=y'], 'maestro'), {
145+
username: 'x',
146+
'api.url': 'y',
147+
});
148+
assert.deepEqual(
149+
collectReplayShellEnv({ AD_VAR_userName: 'shell', AD_VAR_9lives: 'no' }, 'maestro'),
150+
{ userName: 'shell' },
151+
);
152+
assert.deepEqual(collectReplayShellEnv({ AD_VAR_userName: 'shell' }, 'ad'), {});
153+
assert.throws(
154+
() => parseReplayCliEnvEntries(['9lives=x'], 'maestro'),
155+
(error: unknown) =>
156+
error instanceof AppError &&
157+
error.code === 'INVALID_ARGS' &&
158+
/starting with a letter/.test(error.message),
159+
);
160+
assert.throws(
161+
() => parseReplayCliEnvEntries(['AD_FOO=x'], 'maestro'),
162+
/AD_\* namespace is reserved/,
163+
);
164+
assert.throws(() => parseReplayCliEnvEntries(['__proto__=x'], 'maestro'), /not __proto__/);
165+
assert.deepEqual(collectReplayShellEnv({ AD_VAR___proto__: 'x' }, 'maestro'), {});
134166
});
135167

136168
test('resolveReplayAction walks positionals and string flags', () => {
@@ -152,6 +184,31 @@ test('resolveReplayAction walks positionals and string flags', () => {
152184
assert.equal(resolved.flags?.snapshotDepth, 3);
153185
});
154186

187+
test('escapeReplayAction is the inverse of resolveReplayAction except for its live placeholders', () => {
188+
const flags = {
189+
snapshotScope: 'cost ${amount} for ${PASSWORD}',
190+
nested: { label: '${name}', list: ['${a}', 7, { deep: '${b}' }] },
191+
count: 2,
192+
};
193+
const written = escapeReplayAction(
194+
{
195+
ts: 0,
196+
command: 'fill',
197+
positionals: ['label="${name}"', '${PASSWORD}'],
198+
flags: flags as SessionAction['flags'],
199+
runtime: { metroHost: '${HOST}' },
200+
},
201+
new Set(['PASSWORD']),
202+
);
203+
const scope = buildReplayVarScope({
204+
fileEnv: { amount: 'X', name: 'X', a: 'X', b: 'X', HOST: 'X', PASSWORD: 'secret' },
205+
});
206+
const resolved = resolveReplayAction(written, scope, LOC);
207+
assert.deepEqual(resolved.positionals, ['label="${name}"', 'secret']);
208+
assert.deepEqual(resolved.flags, { ...flags, snapshotScope: 'cost ${amount} for secret' });
209+
assert.deepEqual(resolved.runtime, { metroHost: '${HOST}' });
210+
});
211+
155212
test('resolveReplayAction walks runtime hints', () => {
156213
const action: SessionAction = {
157214
ts: 0,
@@ -208,7 +265,7 @@ test.each([
208265
},
209266
{
210267
name: 'CLI -e via parseReplayCliEnvEntries',
211-
run: () => parseReplayCliEnvEntries(['AD_FOO=x']),
268+
run: () => parseReplayCliEnvEntries(['AD_FOO=x'], 'ad'),
212269
keyMatch: /AD_FOO/,
213270
},
214271
{
@@ -234,7 +291,7 @@ test.each([
234291

235292
test('parseReplayCliEnvEntries error wording is user-friendly for invalid keys', () => {
236293
assert.throws(
237-
() => parseReplayCliEnvEntries(['lower=x']),
294+
() => parseReplayCliEnvEntries(['lower=x'], 'ad'),
238295
(error: unknown) =>
239296
error instanceof AppError &&
240297
error.code === 'INVALID_ARGS' &&

0 commit comments

Comments
 (0)