Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-9340): emit nested credential subscripts at code-emission time (#5750)
pedrohsdbd1c68b57b3dd
diff --git a/skyvern/core/script_generations/deterministic_field_naming.py b/skyvern/core/script_generations/deterministic_field_naming.pyindex 51e631f8b..57498fc50 100644--- a/skyvern/core/script_generations/deterministic_field_naming.py+++ b/skyvern/core/script_generations/deterministic_field_naming.py@@ -37,6 +37,7 @@ import refrom dataclasses import dataclassfrom typing import Any+from skyvern.forge.sdk.workflow.context_manager import RANDOM_SECRET_ID_PREFIXfrom skyvern.webeye.actions.actions import ActionTypeCUSTOM_FIELD_ACTIONS: tuple[ActionType, ...] = (@@ -51,9 +52,8 @@ class FieldPick:"""Result of picking a field strategy for a single action.`rule` is the rule that fired: "jinja_ref" | "upstream_schema" |- "intention_derived". The caller can use this to emit telemetry on- rule-distribution and to branch in Phase 2 (e.g. Rule 3 becomes- inline-literal vs ai-proactive instead of synthesis).+ "intention_derived" | "existing_assignment". The caller can use this to+ emit telemetry on rule-distribution."""field_name: str@@ -61,10 +61,57 @@ class FieldPick:description: str | None = None-# `{{ name }}` or `{{ name.attr }}` or `{{ name | filter }}` — we only-# care about the root identifier.+# `{{ name }}` or `{{ name.attr }}` or `{{ name | filter }}` — root identifier only._JINJA_ROOT_RE = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\b")+# `{{ root.sub }}` — captures both the root and one level of attribute,+# used to detect dotted references like `{{credentials.username}}` for+# nested-subscript emission. `\s*` around the dot tolerates the whitespace+# Jinja allows in attribute access (e.g. `{{ credentials . username }}`).+_JINJA_DOTTED_RE = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*([A-Za-z_][A-Za-z0-9_]*)\b")++# `placeholder_<random>_<subkey>` — extracts the trailing sub-key from a+# substitution token recorded in action.text. The random part is fixed-width+# (4 chars) per `WorkflowRunContext.generate_random_secret_id`, but using a+# permissive `[A-Za-z0-9]+` keeps the parser tolerant of future format tweaks.+_PLACEHOLDER_TOKEN_RE = re.compile(rf"^{re.escape(RANDOM_SECRET_ID_PREFIX)}[A-Za-z0-9]+_(.+)$")++# Canonical sub-keys we will emit in `context.parameters[<root>][<sub>]`.+# TOTP excluded: it has dedicated emission paths (get_totp_digit,+# totp_identifier) and racing with sequence annotation is out of scope.+KNOWN_CREDENTIAL_SUBKEYS: frozenset[str] = frozenset({"username", "password"})++# Sub-key name variants → canonical key. Anything outside KNOWN_CREDENTIAL_SUBKEYS+# and this map is treated as unsupported — emitting it would KeyError at runtime.+_CREDENTIAL_SUBKEY_ALIASES: dict[str, str] = {+ "email": "username",+ "email_address": "username",+ "user": "username",+ "login": "username",+ "user_name": "username",+ "pass": "password",+ "passwd": "password",+}++# Intention keywords that map to canonical credential sub-keys.+_USERNAME_KEYWORDS: tuple[str, ...] = ("username", "email", "login", "user id", "userid")+_PASSWORD_KEYWORDS: tuple[str, ...] = ("password", "passcode", "passphrase")++# TOTP-flavored intentions must NOT route to credential subscript — substring+# matches like "one-time password" would otherwise hit `_PASSWORD_KEYWORDS`+# and emit a nested subscript that bypasses get_totp_digit / totp_identifier.+_TOTP_INTENTION_DENYLIST: tuple[str, ...] = (+ "verification code",+ "one-time",+ "one time",+ "otp",+ "2fa",+ "two-factor",+ "totp",+ "mfa code",+ "auth code",+)+# Sanitize an intention string down to a valid snake_case identifier._NON_IDENT = re.compile(r"[^a-z0-9_]+")_REPEAT_UNDERSCORE = re.compile(r"_+")@@ -104,6 +151,66 @@ def extract_jinja_root_names(template: str) -> set[str]:return set(_JINJA_ROOT_RE.findall(template))+def extract_jinja_dotted_pairs(template: str) -> set[tuple[str, str]]:+ """Return `(root, sub)` pairs from dotted `{{root.sub}}` Jinja references.++ Example:+ >>> extract_jinja_dotted_pairs("Email: {{credentials.email}}")+ {("credentials", "email")}+ """+ if not template:+ return set()+ return set(_JINJA_DOTTED_RE.findall(template))+++def normalize_credential_subkey(raw: str) -> str | None:+ """Translate a sub-key name to its canonical credential dict key, or+ None if the raw name doesn't map to anything in the runtime dict."""+ raw_lower = raw.lower()+ if raw_lower in KNOWN_CREDENTIAL_SUBKEYS:+ return raw_lower+ return _CREDENTIAL_SUBKEY_ALIASES.get(raw_lower)+++def _infer_credential_subkey_from_action(action: dict[str, Any]) -> str | None:+ """Identify which credential sub-field an action targets.++ Primary structural signal: a placeholder token of the form+ ``placeholder_<random>_<subkey>`` in the recorded action text (built in+ ``WorkflowRunContext.register_credential_parameter_value``). The sub-key+ is extracted by stripping the prefix and validated against+ ``KNOWN_CREDENTIAL_SUBKEYS`` so a future credential schema with a key+ like ``backup_username`` wouldn't be silently routed to ``username``.++ Fallback: intention keywords, used when the recorded text isn't a+ placeholder token (rare — empty text or post-redaction). The TOTP+ denylist short-circuits before the password-keyword match.+ """+ text = action.get("text") or ""+ if text.startswith(RANDOM_SECRET_ID_PREFIX):+ match = _PLACEHOLDER_TOKEN_RE.match(text)+ if match:+ subkey = match.group(1)+ if subkey in KNOWN_CREDENTIAL_SUBKEYS:+ return subkey+ # Token matched but sub-key isn't canonical (e.g. totp). Return None+ # rather than falling through to intention guessing — the placeholder+ # is authoritative, and an intention like "enter passcode" would+ # otherwise route the user's password into the OTP field.+ return None++ intention = (action.get("intention") or "").lower()+ if not intention:+ return None+ if any(kw in intention for kw in _TOTP_INTENTION_DENYLIST):+ return None+ if any(kw in intention for kw in _PASSWORD_KEYWORDS):+ return "password"+ if any(kw in intention for kw in _USERNAME_KEYWORDS):+ return "username"+ return None++def pick_field_name_for_action(*,action: dict[str, Any],@@ -227,3 +334,36 @@ def pick_field_names_for_actions(picks[key] = pickreturn picks+++def infer_credential_subscript_for_emit(+ *,+ action: dict[str, Any],+ goal_template: str,+ block_type: str | None,+ credential_param_keys: frozenset[str],+) -> tuple[str, str] | None:+ """Return `(root, sub)` if a login-block fill should emit nested+ `context.parameters[<root>][<sub>]`, else None. Multi-credential+ workflows are disambiguated by `{{<root>.<sub>}}` in the goal template."""+ if block_type != "login" or not credential_param_keys:+ return None++ inferred_sub = _infer_credential_subkey_from_action(action)+ if inferred_sub is None:+ return None++ matching_roots_from_jinja = {+ root+ for root, sub in extract_jinja_dotted_pairs(goal_template)+ if root in credential_param_keys and normalize_credential_subkey(sub) == inferred_sub+ }+ if len(matching_roots_from_jinja) == 1:+ return (next(iter(matching_roots_from_jinja)), inferred_sub)+ if len(matching_roots_from_jinja) > 1:+ return None++ if len(credential_param_keys) == 1:+ return (next(iter(credential_param_keys)), inferred_sub)++ return Nonediff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.pyindex 9bb13633b..5b48ae6d4 100644--- a/skyvern/core/script_generations/generate_script.py+++ b/skyvern/core/script_generations/generate_script.py@@ -20,6 +20,7 @@ from libcst import Attribute, Call, Dict, DictElement, FunctionDef, Name, Paramfrom skyvern.config import settingsfrom skyvern.core.script_generations.constants import SCRIPT_TASK_BLOCKS, SCRIPT_TASK_BLOCKS_WITH_COMPLETE_ACTION+from skyvern.core.script_generations.deterministic_field_naming import infer_credential_subscript_for_emitfrom skyvern.core.script_generations.generate_workflow_parameters import (CUSTOM_FIELD_ACTIONS,generate_workflow_parameters_schema,@@ -31,7 +32,10 @@ from skyvern.core.script_generations.parameter_reference_guard import (validate_context_parameter_refs,)from skyvern.forge import app-from skyvern.forge.sdk.workflow.models.parameter import is_sensitive_workflow_parameter+from skyvern.forge.sdk.workflow.models.parameter import (+ WorkflowParameterType,+ is_sensitive_workflow_parameter,+)from skyvern.schemas.workflows import FileStorageTypefrom skyvern.utils.strings import sanitize_identifierfrom skyvern.webeye.actions.action_types import ActionType@@ -113,6 +117,32 @@ def _collect_secret_param_keys(workflow: dict[str, Any]) -> frozenset[str]:return frozenset(keys)+def _collect_credential_param_keys(workflow: dict[str, Any]) -> frozenset[str]:+ """Parameter keys typed `WorkflowParameterType.CREDENTIAL_ID`.++ Narrower than `_collect_secret_param_keys`: only params whose runtime+ value is a `{username, password, totp}` dict expanded by `setup()`.+ """+ target_enum = WorkflowParameterType.CREDENTIAL_ID+ target_str = target_enum.value+ keys: set[str] = set()+ defn = workflow.get("workflow_definition") or {}+ if not isinstance(defn, dict):+ return frozenset()+ for param in defn.get("parameters") or []:+ if not isinstance(param, dict):+ continue+ key = param.get("key")+ if not key:+ continue+ # Workflow definitions can carry the type as the enum object (when+ # constructed live) or its string value (when round-tripped via JSON).+ param_type = param.get("workflow_parameter_type")+ if param_type == target_enum or param_type == target_str:+ keys.add(key)+ return frozenset(keys)++def _collect_upstream_schema_keys(blocks: list[dict[str, Any]]) -> frozenset[str]:"""Return the set of keys introduced by upstream blocks' data_schema.@@ -806,6 +836,9 @@ def _action_to_stmt(assign_to_output: bool = False,value_to_param: dict[str, str] | None = None,use_semantic_selectors: bool = False,+ block_type: str | None = None,+ goal_template: str = "",+ credential_param_keys: frozenset[str] = frozenset(),) -> cst.BaseStatement:"""Turn one Action dict into:@@ -819,6 +852,11 @@ def _action_to_stmt(When *value_to_param* is provided, click prompt strings that contain literalparameter values will be emitted as f-strings referencing``context.parameters['field_name']`` instead of hardcoded text.++ For ``page.fill``/``page.type`` inside a login block, credential fields are+ detected via ``infer_credential_subscript_for_emit`` and emitted as nested+ ``context.parameters[<root>][<sub>]``. Default args preserve existing+ behavior at every call site that doesn't thread the credential context."""method = ACTION_MAP[act["action_type"]]@@ -883,34 +921,52 @@ def _action_to_stmt())elif method in ["type", "fill"]:- # Use context.parameters if field_name is available, otherwise fallback to direct value- if act.get("field_name"):- # Check if this is a multi-field TOTP sequence that needs digit indexing- totp_info = act.get("totp_timing_info") or {}- if totp_info.get("is_totp_sequence") and "action_index" in totp_info:- # Generate: await page.get_totp_digit(context, 'field_name', digit_index)- # This method properly resolves the TOTP code from credentials and returns the specific digit- text_value = cst.Await(- expression=cst.Call(- func=cst.Attribute(- value=cst.Name("page"),- attr=cst.Name("get_totp_digit"),- ),- args=[- cst.Arg(value=cst.Name("context")),- cst.Arg(value=_value(act["field_name"])),- cst.Arg(value=_value(totp_info["action_index"])),- ],- )+ # Dispatch: TOTP sequence → credential subscript → flat field_name → literal.+ # Credential subscript intentionally precedes field_name — the picker has no+ # concept of nested credentials and assigns a flat name even for credential+ # fields, so the emitter overrides it when a credential pick fires.+ totp_info = act.get("totp_timing_info") or {}+ if act.get("field_name") and totp_info.get("is_totp_sequence") and "action_index" in totp_info:+ text_value = cst.Await(+ expression=cst.Call(+ func=cst.Attribute(+ value=cst.Name("page"),+ attr=cst.Name("get_totp_digit"),+ ),+ args=[+ cst.Arg(value=cst.Name("context")),+ cst.Arg(value=_value(act["field_name"])),+ cst.Arg(value=_value(totp_info["action_index"])),+ ],)- else:- text_value = cst.Subscript(+ )+ elif (+ cred_pick := infer_credential_subscript_for_emit(+ action=act,+ goal_template=goal_template,+ block_type=block_type,+ credential_param_keys=credential_param_keys,+ )+ ) is not None:+ cred_root, cred_sub = cred_pick+ text_value = cst.Subscript(+ value=cst.Subscript(value=cst.Attribute(value=cst.Name("context"),attr=cst.Name("parameters"),),- slice=[cst.SubscriptElement(slice=cst.Index(value=_value(act["field_name"])))],- )+ slice=[cst.SubscriptElement(slice=cst.Index(value=_value(cred_root)))],+ ),+ slice=[cst.SubscriptElement(slice=cst.Index(value=_value(cred_sub)))],+ )+ elif act.get("field_name"):+ text_value = cst.Subscript(+ value=cst.Attribute(+ value=cst.Name("context"),+ attr=cst.Name("parameters"),+ ),+ slice=[cst.SubscriptElement(slice=cst.Index(value=_value(act["field_name"])))],+ )else:text_value = _value(act["text"])@@ -1257,6 +1313,7 @@ def _build_block_fn(use_semantic_selectors: bool = False,is_in_for_loop: bool = False,all_blocks: list[dict[str, Any]] | None = None,+ credential_param_keys: frozenset[str] = frozenset(),) -> FunctionDef:# Check for platform-specific pipeline (cloud-only; returns None in OSS)if use_semantic_selectors:@@ -1324,6 +1381,9 @@ def _build_block_fn(assign_to_output=assign_to_output,value_to_param=value_to_param,use_semantic_selectors=use_semantic_selectors,+ block_type=block_type,+ goal_template=block.get("navigation_goal") or block.get("data_extraction_goal") or "",+ credential_param_keys=credential_param_keys,))@@ -3011,6 +3071,7 @@ async def generate_workflow_script_python_code(declared_keys = _collect_declared_param_keys(workflow)upstream_keys = _collect_upstream_schema_keys(blocks)secret_param_keys = _collect_secret_param_keys(workflow)+ credential_param_keys = _collect_credential_param_keys(workflow)goal_template_by_task = _collect_goal_templates(blocks)generated_schema, field_mappings = await generate_workflow_parameters_schema(actions_by_task,@@ -3093,6 +3154,7 @@ async def generate_workflow_script_python_code(value_to_param=value_to_param,use_semantic_selectors=use_semantic_selectors,all_blocks=task_v1_blocks,+ credential_param_keys=credential_param_keys,)temp_module = cst.Module(body=[block_fn_def])block_code = temp_module.code@@ -3169,6 +3231,7 @@ async def generate_workflow_script_python_code(actions_by_task.get(child_block.get("task_id", ""), []),value_to_param=value_to_param,use_semantic_selectors=use_semantic_selectors,+ credential_param_keys=credential_param_keys,)task_v2_block_body.append(cst.EmptyLine())task_v2_block_body.append(cst.EmptyLine())@@ -3364,6 +3427,7 @@ async def generate_workflow_script_python_code(value_to_param=value_to_param,use_semantic_selectors=use_semantic_selectors,is_in_for_loop=True,+ credential_param_keys=credential_param_keys,)inner_block_code = cst.Module(body=[inner_fn_def]).codediff --git a/tests/unit/test_login_block_credential_emit.py b/tests/unit/test_login_block_credential_emit.pynew file mode 100644index 000000000..e41db8091--- /dev/null+++ b/tests/unit/test_login_block_credential_emit.py@@ -0,0 +1,529 @@+"""Tests for login-block credential subscript emission (SKY-9340).++Two layers under test:++1. ``infer_credential_subscript_for_emit`` — a pure helper. Given an action ++ goal template + block_type + credential_param_keys, returns ``(root, sub)``+ for credential fills or ``None`` to defer to existing emission paths.++2. ``_action_to_stmt`` — the emitter. Given a ``page.fill`` action and the+ credential context threaded from ``_build_block_fn``, must emit+ ``context.parameters[<root>][<sub>]`` instead of flat+ ``context.parameters[<picker's name>]`` for credential fills.++Each scenario fixture reflects a shape we observed in production logs.+"""++from __future__ import annotations++import libcst as cst++from skyvern.core.script_generations.deterministic_field_naming import (+ infer_credential_subscript_for_emit,+)+from skyvern.core.script_generations.generate_script import _action_to_stmt+from skyvern.webeye.actions.actions import ActionType+++def _login_action(+ text: str,+ intention: str,+ *,+ field_name: str | None = None,+ action_id: str = "a1",+ xpath: str = "//input",+) -> dict:+ action: dict = {+ "action_type": ActionType.INPUT_TEXT,+ "text": text,+ "intention": intention,+ "action_id": action_id,+ "xpath": xpath,+ }+ if field_name is not None:+ action["field_name"] = field_name+ return action+++def _emit(action: dict, **kwargs) -> str:+ stmt = _action_to_stmt(action, task={}, **kwargs)+ module = cst.Module(body=[stmt] if isinstance(stmt, cst.BaseStatement) else [cst.SimpleStatementLine([stmt])])+ return module.code+++# ---------------------------------------------------------------------------+# Layer 1: helper (infer_credential_subscript_for_emit)+# ---------------------------------------------------------------------------+++def test_helper_dotted_jinja_canonical_subkey() -> None:+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_xxx_username", intention="username for login"),+ goal_template="type {{my_credential.username}}. type {{my_credential.password}}.",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick == ("my_credential", "username")+++def test_helper_dotted_jinja_alias_email_to_username() -> None:+ """`{{cred.email}}` — alias map normalizes `email` → `username`."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("[email protected]", intention="enter the email"),+ goal_template="Email: {{my_credential.email}}\nPassword: {{my_credential.password}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick == ("my_credential", "username")+++def test_helper_dotted_jinja_with_whitespace_around_dot() -> None:+ """Jinja allows whitespace around `.` in attribute access. Without the+ `\\s*` tolerance in `_JINJA_DOTTED_RE`, multi-credential disambiguation+ silently fails when the goal template uses `{{ root . sub }}` form."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_xxx_username", intention="username"),+ goal_template="user: {{ cred_a . username }} pass: {{cred_b.password}}",+ block_type="login",+ credential_param_keys=frozenset({"cred_a", "cred_b"}),+ )+ assert pick == ("cred_a", "username")+++def test_helper_intention_keyword_username() -> None:+ """Two Jinja vars in the goal but only one CREDENTIAL_ID param —+ intention keyword routes to username."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention="What is the login email address?"),+ goal_template="extra: {{extra_login_instructions}} {'cred': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick == ("my_credential", "username")+++def test_helper_intention_keyword_password() -> None:+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention="What is the login password?"),+ goal_template="login with {{my_credential}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick == ("my_credential", "password")+++def test_helper_placeholder_token_text_marks_username() -> None:+ """The recorded action text — when the agent fills from a credential —+ is a `placeholder_<random>_<subkey>` token. Suffix match on the sub-key+ is the canonical structural signal; intention text is just a fallback."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_AbCd_username", intention="enter the value"),+ goal_template="login with {{my_credential}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick == ("my_credential", "username")+++def test_helper_token_with_extra_suffix_is_not_misclassified() -> None:+ """The placeholder parser extracts the full sub-key after the random+ component and validates against `KNOWN_CREDENTIAL_SUBKEYS`. A token like+ `placeholder_AbCd_backup_username` extracts `backup_username`, which is+ NOT in the canonical set, so it falls through."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_AbCd_backup_username", intention=""),+ goal_template="login with {{my_credential}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_token_for_unknown_subkey_falls_through() -> None:+ """Same guarantee for entirely novel sub-keys like `email`. The runtime+ credential dict only contains canonical keys; routing here would+ KeyError. Must fall through."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_AbCd_email", intention=""),+ goal_template="login with {{my_credential}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_does_not_fire_outside_login_block() -> None:+ """Same intention text outside a login block must not route to credential+ subscript — protects non-login forms with username fields."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("alice", intention="What is the username?"),+ goal_template="Add a new user: {{my_credential}}",+ block_type="task",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_does_not_fire_without_credential_param() -> None:+ """No CREDENTIAL_ID-typed param → helper returns None; existing flat path+ runs in the emitter."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("alice", intention="username"),+ goal_template="login with {{some_other_param}}",+ block_type="login",+ credential_param_keys=frozenset(),+ )+ assert pick is None+++def test_helper_does_not_fire_for_totp_intention() -> None:+ """Verification-code intention must not route — TOTP has its own paths."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention="Enter the 6-digit verification code"),+ goal_template="{'cred': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_does_not_fire_for_one_time_password_intention() -> None:+ """`one-time password` contains the substring `password` but is TOTP-flavored.+ The denylist short-circuits before the password keyword check."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention="Enter the one-time password"),+ goal_template="{'cred': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_does_not_fire_for_totp_token_with_passcode_intention() -> None:+ """Regression: a `placeholder_<r>_totp` token whose intention contains+ `passcode` must NOT fall through to the intention path. `passcode` matches+ `_PASSWORD_KEYWORDS` and isn't in the TOTP denylist, so without the+ placeholder-is-authoritative short-circuit the helper would route the+ user's password into the OTP field."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("placeholder_AbCd_totp", intention="enter passcode"),+ goal_template="{'cred': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_does_not_fire_for_unknown_intention() -> None:+ pick = infer_credential_subscript_for_emit(+ action=_login_action("Alice", intention="first name"),+ goal_template="{'cred': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++def test_helper_multi_credential_falls_through_without_dotted_jinja() -> None:+ """Two CREDENTIAL_ID params and no dotted Jinja — helper can't disambiguate."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention="What is the login password?"),+ goal_template="login with {{cred_a}} or {{cred_b}}",+ block_type="login",+ credential_param_keys=frozenset({"cred_a", "cred_b"}),+ )+ assert pick is None+++def test_helper_multi_credential_resolved_by_dotted_jinja() -> None:+ """Two CREDENTIAL_ID params, but goal has `{{cred_a.username}}` only."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("alice", intention="username"),+ goal_template="type {{cred_a.username}}",+ block_type="login",+ credential_param_keys=frozenset({"cred_a", "cred_b"}),+ )+ assert pick == ("cred_a", "username")+++def test_helper_multi_credential_same_subkey_falls_through() -> None:+ """Two credentials both expose `.username` — cannot safely pick one."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("alice", intention="username for login"),+ goal_template="type {{cred_a.username}} or {{cred_b.username}}",+ block_type="login",+ credential_param_keys=frozenset({"cred_a", "cred_b"}),+ )+ assert pick is None+++def test_helper_dotted_jinja_unrecognized_subkey_falls_through() -> None:+ """`{{cred.session_token}}` — `session_token` is not a known credential+ sub-key and has no alias."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("abc123", intention="session token"),+ goal_template="Token: {{my_credential.session_token}}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None+++# ---------------------------------------------------------------------------+# Layer 2: emitter (_action_to_stmt)+# ---------------------------------------------------------------------------+++def test_emitter_credential_field_emits_nested_subscript() -> None:+ """Smoke: a login-block credential field emits+ `context.parameters['my_credential']['username']`."""+ code = _emit(+ _login_action(+ "placeholder_xxx_username", intention="What is the login email?", field_name="phantom_login_email"+ ),+ block_type="login",+ goal_template="login with {{my_credential}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['username']" in code+ assert "context.parameters['phantom_login_email']" not in code+++def test_emitter_password_field_emits_nested() -> None:+ code = _emit(+ _login_action("placeholder_xxx_password", intention="What is the login password?", field_name="phantom_pw"),+ block_type="login",+ goal_template="login with {{my_credential}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['password']" in code+ assert "context.parameters['phantom_pw']" not in code+++def test_emitter_dotted_jinja_alias_routes_email_to_username() -> None:+ code = _emit(+ _login_action("[email protected]", intention="enter the email"),+ block_type="login",+ goal_template="Email: {{my_credential.email}}\nPassword: {{my_credential.password}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['username']" in code+++def test_emitter_dotted_jinja_custom_credential_name() -> None:+ """A workflow whose CREDENTIAL_ID param has a non-`credentials` name."""+ code = _emit(+ _login_action("placeholder_xxx_password", intention="password for login"),+ block_type="login",+ goal_template="type {{bot_password.username}}. type {{bot_password.password}}.",+ credential_param_keys=frozenset({"bot_password"}),+ )+ assert "context.parameters['bot_password']['password']" in code+++def test_emitter_falls_through_to_flat_when_no_credential_param() -> None:+ """No CREDENTIAL_ID-typed param → emitter uses the picker's flat field_name."""+ code = _emit(+ _login_action("alice", intention="username", field_name="login_username"),+ block_type="login",+ goal_template="login with {{some_other_param}}",+ credential_param_keys=frozenset(),+ )+ assert "context.parameters['login_username']" in code+ assert "['username']" not in code # no nested emission+++def test_emitter_falls_through_outside_login_block() -> None:+ code = _emit(+ _login_action("alice", intention="username", field_name="customer_username"),+ block_type="task",+ goal_template="add user {{my_credential}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['customer_username']" in code+ assert "['username']" not in code+++def test_emitter_totp_sequence_path_unchanged() -> None:+ """Multi-cell TOTP actions hit the existing `get_totp_digit` branch."""+ action = _login_action("1", intention="totp digit 0", field_name="totp_code")+ action["totp_timing_info"] = {"is_totp_sequence": True, "action_index": 0}+ code = _emit(+ action,+ block_type="login",+ goal_template="{'cred': '{{my_credential}}'}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "page.get_totp_digit(context, 'totp_code', 0)" in code+ assert "['totp']" not in code+ assert "context.parameters['my_credential']['" not in code+++def test_emitter_one_time_password_intention_does_not_emit_subscript() -> None:+ """Single-cell TOTP with intention "Enter one-time password" — TOTP+ denylist prevents the substring `password` from triggering the+ credential branch."""+ code = _emit(+ _login_action("", intention="Enter the one-time password", field_name="totp_field"),+ block_type="login",+ goal_template="{'cred': '{{my_credential}}'}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']" not in code+ assert "context.parameters['totp_field']" in code+++def test_emitter_falls_through_for_ambiguous_intention() -> None:+ code = _emit(+ _login_action("Alice", intention="first name", field_name="customer_name"),+ block_type="login",+ goal_template="{'cred': '{{my_credential}}'}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['customer_name']" in code+ assert "['username']" not in code+++def test_emitter_default_args_preserve_existing_behavior() -> None:+ """Existing call sites that don't thread credential context still work."""+ code = _emit(+ _login_action("alice", intention="username", field_name="login_username"),+ )+ assert "context.parameters['login_username']" in code+++# ---------------------------------------------------------------------------+# Cross-run scenario fixtures+# ---------------------------------------------------------------------------+#+# Each fixture corresponds to a shape we observed in production. Names are+# generic — see the SKY-9340 plan / per-run reports for the original mapping.+++def test_cross_run_two_jinja_vars_one_credential() -> None:+ """Goal has two Jinja vars (one credential, one free-text). Picker would+ bind to the wrong one (Rule 1 bails on length-2 intersection); emitter+ overrides with nested credential."""+ code = _emit(+ _login_action(+ "placeholder_xxx_username",+ intention="What is the login email address?",+ field_name="extra_login_instructions",+ ),+ block_type="login",+ goal_template=(+ "If there are extra login conditions: {{extra_login_instructions}} {'cred': '{{my_credential}}'}"+ ),+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['username']" in code+++def test_cross_run_dotted_jinja_custom_credential_name() -> None:+ """Goal uses dotted `{{<custom_name>.username}}` and the workflow's+ CREDENTIAL_ID param uses a non-`credentials` name."""+ code = _emit(+ _login_action("placeholder_xxx_username", intention="username", field_name="bot_password"),+ block_type="login",+ goal_template="type {{bot_password.username}}. type {{bot_password.password}}.",+ credential_param_keys=frozenset({"bot_password"}),+ )+ assert "context.parameters['bot_password']['username']" in code+++def test_cross_run_dotted_jinja_email_alias() -> None:+ code = _emit(+ _login_action("[email protected]", intention="enter email", field_name="phantom"),+ block_type="login",+ goal_template="Email: {{my_credential.email}}\nPassword: {{my_credential.password}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['username']" in code+++def test_cross_run_singular_credential_jinja() -> None:+ """Goal has a single Jinja `{{credential}}` (singular), CREDENTIAL_ID+ param matches."""+ code = _emit(+ _login_action("placeholder_xxx_username", intention="What is the username?", field_name="phantom"),+ block_type="login",+ goal_template="{'credential': '{{credential}}'}",+ credential_param_keys=frozenset({"credential"}),+ )+ assert "context.parameters['credential']['username']" in code+++def test_cross_run_no_jinja_in_goal_single_credential() -> None:+ """Goal mentions credentials in prose, no Jinja templating, single+ CREDENTIAL_ID param."""+ code = _emit(+ _login_action("placeholder_xxx_password", intention="password", field_name="phantom"),+ block_type="login",+ goal_template="log in using the credentials provided",+ credential_param_keys=frozenset({"enterprise_credential"}),+ )+ assert "context.parameters['enterprise_credential']['password']" in code+++def test_cross_run_numbered_credential_param_name() -> None:+ """CREDENTIAL_ID param named `<word>_1` (numbered)."""+ code = _emit(+ _login_action("placeholder_xxx_username", intention="username", field_name="user_username"),+ block_type="login",+ goal_template="{'credentials_1': '{{credentials_1}}'}",+ credential_param_keys=frozenset({"credentials_1"}),+ )+ assert "context.parameters['credentials_1']['username']" in code+++def test_cross_run_replaces_reviewer_hardcoded_literal() -> None:+ """A workflow whose cached login was previously rewritten by the AI+ reviewer to hardcode a literal email. Phase 1 emits the credential+ subscript instead, untying it from the static account."""+ code = _emit(+ _login_action("placeholder_xxx_username", intention="username for the login", field_name="login_email"),+ block_type="login",+ goal_template="login with {{my_credential}}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['username']" in code+++def test_cross_run_replaces_reviewer_stripped_value() -> None:+ """A workflow whose cached login had `value=` stripped by the reviewer+ (every fill falling back to AI). Phase 1 restores deterministic+ credential emission."""+ code = _emit(+ _login_action("placeholder_xxx_password", intention="password to log in", field_name="phantom"),+ block_type="login",+ goal_template="log in using the saved credentials\n{'cred': '{{my_credential}}'}",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert "context.parameters['my_credential']['password']" in code+++def test_cross_run_no_credential_id_passes_through() -> None:+ """Workflow without a CREDENTIAL_ID-typed param — picker's flat name+ flows through unchanged."""+ code = _emit(+ _login_action("placeholder_xxx", intention="The username for logging in", field_name="login_username"),+ block_type="login",+ goal_template="log in to the partner portal",+ credential_param_keys=frozenset(),+ )+ assert "context.parameters['login_username']" in code+ assert "['username']" not in code+++def test_cross_run_no_input_actions_helper_returns_none() -> None:+ """Workflow whose recorded login had no INPUT_TEXT actions (cached login+ is goto+complete, fully delegated to runtime agent). The emitter is+ never reached for fills; the helper still returns None on an+ intention-less action."""+ pick = infer_credential_subscript_for_emit(+ action=_login_action("", intention=""),+ goal_template="{'my_credential': '{{my_credential}}'}",+ block_type="login",+ credential_param_keys=frozenset({"my_credential"}),+ )+ assert pick is None