Skip to content

Commit 761317d

Browse files
authored
refactor(daemon): extract native .ad replay to packages/ad-replay (#1478 P5) (#1555)
* refactor(replay): move the dependency-free engine leaves into packages/ad-replay Stage A of the #1478 P5 extraction: vars, plan-digest (+canonical-json, sole consumer), the target-identity classification core, report-action, and suggestion-ranking move verbatim; imports updated. The package facade temporarily re-exports the moved symbols so root consumers keep compiling; a later stage narrows it to inspectAdReplay/runAdReplay only. * chore(layering): register packages/ad-replay in the workspace and DAG * refactor(replay): define the three-operation replay selector port with dual adapters (#1478 P5) * refactor(daemon): route replay handlers through the selector port (#1478 P5) * refactor(replay): split target verification into engine policy and daemon authority (#1478 P5) * refactor(replay): move the .ad step loop behind inspectAdReplay/runAdReplay (#1478 P5) * refactor(replay): lock the ad-replay façade to its real consumers (#1478 P5) * test(replay): prove shared-id demotion on both selector-port adapters (#1555 review) * fix(replay): restore invalid replayBackend rejection on the native path (#1555 review) * refactor(replay): move shared .ad vocabulary to its owner, packages/ad-script (#1555 review) * refactor(replay): neutral step/run outcomes and digest/resume behind inspectAdReplay (#1555 review) P1 "do not smuggle daemon wire failures through a generic": drop the TResponse generic from AdReplayStepRuntime/runAdReplay. executeStep and handleActionFailure now return neutral tagged AdReplayStepOutcome/ AdReplayStepFailure values (kind/message/artifactPaths only); runAdReplay returns a neutral completed/failed AdReplayRunOutcome. The engine never holds or returns a DaemonResponse. The daemon adapter (createAdReplayStepRuntime, session-replay-runtime.ts) keeps its real wire response in a local side-map as it builds each neutral outcome, and runReplayScriptFile reads it back once runAdReplay reports which step failed, so the final response is byte-identical to before this split. P1 "parsing/planning/digest/resume must also occur behind runAdReplay": relocate computeReplayPlanDigest's call site and the --from/--plan-digest resume-point math (resolveReplayEntryIndex) behind inspectAdReplay's manifest as planDigest and a resolveEntryIndex closure. Neither is a new top-level export -- inspectAdReplay/runAdReplay stay the only two. Timing is preserved exactly (still called eagerly in prepareReplayPlan, before prepareReplaySession's coordinator-mutating side effects) since moving resume validation to run inside runAdReplay itself would let a rejected --from request mutate coordinator/session state first -- a real ordering hazard, not just a cosmetic one. computeReplayPlanDigest/ReplayPlanDigestMetadata/resolveReplayEntryIndex leave the ad-replay façade; request-router-repair-expired.test.ts and prepareReplayPlan read the digest/resume result off the manifest instead. * refactor(replay): relocate classifyTargetBindingMatch and pin the ad-replay façade (#1555 review) P1 "complete the binding façade instead of documenting deviations": classifyTargetBindingMatch never had a real consumer reachable through inspectAdReplay/runAdReplay -- both its callers (the daemon's record-time self-check in session-target-evidence.ts and its replay-time classification wrapper in session-replay-target-classification.ts) are daemon files that imported it directly. It interprets TargetAnnotationV1 evidence semantics shared beyond the engine, so it moves to packages/ad-script alongside target-annotation-identity.ts (new target-annotation-classification.ts + its test), and both daemon call sites now import it from there instead of @agent-device/ad-replay. One deviation remains and is reported rather than papered over per the review's own instruction: the four target-verification policy functions (planPreDispatchTargetVerification, planPostResolutionTargetVerification, deriveReplayTargetGuardMismatchEvidence, deriveWaitLandmarkMismatchEvidence) and the ReplaySelectorPort type family stay exported. Their sole caller, session-replay-target-verification.ts, interleaves these pure decisions with daemon-only async work (capture, SessionStore, coordinator/resume stamping, wire shaping) that must stay outside the engine by design; moving their call sites to live only behind runAdReplay would require restructuring that whole orchestration into new fine-grained AdReplayStepRuntime capabilities, which is out of scope for this pass. See packages/ad-replay/src/index.ts's header comment for the full reasoning. P1 "add the reviewer-required exact exported-symbol gate": adds readNamedExports (scripts/layering/package-boundaries.ts), a small parser over a façade's `export { .. } from`, `export type { .. } from`, and direct-declaration forms, and pins @agent-device/ad-replay's exact 21-symbol export list in package-boundaries.test.ts. Plant-verified: a stray `export const` addition failed the assertion; removed it and the gate went green again. * refactor(replay): drive target verification from the engine step loop (#1555 review) Moves the verify-then-dispatch decision flow into packages/ad-replay's step loop so the four target-verification policy functions (plan{PostResolution,PreDispatch}TargetVerification, derive{ReplayTargetGuardMismatch,WaitLandmark}MismatchEvidence) become engine-private and leave the ad-replay façade. The daemon (session-replay-target-verification.ts) shrinks to the narrow AdReplayStepRuntime capabilities the engine drives: routing (beginTargetVerification), capture (captureObservation), classification (classifyTarget), dispatch (dispatchStep), and wire-building (buildRecordedUnverifiableFailure, buildTargetBindingFailure, buildPostDispatchTargetBindingFailure). Wire output and replay-compat stay byte-identical; the exact-symbol façade gate is updated to the shrunken export list. * refactor(daemon): decompose the replay adapter's two over-threshold functions (#1555) * refactor(replay): fold #1554's keep-session terminal-lifecycle policy into the ad-replay engine Rebasing p5/extract-ad-replay onto main pulled in #1554's --keep-session feature, which had grown its own daemon-side terminal-close-suppression predicate (session-replay-terminal-lifecycle.ts's resolveSuppressedTerminalCloseIndex/countExecutedReplayActions) independently of this branch's own engine-side one (step-loop.ts's isRepairArmedTerminalCloseAction). Both are the same decision family — replay --keep-session and an active --save-script repair now share ONE structural resolution (resolveSuppressedTerminalCloseIndex, generalized to "terminal among EXECUTABLE actions" rather than the old physical-last-index check) and one suppression check inside runAdReplay, gated on keepSession OR runtime.isRepairArmed(). AdReplayRunRequest grew a keepSession field; the neutral 'replayed' count in AdReplayRunOutcome is now computed inline in the loop instead of the daemon's old actions.length - entryIndex approximation. requireLiveSessionForKeepSession (the --keep-session live-session postcondition) stays daemon-side, inlined into session-replay-runtime.ts, since it inspects SessionStore state the engine never sees. The daemon-only session-replay-terminal-lifecycle.ts this arrived with is deleted entirely — its isExecutableReplayAction was a duplicate of the engine's own. runReplayScriptFile's Maestro-format routing (including the new --keep-session Maestro rejection) was extracted into routeMaestroReplay to keep the function under fallow's complexity threshold after re-threading keepSession through it. Added packages/ad-replay/src/internal/__tests__/step-loop.test.ts covering the unified suppression decision (both keepSession and repair-armed) directly against runAdReplay, including the terminal-among-executable-actions case with a trailing nested replay marker. The daemon-level integration tests (6 tests in session-replay-terminal-lifecycle.test.ts, exercising the same behavior through runReplayScriptFile) and the SDK provider-scenario test (active-session-script-publication.test.ts) needed no changes and pass unmodified. * refactor(daemon): decompose session-replay-runtime.ts into three modules (#1555) Splits the ~1096-line replay runtime into cohesive pieces, keeping session-replay-runtime.ts as thin orchestration (~240 LOC): - session-replay-runtime-engine-adapter.ts: the AdReplayStepRuntime adapter (createAdReplayStepRuntime, the build*Failure capability implementations, and the lastResponse/lastObservation side-map mechanics), extracted verbatim. - session-replay-runtime-plan.ts: extended with the plan-side helpers (validateReplayBackendFlag, inspectReplayPlanManifest, resolveReplayPlanEntryIndex, prepareReplayPlan, routeMaestroReplay) alongside the buildReplayMetadataFlags helper already there — buildReplayMetadataFlags is now module-private since its one caller moved into the same file. Also introduces ReplayScriptFileParams, named here (instead of derived via Parameters<typeof runReplayScriptFile>) so routeMaestroReplay can reference the shape without importing back from session-replay-runtime.ts. - session-replay-runtime-session.ts (new): session preparation (prepareReplaySession and its coordinator arming/repair-preflight helpers), extracted verbatim. Coordinator ownership is unchanged: createReplayCoordinator is still constructed only in session-replay-runtime.ts, matching replay-coordinator-ownership.test.ts's allowlist as-is — every extracted module receives the already-constructed ReplayCoordinator as a parameter. Pure move; no behavior change. * test(replay): cover pre-step artifact ordering and resume-before-mutation (#1555) Two invariants found during the P5 decomposition pass now have direct counterfactual-verified coverage: - packages/ad-replay/src/internal/__tests__/step-loop.test.ts: a post-dispatch target-binding mismatch (dispatchWithGuard) must report the accumulated PRE-step artifact snapshot it was called with, never the artifacts the failed dispatch itself produced. Verified red by swapping the buildPostDispatchTargetBindingFailure call to outcome.artifactPaths. - src/daemon/handlers/__tests__/session-replay-runtime-plan.test.ts: a rejected --from/--plan-digest resume must never reach prepareReplaySession's coordinator-mutating writes (the R2 ordering invariant) — a pre-armed repair transaction and corrective-resume watermark are asserted byte-for-byte unchanged after rejection. Verified red by calling prepareReplaySession before honoring the plan-validation rejection. * fix(ad-replay): enforce the exact two-entrypoint facade (#1555 review P1) packages/ad-replay/src/index.ts now exports exactly two value symbols, inspectAdReplay and runAdReplay, and zero types — formatReplaySuccessMessage (presentation) moves beside its one caller in session-replay-runtime.ts, and every type a root daemon file needs is derived structurally off the two entrypoints in the one new src/daemon/ad-replay-facade-types.ts module instead of being named off the façade. scripts/layering/package-boundaries.ts's readNamedExports is rewritten on oxc-parser's own static-export table instead of a regex, so it can no longer silently miss a widening export form: a bare `export *` re-export or an `export default` now throws (an un-enumerable, and therefore un-pinnable, export), while `export * as ns` and every other enumerable form is still counted. The pinned exact-symbol assertion in package-boundaries.test.ts is narrowed to ['inspectAdReplay', 'runAdReplay']. * fix(ad-replay): translate wire failures before the engine boundary (#1555 review P1) AdReplayDispatchOutcome's guard-mismatch/landmark-mismatch variants carried a generic `details: Record<string, unknown> | undefined` bag straight off the wire response — a daemon wire projection crossing into the engine even though the outcome itself was already a neutral type. The daemon adapter (session-replay-runtime-engine-adapter.ts) now narrows that bag into the typed AdReplayGuardMismatchEvidence/AdReplayLandmarkMismatchEvidence shapes (observed identity, expected/observed structural denotation, ancestry entries, match count) before returning the outcome; the unknown-parsing readers move there with the wire-reading responsibility they always were. target-verification.ts's deriveReplayTargetGuardMismatchEvidence/ deriveWaitLandmarkMismatchEvidence now consume only the typed values — no `unknown`-valued record type remains on any engine-crossing signature. * fix(ad-replay): move variable semantics/planning behind runAdReplay (#1555 review P1) The daemon assembled the `${VAR}` scope (buildPreparedReplayScope) and interpolated actions at two independent call sites: dispatch's own (invokeReplayAction) and target verification's separate one (resolveTargetVerificationEntry) — duplicated orchestration the P5 design assigns to the engine. runAdReplay's request now carries the raw scope INPUTS (varSources: plain builtins/file/shell/cli-env data, plus actionLines/actionSourcePaths/ resolvedPath for interpolation-error location) instead of a built scope; the engine builds the scope and resolves each action exactly once per step, handing the RESOLVED action to dispatchStep/beginTargetVerification while every other capability still receives the ORIGINAL recorded action (a target-binding divergence reports the recorded selector, never an expanded ${VAR}). This is the one resolution site now — session-replay-action-runtime.ts's invokeReplayAction and session-replay-target-verification.ts's resolveTargetVerificationEntry no longer hold a scope or call resolveReplayAction themselves. Scrub-value collection (collectReplayScrubbableVarValues, for divergence-report redaction) is kept single-sourced in the engine too: it's computed from the engine's own live scope and threaded to each build-failure/handleActionFailure capability as an explicit scrubVars argument, rather than the daemon recomputing it from a second scope object (which would have gone stale, since expandedBuiltinNames tracking now only happens engine-side). The Maestro replay path's own daemon-side vars usage is unrelated (a different engine) and is out of scope here. * fix(ad-script): make ${VAR} interpolation a linear scanner CodeQL flagged the interpolation regex's fallback group as js/polynomial-redos once vars.ts moved into packages/ (library-input classification): every ${NAME:- prefix of an unclosed input rescanned to end-of-string, quadratic overall — 1,857 ms measured on 20k repetitions of '${A:-['. Replaced with a single-pass scanner; failed fallback scans emit their span verbatim and resume after it (escape-pair alignment is identical from every candidate start inside the span, so no later candidate can terminate where the failed scan could not). Equivalence: 200k-trial differential fuzz against the retired regex over the adversarial alphabet, zero mismatches; both adversarial shapes now resolve in 1-2 ms. * refactor(ad-replay): typed façade replaces the zero-type rule (#1555 structural-quality review) Reverses the exact-two-value zero-type export shape #1555's second review pass established: it forced every root type derivation through one shim (src/daemon/ad-replay-facade-types.ts) and left four daemon-side twin types (TargetVerificationEntry, TargetClassificationOutcome, TargetBindingFailureEvidence, ReplayVerifiedTargetGuard) plus a toDaemonEvidence copy translator shadowing the engine's own shapes. packages/ad-replay/src/index.ts now exports inspectAdReplay/runAdReplay (unchanged, still the only two values) plus the neutral vocabulary their signatures are built from, by name — following packages/maestro's façade precedent. The exact-symbol gate in scripts/layering/package-boundaries.test.ts is widened to pin the full sorted list (values + types). The four daemon twins are deleted; session-replay-target-verification.ts and session-replay-runtime-engine-adapter.ts now use the engine's own AdReplayVerificationEntry/AdReplayTargetClassification/ AdReplayTargetBindingEvidence/AdReplayVerifiedTargetGuard directly. TargetBindingDivergenceBuilt's array fields are now readonly-compatible, so toDaemonEvidence's copy is gone — evidence flows through unchanged. * fix(ad-replay): honor the selector port's own contract in the parse gate target-verification.ts's planPreDispatchTargetVerification used resolveRecordedTarget (operation 2, resolve) over an empty node tree purely to read its parse-invalid reason — a resolve call standing in for a parse call, even though readSelectorExpression (operation 1, parse) exists to answer exactly that question and was already unused inside the engine. Replaced with port.readSelectorExpression('ordinary', [token]). The mapping is not 'invalid' -> skip: production's 'ordinary'/'wait' grammars only ever record a boundary once it has already parsed, so a single malformed token can only come back 'not-applicable' there ('invalid' is unreachable from this call site on the production adapter). Both non-'expression' outcomes map to skip, matching the historical behavior (a single parse-invalid reason covered both cases). platform dropped from the function's params — it was only ever threaded to the resolve call this replaces. Added a contract-suite cell pinning the exact (diverging) discriminant each adapter reports for a selector-shaped-but-malformed bare token, and why the divergence is harmless for the one real consumer. * refactor(ad-replay): split step-loop.ts and shrink the daemon adapter (#1555 structural-quality review) step-loop.ts (810 LOC) splits three ways, following packages/maestro's own precedent: - internal/runtime-port-types.ts: the AdReplayStepRuntime boundary vocabulary (all the neutral types the engine/daemon exchange). - internal/verify-dispatch.ts: verifyAndDispatchStep + its dispatchNoGuard/ dispatchWithGuard helpers. - internal/step-loop.ts: runAdReplay itself plus the terminal-close/ executable-action structural logic (isExecutableReplayAction, resolveSuppressedTerminalCloseIndex). packages/ad-replay/src/index.ts's type exports now source from runtime-port-types.ts. step-loop.test.ts's AdReplayStepRuntime import moves to the new path (no assertion changes). src/daemon/handlers/session-replay-runtime-engine-adapter.ts (553 LOC after item 1's twin removal) shrinks to 294 via two further extractions: - session-replay-dispatch-narrowing.ts: the wire `details` bag -> typed evidence narrowing and dispatch-failure classification. - session-replay-runtime-step-support.ts: ReplayStepContext (moved here to avoid a cycle with the adapter, which re-exports it by name) plus the failure-wrapping/diagnostics-support helpers. Final LOC: adapter 294, dispatch-narrowing 148, step-support 153, step-loop 225, verify-dispatch 246, runtime-port-types 374. * test(ad-replay): package-local tests for resume.ts/target-verification.ts + terminal-lifecycle test rename resume.test.ts covers resolveReplayEntryIndex directly (previously only exercised transitively through the daemon's session-replay-runtime-plan tests): no --from/--plan-digest, the paired-flags requirement, in-range --from, out-of-range rejection, stale-digest rejection, the authorized empty-tail boundary (actionCount + 1) gated on a matching watermark, and the unperformed-record-and-heal growth check. Counterfactual run and restored: widening describeOutOfRangeResumeFrom's bound turns the out-of-range/ empty-tail-without-watermark assertions red (2 failures observed). target-verification.test.ts covers all four engine policy functions directly: the two plan* pre-capture gates and the two derive* post-dispatch evidence builders, including item 2's own new decision surface (a fake ReplaySelectorPort proving both non-'expression' readSelectorExpression outcomes map to skip). Counterfactual run and restored: narrowing the check to the literal `'invalid' -> skip` reading turns the 'not-applicable' case red (reports recorded-unverifiable instead of skip). session-replay-terminal-lifecycle.test.ts renamed to session-replay-runtime-keep-session.test.ts: its production module (session-replay-terminal-lifecycle.ts) was already deleted by the #1554 fold-in, and its six cases drive the full runReplayScriptFile round trip against a real SessionStore (including daemon-only postconditions the engine's step loop never reaches) rather than testing engine policy through the façade in isolation — the engine's own terminal-close-suppression decision already has direct, cheaper coverage in step-loop.test.ts. No assertion changes; both files' header comments cross-reference the split. * refactor(ad-replay): compute scrub values once per step, one name end to end collectReplayScrubbableVarValues(scope) was called fresh at 5 separate return points inside one verifyAndDispatchStep invocation plus once more in handleActionFailure — always the same result, since nothing between them mutates scope. step-loop.ts's runAdReplay now computes scrubVars ONCE per step, right after resolveReplayAction (the one call that can grow the scope's expanded-builtins set), and threads it as a plain readonly AdReplayScrubValue[] value; verify-dispatch.ts no longer imports ReplayVarScope or collectReplayScrubbableVarValues at all. "One name" end to end: the daemon's TargetBindingDivergenceContext.scrubVars and withReplayFailureDiagnostics's scrubVars param used a separately-derived ReturnType<typeof collectReplayScrubbableVarValues> (mutable array) instead of the engine's own AdReplayScrubValue, requiring a [...scrubVars] copy at every daemon call site to satisfy the mutable-array type. Both now use readonly AdReplayScrubValue[]/readonly ReplayVarScrubEntry[] (structurally identical, already readonly-safe downstream — scrubReplayVarValues and createReplayDivergenceSanitizer already accepted readonly arrays), so the four [...scrubVars] copies in session-replay-runtime-engine-adapter.ts are gone. * fix(daemon): make lastObservation genuinely per-step, not per-run createAdReplayStepRuntime's lastObservation closure lives for the whole replay run (one factory call covers every step), but was never reset between steps. Every current buildTargetBindingFailure call site happens to be preceded by this same step's own captureObservation, so the `lastObservation ?? { reason: 'observation-missing' }` fallback could never actually fire — but if it ever did (a future call path reaching buildTargetBindingFailure without capturing first), it would silently attach the PREVIOUS step's screen instead of reporting the missing-capture condition the fallback message claims. armStep runs exactly once per step, before any of that step's other capabilities (verified against step-loop.ts's runAdReplay loop order) — the natural per-step boundary. It now clears lastObservation first. No behavior change on any reachable path today (full daemon + ad-replay suite: 1766/1766 green); an unrelated device-claim-prune contention flake was observed once and did not reproduce on isolated or full-suite reruns. * docs(ad-replay): fix decayed review-changelog comments naming defunct symbols Four comments named symbols/paths that no longer exist, left behind by earlier review passes describing PR history rather than the current constraint: - session-replay-runtime-step-support.ts / session-replay-runtime.ts (2 sites): referenced a function called executeStep, which was never reintroduced under that name after the P5 split — the actual mechanism is the runtime's dispatch/build-failure capabilities recording into the lastResponse side-map. - session-replay-runtime.ts: referenced an engine collectArtifactPaths capability that does not exist — artifactPaths is a daemon-side Set the adapter mutates via collectReplayActionArtifactPaths. - packages/ad-replay/src/internal/selector-port.ts: pointed at ./testing/in-memory-selector-port.ts, the in-memory adapter's pre-stage-D location — it has lived at src/__tests__/test-utils/in-memory-replay-selector-port.ts since. - session-replay-repair-hint.ts / session-replay-runtime-step-support.ts (2 sites): named target-identity.ts, which does not exist (the real file is target-identity-node.ts); the second site additionally mislabeled classifyReplayTarget as engine-side when it is daemon-side (session-replay-target-classification.ts). Comment-only; no behavior change. * refactor(ad-script): move declaredScriptPlatform to its natural shared owner packages/ad-replay/src/internal/inspect.ts's declaredScriptPlatform and src/daemon/replay-device-selection.ts's readScriptReplaySelection each kept their own copy of the same "platform declared before the first open" scan over runtime/open actions — .ad script semantics, not engine or daemon policy, needed independently by ad-replay's plan-digest precedence and the daemon's device-selection platform resolution. Verified this was a genuine duplicate (not the single-sourced state I initially reported): readScriptReplaySelection's platform-tracking loop computes the identical result via a differently-shaped traversal fused with its own app-target scan. resolveDeclaredScriptPlatform now lives in packages/ad-script (its natural owner: the one package both ad-replay and the daemon already depend on, avoiding the R11 issue that justified the original duplication). The daemon's app-target scan stays its own separate pass; fusing it back into the shared function would smuggle a daemon-only concern into ad-script for no measurable cost (the actions array is small, and the shared function already stops at the same point the app-target scan needs to look). * docs(ad-replay): fix package.json description to match the current façade Described "target-identity, variable substitution, plan-digest, and report primitives" — the wide pre-#1555-review façade shape. Vars/identity/report vocabulary moved to ad-script/daemon across the P5 and #1555 review passes; the package now exports exactly inspectAdReplay/runAdReplay plus the neutral AdReplayStepRuntime vocabulary. Description updated to match. * refactor(daemon): fold the step-support fragment back into the engine adapter A simplicity audit judged session-replay-runtime-step-support.ts a size-target fragment, not a concern boundary: four unrelated concerns, one consumer, and a header comment admitting it existed to satisfy the <300 LOC metric. Folded back; the previously-exported helpers are module-private again; the adapter's honest size is renegotiated from the plan metric (dispatch-narrowing stays extracted — it has one nameable job).
1 parent 95b4623 commit 761317d

71 files changed

Lines changed: 5685 additions & 1644 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.

‎fallow-baselines/health.json‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,14 @@
1818
"count": 1
1919
}
2020
},
21+
"src/__tests__/test-utils/in-memory-replay-selector-port.ts": {
22+
"complexity_moderate": {
23+
"count": 2
24+
},
25+
"crap_moderate": {
26+
"count": 2
27+
}
28+
},
2129
"src/cli-schema/cli-config.ts": {
2230
"crap_moderate": {
2331
"count": 1

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@
145145
"check:unit": "pnpm check:contention-retry && pnpm test:unit && pnpm test:smoke",
146146
"check": "pnpm check:tooling && pnpm check:fallow && pnpm check:unit",
147147
"prepack": "pnpm check:mcp-metadata && pnpm package:npm",
148-
"typecheck": "tsc -b packages/xml packages/kernel packages/contracts packages/ad-script packages/maestro packages/replay-test packages/provider-webdriver packages/provider-limrun && tsc -p tsconfig.json && tsc -p examples/sdk/tsconfig.json",
148+
"typecheck": "tsc -b packages/xml packages/kernel packages/contracts packages/ad-script packages/ad-replay packages/maestro packages/replay-test packages/provider-webdriver packages/provider-limrun && tsc -p tsconfig.json && tsc -p examples/sdk/tsconfig.json",
149149
"test-app:install": "pnpm install --dir examples/test-app",
150150
"test-app:start": "pnpm --dir examples/test-app start",
151151
"test-app:ios": "pnpm --dir examples/test-app ios",
@@ -245,6 +245,7 @@
245245
"yaml": "^2.9.0"
246246
},
247247
"devDependencies": {
248+
"@agent-device/ad-replay": "workspace:*",
248249
"@agent-device/ad-script": "workspace:*",
249250
"@agent-device/contracts": "workspace:*",
250251
"@agent-device/kernel": "workspace:*",

‎packages/ad-replay/package.json‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
{
2+
"name": "@agent-device/ad-replay",
3+
"version": "0.0.0",
4+
"private": true,
5+
"sideEffects": false,
6+
"type": "module",
7+
"description": "Private native .ad replay engine for agent-device: manifest inspection (inspectAdReplay) and the step-loop execution engine (runAdReplay), plus the neutral AdReplayStepRuntime vocabulary the daemon adapter implements.",
8+
"dependencies": {
9+
"@agent-device/ad-script": "workspace:*",
10+
"@agent-device/contracts": "workspace:*",
11+
"@agent-device/kernel": "workspace:*"
12+
},
13+
"exports": {
14+
".": {
15+
"types": "./src/index.ts",
16+
"default": "./src/index.ts"
17+
}
18+
}
19+
}

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

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
/**
2+
* The `ad-replay` package façade (#1478 P5 stage D — narrowed; report-action/
3+
* suggestion-ranking/vars/identity-vocabulary further narrowed by the P5
4+
* review pass; plan-digest/resume and `classifyTargetBindingMatch` further
5+
* narrowed by the #1555 review pass, "complete the binding façade instead of
6+
* documenting deviations"; the target-verification policy functions further
7+
* narrowed by the #1555 review's R3 pass, "target verification must happen
8+
* INSIDE the engine"). `scripts/layering/package-boundaries.test.ts` asserts
9+
* this file's exact export list — see "the real tree parses, declares, and
10+
* passes R11" — so a stray export (including one this parser cannot
11+
* enumerate a name for, like `export *`) fails that gate, not just a comment
12+
* mismatch.
13+
*
14+
* The binding design (issue comment 5156017698) is two value entrypoints —
15+
* `inspectAdReplay` + `runAdReplay` — plus the neutral vocabulary their
16+
* signatures are built from, exported by name (#1555 structural-quality
17+
* review, "typed façade replaces the zero-type rule"): a package a root
18+
* consumer must integrate against through hand-derived `Parameters<...>`/
19+
* `ReturnType<...>` gymnastics in a SINGLE allowed root module
20+
* (`src/daemon/ad-replay-facade-types.ts`, since deleted) is a shim tax, not
21+
* an isolation win — every derived name still had to be re-exported from that
22+
* one file for every other root module to use, and every daemon-side type
23+
* that shadowed an engine type by hand (`TargetVerificationEntry`,
24+
* `TargetClassificationOutcome`, `TargetBindingFailureEvidence`,
25+
* `ReplayVerifiedTargetGuard`, plus a `toDaemonEvidence` copy translator
26+
* between mutable and readonly array shapes) was a duplicate definition that
27+
* could silently drift from the type it mirrored. `packages/maestro`'s
28+
* façade (`facade-execution.ts`/`facade-runtime-port.ts`/…) is the precedent:
29+
* a package boundary is enforced by an exact, gate-pinned export LIST, not by
30+
* exporting zero types. The gate below now pins values AND types together,
31+
* so a stray widening — a type accidentally exported, or one accidentally
32+
* dropped that a root file was still deriving by hand — fails loudly either
33+
* way.
34+
*
35+
* `inspectAdReplay` is the read-only `.ad` manifest reader — the plan-digest
36+
* hash (`plan-digest.ts`, `computeReplayPlanDigest`) and the `--from`/
37+
* `--plan-digest` resume-point math (`resume.ts`, `resolveReplayEntryIndex`)
38+
* are internal-only; the manifest carries the digest as `planDigest` and the
39+
* resume math as a `resolveEntryIndex` closure instead, so
40+
* `session-replay-runtime-plan.ts`'s `prepareReplayPlan` and
41+
* `request-router-repair-expired.test.ts` read them off the manifest rather
42+
* than importing the underlying functions. `AdReplayManifest` is its return
43+
* type and `AdReplayVarSources` is `runAdReplay`'s `${VAR}` scope-input
44+
* shape — both named here since `session-replay-runtime-plan.ts` threads them
45+
* by name across its own helper signatures.
46+
*
47+
* `runAdReplay` is the `.ad` step loop; `AdReplayStepRuntime` is the runtime
48+
* capability bag the daemon adapter
49+
* (`session-replay-runtime-engine-adapter.ts`) implements to thread it,
50+
* including the `ReplaySelectorPort` instance every daemon call site that
51+
* threads a port value names by the SAME type. Two adapters implement the
52+
* port: the production adapter (`src/daemon/replay-selector-port.ts`) and
53+
* the in-memory adapter for this package's own contract suite
54+
* (`src/__tests__/test-utils/in-memory-replay-selector-port.ts` — relocated
55+
* there, #1478 P5 stage D, because package-internal code may not "reach back
56+
* into root `src/`", R11, once its only remaining consumer was a root test).
57+
*
58+
* `./internal/target-verification.ts`'s four policy functions
59+
* (`planPostResolutionTargetVerification`, `planPreDispatchTargetVerification`,
60+
* `deriveReplayTargetGuardMismatchEvidence`, `deriveWaitLandmarkMismatchEvidence`)
61+
* stay engine-private — they are called only from `./internal/verify-dispatch.ts`'s
62+
* `verifyAndDispatchStep`, never the daemon — but the TYPED evidence shapes
63+
* they consume (`AdReplayGuardMismatchEvidence`, `AdReplayLandmarkMismatchEvidence`)
64+
* and the classification/guard/binding-evidence/verification-routing shapes
65+
* `verifyAndDispatchStep` exchanges with the daemon's `AdReplayStepRuntime`
66+
* implementation (`AdReplayVerificationEntry`, `AdReplayTargetClassification`,
67+
* `AdReplayTargetBindingEvidence`, `AdReplayVerifiedTargetGuard`,
68+
* `AdReplayDispatchGuard`, `AdReplayDispatchOutcome`) ARE named here: the
69+
* daemon builds/reads real values of these shapes directly now (routing in
70+
* `session-replay-target-verification.ts`, wire-narrowing in
71+
* `session-replay-runtime-engine-adapter.ts`) rather than re-declaring a
72+
* structurally-identical twin per module.
73+
*
74+
* `${VAR}` scope/planning: the engine builds the `${VAR}` scope (via
75+
* `@agent-device/ad-script`) from the request's `varSources` and resolves
76+
* each action exactly once per step, handing the daemon's `dispatchStep`/
77+
* `beginTargetVerification` capabilities the RESOLVED action — never a raw
78+
* action plus a scope for the daemon to interpolate itself (#1555 review P1,
79+
* "move variable semantics/planning behind the replay entrypoint"). The
80+
* `${VAR}`-scrub values a divergence report redacts (`AdReplayScrubValue`)
81+
* are threaded the same direction, as an explicit argument on each
82+
* build*Failure/handleActionFailure capability, computed ONCE per run from
83+
* the engine's own live scope — never recomputed daemon-side from a second
84+
* scope object, and never re-collected per call site.
85+
*/
86+
87+
export { inspectAdReplay } from './internal/inspect.ts';
88+
export type { AdReplayManifest } from './internal/inspect.ts';
89+
90+
export { runAdReplay } from './internal/step-loop.ts';
91+
92+
export type {
93+
AdReplayDispatchGuard,
94+
AdReplayDispatchOutcome,
95+
AdReplayScrubValue,
96+
AdReplayStepFailure,
97+
AdReplayStepRuntime,
98+
AdReplayTargetBindingEvidence,
99+
AdReplayTargetClassification,
100+
AdReplayVarSources,
101+
AdReplayVerificationEntry,
102+
AdReplayVerifiedTargetGuard,
103+
} from './internal/runtime-port-types.ts';
104+
105+
export type {
106+
AdReplayGuardMismatchEvidence,
107+
AdReplayLandmarkMismatchEvidence,
108+
} from './internal/target-verification.ts';
109+
110+
export type {
111+
ReplayRecordedTargetDisambiguation,
112+
ReplayRecordedTargetPolicy,
113+
ReplayRecordedTargetResolution,
114+
ReplaySelectorCandidateOptions,
115+
ReplaySelectorExpressionOutcome,
116+
ReplaySelectorGrammar,
117+
ReplaySelectorPort,
118+
} from './internal/selector-port.ts';

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

File renamed without changes.
Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import {
4+
resolveReplayEntryIndex,
5+
type AdReplayEntryIndexParams,
6+
type PendingRecordAndHeal,
7+
} from '../resume.ts';
8+
9+
/**
10+
* #1555 structural-quality review ("package-local tests... resume.ts and
11+
* cover its branches; counterfactual per docs/agents/testing.md on at least
12+
* the rejection path"): `resolveReplayEntryIndex` was previously exercised
13+
* only transitively, through the daemon's
14+
* `session-replay-runtime-plan.test.ts` (`resolveReplayPlanEntryIndex`
15+
* wrapping the manifest's `resolveEntryIndex` closure). This suite covers
16+
* the pure resume-point math directly, at package level, cheaper than the
17+
* daemon round trip.
18+
*/
19+
20+
const PLAN_DIGEST = 'a'.repeat(64);
21+
const OTHER_DIGEST = 'b'.repeat(64);
22+
const ACTION_COUNT = 5;
23+
24+
function params(overrides: Partial<AdReplayEntryIndexParams> = {}): AdReplayEntryIndexParams {
25+
return {
26+
from: undefined,
27+
digest: undefined,
28+
pendingRecordAndHeal: undefined,
29+
sessionActionsLength: 0,
30+
...overrides,
31+
};
32+
}
33+
34+
test('no --from and no --plan-digest resolves to the plan start (entry index 0)', () => {
35+
const result = resolveReplayEntryIndex(params(), ACTION_COUNT, PLAN_DIGEST);
36+
assert.deepEqual(result, { ok: true, value: 0 });
37+
});
38+
39+
test('--from without --plan-digest is rejected, and the reverse pairing too', () => {
40+
const fromOnly = resolveReplayEntryIndex(params({ from: 2 }), ACTION_COUNT, PLAN_DIGEST);
41+
assert.equal(fromOnly.ok, false);
42+
if (fromOnly.ok) throw new Error('unreachable');
43+
assert.match(fromOnly.message, /--from requires --plan-digest/);
44+
45+
const digestOnly = resolveReplayEntryIndex(
46+
params({ digest: PLAN_DIGEST }),
47+
ACTION_COUNT,
48+
PLAN_DIGEST,
49+
);
50+
assert.equal(digestOnly.ok, false);
51+
if (digestOnly.ok) throw new Error('unreachable');
52+
assert.match(digestOnly.message, /--from requires --plan-digest/);
53+
});
54+
55+
test('a valid in-range --from resolves to the 0-based entry index (from - 1)', () => {
56+
const result = resolveReplayEntryIndex(
57+
params({ from: 3, digest: PLAN_DIGEST }),
58+
ACTION_COUNT,
59+
PLAN_DIGEST,
60+
);
61+
assert.deepEqual(result, { ok: true, value: 2 });
62+
});
63+
64+
// ---------------------------------------------------------------------------
65+
// Rejection: out-of-range --from.
66+
// ---------------------------------------------------------------------------
67+
68+
test('rejection: --from below 1 or above the plan length (with no matching empty-tail watermark) is out of range', () => {
69+
const zero = resolveReplayEntryIndex(
70+
params({ from: 0, digest: PLAN_DIGEST }),
71+
ACTION_COUNT,
72+
PLAN_DIGEST,
73+
);
74+
assert.equal(zero.ok, false);
75+
if (zero.ok) throw new Error('unreachable');
76+
assert.match(zero.message, /out of range for a 5-step plan/);
77+
78+
// ACTION_COUNT + 1 (6) is the one legal empty-tail boundary, but ONLY with
79+
// a matching watermark (covered separately below) — absent one, it is out
80+
// of range exactly like anything past it.
81+
const pastEnd = resolveReplayEntryIndex(
82+
params({ from: ACTION_COUNT + 2, digest: PLAN_DIGEST }),
83+
ACTION_COUNT,
84+
PLAN_DIGEST,
85+
);
86+
assert.equal(pastEnd.ok, false);
87+
if (pastEnd.ok) throw new Error('unreachable');
88+
assert.match(pastEnd.message, /out of range for a 5-step plan/);
89+
90+
const emptyTailNoWatermark = resolveReplayEntryIndex(
91+
params({ from: ACTION_COUNT + 1, digest: PLAN_DIGEST }),
92+
ACTION_COUNT,
93+
PLAN_DIGEST,
94+
);
95+
assert.equal(emptyTailNoWatermark.ok, false);
96+
if (emptyTailNoWatermark.ok) throw new Error('unreachable');
97+
assert.match(emptyTailNoWatermark.message, /out of range for a 5-step plan/);
98+
});
99+
100+
// Counterfactual (docs/agents/testing.md): reverting describeOutOfRangeResumeFrom's
101+
// `from <= actionCount` bound to `from <= actionCount + 1` (dropping the
102+
// authorization gate entirely) turns this red — verified by hand, restored
103+
// before commit. Recorded here so the proof does not have to be re-derived:
104+
// `git stash` a local edit changing `from <= actionCount` to
105+
// `from <= actionCount + 1` in resume.ts, re-run this file, observe the
106+
// "rejection: --from below 1..." case fail on its `pastEnd`/`emptyTailNoWatermark`
107+
// assertions, then `git stash pop` to restore.
108+
109+
test('rejection: --plan-digest that does not match the current plan digest is stale', () => {
110+
const result = resolveReplayEntryIndex(
111+
params({ from: 2, digest: OTHER_DIGEST }),
112+
ACTION_COUNT,
113+
PLAN_DIGEST,
114+
);
115+
assert.equal(result.ok, false);
116+
if (result.ok) throw new Error('unreachable');
117+
assert.match(result.message, /does not match the current plan digest/);
118+
});
119+
120+
// ---------------------------------------------------------------------------
121+
// Empty-tail resume: the ONE ordinal beyond the plan's end (actionCount + 1),
122+
// authorized only for the exact session/target that produced the watermark.
123+
// ---------------------------------------------------------------------------
124+
125+
test('empty-tail: actionCount + 1 resolves when the watermark matches and the session has grown since the divergence', () => {
126+
const pendingRecordAndHeal: PendingRecordAndHeal = {
127+
expectedFrom: ACTION_COUNT + 1,
128+
actionsCountAtDivergence: 3,
129+
};
130+
const result = resolveReplayEntryIndex(
131+
params({
132+
from: ACTION_COUNT + 1,
133+
digest: PLAN_DIGEST,
134+
pendingRecordAndHeal,
135+
sessionActionsLength: 4, // grew past actionsCountAtDivergence
136+
}),
137+
ACTION_COUNT,
138+
PLAN_DIGEST,
139+
);
140+
assert.deepEqual(result, { ok: true, value: ACTION_COUNT });
141+
});
142+
143+
test('empty-tail: a watermark for a DIFFERENT --from ordinal does not authorize this one', () => {
144+
const pendingRecordAndHeal: PendingRecordAndHeal = {
145+
expectedFrom: ACTION_COUNT, // not ACTION_COUNT + 1
146+
actionsCountAtDivergence: 3,
147+
};
148+
const result = resolveReplayEntryIndex(
149+
params({
150+
from: ACTION_COUNT + 1,
151+
digest: PLAN_DIGEST,
152+
pendingRecordAndHeal,
153+
sessionActionsLength: 4,
154+
}),
155+
ACTION_COUNT,
156+
PLAN_DIGEST,
157+
);
158+
assert.equal(result.ok, false);
159+
if (result.ok) throw new Error('unreachable');
160+
assert.match(result.message, /out of range for a 5-step plan/);
161+
});
162+
163+
// ---------------------------------------------------------------------------
164+
// Heal semantics: the watermark alone is not enough — the session's own
165+
// recorded action count must have grown, proving the corrective press (or
166+
// re-recorded read) actually happened in this repair segment.
167+
// ---------------------------------------------------------------------------
168+
169+
test('heal: a matching watermark with NO session growth is rejected as an unperformed record-and-heal', () => {
170+
const pendingRecordAndHeal: PendingRecordAndHeal = {
171+
expectedFrom: ACTION_COUNT + 1,
172+
actionsCountAtDivergence: 3,
173+
};
174+
const result = resolveReplayEntryIndex(
175+
params({
176+
from: ACTION_COUNT + 1,
177+
digest: PLAN_DIGEST,
178+
pendingRecordAndHeal,
179+
sessionActionsLength: 3, // unchanged since the divergence — no corrective action recorded
180+
}),
181+
ACTION_COUNT,
182+
PLAN_DIGEST,
183+
);
184+
assert.equal(result.ok, false);
185+
if (result.ok) throw new Error('unreachable');
186+
assert.match(result.message, /no corrective action was\s+recorded in this repair segment/);
187+
assert.match(result.message, /--record/);
188+
});
189+
190+
test('heal: the unperformed-record-and-heal message is scoped to the matching watermark, not a generic in-range --from', () => {
191+
// A mid-plan --from that never matches a pending watermark's expectedFrom
192+
// is not subject to the growth check at all — it is either accepted
193+
// (in-range) or rejected as out-of-range, never as "unperformed".
194+
const pendingRecordAndHeal: PendingRecordAndHeal = {
195+
expectedFrom: ACTION_COUNT + 1,
196+
actionsCountAtDivergence: 3,
197+
};
198+
const result = resolveReplayEntryIndex(
199+
params({
200+
from: 2,
201+
digest: PLAN_DIGEST,
202+
pendingRecordAndHeal,
203+
sessionActionsLength: 3,
204+
}),
205+
ACTION_COUNT,
206+
PLAN_DIGEST,
207+
);
208+
assert.deepEqual(result, { ok: true, value: 1 });
209+
});

0 commit comments

Comments
 (0)