agentiqa 1.1.45-staging.3ddbb47 → 1.1.45-staging.492ddd5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +5 -5
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -5,7 +5,7 @@ ${n.message}`),r?new W1.VercelOidcTokenError(r):n}return t}function Qh(){let t=(
|
|
|
5
5
|
`)+`
|
|
6
6
|
`}import{spawn as Dte}from"node:child_process";import{mkdirSync as Lte,writeFileSync as Fte,existsSync as Ute,statSync as $te}from"node:fs";import{tmpdir as jte}from"node:os";import Ev from"node:path";import{createInterface as Bte}from"node:readline";var oL=["password","secret","token","credential","apikey","api_key"];function Vi(t){let e={};for(let[n,r]of Object.entries(t))oL.some(s=>n.toLowerCase().includes(s))?e[n]="[REDACTED]":typeof r=="object"&&r!==null&&!Array.isArray(r)?e[n]=Vi(r):e[n]=r;return e}function qi(t){if(typeof t=="string")return t;if(t&&typeof t=="object"&&typeof t.id=="string")return t.id}var bo=class{emit(){}async flush(){}};function Kr(t,e){return{projectId:t.projectId,sessionKind:t.kind,title:t.title,model:t.config?.model,layoutPreset:t.config?.layoutPreset,screenWidth:t.config?.screenWidth,screenHeight:t.config?.screenHeight,testCoverage:t.config?.happyPathOnly??!0?"happy_path":"full",targetPlatform:t.config?.platform??"web",initialUrl:t.config?.initialUrl,testPlanId:t.testPlanId,agentMode:t.config?.mobileConfig?.mobileAgentMode,deviceMode:t.config?.mobileConfig?.deviceMode,appIdentifier:t.config?.mobileConfig?.appIdentifier,snapshotOnly:t.config?.snapshotOnly,headless:t.config?.headless,hasExtension:t.config?.extensionPath?!0:void 0,maxIterations:t.config?.maxIterationsPerTurn,...e}}var Gi=class{url;constructor(e="http://localhost:8787"){this.url=e}emit(e){fetch(`${this.url}/ingest`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}async flush(){}destroy(){}};var lL="The AI service is temporarily unavailable. Please retry shortly.";function Sr(t){let e=t.toLowerCase();return e.includes("providerunavailableforlocationerror")||e.includes("provider_location_unsupported")||e.includes("user location is not supported for the api use")||e.includes("location is not supported for the api use")}function _o(){return lL}function ys(t){let e=t.toLowerCase();return e.includes("input token count exceeds")||e.includes("exceeds the maximum number of tokens")||e.includes("maximum number of tokens allowed")||e.includes("maximum context length")||e.includes("context length")||e.includes("context window")||e.includes("prompt is too long")||e.includes("too many tokens")}function vs(t={}){return t.isChildAgent?"Explorer paused because the page/context was too large to process in one pass. Partial findings were preserved; retry this slice with a narrower scope.":"I collected partial evidence, but the page/context was too large to process in one pass. Please retry with a narrower scope or ask me to continue from the current state."}var Mv=["google.com","youtube.com","claude.ai","chatgpt.com","openai.com","gemini.google.com","bing.com","duckduckgo.com","wikipedia.org","facebook.com","instagram.com","tiktok.com","x.com","twitter.com","reddit.com","github.com","amazon.com","netflix.com","linkedin.com","apple.com","microsoft.com","yahoo.com","whatsapp.com"];function Js(t){if(!t)return{matched:!1,host:null};let e=null;try{let r=t.startsWith("http")?t:`https://${t}`;e=new URL(r).hostname.toLowerCase().replace(/^www\./,"")}catch{return{matched:!1,host:null}}return{matched:Mv.some(r=>e===r||e.endsWith(`.${r}`)),host:e}}var Dv="The AI service is temporarily unavailable. Please retry shortly.",cL=/(ai\s*studio|ai_apicallerror|api[\s-]*key|billing|gemini|google\s+ai|openai|anthropic|provider|provider_location_unsupported|quota|rate[\s-]*limit|rate-limited|spend[\s-]*cap|spendcap|llm[\s_-]*access|overage|upgrade\s+url|reason=|location is not supported for the api use|aistudio\.google\.com|cloud\.google\.com\/billing)/i;function Qp(t){if(typeof t!="string")return;let e=t.replace(/\s+/g," ").trim();return e.length>0?e:void 0}function Sc(t){let e=Qp(t);return e?cL.test(e):!1}function Zp(t){let e=Qp(t);if(e)return Sc(e)?Dv:e}function eh(t){return t.targetHostKind==="loopback"||t.engineReachability==="reached_but_app_crashed"?null:t.providerRegionUnsupported?{reason:"provider_region_unsupported",targetHostKind:t.targetHostKind}:t.engineReachability==="unreachable_dns"&&t.targetHostKind!=="public"||t.engineReachability==="unreachable_connect"||t.engineReachability==="unreachable_tls"||t.engineReachability==="unreachable_4xx"||t.engineReachability==="unreachable_engine_blocked"?{reason:"target_unreachable_from_engine",targetHostKind:t.targetHostKind}:null}var uL={provider_region_unsupported:"Our managed engine couldn't process this run in the current region. Try running the same test from your own machine using the cloud-enabled CLI.",target_unreachable_from_engine:"Our managed engine couldn't reach your target URL from its cloud region. This can happen with local tunnels, private hosts, or sites that block or do not route traffic from our cloud egress. Try running the same test from your own machine using the desktop app or cloud-enabled CLI."};function Lv(t){return uL[t]}function Fv(t){let e=["agentiqa run"],n=t.engineUrl?.trim();return n&&e.push(`--engine ${n}`),t.testPlanId&&e.push(`--plan-id ${t.testPlanId}`),e.push(`--url ${t.targetUrl}`),e.join(" ")}function th(t){let e=t.testPlanId??null;return{reason:t.decision.reason,targetHostKind:t.decision.targetHostKind,targetUrl:t.targetUrl,testPlanId:e,engineUrl:t.engineUrl,cliCommand:Fv({engineUrl:t.engineUrl,targetUrl:t.targetUrl,testPlanId:e}),reasonHumanReadable:Lv(t.decision.reason)}}var nh="assistant_v2_unreachable_target_fallback_offered";function rh(t){return{reason_class:t.reason,target_host_kind:t.targetHostKind,suggested_cli_command_emitted:t.cliCommand.length>0}}import{z as Qe}from"zod";var Uv=Qe.enum(["L1","L2","L3","L4"]),$v=Qe.enum(["attestation","defect-detected","fix-verified","pipeline-health","deferral"]),jv=Qe.enum(["pass","fail","flake","error"]),dL=Qe.string().trim().regex(/^att_[0-9a-z-]+$/i,'Attestation IDs must start with "att_"'),pL=Qe.string().trim().regex(/^(?:ci|agent|human|local):[a-z0-9][a-z0-9-]*$/i),hL=Qe.object({pass:Qe.number().int().min(0),fail:Qe.number().int().min(0),flake:Qe.number().int().min(0).optional(),error:Qe.number().int().min(0).optional()}),fL=Qe.object({id:Qe.string().trim().min(1),status:Qe.enum(["PASS","FAIL","SKIP"]),reason:Qe.string().trim().min(1).optional()}),mL=Qe.object({scenarioIds:Qe.array(Qe.string().trim().min(1)),scenarios:Qe.array(fL).optional(),counts:hL,failedStep:Qe.string().trim().min(1).nullable()}),gL=Qe.object({type:Qe.string().trim().min(1),url:Qe.string().trim().url()}),yL=Qe.object({by:Qe.string().trim().min(1),reason:Qe.string().trim().min(1),issueId:Qe.string().trim().min(1)}).nullable(),vL=Qe.object({sha:Qe.string().trim().min(1),prNumber:Qe.number().int().positive().optional(),night:Qe.string().trim().min(1).optional(),env:Qe.string().trim().min(1).optional()}),bL=Qe.object({schemaVersion:Qe.literal(1),kind:$v,id:dL,subject:vL,claimIds:Qe.array(Qe.string().trim().min(1)).min(1),layer:Uv,producer:pL,verdict:jv,detail:mL,artifacts:Qe.array(gL),waiver:yL,startedAt:Qe.string().trim().datetime({local:!1}),finishedAt:Qe.string().trim().datetime({local:!1}),signature:Qe.null()}).strict();var Xs={createSession:()=>"/api/engine/session",getSession:t=>`/api/engine/session/${t}`,agentMessage:t=>`/api/engine/session/${t}/message`,bootstrap:t=>`/api/engine/session/${t}/bootstrap`,runTestPlan:t=>`/api/engine/session/${t}/run`,runnerMessage:t=>`/api/engine/session/${t}/runner-message`,stop:t=>`/api/engine/session/${t}/stop`,addCredentials:t=>`/api/engine/session/${t}/credentials`,setUserProvidedTestEmail:t=>`/api/engine/session/${t}/user-provided-test-email`,deleteSession:t=>`/api/engine/session/${t}`,evaluate:t=>`/api/engine/session/${t}/evaluate`,batchRun:t=>`/api/engine/session/${t}/batch-run`,chatTitle:()=>"/api/engine/chat-title"};function Bv(t){if(t.search?.trim())return null;let e=t.labelIds??[];return e.length===0?"_global":e.length===1?`lbl_${e[0]}`:null}function Vv(t){let e=new Intl.Collator(void 0,{numeric:!0});return(n,r)=>{let s=n.sortIndices?.[t],i=r.sortIndices?.[t];if(s!=null&&i!=null)return s-i;if(s!=null)return-1;if(i!=null)return 1;if(t!=="_global"){let l=n.sortIndices?._global,c=r.sortIndices?._global;if(l!=null&&c!=null)return l-c;if(l!=null)return-1;if(c!=null)return 1}let a=/^\s*\d/.test(n.title),o=/^\s*\d/.test(r.title);return a!==o?a?-1:1:a?e.compare(n.title,r.title):n.createdAt!==r.createdAt?n.createdAt-r.createdAt:n.id.localeCompare(r.id)}}var _L=/\bupload\b/i,wL=/\b(sign[ -]?in|log[ -]?in|authenticate|password)\b/i;function SL(t){return(t.type==="action"||t.type==="setup")&&typeof t.text=="string"&&_L.test(t.text)}function EL(t){return(t.steps??[]).some(e=>e.type==="setup"&&(e.authRole==="login"||wL.test(e.text??"")))}function qv(t){if(!t)return!1;try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"}catch{return!1}}function Gv(t,e={}){let n=[];for(let[r,s]of(t.steps??[]).entries()){if(!SL(s))continue;(s.fileAssets??[]).some(a=>!!a.r2Url)||n.push({code:"upload_step_missing_durable_asset",stepIndex:r,message:`Step ${r+1} ("${(s.text??"").slice(0,80)}") uploads a file but carries no durable fileAsset (r2Url). A fresh run on another machine cannot materialize the file and will fail with a missing-asset error (AG-6734). Re-attach the file so it persists with the plan.`})}return e.targetRequiresAuth&&!EL(t)&&n.push({code:"auth_target_missing_signin_step",message:"The target requires authentication but the plan has no sign-in setup step. A fresh session lands on the login page without scripted credentials/method and blocks before any plan step (AG-6732). Add a setup step that signs in with the stored credential (pin the method, e.g. Email/Password)."}),!qv(t.config?.initialUrl)&&!qv(e.projectInitialUrl??void 0)&&n.push({code:"initial_url_unresolved",message:"Neither the plan config nor the project provides a resolvable http(s) start URL. The run cannot deterministically navigate to the app under test."}),n}var TL=[[/email\s*\/?\s*password|sign in with email|email address/i,"Email/Password"],[/microsoft|azure ad|entra/i,"Microsoft"],[/google/i,"Google"],[/\bsso\b|saml|okta|single sign/i,"SSO"],[/email[\s\S]{0,80}password|password[\s\S]{0,80}email/i,"Email/Password"]];function IL(t){let e=t.map(n=>n.text).join(`
|
|
7
7
|
`);for(let[n,r]of TL)if(n.test(e))return r}function xL(t){let e=t.map(s=>s.text).join(`
|
|
8
|
-
`),n=e.match(/credential\s+'([^']+)'|'([^']+@[^']+)'/i);return n?n[1]??n[2]:e.match(/[\w.+-]+@[\w.-]+\.\w+/)?.[0]}function AL(t){let e=t.map((u,d)=>u.authRole==="login"?d:-1).filter(u=>u>=0);if(e.length<=1)return t;let n=e.map(u=>t[u]),r=IL(n),s=xL(n),i=s?` as '${s}'`:"",o={text:r?`Sign in with ${r}${i}`:`Log in${i}`,type:"setup",authRole:"login"},l=e[0],c=[];for(let u=0;u<t.length;u++){if(t[u].authRole==="login"){u===l&&c.push(o);continue}c.push(t[u])}return c}function wo(t,e){if(e?.authModeHint==="under_test")return{steps:t,authMode:"under_test"};let n=t.filter(o=>o.authRole);if(n.length===0)return{steps:t};let r=n.filter(o=>o.authRole==="probe"),s=n.filter(o=>o.authRole==="login"),i=t.filter(o=>!o.authRole);return{steps:AL([...r,...s,...i]),authMode:"precondition"}}var sh={GROUNDED_EXPECTATIONS:{key:"GROUNDED_EXPECTATIONS",envVars:["AGENTIQA_GROUNDED_EXPECTATIONS","AGENTIQA_EXPERIMENT_GROUNDED_EXPECTATIONS"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"When on, run_complete batch-judges provisionally-passing steps for expectation drift (heal cosmetic, fail-closed critical/judge-unavailable) instead of trusting the model grade verbatim.",designDoc:"docs/plans/2026-07-07-grounded-expectations-phase-b-design.md",status:"active",added:"2026-07-07",notes:"GRADUATED 2026-07-21 (default on): prod ran env-ON (AGENTIQA_EXPERIMENT_GROUNDED_EXPECTATIONS=1 on the orchestrator) since 2026-07-10 with zero grounded-attributable false-FAIL; nightly regressions in the window were all infra/render flake. This flip normalizes code to the already-live prod behavior \u2014 remove the orchestrator env vars (both namespaces) once this reaches each environment."},LOOP_VISION_ESCALATION_CHAT:{key:"LOOP_VISION_ESCALATION_CHAT",envVars:["AGENTIQA_LOOP_VISION_ESCALATION_CHAT","AGENTIQA_EXPERIMENT_LOOP_VISION_ESCALATION_CHAT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Extends loop-detection vision-supervisor escalation to the Coordinator/chat lane; off disables it for chat only (the master LOOP_VISION_ESCALATION still governs the Runner/Explorer lanes).",designDoc:"docs/plans/2026-07-07-loop-detection-vision-supervisor-design.md",status:"active",added:"2026-07-07",notes:"Staged default-OFF originally, flipped default-ON once baked (AG-6995) \u2014 reads via killSwitchDisabled today."},PIN_PAGE_GROUNDING:{key:"PIN_PAGE_GROUNDING",envVars:["AGENTIQA_PIN_PAGE_GROUNDING","AGENTIQA_EXPERIMENT_PIN_PAGE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Runner-lane pin page-grounding: a criterion's pinned expectedValue must appear in the literal full-page a11y text at verify-evidence capture (parroted grade notes no longer suffice). Detection runs in shadow (telemetry) unless VALUE_GROUNDING_ENFORCE is on; '0' disables detection AND the forced full-snapshot capture entirely.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-10"},ISSUE_QUOTE_GROUNDING:{key:"ISSUE_QUOTE_GROUNDING",envVars:["AGENTIQA_ISSUE_QUOTE_GROUNDING","AGENTIQA_EXPERIMENT_ISSUE_QUOTE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Chat-lane hallucinated-quote gate on report_issue: a quoted literal asserted as visible must appear in the freshly captured full a11y snapshot. Detection runs in shadow (telemetry) unless VALUE_GROUNDING_ENFORCE is on; '0' disables detection AND the forced full-snapshot capture entirely.",designDoc:"packages/engine-core/src/negativeStateEvidence.ts",status:"active",added:"2026-07-10"},VALUE_GROUNDING_ENFORCE:{key:"VALUE_GROUNDING_ENFORCE",envVars:["AGENTIQA_VALUE_GROUNDING_ENFORCE","AGENTIQA_EXPERIMENT_VALUE_GROUNDING_ENFORCE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Flips both value-grounding gates (PIN_PAGE_GROUNDING, ISSUE_QUOTE_GROUNDING) from shadow telemetry (would_fail / would_bounce diag logs) to enforcement: pin absence records a real per-step oracle failure that fails run_complete; a hallucinated visible quote rejects the report_issue filing.",designDoc:"packages/engine-core/src/killSwitch.ts",status:"active",added:"2026-07-10",notes:"Shadow-first rollout: two adversarial review rounds each surfaced false-fail classes on a hard-fail gate, so enforcement waited on a staging soak. PARKED 2026-07-21 (steering decision, Alex): VERIFY_REOBSERVE_WITHHOLD (graduated default-ON) strictly dominates this hard-fail path \u2014 it closes the same blind-verdict/pin-absence hole with a soft-withhold that never manufactures the false-FAIL classes both review rounds surfaced. Never graduate the enforcement; the oracle_failure recording branch is a deletion candidate. Detection stays: PIN_PAGE_GROUNDING + ISSUE_QUOTE_GROUNDING (default-ON) keep their shadow would_fail/would_bounce telemetry. Remove the staging orchestrator env var (AGENTIQA_EXPERIMENT_VALUE_GROUNDING_ENFORCE) \u2014 the force-ON soak is moot.",graduation:{status:"parked",gate:"Retired in favor of VERIFY_REOBSERVE_WITHHOLD (soft-withhold successor). Do not graduate; delete the enforcement branch once the successor has a clean prod window.",evidence:"F2b eval proof: enforce cannot catch the abstain{snapshot_incremental} class (identical RED both legs); panel + review-round history of false-fail classes on the hard-fail path",owner:"steering (Alex)",review:"2026-08-15"}},RESUME_INPUT_ASK_USER:{key:"RESUME_INPUT_ASK_USER",envVars:["AGENTIQA_RESUME_INPUT_ASK_USER","AGENTIQA_EXPERIMENT_RESUME_INPUT_ASK_USER"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Coordinator turn-continuity: when on, a child Explorer's ask_user that blocks on a MISSING INPUT (a file to upload, a path/value \u2014 not an email/generic async wait) arms a resumable `input_wait` pause that persists the halted child's OBJECTIVE; the next user turn resumes that SAME objective (re-attaching session attachments) instead of falling through to free re-decomposition, and re-asks for the SAME objective when the required file is still absent. Off = byte-identical to today (missing-input ask_user arms no pause; the email-wait / generic-wait paths are unchanged).",designDoc:"docs/plans/2026-07-20-paused-task-resume-design.md",status:"active",added:"2026-07-20",notes:"GRADUATED 2026-07-21 (default on) via the bound-eval arm of its gate: chat/paused-task-resume green 2/2 replicates on origin/staging (pause armed on the missing-file ask_user; resume carried the SAME objective tokens (upload + filename) with an explicit no-re-plan prompt; text-only reply correctly re-asked for the same file) + the earlier recorded GRADUATION-PASS on the lio replay (asess_1784568697674). Organic staging soak was vacuous (organic chat never hits a missing-input upload ask_user \u2014 0 input_wait events in 12 sessions), so the eval arm is the gate per the evidence-count doctrine. Renderer attachment-drop discriminator stays a SEPARATE open item (PostHog coordinator_started.has_attachments). Remove the staging orchestrator env var once this reaches staging."},VERIFY_REOBSERVE_WITHHOLD:{key:"VERIFY_REOBSERVE_WITHHOLD",envVars:["AGENTIQA_VERIFY_REOBSERVE_WITHHOLD","AGENTIQA_EXPERIMENT_VERIFY_REOBSERVE_WITHHOLD"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Runner-lane grade-time re-observe + soft-withhold (batch.verify-never-blind fix). When a pinned STRICT verify criterion cannot be grounded at grade time \u2014 the snapshot is not full (abstain snapshot_incremental/missing/thin) or the value is absent from a full a11y snapshot (would_fail) \u2014 the runtime takes ONE fresh forced-full a11y re-capture and re-grounds before accepting the verdict. Groundable after re-observe (value was present but the grade-time capture was imageless/incremental) \u2192 the model verdict stands; still ungroundable \u2192 the step is SOFT-withheld to a 'warning'+note (NON-confident, never a hard fail, never routed through the VALUE_GROUNDING_ENFORCE oracle_failure path). Closes the blind-verdict hole (F2a canvas + F2b incremental) WITHOUT manufacturing false-FAILs on values present-to-user but absent from the a11y outline (virtualized/scrolled-off rows).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-21",notes:"GRADUATED 2026-07-21 (default on), same-day evidence gate approved by Alex in lieu of a calendar soak: (1) staging replay-soak on the lio fixture (proj_mqzn31900, 3 sequential replicates of the only expectedValue-pinned plan) \u2014 zero false-withholds across 6 present-pin observations, withholds only on genuinely-absent values, surgical parity (grounded and no-pin verdicts untouched, check-only plans fully inert), no failing run laundered to pass, no material latency delta; (2) the grounded-rescue + Regression A/B legs banked by the fix-gate eval run (F2b re-observe\u2192grounded\u2192pass, healthy batch zero-fire, below-fold DOM value grounds). Product semantics approved by Alex: pinned-strict TRUE-MISMATCH fails also downgrade to warning (observed-value note preserved) until typed-match (AG-7753) restores precise typed fails. The two evals (runner-verify-blind-canvas / -incremental) remain the regression gate: fix OFF must reproduce, ON must resolve. Independent of VALUE_GROUNDING_ENFORCE \u2014 when off, that flag behaves unchanged. Remove the staging orchestrator env var once this reaches staging."},VERIFY_GATED_DONE:{key:"VERIFY_GATED_DONE",envVars:["AGENTIQA_VERIFY_GATED_DONE","AGENTIQA_EXPERIMENT_VERIFY_GATED_DONE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Cross-checks a 'done'/'passed' claim against deterministic completion-time oracle failures (wait-style); off restores trusting the model's completion claim verbatim.",designDoc:"docs/plans/2026-07-06-verification-gated-done-design.md",status:"active",added:"2026-07-06"},VERIFY_CONFLICT_RECONCILE:{key:"VERIFY_CONFLICT_RECONCILE",envVars:["AGENTIQA_VERIFY_CONFLICT_RECONCILE","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_RECONCILE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Downgrades a verification-conflict force-FAIL to a step-level warning (run not failed) when every plan criterion on the conflicted step passed with a substantiated note AND the only unresolved oracle is an agent-invented wait literal absent from the plan; off restores the unconditional bounce-then-fail-closed (false-negative on incident asess_1784155719395_h62evpmp).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-16"},VERIFY_RECONCILE_CLEAN_PASS:{key:"VERIFY_RECONCILE_CLEAN_PASS",envVars:["AGENTIQA_VERIFY_RECONCILE_CLEAN_PASS","AGENTIQA_EXPERIMENT_VERIFY_RECONCILE_CLEAN_PASS"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Presentation of a VERIFY_CONFLICT_RECONCILE-reconciled verify step: on, the reconciled step is a clean PASS and the reconciliation is recorded only in the structured verification_conflict_reconciled diag event (no engine-jargon note on the user-facing step); off restores the legacy step-level WARNING plus the explanatory note. Independent of VERIFY_CONFLICT_RECONCILE, which decides WHETHER a conflict reconciles at all \u2014 this only changes how an already-reconciled step is surfaced.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-22"},VERIFY_PRESENCE_WAIT_FLOOR:{key:"VERIFY_PRESENCE_WAIT_FLOOR",envVars:["AGENTIQA_VERIFY_PRESENCE_WAIT_FLOOR","AGENTIQA_EXPERIMENT_VERIFY_PRESENCE_WAIT_FLOOR"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Raises a verify-step presence oracle wait (wait_for_element on a `verify` plan step) to a minimum budget (20s) so a slow-rendering but PRESENT element \u2014 e.g. Miro\'s Templates carousel "Blank board" card, which paints several seconds after the dashboard is otherwise interactive \u2014 is not falsely failed by the 5s default wait budget (staging step-5 login/dashboard flake, sessions asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1, where the next action successfully CLICKED "Blank board"). Floor-only: never lowers a larger model-supplied timeout; off restores the model-supplied / 5s-default budget. Fail-closed preserved \u2014 a genuinely-absent element still times out at the larger budget and records the same oracle failure, so no false-PASS is introduced. Applied in RunnerRuntime.raiseVerifyPresenceWaitBudget (Runner/test-plan lane only; Explorer/Coordinator have no plan steps).',designDoc:"packages/engine-core/src/verifyPresenceWaitBudget.ts",status:"active",added:"2026-07-25"},ABSENCE_AWARE_VERIFY:{key:"ABSENCE_AWARE_VERIFY",envVars:["AGENTIQA_ABSENCE_AWARE_VERIFY","AGENTIQA_EXPERIMENT_ABSENCE_AWARE_VERIFY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Absence-assertion verify oracle (issue_742c9da8), a BEFORE\u2192AFTER differential. A verify step that asserts a NEGATIVE (the target is GONE) is verified with the presence-only wait_for_element, whose legitimate timeout on the correctly-absent, PLAN-GROUNDED literal is recorded as an oracle failure and force-FAILS the run at run_complete (canReconcileVerificationConflict refuses the plan-grounded literal \u2014 correct for a PRESENCE assertion, wrong for an absence one). Detection ALWAYS runs (shadow): for a conflicted verify step whose step text / any criterion check asserts THIS TARGET's absence (checkTextAssertsAbsence \u2014 the target literal is stripped first, then an EXPLICIT absence lexeme must survive; a negation inside the target NAME or an incidental 'not' cannot route it) and whose unresolved oracle is a wait-style action with a captured target literal, it classifies CONFIRMED vs ABSTAIN and emits an `absence_verify_oracle:shadow` diag. CONFIRMED requires the wait-literal's OWN before\u2192after transition: (a) GENUINELY ABSENT from a FULL, substantive, NON-canvas, non-load-failure AFTER snapshot retained for that step (never the model's note), AND (b) pinPresentInPage-TRUE in an EARLIER full+whole-page+substantive+same-origin BEFORE snapshot (the presence ledger \u2014 reusing the retained full-snapshot maps), AND every graded criterion passed substantiated. The weak container-noun positive anchor is DROPPED as the load-proof (before-presence + whole-page liveness replaces it); a load-failure/retry interstitial AFTER page is REJECTED (snapshotShowsLoadFailure). When this flag is ON it ENFORCES: a CONFIRMED absence reconciles the conflict to a PASS (via the VERIFY_CONFLICT_RECONCILE clean-pass rail), and an ABSTAIN (no full snapshot / canvas / target still present / load-failure after / NO before-presence \u2014 the target was never shown present / unsubstantiated criteria) soft-withholds the step to a WARNING (never a hard fail, never a clean pass). Off leaves every verdict byte-identical (the plan-grounded absence timeout still force-FAILs) with the shadow diag only. Positive (presence) assertions are untouched (checkTextAssertsAbsence false \u2192 inapplicable \u2192 the existing timeout-fails behavior). Runner lane only (RunnerRuntime run_complete).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-25",notes:"GRADUATED 2026-07-26 (default ON) \u2014 the FIRST live trust-verdict graduation. Enforcement (reconcile-to-pass on CONFIRMED / soft-withhold-to-warning on ABSTAIN) is now the no-env default; detection had run in shadow since 2026-07-25 (absence_verify_oracle:shadow diag) \u2014 the PIN_PAGE_GROUNDING / VERIFY_REOBSERVE_WITHHOLD shadow-first precedent. GRADUATION EVIDENCE: the kind-agnostic graduation benchmark (#1857, e2e/benchmark/) returned GATE=GO on the absence corpus (4 false-FAILs fixed \u2192 PASS, 0 regressions, 0 new false-PASS, 0 marginal LLM cost) and is adversarially proven able to say NO-GO; a fresh-build re-confirm held (confirmed-absence\u2192PASS fixes #1816 / unconfirmable\u2192WARNING / still-present\u2192no false-PASS; the full engine-core suite is byte-identical ON vs OFF except the graduated verdicts). HARD CONSTRAINT (unchanged): confirm fires ONLY on the wait-literal's OWN before\u2192after transition (present in an earlier same-origin full+substantive+non-canvas snapshot, absent from the non-load-failure after one) read from real page snapshots \u2014 never the model's note nor a disjoint absence lexeme \u2014 so a hallucinated 'it's gone', a never-loaded presence target (compound presence+absence), and a silently-blank list echoing the container noun all abstain to WARNING rather than confirming; no false-PASS is reintroduced. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND ABSENCE_AWARE_VERIFY listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire); an explicit AGENTIQA_ABSENCE_AWARE_VERIFY=0 still restores the byte-identical pre-graduation force-FAIL behavior. Read site: packages/engine-core/src/RunnerRuntime.ts (absenceAwareVerifyEnabled). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.absenceVerifyFalseFail.test.ts (end-to-end, now green for the right reason) + RunnerRuntime.absenceVerifyHardening.test.ts. Claim runner.absence-assertion-verify is now bound green."},GROUNDED_STATE_VERIFIER:{key:"GROUNDED_STATE_VERIFIER",envVars:["AGENTIQA_GROUNDED_STATE_VERIFIER","AGENTIQA_EXPERIMENT_GROUNDED_STATE_VERIFIER"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S1 escalation gate + shadow instrumentation (Tier-2 vision-extraction cost sizing; design docs/plans/2026-07-25-grounded-state-verifier-design.md). SHADOW-ONLY / MEASUREMENT-ONLY: this slice makes NO model call and NEVER alters a verdict, verdict input, or any other diagnostic. When on, the runner's Tier-1 deterministic pin page-grounding oracle (checkPinPageGrounding), at each GROUNDABILITY abstain on a step carrying a countable expectedValue pin \u2014 canvas_dominant, a non-full/incremental a11y snapshot, or a thin/missing snapshot (NOT the transient/ephemeral-text abstain) \u2014 consults the surface-agnostic capture-groundability signal (captureModeGroundsAbsence, keyed on captureMode, NOT a surface-name check) and emits a structured `verifier_escalated` diag {stepIndex, reason, assertionKind, captureMode, wouldNeedTier2:true} for a capture a vision extractor could ground (the genuine Tier-2 candidate), or `verifier_escalation_abstained` {\u2026, wouldNeedTier2:false, floor:'inconclusive'} when even vision cannot ground it (the fail-closed floor \u2014 abstain, never escalate-and-guess). Off \u21D2 byte-identical to today: the escalation diags are not emitted and nothing else changes. Sizes S2's per-verify vision-extraction cost by measuring how often and WHERE Tier-1 abstains on countable state assertions.",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S1 of the grounded-state verifier (measurement slice). Default OFF; SHADOW-ONLY and verdict-inert even when ON \u2014 this slice only emits verifier_escalated / verifier_escalation_abstained shadow diags at the checkPinPageGrounding abstain points, makes no model call, and changes no verdict. The escalation decision keys on captureModeGroundsAbsence (capture fidelity / checkPinPageGrounding outcome), NOT on canvasDominant/surface identity, so a non-canvas vision-groundable surface escalates through the same path (spec AC-7). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateVerifierEnabled \u2192 maybeEmitVerifierEscalation, called from checkPinPageGrounding); pure logic in packages/engine-core/src/groundedStateVerifier.ts. Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateVerifier.test.ts (wiring, flag-OFF byte-identical) + groundedStateVerifier.test.ts (pure groundability keying). S2 (prompt-only extractor + deterministic comparator) is the next slice and adds the actual Tier-2 call behind this same flag.",graduation:{status:"gated",gate:"S1 is measurement-only (no verdict change), so it graduates by FEEDING S2, not by flipping default-on: a staging shadow soak of verifier_escalated / verifier_escalation_abstained sizes the Tier-1-abstain-on-countable-state rate (per reason + captureMode) that S2 (prompt-only vision extractor + deterministic comparator, same flag) is built against. The flag advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; S1 alone never flips default-on.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events (escalation rate + reason/captureMode breakdown) + the engine-core RunnerRuntime.groundedStateVerifier + groundedStateVerifier unit suites",owner:"steering (Alex)",review:"2026-08-08"}},GROUNDED_STATE_EXTRACT:{key:"GROUNDED_STATE_EXTRACT",envVars:["AGENTIQA_GROUNDED_STATE_EXTRACT","AGENTIQA_EXPERIMENT_GROUNDED_STATE_EXTRACT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S2 prompt-only vision EXTRACTOR + deterministic presence COMPARATOR (design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1's free measurement stays independently runnable). SHADOW-ONLY: when on AND a stateExtractor is wired, each S1 escalation candidate (a Tier-1 checkPinPageGrounding abstain on a vision-groundable capture carrying a PRESENCE assertion, deduped one-call-per-step) gets ONE no-task-stake vision extraction at run_complete that enumerates what is on screen into a FIXED schema (objects/text/labels/counts) \u2014 NEVER a verdict (AC-2: the prompt receives no assertion outcome and no pass/fail framing). A DETERMINISTIC comparator then decides presence of the plan-text-derived target against that extraction, reproducibly from the logged extraction + target without re-calling the model (AC-3), and the runtime LOGS the would-be verdict + its PARITY vs the driver's current grade (grounded_state_extract diag). This slice changes NO live verdict. FAIL-CLOSED (Decision 7): any missing image / extractor abstain / non-answer / error / timeout / ambiguous or thin comparison \u2192 INCONCLUSIVE, never a pass. Off \u21D2 zero extraction calls, no candidate collection, byte-identical behavior (AC-6). Cost: one extraction call per escalated presence step, hard-capped (fork E).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S2 of the grounded-state verifier (prompt-only extractor + deterministic presence comparator). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be presence verdict and its parity vs the driver grade (grounded_state_extract / _start / _done diags), makes at most ONE extraction model call per escalated step (fork-E hard cap), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER so S1 measurement runs without paying S2 cost. Requires deps.stateExtractor wired (getStateExtractor in apps/execution-engine/src/buildDeps.ts) \u2014 absent \u21D2 inert. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateExtractEnabled \u2192 candidate recording in maybeEmitVerifierEscalation, consumed by runGroundedStateExtractions at run_complete); extractor + comparator in packages/engine-core/src/groundedStateExtractor.ts. Acceptance tests: packages/engine-core/src/__tests__/groundedStateExtractor.test.ts (pure prompt/parser/comparator/parity \u2014 AC-2/AC-3) + RunnerRuntime.groundedStateExtract.test.ts (wiring, shadow-no-mutation, fail-closed, one-call cap, seam guard, flag-OFF byte-identical). Binds claim verify.grounded-state-extract-then-compare. S3 (GROUNDED_STATE_DIFFERENTIAL) adds the before\u2192after differential for absence + modification.",graduation:{status:"gated",gate:"S2 is shadow-first (no verdict change). Graduation gates the PRESENCE case only, and only after: (1) a staging verdict-parity shadow soak of grounded_state_extract shows the extract-then-compare would-verdict matching the driver grade on DOM-groundable controls and DISAGREEing (would_fail on a driver-passed step) on the canvas false-pass fixtures (project_canvas_direct_draw_test) that the driver self-grade lets through today; (2) the extractor accuracy on the canvas presence fixtures clears the fork-G bar (else spec the fine-tuned extractor first). Advancing to a LIVE verdict path is a separate step from flipping this flag to shadow-on.",evidence:"staging grounded_state_extract / _start / _done diag events (would-verdict + parity + inconclusive-rate breakdown) + the engine-core groundedStateExtractor + RunnerRuntime.groundedStateExtract unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_DIFFERENTIAL:{key:"GROUNDED_STATE_DIFFERENTIAL",envVars:["AGENTIQA_GROUNDED_STATE_DIFFERENTIAL","AGENTIQA_EXPERIMENT_GROUNDED_STATE_DIFFERENTIAL"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S3 BEFORE\u2192AFTER DIFFERENTIAL (absence \u2282 update) for ABSENCE + MODIFICATION (design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1 measurement) / GROUNDED_STATE_EXTRACT (S2 single-after presence). SHADOW-ONLY: when on AND a stateExtractor is wired, each S1 escalation candidate (a Tier-1 checkPinPageGrounding abstain on a vision-groundable capture carrying an ABSENCE or MODIFICATION assertion, deduped one-call-per-step) runs the S2 no-task-stake vision extraction on BOTH the persisted baseline (before, resolveBaselineMessage) and verify (after, resolveEvidenceMessage) frames \u2014 each with S2's IDENTICAL constant task-blind prompt (AC-2: task-blind on BOTH frames, no assertion / no expected value / no pass/fail framing) \u2014 and a DETERMINISTIC differential comparator decides the verdict from the two extractions + the plan-text-derived target, reproducibly without re-calling the model (AC-3). ABSENCE: target present-before \u2227 absent-after \u2192 would_pass (confirmed_absent); still present-after \u2192 would_fail; before-presence unestablished / after unreadable \u2192 inconclusive. MODIFICATION: a count that changed to the expected value, or a crisp new value that appeared (before-absent + after-present) \u2192 would_pass; unresolvable \u2192 inconclusive. The runtime LOGS the would-be differential verdict + its PARITY vs the driver grade (grounded_state_differential diag); this slice changes NO live verdict. FAIL-CLOSED (Decision 7): any missing-before / unreadable / extractor abstain / error / timeout / ambiguous or unresolvable comparison \u2192 INCONCLUSIVE, never a pass. Canvas is IN scope (the extractor is vision; before/after frames exist via blind-double-read), identified by the plan DESCRIPTOR (fork D1) with an ambiguous match abstaining to inconclusive \u2014 never re-identifying an anonymous object. Off \u21D2 zero candidate collection, zero extraction calls, byte-identical behavior (AC-6). Cost: at most TWO extraction calls per escalated differential step (before + after, fork-E bounded call budget), hard-capped, batched under a deadline.",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:'S3 of the grounded-state verifier (before\u2192after differential; absence \u2282 update). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be differential verdict and its parity vs the driver grade (grounded_state_differential / _start / _done diags), makes at most TWO extraction model calls per escalated step (before + after; fork-E bounded budget, hard-capped, batched under a deadline \u2192 timeout inconclusive), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2). Requires deps.stateExtractor wired (getStateExtractor in apps/execution-engine/src/buildDeps.ts, reused per-frame) \u2014 absent \u21D2 inert. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateDifferentialEnabled \u2192 differential-candidate recording in maybeEmitVerifierEscalation, consumed by runGroundedStateDifferentials at run_complete); pure differential comparator in packages/engine-core/src/groundedStateDifferential.ts (reuses S2 groundedStateExtractor). Acceptance tests: packages/engine-core/src/__tests__/groundedStateDifferential.test.ts (pure differential \u2014 absence/modification/fail-closed, #1816 RED\u2192GREEN comparator soak hook + green-guard, AC-2/AC-3) + RunnerRuntime.groundedStateDifferential.test.ts (wiring, before+after two-frame extraction, shadow-no-mutation, fail-closed on missing-before/unreadable/timeout, one-differential-per-step cap, canvas descriptor-match, flag-OFF byte-identical). Binds claim verify.grounded-state-extract-then-compare. S4 (GROUNDED_STATE_INCONCLUSIVE) maps verifier-abstain \u2192 the inconclusive floor. Trust-layer Slice 1 (routing-gap fix) ALSO gates a STATIC single-frame COUNT comparator on this same flag: a count-intent assertion ("exactly 3 shapes" \u2014 authored factKind:count or an NL count check) escalates a count candidate and, at run_complete, runGroundedStateCounts runs ONE task-blind extraction + the deterministic compareCount (extracted 4 \u2260 expected 3 \u2192 grounded_state_count would_fail(after_count_mismatch); 3 = 3 \u2192 would_pass(confirmed_count)); shadow-only, fail-closed, one-call-per-step. Acceptance: RunnerRuntime.groundedStateCount.test.ts + the compareCount/checkTextAssertsCount cases in groundedStateDifferential.test.ts; end-to-end firewall proof eval runner-verify-count-canvas.',graduation:{status:"gated",gate:"S3 is shadow-first (no verdict change). Graduation gates the ABSENCE + MODIFICATION differential and only after: (1) a staging verdict-parity shadow soak of grounded_state_differential shows the #1816 reproduced-RED absence scenario would flip RED\u2192GREEN under the differential (confirmed_absent \u2192 would_pass on a driver-failed step) WITHOUT regressing the paired green-guard fixture (target-still-present \u2192 would_fail / driver-pass preserved); (2) new MODIFICATION fixtures (count + value-appearance) shadow-soak clean; (3) the extractor accuracy on the canvas absence/modification fixtures clears the fork-G bar. Advancing to a LIVE verdict path is a separate step from flipping this flag to shadow-on.",evidence:"staging grounded_state_differential / _start / _done diag events (would-verdict + parity + inconclusive-rate breakdown, #1816 RED\u2192GREEN) + the engine-core groundedStateDifferential + RunnerRuntime.groundedStateDifferential unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-22"}},GROUNDED_STATE_INCONCLUSIVE:{key:"GROUNDED_STATE_INCONCLUSIVE",envVars:["AGENTIQA_GROUNDED_STATE_INCONCLUSIVE","AGENTIQA_EXPERIMENT_GROUNDED_STATE_INCONCLUSIVE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S4 FAIL-CLOSED INCONCLUSIVE FLOOR wiring (Decision 7 + Fork F2; design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3). SHADOW-ONLY: when on, each verifier ABSTAIN \u2014 the S1 escalation fail-closed floor (verifier_escalation_abstained, a capture even a vision extractor cannot ground) and every S2 presence / S3 differential `inconclusive` outcome (thin/unreadable capture, extractor refusal/error/timeout, before-presence unestablished, after unreadable, ambiguous match, unresolved count) \u2014 is ALSO mapped to the typed inconclusive floor and LOGGED (grounded_state_inconclusive diag): the DISTINCT `verifier_inconclusive:{reason}` sub-reason + the interim `warning` step status (Fork F2 \u2014 a NEUTRAL 'couldn't tell', NOT an alarm-amber defect per project_warning_display_semantics) + the verifierInconclusive marker + migratesTo:'inconclusive'. This slice mutates NO stepResult and changes NO verdict \u2014 it computes/LOGS the would-be floor mapping only. HONESTY FLOORS: an abstain NEVER maps to `passed` (VERIFIER_INCONCLUSIVE_STEP_STATUS is warning/inconclusive, never passed), and a genuine would_pass/would_fail is never floored (inconclusiveFloorForVerdict returns null on a non-inconclusive verdict; the wiring only fires on the S2/S3 abstain paths + the S1 abstained floor). ONE migration point: flip VERIFIER_INCONCLUSIVE_STEP_STATUS (groundedStateInconclusive.ts) from `warning` to step-level `inconclusive` when Layered-Hybrid Phase-1 lands that status in the step enum. Off \u21D2 zero mapping, zero logs, byte-identical (AC-6).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S4 of the grounded-state verifier (fail-closed inconclusive floor; interim warning-with-distinct-sub-reason, Fork F2). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be inconclusive floor mapping (grounded_state_inconclusive diag), makes NO model call (pure wiring of S1/S2/S3 abstain outcomes), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3); the abstains it maps only exist when those slices run, so S4 is additive telemetry on top of them. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateInconclusiveEnabled \u2192 maybeLogInconclusiveFloor, called at the S1 verifier_escalation_abstained floor in maybeEmitVerifierEscalation + the S2/S3 logInconclusive abstain choke points in runGroundedStateExtractions / runGroundedStateDifferentials); pure mapping in packages/engine-core/src/groundedStateInconclusive.ts (the ONE migration point VERIFIER_INCONCLUSIVE_STEP_STATUS). Acceptance tests: packages/engine-core/src/__tests__/groundedStateInconclusive.test.ts (pure \u2014 each abstain reason \u2192 typed sub-reason \u2192 interim warning-never-passed, distinct-from-product-warning, migration seam, would_pass/would_fail never floored) + RunnerRuntime.groundedStateInconclusive.test.ts (wiring \u2014 flag-OFF byte-identical, shadow-no-mutation, floor logged per S1/S2/S3 abstain, no floor on a would_pass step). Binds claim verify.grounded-state-extract-then-compare. S5 broadens the groundability surface + fine-tune trigger.",graduation:{status:"gated",gate:"S4 is shadow-first (no verdict change) and the INTERIM F2 mapping (warning-with-distinct-sub-reason). Graduation to a LIVE floor is a SEPARATE, later step from flipping this flag shadow-on and requires: (1) a staging shadow soak of grounded_state_inconclusive confirming the abstain\u2192floor breakdown (source / reason / rate) is sane and that no would_pass/would_fail is ever floored (the honesty invariants hold in the field); (2) the S2/S3 verdict-parity soaks having graduated their live-verdict paths (an inconclusive floor is only meaningful once the extract-then-compare verdicts gate); (3) the UI rendering the verifier_inconclusive sub-reason as a NEUTRAL could-not-tell (not alarm-amber). The clean F2\u2192F1 migration (flip VERIFIER_INCONCLUSIVE_STEP_STATUS warning\u2192inconclusive at the ONE point) lands when Layered-Hybrid Phase-1 ships the step-level inconclusive status.",evidence:"staging grounded_state_inconclusive diag events (abstain\u2192floor mapping: source/reason/sub-reason/interim-status breakdown, honesty-invariant field check) + the engine-core groundedStateInconclusive + RunnerRuntime.groundedStateInconclusive unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-29"}},GROUNDED_STATE_FINETUNE_METRIC:{key:"GROUNDED_STATE_FINETUNE_METRIC",envVars:["AGENTIQA_GROUNDED_STATE_FINETUNE_METRIC","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FINETUNE_METRIC"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S5 FINE-TUNE TRIGGER METRIC (Fork G: DEFINE the trigger, do NOT fine-tune; design docs/plans/2026-07-25-grounded-state-verifier-design.md). The final sibling flag to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) / GROUNDED_STATE_INCONCLUSIVE (S4). SHADOW-ONLY: when on AND an S2/S3 shadow batch runs, the runtime ACCUMULATES per-SURFACE outcome counts from the extract-then-compare batches \u2014 extractor-abstain (the prompt-only extractor produced no facts), comparator-inconclusive (facts extracted but no definite verdict), and parity agree/disagree \u2014 bucketed by the escalation reason \u2192 surface class (canvas_dominant\u2192canvas, thin\u2192image_or_svg, incremental/non_full\u2192partial_capture; a DIAGNOSTIC label over the already-recorded reason, NOT a surface-name gate \u2014 the escalation gate stays keyed on captureModeGroundsAbsence, Fork A1). After both batches it LOGS the evaluated fine-tune trigger report against the STATED bar (grounded_state_finetune_metric diag): per surface the extractor-abstain rate, inconclusive rate, disagreement rate, and a would-trigger-fine-tune flag (Fork-G graduation signal, ADVISORY). This makes the prompt-only\u2192dedicated/fine-tuned graduation a DATA read; prompt-only stays v1 (Decision 6) \u2014 this slice invests in NO model, mutates NO stepResult, and changes NO verdict. The metric only has samples to fold when S2 and/or S3 also run. Off \u21D2 zero accumulation, zero logs, byte-identical (AC-6). The STATED bar: per surface, after live graduation, extractor-abstain rate > 0.20 OR inconclusive rate > 0.40 over \u2265 50 escalated extract-then-compares triggers a dedicated/fine-tuned extractor FOR THAT SURFACE (parity-disagreement is reported but NOT a trigger input \u2014 a high disagreement can be the extractor CATCHING driver false-passes, the desired signal).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S5 of the grounded-state verifier (fine-tune trigger metric; Fork G define-not-fine-tune) and the LAST vision-tier slice. Default OFF; SHADOW-ONLY \u2014 even when ON it only accumulates the per-surface outcome breakdown from the S2/S3 shadow batches and LOGS the evaluated trigger report (grounded_state_finetune_metric diag), makes NO model call (pure metric over existing S2/S3 outcomes), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) / GROUNDED_STATE_INCONCLUSIVE (S4); the outcomes it folds only exist when S2/S3 run, so S5 is additive telemetry on top of them. The companion BROADEN half of S5 (SVG/image coverage, spec AC-7 generalized) needed NO gate change \u2014 the S1/S2/S3 path already keys on captureModeGroundsAbsence (Fork A1), so broadening is a fixture/coverage add, proven by the RunnerRuntime.groundedStateBroaden test. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateFineTuneMetricEnabled \u2192 the run_complete accumulator threaded into runGroundedStateExtractions / runGroundedStateDifferentials, emitted by emitFineTuneTriggerMetric); pure metric + STATED bar in packages/engine-core/src/groundedStateFineTuneTrigger.ts (FINETUNE_TRIGGER_BAR). Acceptance tests: packages/engine-core/src/__tests__/groundedStateFineTuneTrigger.test.ts (pure surface mapping / fold / rates / bar evaluation) + RunnerRuntime.groundedStateFineTuneMetric.test.ts (wiring \u2014 per-surface fold from S2/S3, flag-OFF byte-identical, shadow-no-mutation) + RunnerRuntime.groundedStateBroaden.test.ts (AC-7 generalized: a non-canvas SVG/image surface escalates + extracts + compares through the identical path). Binds claim verify.grounded-state-extract-then-compare. COMPLETES the S1\u2013S5 vision-tier build; remaining work is soak + graduation flips (Alex).",graduation:{status:"gated",gate:"S5 is shadow-first (no verdict change) and DEFINES the Fork-G fine-tune trigger \u2014 it does not fine-tune. The metric graduates by FEEDING the fine-tune decision, not by flipping default-on: a staging shadow soak of grounded_state_finetune_metric measures each surface (canvas / image_or_svg / partial_capture) extractor-abstain + inconclusive rate against the STATED bar (FINETUNE_TRIGGER_BAR: abstain > 0.20 OR inconclusive > 0.40 over \u2265 50 escalated steps). Investing in a dedicated/fine-tuned extractor for a surface is triggered ONLY when that surface clears the bar AFTER the S2/S3 extract-then-compare has graduated live on it (Decision 6: prompt-only ships regardless). This flag alone never flips default-on.",evidence:"staging grounded_state_finetune_metric diag events (per-surface extractor-abstain / inconclusive / disagreement rate + would-trigger evaluation vs FINETUNE_TRIGGER_BAR) + the engine-core groundedStateFineTuneTrigger + RunnerRuntime.groundedStateFineTuneMetric + RunnerRuntime.groundedStateBroaden unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-09-05"}},GROUNDED_STATE_NL_TRIGGER:{key:"GROUNDED_STATE_NL_TRIGGER",envVars:["AGENTIQA_GROUNDED_STATE_NL_TRIGGER","AGENTIQA_EXPERIMENT_GROUNDED_STATE_NL_TRIGGER"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 1 \u2014 un-inert the grounded-state verifier for PINLESS criteria (design docs/plans/2026-07-26-groundability-contract-design.md). The Tier-1 pin page-grounding oracle (checkPinPageGrounding) early-returns when a criterion carries no expectedValue pin, so a real/canvas plan's natural-language {check,strict} assertion never reached the S1 escalation path \u2014 the grounded-state verifier was provably INERT on exactly the canvas surfaces (Miro/Figma) it was built for. When on, a PINLESS verify step whose RUNTIME fact-kind (deriveVerifyAssertionKind) is a non-default state-change kind \u2014 `absence` or `modification` \u2014 routes through the SAME capture-groundability abstain\u2192escalate logic the pinned path uses (maybeEmitVerifierEscalation \u2192 buildVerifierEscalation), keyed on the IDENTICAL captureModeGroundsAbsence gate (a capture even a vision extractor cannot ground abstains to the fail-closed inconclusive floor, never escalate-and-guess). F2 ANTI-FLOOD: the DEFAULT `presence` kind is EXCLUDED \u2014 deriveVerifyAssertionKind defaults to presence for everything, so escalating on presence would flood every pinless ungroundable step; only absence/modification (which the classifier returns deliberately) escalate in Slice 1 (authored count/value are Slice 2). ESCALATION-TRIGGER ONLY: matchType/comparison/expectedValue-as-comparator are untouched, this is shadow/verdict-inert like S1\u2013S5, and it emits nothing on its own \u2014 the escalation diag / candidate still requires GROUNDED_STATE_VERIFIER / _EXTRACT / _DIFFERENTIAL / _INCONCLUSIVE. Off \u21D2 byte-identical: the pinless early-return stands, zero new telemetry, zero behavior change (AC-6).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-25",notes:"Groundability-contract Slice 1 (PR-A). Default OFF; SHADOW-ONLY and verdict-inert even when ON \u2014 it only relocates the S1 escalation TRIGGER for pinless criteria off the expectedValue pin onto the existing runtime fact-kind classifier (deriveVerifyAssertionKind). NO schema change (migration-safe). The escalate-vs-abstain disposition stays keyed on the exact captureModeGroundsAbsence gate reused from the pinned path (GUARDRAIL 1: no pinless bypass). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateNlTriggerEnabled \u2192 maybeEmitPinlessNlEscalation, called at the checkPinPageGrounding pinless early-return; routes through the shared maybeEmitVerifierEscalation). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateNlTrigger.test.ts (pinless absence/modification escalates on ungroundable canvas/thin/non_full; groundable-mode capture abstains to the inconclusive floor NOT escalate; presence pinless never escalates \u2014 F2 anti-flood; flag-OFF byte-identical; pinned path unchanged). OVERLAP NOTE: ABSENCE_AWARE_VERIFY (#1818, classifyAbsenceVerifyConflict / wait-oracle literal) is a DISTINCT pin-independent absence route \u2014 both are shadow/verdict-inert, so absence carries a DOUBLE shadow signal; do not double-count in soak evidence. Slice 2 adds authored count/value kinds.",graduation:{status:"gated",gate:"Slice 1 is measurement-only (no verdict change): it graduates by FEEDING the same S2/S3 extract-then-compare shadow soak \u2014 a staging shadow soak of verifier_escalated / verifier_escalation_abstained on PINLESS absence/modification steps (canvas/real plans) sizes the escalation rate the vision tier is built against, previously unmeasurable because pinless steps never escalated. The flag advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; Slice 1 alone never flips default-on. Slice 2 (authored count/value kinds) is a separate gated slice.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events on pinless absence/modification steps (escalation rate + reason/captureMode breakdown, de-duplicated against the ABSENCE_AWARE_VERIFY absence shadow signal) + the engine-core RunnerRuntime.groundedStateNlTrigger unit suite",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_FACTKIND_AUTHORED:{key:"GROUNDED_STATE_FACTKIND_AUTHORED",envVars:["AGENTIQA_GROUNDED_STATE_FACTKIND_AUTHORED","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FACTKIND_AUTHORED"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 2 \u2014 consume the MODEL-authored `factKind` as source-of-truth for the grounded-state escalation trigger's assertion shape (design docs/plans/2026-07-26-groundability-contract-design.md). Builds on Slice 1 (GROUNDED_STATE_NL_TRIGGER, pinless escalation on runtime absence/modification). The new OPTIONAL `factKind` enum (value|count|presence|absence|modification|relation) on TestPlanV2Criterion is authored by the generation model (all three producer schemas) as a deliberate typed choice (spawn_agent authMode/authSurfaceKind precedent). When on, a criterion carrying an AUTHORED factKind (a) OVERRIDES the runtime deriveVerifyAssertionKind inference (mapped 6\u21923 for the escalation branch, Fork F1: absence\u2192absence, modification\u2192modification, value/count/presence/relation\u2192presence) AND (b) LIFTS Slice 1's F2 anti-flood filter for that step so ANY authored kind escalates \u2014 authoring IS the deliberate groundable-fact signal \u2014 still gated by the IDENTICAL captureModeGroundsAbsence floor (a capture even a vision extractor cannot ground abstains to the fail-closed inconclusive floor, NEVER escalate-and-guess), routed per collapsed kind (absence/modification \u2192 S3 differential candidate; value/count/presence/relation \u2192 S2 presence-family extraction candidate). This fixes the count/canvas case (authored count \u2192 escalates to S2 extraction) WITHOUT the runtime-presence flood. UNAUTHORED criteria keep Slice 1's runtime path EXACTLY (only absence/modification escalate; the runtime `presence` default does NOT). matchType/comparison/expectedValue-as-comparator UNTOUCHED; SHADOW-ONLY / verdict-inert like S1\u2013S5; it emits nothing on its own \u2014 the escalation diag / candidate still requires GROUNDED_STATE_VERIFIER / _EXTRACT / _DIFFERENTIAL / _INCONCLUSIVE. Off (or factKind absent) \u21D2 byte-identical: the field is unread, Slice 1's runtime behavior stands (AC-6). The field may be authored + persisted with this flag OFF (harmless, unread).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-25",notes:"Groundability-contract Slice 2 (PR-B). Default OFF; SHADOW-ONLY and verdict-inert even when ON. Read sites: packages/engine-core/src/RunnerRuntime.ts (groundedStateFactKindAuthoredEnabled \u2192 authoredFactKind, consumed by deriveVerifyAssertionKind override + the pinless F2-filter lift in maybeEmitPinlessNlEscalation). Field: packages/shared-types/src/index.ts (FactKind + TestPlanV2Criterion.factKind); producer schemas: coordinatorToolDefs.ts test_plan_criteria_schema, agentToolDefs.ts criteria_schema, runnerToolDefs.ts step_with_criteria_schema (thin inline); generation steer: planStepGuidance.ts buildCriteriaFactKindGuidance; 6\u21923 mapping + type-guard: groundedStateVerifier.ts factKindToAssertionKind / isAuthoredFactKind. DROP-SITES registered (else a plain step-text edit silently wipes the authored field \u2014 the matchType bug): renderer finalizeCriterion (apps/desktop-next/.../testPlanStepsSerde.ts) + server carryCriterionPins (apps/web-next/lib/testPlanSaveNormalize.ts) \u2014 both preserve factKind on an UNCHANGED check, drop it on an EDITED check (\u2192 runtime fallback, safe). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateFactKindAuthored.test.ts (authored count/presence on ungroundable canvas \u2192 S2 extraction candidate; authored absence \u2192 S3 differential candidate; authored + degraded capture \u2192 inconclusive floor, no escalate-and-guess; flag OFF \u2192 byte-identical field-unread Slice-1 behavior; field absent \u2192 Slice-1 behavior) + drop-site round-trip tests in testPlanStepsSerde.test.ts / testPlanSaveNormalize.test.ts. The MANDATORY real-runtime generation eval + the qa-box claim verify.groundability-contract-authored are Slice-2b (separate follow-on), NOT this PR. OVERLAP NOTE: composes with GROUNDED_STATE_NL_TRIGGER (Slice 1) via the shared maybeEmitPinlessNlEscalation helper.",graduation:{status:"gated",gate:"Slice 2 is measurement-only (no verdict change): it graduates by FEEDING the same S2/S3 extract-then-compare shadow soak, now widened to authored count/value/presence/relation kinds (the count/canvas case Slice 1 could not reach because runtime presence does not escalate). It advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; Slice 2 alone never flips default-on. Requires the Slice-2b generation eval (real ExplorerRuntime/CoordinatorRuntime authoring the correct factKind) to gate the authoring quality before any graduation.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events on PINLESS authored-factKind steps (escalation rate + factKind/reason/captureMode breakdown) + the engine-core RunnerRuntime.groundedStateFactKindAuthored unit suite; graduation additionally blocked on the Slice-2b real-runtime generation eval (authoring-distribution baseline)",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_FACTKIND_TYPING_PASS:{key:"GROUNDED_STATE_FACTKIND_TYPING_PASS",envVars:["AGENTIQA_GROUNDED_STATE_FACTKIND_TYPING_PASS","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FACTKIND_TYPING_PASS"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 2b \u2014 MODEL-authored focused second-pass factKind typing that FIXES the realistic-authoring gap (design docs/plans/2026-07-26-groundability-contract-design.md). Slice 2 (GROUNDED_STATE_FACTKIND_AUTHORED) consumes an authored `factKind`, but the live ExplorerRuntime authors it on ~0% of criteria produced by a realistic multimodal explore (screenshots + long trace + coordinator\u2192explorer spawn = the load that suppresses a deeply-nested OPTIONAL enum) \u2014 MEASURED 0/8 on e2e/evals/plans/groundability-factkind-explored.ts, and the three natural schema fixes (imperative guidance, required field, field reorder) ALL stayed 0%. But a FOCUSED low-load typing call over JUST the drafted check-texts types factKind at 100% (probe 78/78, real gemini-3-flash-preview). When on, AFTER the Explorer's draftTestCase is finalized (assistant_v2_report accept seam, past every re-prompt gate), a SEPARATE model-authored pass (packages/engine-core/src/factKindTypingPass.ts runFactKindTypingPass) collects the verify criteria that LACK an authored factKind, makes ONE batched Gemini call (the session's own model + the REAL buildCriteriaFactKindGuidance the producer schema ships; generateText + Output.object, thinkingBudget:0) that returns {index,factKind}[], and writes the kind back onto each criterion IN PLACE. It is MODEL-authored (a real Gemini call), NOT the rejected deterministic runtime factKind inference. NO OVERWRITE: only a MISSING factKind is filled (an already-authored kind is skipped at collect + double-guarded at write-back). FAIL-SAFE: any error/empty/timeout/invalid-kind leaves factKind UNSET (falls through to runtime inference) \u2014 never crashes authoring, never writes a garbage kind. SHADOW-SAFE: the written factKind is read ONLY by the separately flag-gated GROUNDED_STATE_FACTKIND_AUTHORED verifier (default-OFF), so verdicts are byte-identical whether or not this pass ran. Off \u21D2 the caller never invokes the module: ZERO new model calls, byte-identical authoring (AC-6).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-26",notes:"Groundability-contract Slice 2b (the realistic-authoring FIX; a flag-gated prototype \u2014 adding a model call to the authoring flow is Alex's architecture/graduation call). Default OFF; when ON adds ONE auxiliary Gemini call per COMPLETED explore that produced untyped verify criteria (batched, text-only, cost-isolated via emitAuxiliaryLlmUsage \u2014 not a billable step). Read site: packages/engine-core/src/ExplorerRuntime.ts assistant_v2_report accept seam (killSwitchEnabled('GROUNDED_STATE_FACTKIND_TYPING_PASS') \u2192 runFactKindTypingPass over draftTestCase.steps, mutating criteria in place BEFORE the report message is persisted/emitted, so the authored factKind rides both the saved plan and the diag). Pure module core (collectUntypedVerifyCriteria / buildFactKindTypingPrompt / mapTypesByIndex / applyFactKindTypes) + the single generateText seam. Unit suite: packages/engine-core/src/__tests__/factKindTypingPass.test.ts (ON fills missing factKind from a mocked typing response; OFF = no call / byte-identical; already-authored factKind never overwritten; error/empty response \u2192 factKind stays unset, fail-safe). RE-MEASURE: e2e/evals/plans/groundability-factkind-explored.ts COMMITTED_BASELINE carries the with-typing-pass authored-rate alongside the without (0/8).",graduation:{status:"gated",gate:"The realistic-authoring re-measure (groundability-factkind-explored with GROUNDED_STATE_FACTKIND_TYPING_PASS ON) shows the authored-factKind rate on the real explore path jump from ~0% to high (target near the probe 100%, \u2265~85%) with CORRECT kinds, AND the engine-core factKindTypingPass unit suite green (fill / no-overwrite / fail-safe / off-byte-identical). Graduation to any verdict path additionally requires GROUNDED_STATE_FACTKIND_AUTHORED (the consumer) to graduate under its own shadow-soak \u2014 this pass only PRODUCES the field.",evidence:"e2e/evals/plans/groundability-factkind-explored.ts with-typing-pass measuredAt entry (authored-rate + kind-correctness) + the engine-core factKindTypingPass unit suite + factkind_typing_pass diag events",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_UNIFIED:{key:"GROUNDED_STATE_UNIFIED",envVars:["AGENTIQA_GROUNDED_STATE_UNIFIED","AGENTIQA_EXPERIMENT_GROUNDED_STATE_UNIFIED"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Trust-layer Slice 2 \u2014 PER-SNAPSHOT UNIFICATION (design docs/plans/2026-07-26-trust-layer-slice-2-per-snapshot-unification-design.md; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md). Collapses the three Slice-1 per-kind run_complete batches (runGroundedStateCounts / runGroundedStateExtractions / runGroundedStateDifferentials \u2014 each re-extracting once PER step/kind) into ONE task-blind extraction PER SNAPSHOT feeding ONE typed-comparator dispatch, and introduces the verdict SPECTRUM (Verified / Assessed / Inconclusive) + semantic matchType. SHADOW-ONLY: when on AND a stateExtractor is wired, it consumes the SAME escalation candidates the per-kind batches do (its flag is OR-ed into the maybeEmitVerifierEscalation candidate-recording seam), groups them by shared captured AFTER-frame (groupCandidatesBySnapshot \u2014 verify-steps sharing a frame with no intervening state-mutating action share ONE extraction; differential candidates additionally share ONE run-start baseline extraction), runs ONE extraction per unique frame, and for each candidate runs its typed comparator (compareCount / comparePresence / compareAbsenceDifferential / compareModificationDifferential) \u2014 or, for a matchType:'semantic' criterion, the task-blind concept classifier (deps.conceptClassifier) \u2014 against that shared extraction. It LOGS grounded_state_unified (band + shadowVerdict + parity vs the driver grade) + grounded_state_unified_start/_done (the extraction-vs-comparison counts that PROVE 1-extraction-per-snapshot); it mutates NO stepResult and changes NO verdict. Part B is a REFACTOR that must be verdict-PARITY with the three per-kind paths: the unified would-verdict equals what the retired per-kind batch logged (same evidence resolution + same target derivation + same deterministic comparator on the same extraction). The verdict spectrum: a deterministic comparator would_pass/would_fail \u2192 Verified (the no-false-positive guarantee); a low-confidence semantic result \u2192 Assessed (the SLOT only \u2014 the independent reasoned judge is a LATER slice); no confident extraction/classification / missing image / extractor abstain / error / timeout / unresolvable comparison / unavailable semantic classifier \u2192 the fail-closed Inconclusive floor, NEVER a pass. Task-blindness preserved: the extraction prompt (buildExtractionQuestion) carries observation targets only and the semantic classifier carries a concept + a neutral observation rendering \u2014 NEVER the expected values or pass/fail framing. It runs ALONGSIDE the per-kind batches (its own flag) so the shadow soak can prove parity BEFORE the per-kind methods are physically retired. Off \u21D2 zero candidate consumption here, zero extraction calls, byte-identical (the per-kind paths, if their flags are on, are untouched) (AC-6). Cost: #snapshots (+1 shared before, if any differential) extraction calls per run \u2014 strictly \u2264 the sum of the three per-kind batches, and 1 for N verify-steps on one screen.",designDoc:"docs/plans/2026-07-26-trust-layer-slice-2-per-snapshot-unification-design.md",status:"active",added:"2026-07-26",notes:"Trust-layer Slice 2 (per-snapshot unification). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes + LOGS the would-be verdict-spectrum result and its parity vs the driver grade (grounded_state_unified / _start / _done diags), makes #snapshots (+1 shared before) extraction calls plus one concept-classifier call per semantic candidate (both cost-isolated Flash-model seams via emitAuxiliaryLlmUsage, hard-capped, batched under the same deadline as the per-kind batches), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) \u2014 it consumes the SAME candidate maps and reuses the SAME comparators, so its would-verdicts are byte-parity with the three per-kind batches (the Slice-2 acceptance gate). Requires deps.stateExtractor wired; a matchType:'semantic' criterion additionally requires deps.conceptClassifier (absent \u21D2 that candidate floors to Inconclusive). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateUnifiedEnabled \u2192 the OR-ed candidate recording in maybeEmitVerifierEscalation + collectUnifiedCandidates + runGroundedStateUnified at run_complete); pure core (snapshot grouping / verdict spectrum / semantic mapping) in packages/engine-core/src/groundedStateUnified.ts. Acceptance tests: packages/engine-core/src/__tests__/groundedStateUnified.test.ts (pure \u2014 grouping, spectrum mapping, semantic mapping) + RunnerRuntime.groundedStateUnified.test.ts (wiring \u2014 verdict-PARITY vs the three per-kind batches, ONE extraction for N\u22653 verify-steps on one snapshot, semantic success\u2192Verified / ambiguous\u2192Assessed / error\u2192Verified-FAIL, shadow-no-mutation, flag-OFF byte-identical). Evals: e2e/evals/plans/trust-unified-parity.ts (runner-trust-unified-parity), trust-unified-batching.ts (runner-trust-unified-batching), trust-unified-semantic.ts (runner-trust-unified-semantic). The three per-kind batch methods are RETAINED in this slice as the parity oracle; their physical removal is the graduation follow-up. Binds claim verify.grounded-state-extract-then-compare.",graduation:{status:"gated",gate:"Slice 2 is shadow-first (no verdict change). Graduation gates on: (1) a staging verdict-PARITY shadow soak of grounded_state_unified vs the per-kind grounded_state_count / _extract / _differential diags showing ZERO would-verdict drift across the count / presence / absence / modification fixtures; (2) grounded_state_unified_done confirming extractions == #snapshots (+ shared before), NOT #comparisons (the batching win) in the field; (3) the semantic-matchType Assessed slot behaving (confident \u2192 Verified, ambiguous \u2192 Assessed, contradiction \u2192 Verified-FAIL) at an acceptable concept-classifier accuracy. ONLY after parity is proven do the three per-kind batch methods get physically retired (a separate refactor PR) and does advancing to a LIVE verdict path get considered \u2014 both separate steps from flipping this flag shadow-on.",evidence:"staging grounded_state_unified / _start / _done diag events (spectrum verdict + parity + extraction-vs-comparison counts) cross-checked against the per-kind diags for parity + the engine-core groundedStateUnified + RunnerRuntime.groundedStateUnified unit suites + the trust-unified-parity / -batching / -semantic evals + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-09-05"}},INTERACTION_CLEARS_PRESENCE_ORACLE:{key:"INTERACTION_CLEARS_PRESENCE_ORACLE",envVars:["AGENTIQA_INTERACTION_CLEARS_PRESENCE_ORACLE","AGENTIQA_EXPERIMENT_INTERACTION_CLEARS_PRESENCE_ORACLE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Interaction-clears-presence-oracle (rank-2 of the step-5 slow-render flake wave, sibling to VERIFY_PRESENCE_WAIT_FLOOR's rank-1 budget raise). A verify-step PRESENCE wait oracle (wait_for_element) that STILL times out after the raised budget records an unresolved oracle failure that verify-gated-done only lets a fresh successful wait_for_element/run_js clear \u2014 a screenshot or a successful click is refused and the plan-grounded literal blocks canReconcileVerificationConflict \u2014 so a genuinely-present-but-slow element force-FAILs (staging sessions asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1, where the NEXT step's click_at('Blank board') SUCCEEDED and navigated). When on, a subsequent SUCCESSFUL deterministic click_at (or a type_text_at/set_focused_input_value write) on the current verify step or the one immediately preceding it (lookback 1) whose ENGINE-RESOLVED element identity (clickTarget.accessibleName/textContent for a ref/coordinate click, clickedElement.textContent for a label click, or typedIntoField \u2014 the resolved field's accessible name \u2014 for a type write; never the model's narration or the typed VALUE) whole-token-substantiates (citationSubstantiates \u2014 the SAME contiguous-token machinery pinPresentInPage uses, NOT substring) the failed wait's captured target literal CLEARS that step's wait-oracle failure \u2014 engine-observed, un-hallucinable proof of presence, strictly stronger than the screenshot the gate already refuses. HARD CONSTRAINTS (no false-PASS): whole-token resolved-name match only, gated by a SIGNIFICANCE floor (the wait literal must carry a \u22654-char token OR \u22652 tokens \u2014 a bare common single short token like \"ok\"/\"3\" whole-token-matches an unrelated control name too easily, so it can never clear); the #1476 real-hit guard (a coordinate no-op-success \u2014 noObservedEffect side channel \u2014 and a non-interactive pixel landing whose accessibleName merely mirrors a container's textContent are BOTH rejected, so a click that reports success but hit nothing cannot launder a miss); a type only ever clears when it genuinely resolved+focused a named field (typedIntoField populated \u2014 a blind write carries no identity); scope = wait-style presence oracle only (isVerificationOracleAction, NEVER the plan-derived pin-page-grounding oracle) on a Runner verify step; an ABSENCE-intent verify step (checkTextAssertsAbsence over the step text + criteria) is NEVER cleared \u2014 a successful interaction DISPROVES an absence assertion, so clearing would manufacture a pass on a real absence-violation bug; fail-closed (a genuinely-absent element cannot be successfully interacted with, and an ambiguous / non-matching / insignificant-literal / stale-beyond-lookback / absence-intent identity does NOT clear \u2014 the force-fail stands). SHADOW-FIRST: off (default) leaves every verdict identical (the force-fail stands) and only emits an `interaction_clears_presence_oracle:would_clear` diag of what it WOULD have cleared, so a staging soak can confirm it fires only on genuine presence before the flip; on makes the clear live (`\u2026:cleared`).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-25",notes:"Default OFF in code; detection runs in shadow always (interaction_clears_presence_oracle:would_clear diag), the actual clear is gated \u2014 the ABSENCE_AWARE_VERIFY / PIN_PAGE_GROUNDING shadow-first precedent. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add INTERACTION_CLEARS_PRESENCE_ORACLE to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/RunnerRuntime.ts (interactionClearsPresenceOracleEnabled \u2192 maybeInteractionClearsPresenceOracle, called from the browser-action dispatch after recordOffPlanResolvedClick). Resolved-identity sources: label click \u2192 response.clickedElement.text (clickByLabel only populates it after resolving exactly one clickable control by name AND clicking without error \u2014 un-hallucinable); ref/coordinate click \u2192 response.clickTarget.accessibleName/text, admitted ONLY when isInteractiveClickTarget(clickTarget) so a pixel that landed on a text container cannot launder via the accessibleName\u2192textContent fallback; type write (type_text_at / set_focused_input_value) \u2192 response.typedIntoField (getFocusedFieldName \u2014 the accessible name of the field the write actually resolved+focused; the typed VALUE is never an identity). SIGNIFICANCE floor (waitLiteralHasSignificantTokens over the same tokenizeCitation basis the match uses): a bare common single short token (a status word, a lone digit) whole-token-matches an unrelated resolved name too easily, so the wait literal must carry a \u22654-char token OR \u22652 tokens or it never clears. Lookback is intentionally tight (1 step) to keep a stale REAL miss from an earlier step from being laundered by a same-named element that appears much later; a soak may widen it. Absence-intent verify steps are excluded via checkTextAssertsAbsence (a successful interaction disproves an absence assertion \u2192 would be a false-PASS); a suppressed match emits interaction_clears_presence_oracle:absence_skip. Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.interactionClearsPresenceOracle.test.ts (flag-OFF shadow-only + byte-identical for both click and type, flag-ON label + ref + type clear, type resolved-different-field reject, type-with-no-resolved-field reject, significance-floor bare-one-token reject, #1476 no-op reject, non-interactive container-text reject, non-matching-element reject, whole-token-not-substring, genuinely-absent still-fails, absence-intent step NEVER cleared, pin-page-grounding scope guard, cross-step lookback bound).",graduation:{status:"gated",gate:"Staging shadow soak clean (interaction_clears_presence_oracle:would_clear fires ONLY where a successful click genuinely resolved+acted on an element whose engine-resolved identity whole-token-matches the failed wait literal \u2014 never on a #1476 coordinate no-op, a non-interactive container-text mirror, an absence-intent verify step, or a stale failure beyond the 1-step lookback) AND the engine-core interaction-clears-presence-oracle detection-inversion passes (flag OFF \u2192 the timed-out presence step still force-FAILs; flag ON \u2192 a matching successful click clears it to a PASS, a no-op/non-matching/absent/absence-intent element still FAILs)",evidence:"staging interaction_clears_presence_oracle:would_clear / :cleared diag events (clear rate + resolvedVia/literal breakdown) + the RunnerRuntime.interactionClearsPresenceOracle unit suite + the step-5 slow-render rehearsal replay (asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1)",owner:"steering (Alex)",review:"2026-08-01"}},CANVAS_STRATEGY:{key:"CANVAS_STRATEGY",envVars:["AGENTIQA_CANVAS_STRATEGY","AGENTIQA_EXPERIMENT_CANVAS_STRATEGY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Enables the canvas-app (Miro/Figma/spreadsheet) per-turn strategy prompt injection and the coordinate-action tool-result caveat; off drops both so a false canvas classification cannot alter targeting guidance.",designDoc:"docs/plans/2026-07-06-canvas-capability-design.md",status:"active",added:"2026-07-06"},SCREENSHOT_DIRECT_UPLOAD:{key:"SCREENSHOT_DIRECT_UPLOAD",envVars:["AGENTIQA_SCREENSHOT_DIRECT_UPLOAD","AGENTIQA_EXPERIMENT_SCREENSHOT_DIRECT_UPLOAD"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Analytics-sink screenshot upload path: on, the sink fetches a presigned R2 PUT URL from /api/analytics/presign-screenshot and PUTs the PNG straight to R2 (bytes never transit web-next); "0" forces the legacy base64 /api/analytics/upload-image route. On any presign/PUT failure the sink falls back to the legacy route per-screenshot regardless of this switch.',designDoc:"packages/engine-core/src/sinks/RemoteAnalyticsSink.ts",status:"active",added:"2026-07-19"},SAME_GOAL_ABORT:{key:"SAME_GOAL_ABORT",envVars:["AGENTIQA_SAME_GOAL_ABORT","AGENTIQA_EXPERIMENT_SAME_GOAL_ABORT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Escalates consecutive milestone-free supervisor REDIRECT verdicts into an abort-then-block, bounding a stuck same-goal step; off leaves the supervisor redirecting until the iteration budget runs out.",designDoc:"docs/plans/2026-07-06-canvas-capability-design.md",status:"active",added:"2026-07-06"},TARGET_CONTAINMENT:{key:"TARGET_CONTAINMENT",envVars:["AGENTIQA_TARGET_CONTAINMENT","AGENTIQA_EXPERIMENT_TARGET_CONTAINMENT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Keeps the agent within the app-under-test origin at every navigation chokepoint; off makes every boundary check return "allow" (pre-containment behavior).',designDoc:"packages/engine-core/src/BasePlaywrightService.ts",status:"active",added:"2026-07-05"},PIN_SUBSTANTIATION:{key:"PIN_SUBSTANTIATION",envVars:["AGENTIQA_PIN_SUBSTANTIATION","AGENTIQA_EXPERIMENT_PIN_SUBSTANTIATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Flips a criterion the model graded "passed" to failed when the pinned expected value is not substantiated; off returns the model grade verbatim (pins still render, enforcement is off).',designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-07"},PIN_CROSS_STEP_SUBSTANTIATION:{key:"PIN_CROSS_STEP_SUBSTANTIATION",envVars:["AGENTIQA_PIN_CROSS_STEP_SUBSTANTIATION","AGENTIQA_EXPERIMENT_PIN_CROSS_STEP_SUBSTANTIATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:`FIX 3 (extends FIX 2 to the cross-STEP misattribution class). Before Amendment 5a synthesizes a strict pinned criterion as "never graded \u2192 unconfirmed \u2192 fail", it searches EARLIER step entries for an ORPHAN grade of the IDENTICAL check \u2014 graded passed=true, bound to NONE of its own step's plan criteria, and whose observed value substantiates THIS pin's expectedValue (the SAME substantiatePinnedCriterion gate). A match means the grading LLM misfiled the pin under a PRECEDING/action step (prod asess_1785211658727: step 2's 3 strict pins graded inside step 1, an action step), so the pin was really evaluated \u2014 the substantiated pass is relocated to its own slot instead of false-failing the step. Off restores FIX 2 behavior verbatim (no cross-step search). The rescue is SCOPED to misattributed grades, not a blanket 'a passing grade exists elsewhere': (1) only orphan grades qualify \u2014 a step's OWN bound verdict is never borrowed, so a still-passing earlier verify cannot mask a later regression; (2) a contradicting FAILING grade for the same check anywhere blocks the rescue; (3) only a STRICTLY EARLIER step's grade qualifies, so a later step's page state is never laundered backward onto an earlier assertion (a backward misattribution stays fail-closed); (4) the caller only rescues a pin unique among plan verify criteria. Outside that envelope the pre-existing fail-closed synthesis stands. EVIDENCE-EPOCH DISPOSITION (steering 2026-07-28): 'strictly earlier' does not mean 'same page state', so a rescue is only a silent PASS when NO state-changing plan step (type action/setup) sits STRICTLY BETWEEN the rescuing entry and the pin's own step \u2014 the confirmed prod shape (verify step k's grades misfiled under the immediately preceding action step k-1) has nothing in between, so it keeps its full PASS rescue. A STALE-FORWARD rescue (an intervening action/setup broke the epoch, so the observation may predate a regression) is instead SOFT-WITHHELD to a step-level 'warning' \u2014 the criterion carries the substantiated pass noted 'substantiated by an earlier-step grade; not re-verified at this step' and the step is demoted passed->warning (never a hard fail, never a clean pass; run status is untouched since only 'failed' steps downgrade a run). This is the ABSENCE_AWARE_VERIFY-ABSTAIN / GROUNDING_EPOCH_FIDELITY withhold rail: the criterion stays passed:true on purpose, because flipping it would route deriveStepStatusFromCriteria to a hard 'failed' on a strict criterion (warning-cap-only). Every accepted rescue emits RunnerRuntime log pin_cross_step_substantiated {stepIndex, sourceStep, expected, orphanCandidates, corpusSize, reason} for prod frequency/provenance, where reason is 'same-epoch-rescue' (PASS) or 'stale-forward-warning' (withheld). SHARED BINDER (round 4): the orphan test (guard 1) READS the already-computed per-entry bindings from bindGradesToPlanSlots \u2014 the ONE authoritative two-pass binder that also drives FIX 2's cross-entry union and the reported criteria results \u2014 and never re-derives them. An earlier revision ran its own SEQUENTIAL bindGradeToPlanIdx loop, which diverges from the two-pass binder wherever a rephrased grade's positional fallback would steal a slot a later grade matches by exact text: the authoritative binder books that grade onto its own step (non-orphan) while the sequential mirror leaves it unbound (orphan) and thus eligible to rescue another step's pin \u2014 an EMERGENT false-PASS reachable only with PIN_CROSS_STEP_SUBSTANTIATION and CRITERION_BIND_RESIDUAL both on, which each flag's own tests miss. Pinned by a 4-cell flag-matrix test. PER-CRITERION FLOOR (round 4): the rescue pushes a synthetic passed result, which switched OFF the whole-step zero-grade 'unsubstantiated verify' floor (that floor tests criteriaResults.length === 0) for the step's OTHER criteria \u2014 and Amendment 5a itself only covers PINNED strict criteria, so a plain strict criterion beside a rescued pin was adjudicated by nothing and rode through on the reported 'passed'. On steps where a rescue fired, each plan criterion that is in neither the FIX 2 union nor Amendment 5a's coverage AND has no matching grade anywhere in the cross-step corpus now synthesizes its own failure (strict) or warning (strict:false), emitting pin_cross_step_sibling_unsubstantiated {stepIndex, check, strict, rescuedPinsOnStep}. Scoped to rescue-touched steps so no untouched verdict moves, and gated on 'ungraded ANYWHERE' so the whole-step misattribution the rescue tolerates is not re-punished.`,designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-28"},CHECK_TEXT_ATOM_PIN:{key:"CHECK_TEXT_ATOM_PIN",envVars:["AGENTIQA_CHECK_TEXT_ATOM_PIN","AGENTIQA_EXPERIMENT_CHECK_TEXT_ATOM_PIN"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"run_complete grade-time atom pinning: a strict verify criterion whose check text pins exactly one URL literal (http(s):// or bare localhost) and carries no expectedValue has that literal promoted to an effective expectedValue so the pin-substantiation / grounding machinery fires on it, plus a deterministic URL-host floor that fails the criterion closed (naming both hosts) when the evidence observes a different-host URL and preserves the pass on a scheme-only / trailing-slash difference \u2014 regardless of what the substantiation/drift judge decided. Off leaves a bare {check, strict} URL criterion ungraded past the model self-grade (pre-feature behavior).",designDoc:"docs/plans/2026-07-19-ag7727-run-fidelity-fixes-design.md",status:"active",added:"2026-07-19"},TYPED_MATCH:{key:"TYPED_MATCH",envVars:["AGENTIQA_TYPED_MATCH","AGENTIQA_EXPERIMENT_TYPED_MATCH"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Routes pin-substantiation's observed-vs-expected comparison through the typed match-comparator registry keyed on a criterion's `matchType` (country ISO-3166 fold DE\u2261Germany, locale numeric equality); a typed match keeps a pass the brittle literal compare would have flipped, a typed mismatch (wrong country) flips closed. Off (or an absent/`literal` matchType) restores the pure literal `citationSubstantiates` behavior verbatim \u2014 inert until a criterion carries a matchType, so this only removes a false-fail class, never changes an untyped verdict (AG-7753).",designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-20"},COUNTRY_EQUIV_RESCUE:{key:"COUNTRY_EQUIV_RESCUE",envVars:["AGENTIQA_COUNTRY_EQUIV_RESCUE","AGENTIQA_EXPERIMENT_COUNTRY_EQUIV_RESCUE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'C2 country-equivalence rescue in run_complete pin substantiation: when an already model-PASSED strict criterion\'s literal citation fails, the citation is retried with every recognized country surface form on BOTH sides folded to its ISO-3166 alpha-3, so an address that differs ONLY by country NAME vs CODE ("\u2026H\xF6henkirchen Germany" pin vs "\u2026H\xF6henkirchen DE" observed, prod Lio tp_5a2a7f4c step 9) substantiates instead of brittle-failing. Narrowly scoped: the rescue runs only for a country-SHAPED pin \u2014 `matchType: \'country\'`, or (untyped/literal/text-normalized/presence) a pin whose TERMINAL token is a full country NAME or alpha-3; a bare terminal alpha-2 pin ("Dover, DE") and every number/currency/url/semantic matchType are excluded. The fold itself only rewrites a country NAME anywhere, and a country CODE only as an uppercase token in the terminal country slot (never before a US zip), with subdivision/unit collisions (CA/NL/GB/CH/IE/PL/PT/SE/IN/CAN/NOR/\u2026) restricted to a sole-token read. That extra ambiguity is FOLD-SCOPED (`FOLD_AMBIGUOUS_ALPHA2`/`FOLD_AMBIGUOUS_ALPHA3`): the shared gazetteer read by citedCountry/compareTyped \u2014 i.e. the typed-atom floor and the predicate-basis typed comparator, neither of which this switch gates \u2014 is untouched BY THIS FLAG, verified by a differential sweep of the whole gazetteer. Off restores the pure literal `citationSubstantiates` verdict, so this flag only ever removes a false-FAIL class and nothing this flag contributes survives turning it off. NOTE (AG-8212, 2026-07-29) \u2014 that is a statement about THIS flag, not about the comparator stack as a whole: the OBSERVED scan has since gained its own ungated guard (the same eight collision-prone alpha-2 codes are now gated in citedCountry too, so a bare code buried in prose resolves a country only when a full NAME corroborates it or when it is the sole token), which this switch does not gate and cannot revert. The fold path and both fold-ambiguity sets remain pre-C2 byte-identical, and the AUTHORED read (`citedCountryAuthored`, what the typed-atom floor recognizes the author\'s check text with) is unchanged. Split out of TYPED_MATCH (which stays inert on untyped criteria) because this rescue fires on criteria that carry NO matchType.',designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-28"},TYPED_ATOM_FLOOR:{key:"TYPED_ATOM_FLOOR",envVars:["AGENTIQA_TYPED_ATOM_FLOOR","AGENTIQA_EXPERIMENT_TYPED_ATOM_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"AG-7753 Phase 2 strict-unpinned typed-atom floor. run_complete detection ALWAYS runs (shadow): for a strict verify criterion the model graded passed that carries NO expectedValue and whose check text names exactly one recognized typed atom (country ISO-3166 / currency ISO-4217 / number \u2014 the generalization of #1685's URL host floor), the page-read observed value (a11y snapshot, else the structured `observed` grade field; disagreement \u2192 abstain) is compared to the recognized expectation via compareTyped. On a same-type MISMATCH (France where Germany expected) it emits a shadow `typed_atom_floor:would_fail` diag; when this flag is ON it ENFORCES \u2014 flipping the criterion passed\u2192false (only-fails, never originates a pass) and emitting `typed_atom_floor:fire`. Off leaves every verdict byte-identical (shadow diag only). URL stays owned by CHECK_TEXT_ATOM_PIN \u2014 a URL-bearing check is not recognized here.",designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-20",notes:"GRADUATED 2026-07-21 (default on) via the evidence-count doctrine: detection-inversion PROVEN twice \u2014 deterministically in RunnerRuntime.typedAtomFloor.test.ts (33 assertions) and live in the runner/typed-atom-country-floor L3 eval (qa-exhaustive 29861680933: seeded wrong-country step correctly failed) after the self-testing fixture deploy was unblocked (productionBranch was pinned to main). Shadow soak was clean but thin (organic staging plans carry no recognizable unpinned atoms \u2014 vacuous-soak class). Enforcement only-fails a same-type mismatch, never originates a pass. Distinct from TYPED_MATCH (Phase 1, default ON, pinned-criterion fold) and CHECK_TEXT_ATOM_PIN (#1685, URL host floor). Runner lane only (RunnerRuntime run_complete)."},COMPLETION_EVIDENCE_FLOOR:{key:"COMPLETION_EVIDENCE_FLOOR",envVars:["AGENTIQA_COMPLETION_EVIDENCE_FLOOR","AGENTIQA_EXPERIMENT_COMPLETION_EVIDENCE_FLOOR"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Completion-evidence floor for the CHAT/CLI objective lane (the ungrounded-ship seam VERIFY_GATED_DONE misses: it fires only on a failed wait-oracle in the last 5 actions, so a fabricated value with no failing wait ships silently). Detection ALWAYS runs (shadow) at ExplorerRuntime.handleReport on a terminal `completed` report: for an evidence-bearing objective (find/copy/extract a named value) it grounds the agent's TYPED CLAIM (the optional `extractedValues` field on the assistant_v2_report payload; free-text is never parsed): a claimed value found nowhere in the runtime a11y-snapshot corpus nor in runtime_observed revealed facts (whole-token `citationSubstantiates` \u2014 free-form; `compareTyped`'s closed grammar does NOT apply) emits a shadow `completion_grounding:would_demote` diag; a completed extraction objective with NO typed claim is shadow-only signal (reason no_typed_claim) and is NEVER enforced. Label-presence in the corpus never substantiates a value (v1.1). When this flag is ON it ENFORCES the typed-claim-fabrication path only \u2014 attaching an Explorer `VerificationConflict` with the NEW source `completion_ungrounded` (own card copy; NO terminal blockKind) that the existing verification-conflict rail (`applyVerificationConflictFindings` / `focusedTaskVerdictRecommendation`) demotes to do_not_ship in BOTH Coordinator producers. ABSTAINS (never demotes) when the objective is not evidence-bearing, the target is undecidable, or the observed corpus is thin/absent (canvas/off-DOM/dynamic value not in the snapshot) \u2014 demote-on-absence must abstain on any evidence-availability gap (blind-double-read precedent). Off leaves every verdict byte-identical (shadow diag only). Distinct from TYPED_ATOM_FLOOR (runner lane, closed-grammar value mismatch); this is the chat-lane grounding net (absence of any observed evidence, not value-correctness).",designDoc:"docs/plans/2026-07-21-completion-evidence-floor-design.md",status:"active",added:"2026-07-21",notes:"Default OFF in code; detection runs in shadow always (would_demote diag), enforcement is gated \u2014 the PIN_PAGE_GROUNDING / TYPED_ATOM_FLOOR shadow-first precedent. Single Explorer-level hook (handleReport) so both Coordinator verdict producers surface it (the cross-producer parity bug class, PR #643). Chat/Explorer lane only (assistant_v2_report). v1.1: enforcement requires a typed extractedValues claim proven absent from corpus+facts (provable fabrication); strict-extraction recognizer with common-UI-word stoplist (generic read/find objectives abstain); no-typed-claim path stays shadow-only so the soak measures claim-population rate. Grounds fabrication of a claimed value, NOT mis-selection of a real-but-wrong on-page value.",graduation:{status:"gated",gate:"Staging shadow soak clean (would_demote fires on the wandering-maze fabricate-and-ship replicates, zero would_demote on legitimately-shipping value-extraction controls) AND the engine-core completion-evidence-floor detection-inversion passes (floor OFF \u2192 fabricate-and-ship rides through as ship, ON \u2192 do_not_ship on the identical input in BOTH producers)",evidence:"staging completion_grounding:would_demote diag events + the engine-core completion-evidence-floor unit suite + the loop-detection/wandering-self-stop flag-ON graduation run",owner:"steering (Alex)",review:"2026-07-23"}},SETUP_NOTE_GROUNDING:{key:"SETUP_NOTE_GROUNDING",envVars:["AGENTIQA_SETUP_NOTE_GROUNDING","AGENTIQA_EXPERIMENT_SETUP_NOTE_GROUNDING"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Setup/action step-note grounding \u2014 surface S-A of the substantiation-fidelity (\"honest words\") track. Detection ALWAYS runs (shadow) at RunnerRuntime run_complete, after substantiation + the typed-atom floor: for each setup/action step (verify steps out of scope) graded passed/warning whose NOTE names a completed UI action (a closed past-tense/gerund verb lexicon \u2014 entered/typed/filled/submitted/clicked/selected/uploaded/dragged/\u2026) it checks the step's own planStepIndex-stamped action-tool window; a note asserting an action with ZERO grounding action tool calls in-window (the census shape asess_1784714866561_jhc34ht9 \u2014 pre-authed login steps graded green with 'Entered the email'/'Submitted the login form' notes and no type_*/click ever fired) emits a shadow `narration_fidelity:would_flag{surface:'setup_note', stepIndex, claim, missing_action, toolCallsInWindow}`. ABSTAINS (never flags) on a verify/read-only step, a note with no action verb, a non-terminal grade, or a window carrying ANY grounding action tool \u2014 ambiguity always abstains (closed allowlist). When this flag is ON it ENFORCES honest note substitution \u2014 the fabricated action clause is replaced with an honest precondition note; the step's verdict/status is UNTOUCHED (never a hard fail \u2014 the precondition was met, just not by the asserted action). Off leaves every stepResults note byte-identical (shadow diag only). Distinct from TYPED_ATOM_FLOOR (verify-criterion value mismatch) and COMPLETION_EVIDENCE_FLOOR (chat-lane claimed-value fabrication); this grounds SETUP/ACTION step NARRATION against the action log.",designDoc:"docs/plans/2026-07-22-substantiation-fidelity-design.md",status:"active",added:"2026-07-22",notes:"Default OFF in code; detection runs in shadow always (would_flag diag), enforcement (honest note substitution) is gated \u2014 the COMPLETION_EVIDENCE_FLOOR / TYPED_ATOM_FLOOR shadow-first precedent. Single RunnerRuntime run_complete pass (mirrors the typed-atom floor shadow). Deterministic \u2014 ~zero marginal LLM cost (reads the already-collected stepResults notes + the planStepIndex-stamped action-message log). P0 of the substantiation-fidelity track (S-A); S-B/S-C/S-D are separate per-phase flags.",graduation:{status:"gated",gate:"Staging shadow soak clean (narration_fidelity:would_flag{surface:'setup_note'} fires on the census-shaped reproduced-RED fixture, zero would_flag on legitimately-honest action notes whose tool call fired) AND the engine-core setupNoteGrounding detection-inversion passes (rip the pass out \u2192 the fixture stops flagging; enforce-ON rewrites the note, verdict untouched, on the identical input)",evidence:"staging narration_fidelity:would_flag diag events + the engine-core setupNoteGrounding + RunnerRuntime.setupNoteGrounding unit suites + the runner/narration-ghost-setup reproduced-RED eval",owner:"steering (Alex)",review:"2026-07-29"}},GROUNDING_EPOCH_FIDELITY:{key:"GROUNDING_EPOCH_FIDELITY",envVars:["AGENTIQA_GROUNDING_EPOCH_FIDELITY","AGENTIQA_EXPERIMENT_GROUNDING_EPOCH_FIDELITY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Criterion grounding-epoch fidelity \u2014 surface S-B of the substantiation-fidelity (\"honest words\") track. Detection ALWAYS runs (shadow) at RunnerRuntime run_complete, after substantiation + grounding + the typed-atom floor: for each verify-step criterion substantiated as PASSED it compares the criterion's grounding epoch (the monotonic capture/generation index at which its pinned value was actually groundable in a full page snapshot) against the step's OWN verify-time epoch. A value groundable ONLY in a STRICTLY-LATER capture \u2014 a subsequent step's / a different entity's snapshot \u2014 is cross-entity-deferred grounding (the census asess_1784714866561_jhc34ht9 step 6: base-draft pins pin_page_grounding:would_fail at the step's own epoch, then matched off the duplicate-draft (e674/e731) and submitted-request (e1337) snapshots, all past the base-draft epoch) and emits a shadow `narration_fidelity:would_flag{surface:'grounding_epoch', stepIndex, criterion, groundingEpoch, stepEpoch, epochDriftRefs}`. ABSTAINS (never flags) on a value grounded at/before the step's own epoch (honest same-epoch grounding, or a legitimately-earlier carried observation), an explicitly carried-forward observation with recorded provenance, a criterion that did not pass, or an UNDETERMINED epoch (a missing epoch never manufactures a flag). When this flag is ON it ENFORCES via the existing VERIFY_REOBSERVE_WITHHOLD soft-withhold rail: the cross-entity-grounded criterion is treated as UNCONFIRMED and routed to a warning (never a red fail \u2014 the values may be correct; the fix removes the false EVIDENCE ATTRIBUTION, not the pass). Off leaves every verdict byte-identical (shadow diag only). Distinct from PIN_PAGE_GROUNDING (value ABSENCE at grade time) and SETUP_NOTE_GROUNDING (setup/action step NARRATION); this grounds a verify criterion's EVIDENCE-EPOCH provenance.",designDoc:"docs/plans/2026-07-22-substantiation-fidelity-design.md",status:"active",added:"2026-07-23",notes:"Default OFF in code; detection runs in shadow always (would_flag diag), enforcement (soft-withhold to warning via VERIFY_REOBSERVE_WITHHOLD) is gated \u2014 the COMPLETION_EVIDENCE_FLOOR / SETUP_NOTE_GROUNDING shadow-first precedent. Single RunnerRuntime run_complete pass (mirrors the setup-note-grounding shadow). Deterministic \u2014 ~zero marginal LLM cost (reconstructs each step's own capture epoch + each pinned value's grounding epoch from the retained per-generation full snapshots collected during the run). P1 of the substantiation-fidelity track (S-B); S-A (SETUP_NOTE_GROUNDING) shipped P0, S-C/S-D are separate flags.",graduation:{status:"gated",gate:"Staging shadow soak clean (narration_fidelity:would_flag{surface:'grounding_epoch'} fires on the census-shaped A\u2192duplicate-B reproduced-RED fixture, zero would_flag on same-epoch honest grounding controls) AND the engine-core groundingEpochFidelity detection-inversion passes (rip the drift out \u2192 the fixture stops flagging; enforce-ON soft-withholds the criterion to warning, never red, on the identical input)",evidence:"staging narration_fidelity:would_flag diag events + the engine-core groundingEpochFidelity + RunnerRuntime.groundingEpoch unit suites + the runner/narration-grounding-epoch reproduced-RED eval",owner:"steering (Alex)",review:"2026-07-30"}},NOTE_CONTRADICTION_FLOOR:{key:"NOTE_CONTRADICTION_FLOOR",envVars:["AGENTIQA_NOTE_CONTRADICTION_FLOOR","AGENTIQA_EXPERIMENT_NOTE_CONTRADICTION_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Terminal-error verdict-honesty Layer A \u2014 the deterministic note-contradiction floor (run_27825c90). Detection ALWAYS runs (pure module) at RunnerRuntime run_complete, LAST \u2014 after every fail gate: for a step the model graded `passed` carrying a passed criterion whose OWN note/groundingObservation text contains a conservative error marker (error/failed/failure/timeout/timed out/aborted/exception/went wrong, word-boundary) that the criterion's own check/expectedValue (or its step text) does NOT license, it caps that step to `warning` with an explanatory note. A marker GOVERNED BY A NEGATOR in the same clause (no/not/never/without/none/zero/didn't/no longer/free of/\u2026 \u2014 see NEGATOR_RE) is BENIGN and never caps ('No error appeared', 'verified no timeout occurred'), so a note that negates every marker is skipped; a note that re-asserts an error after negating one ('no error at first, then Error: timeout appeared') still caps. ONE-DIRECTIONAL \u2014 only caps a passed step (never rescues/escalates a model-failed grade; the criterion result stays passed, the STEP status is soft-withheld like VERIFY_REOBSERVE_WITHHOLD). Check-text licensing is dumb-string (accepts the documented `verify NO error` negation blind spot on the CHECK \u2014 Layer B handles it semantically). This flag ALSO gates the deterministic report_issue verdict-bearing fold (decision 6): a high/medium-severity `logical` issue filed during an otherwise-clean `passed` run caps the run at `warning`. When ON it ENFORCES; off \u21D2 `note_contradiction:would_cap` / `report_issue_contradiction:would_cap` diags and every verdict byte-identical. Distinct from Layer B (TERMINAL_ERROR_FLOOR, a model terminal-screen read). Ships default-ON (the trap eval's warning-cap signature only greens with both floors live).",designDoc:"docs/plans/2026-07-23-terminal-error-verdict-honesty-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception (not graduated from an off default) \u2014 registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED. Deterministic (~zero marginal LLM cost \u2014 scans the already-collected stepResults notes + grounding observations). Pure logic in packages/engine-core/src/noteContradictionFloor.ts; applied at RunnerRuntime run_complete AFTER all fail gates so it only ever touches a still-passed step. Runner lane only. Layer A of the terminal-error wave; TERMINAL_ERROR_FLOOR is Layer B."},TERMINAL_ERROR_FLOOR:{key:"TERMINAL_ERROR_FLOOR",envVars:["AGENTIQA_TERMINAL_ERROR_FLOOR","AGENTIQA_EXPERIMENT_TERMINAL_ERROR_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Terminal-error verdict-honesty Layer B \u2014 one unconditional terminal-screen model read per plan run (run_27825c90). At RunnerRuntime run_complete (LAST, after every fail gate) the terminal capture plus the plan's step texts are sent through the existing `deps.blindReader` seam, asked whether an app error/failure state is visible that no plan step asserts. The terminal frame is selected DELIBERATELY from the in-memory `_screenshots` ledger (NOT R2 \u2014 works in the anonymous eval lane where imageStorage is null): the LAST full-frame capture (crops and post-upload shots are skipped; each push site is kind-tagged), abstaining when none exists or when it predates the last browser action (stale). Licensing is SEMANTIC (the reader sees the step texts, so it handles negation like `verify NO error is shown`). An unlicensed visible error \u21D2 cap the run at `warning` by demoting the highest-index PASSED step (via capRunToWarning \u2014 never a skipped/failed step; when a sibling floor already capped the terminal step, the quote is appended, not double-capped) and quote the error text in the step note + run summary. Reader unavailable / no full-frame / stale frame / non-answer / licensed error \u21D2 abstain no-op (never a new false-fail). ONE-DIRECTIONAL (only caps a still-passed step; the binary run status never flips \u2014 `warning` is the step-level/derived aggregate). When ON it ENFORCES; off \u21D2 `terminal_error:would_cap` shadow, no cap. This is the ONLY layer that fires when the model never transcribes the banner into any note (the incident shape). Distinct from Layer A (NOTE_CONTRADICTION_FLOOR, deterministic note scan). Ships default-ON.",designDoc:"docs/plans/2026-07-23-terminal-error-verdict-honesty-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception \u2014 registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED. Cost \u2248 one cheap Flash vision call per plan run (the cost-isolated blindReader model, same as BLIND_DOUBLE_READ). Detection (the read) runs whenever a reader + final capture are available so the switch shadows (`terminal_error:would_cap`) when off; a later cost-driven change could guard the call on the flag. Pure prompt/interpretation in packages/engine-core/src/terminalErrorFloor.ts. Runner lane only. Layer B of the terminal-error wave; NOTE_CONTRADICTION_FLOOR is Layer A + the report_issue fold."},BLIND_DOUBLE_READ:{key:"BLIND_DOUBLE_READ",envVars:["AGENTIQA_BLIND_DOUBLE_READ","AGENTIQA_EXPERIMENT_BLIND_DOUBLE_READ"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"When on, run_complete independently re-reads the persisted evidence screenshot for each pinned criterion that survived substantiation as passed (a blind LLM read that never sees the expected value) and flips the pass to failed when the observed value does not match the pin; abstains (no-op) on missing image / R2 read failure / reader non-answer / batch timeout. Off makes zero extra LLM calls and leaves every verdict unchanged.",designDoc:"docs/plans/2026-07-15-blind-double-read-design.md",status:"active",added:"2026-07-15",notes:"Default OFF in code; forced ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_BLIND_DOUBLE_READ=1) \u2014 the exact GROUNDED_EXPECTATIONS precedent. Prod enablement is a later explicit flip after nightly baselines. Runner lane only (RunnerRuntime run_complete).",graduation:{status:"gated",gate:"HARDENED 2026-07-21: BDR must actually FIRE (reads>0) and FLIP on runner/blind-read-conflation-trap \u2014 not merely avoid errors. BLOCKED on the evidence-resolution gap: on the conflation trap BDR abstained missing_image (resolveEvidenceMessage found no hasScreenshot+planStepIndex message \u2014 the model graded from the inline tool-result snapshot, which is never persisted as a screenshot message) and the seeded false-pass shipped (qa-exhaustive 29861680933). Fix = guarantee a planStepIndex-stamped verify screenshot (STEP_MARKER_FOLD stamping path is the natural vehicle \u2014 same root as the run-detail evidence-fidelity gap) or broaden resolveEvidenceMessage fallback. Plus: no new false-FAIL class on nightly runner baselines (MET as of 07-21; abstains acceptable). tp_00b325d5 confirm-path re-verified 07-21 (2 reads/2 confirms/0 flips).",evidence:"runner/blind-read-{parroting,conflation}-trap eval verdicts (conflation must flip) + blind_double_read diag events + nightly runner baselines",owner:"steering (Alex)",review:"2026-07-28"}},NEVER_GRADED_RETRY:{key:"NEVER_GRADED_RETRY",envVars:["AGENTIQA_NEVER_GRADED_RETRY","AGENTIQA_EXPERIMENT_NEVER_GRADED_RETRY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'When on (and a criterionRegrader is wired at engine boot), run_complete re-asks the grader ONCE for a STRICT pinned required criterion that NO stepResults entry graded (genuine model-omission \u2014 absent from the FIX 2 cross-entry union) before Amendment 5a synthesizes its "never graded \u2192 unconfirmed \u2192 fail". The returned grade is fed through the SAME substantiatePinnedCriterion gate, so only a re-grade that independently CITES the pinned value rescues the pin to passed; a returned FAIL, an unsubstantiated pass, or an abstain (no image / read failure / non-answer / error / batch timeout) leaves the "never graded" fail byte-identical. Cap ONE retry per pin, no loops. Off makes zero extra LLM calls and leaves every verdict unchanged.',designDoc:"docs/plans/2026-07-27-never-graded-retry-design.md",status:"active",added:"2026-07-27",notes:"Default OFF in code; force ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_NEVER_GRADED_RETRY=1) \u2014 the BLIND_DOUBLE_READ / GROUNDED_EXPECTATIONS shadow-first precedent. Prod enablement is a later explicit flip after a benchmark + staging soak. Runner lane only (RunnerRuntime run_complete, buildRunnerDeps.getCriterionRegrader \u2014 the SAME cost-isolated Flash model as blindReader; child Runners on the web-coordinator lane do not receive it yet, mirroring blindReader's own coordinator-forward gap). COMPOSES with (does not regress) PR #1884 FIX 2: the retry fires ONLY on pins genuinely absent from the cross-entry union FIX 2 computes, i.e. exactly the omission FIX 2 deliberately left as a fail. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add NEVER_GRADED_RETRY to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/RunnerRuntime.ts (neverGradedRetryEnabled \u2192 runNeverGradedRetries). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.neverGradedRetry.test.ts.",graduation:{status:"gated",gate:"FIRST SLICE = build + unit (this PR): shadow behind the default-OFF flag, byte-identical when off, fail-closed-safe (retry never manufactures a pass; a genuinely-ungraded-after-retry pin still fails). GRADUATION (later, separate slices) needs: (1) a kind-agnostic graduation benchmark (e2e/benchmark/, the ABSENCE_AWARE_VERIFY #1857 precedent) showing the Lio-s2 omission false-FAIL class is rescued to PASS with 0 new false-PASS and 0 regressions on the runner corpus, adversarially proven able to say NO-GO; (2) a staging shadow/force-ON soak measuring re-grade fire rate + rescue vs abstain vs still-fail; (3) parity when BLIND_DOUBLE_READ is also on; (4) gate-review sign-off (Alex).",evidence:"never_graded_retry:{start,rescue,abstain,still_fail} diag events + the graduation benchmark verdict + a staging soak on re-grade outcomes",owner:"steering (Alex)",review:"2026-08-03"}},EVIDENCE_FIDELITY:{key:"EVIDENCE_FIDELITY",envVars:["AGENTIQA_EVIDENCE_FIDELITY","AGENTIQA_EXPERIMENT_EVIDENCE_FIDELITY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"P0 of the evidence-fidelity ('honest pictures') design: makes full_page_screenshot honest. When on, BasePlaywrightService.fullPageScreenshot climbs a capture ladder (document_full \u2192 cdp_full \u2192 scroll_stitch \u2192 viewport_degraded) so an inner-overflow layout (asklio line-items, where the document is viewport-height but the scrollable content lives in an inner overflow:auto container) is captured at its true extent instead of a silent viewport crop; the ONLY non-full path stamps EnvState.captureMode 'viewport_degraded' and emits the full_page_capture:degraded marker \u2014 never a silent lie. Off is byte-identical to today EXCEPT the geometry measurement + a shadow degradation marker still run (detect-only) so staging can measure the lie's live frequency before the capture behavior flips. EnvState.captureMode is set in BOTH states.",designDoc:"docs/plans/2026-07-22-verify-evidence-fidelity-design.md",status:"active",added:"2026-07-22",notes:"Default OFF in code; force ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_EVIDENCE_FIDELITY=1) \u2014 the GROUNDED_EXPECTATIONS / BLIND_DOUBLE_READ precedent. Prod flip is a later explicit step after nightly baselines + a shadow soak on the degradation marker. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add EVIDENCE_FIDELITY to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: (P0) packages/engine-core/src/BasePlaywrightService.ts fullPageScreenshot \u2192 the honest capture ladder; (P1) packages/engine-core/src/RunnerRuntime.ts \u2192 per settled static-verify batch, capture ONE canonical honest full_page_screenshot, derive planStepIndex-stamped per-criterion crops (region resolved off the graded node; uncropped fallback), and persist a StepEvidenceRef on each TestPlanV2StepResult/CriterionResult at run_complete. Flag OFF is byte-identical to today EXCEPT the P0 shadow degradation marker: no canonical capture, no refs. P1 supersedes the run-detail findStepEvidenceIndex heuristic on runs that carry refs (legacy no-ref runs fall back). P2 (flip BLIND_DOUBLE_READ on the planStepIndex-stamped evidence P1 now produces) is the remaining follow-up gated on this.",graduation:{status:"gated",gate:"P0/P1 reproduced-RED evals green with the flag ON (runner-fullpage-honesty capture-mode/height/marker facts; degraded-abstain unit; P1 wrong-region + stamping-integrity) AND a staging shadow soak on the full_page_capture:degraded marker showing the expected live frequency with NO capture regression on batch.verify-never-blind",evidence:"full_page_capture:degraded diag events (staging shadow soak) + the engine-core capture-honesty integration test + the captureFidelity unit suite + the batch.verify-never-blind regression",owner:"steering (Alex)",review:"2026-07-29"}},PER_ACTION_BILLED_STEPS:{key:"PER_ACTION_BILLED_STEPS",envVars:["AGENTIQA_PER_ACTION_BILLED_STEPS","AGENTIQA_EXPERIMENT_PER_ACTION_BILLED_STEPS"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Decouples the billed step count from the LLM-iteration count (W1 of the batched-actions design, Decision 6). When on, the main-loop agent_step llm_usage event carries an additive billedUnits integer = executed browser actions + verify captures this turn (a marker-only signal_step turn earns 0); ingest sums it into run_billing.step_count. Off omits the field entirely, so ingest bills one step per agent_step event \u2014 byte-identical behavior AND billing to pre-change. The only intended billing delta when on (today, one-action-per-turn) is that marker-only iterations bill 0 instead of 1; a batched turn executing k actions will bill k (W3).",designDoc:"docs/plans/2026-07-18-batched-actions-design.md",status:"active",added:"2026-07-18",notes:"GRADUATED 2026-07-21 (default on): staging run_billing parity check over the force-ON window (since 07-18) held exactly \u2014 116/116 flag-ON runs with step_count == executed actions + verify captures, 99/99 marker-only iterations billed 0; billing.batched-steps-parity unit lane green. Billing substrate for the batched-actions family (W1). Read site: packages/engine-core/src/billedUnits.ts (perActionBilledStepsEnabled). Remove the staging orchestrator env var once this reaches staging."},STEP_MARKER_FOLD:{key:"STEP_MARKER_FOLD",envVars:["AGENTIQA_STEP_MARKER_FOLD","AGENTIQA_EXPERIMENT_STEP_MARKER_FOLD"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Phase 1 of the batched-actions design (Decision 3): when on, the RunnerRuntime run-mode prompt instructs the model to emit the signal_step boundary marker TOGETHER with the signaled step's FIRST action in the SAME turn \u2014 but ONLY for setup/action steps; VERIFY steps keep the separate marker turn so evidence is never captured blind. This collapses the ~18.7% of runner iterations that are marker-only today. HARD COUPLING: inert unless PER_ACTION_BILLED_STEPS is ALSO enabled \u2014 a folded turn under iteration-billing would bill 1 where marker+action should bill 2, breaking billing parity. The code guard (stepMarkerFold.ts::stepMarkerFoldEnabled = STEP_MARKER_FOLD && PER_ACTION_BILLED_STEPS) makes the fold prompt byte-identical to pre-change whenever PER_ACTION_BILLED_STEPS is off, so this flag alone changes nothing. No engine dispatch change: the multi-call loop already runs signal_step before the folded action in order (both in one generation the model saw the same screen), and billedUnits (W1) already counts marker+action as 1 billed unit.",designDoc:"docs/plans/2026-07-18-batched-actions-design.md",status:"active",added:"2026-07-18",notes:"Default OFF in code. Prompt-only change (no engine dispatch or verify-flow change). Read site: packages/engine-core/src/stepMarkerFold.ts (stepMarkerFoldEnabled), consumed in RunnerRuntime.buildRunnerPrompt run-mode signal_step cadence directive. The AND-coupling with PER_ACTION_BILLED_STEPS lives in code, not just here: flipping STEP_MARKER_FOLD=1 while PER_ACTION_BILLED_STEPS stays off is a no-op.",graduation:{status:"gated",gate:"Default-off soak on staging, then a staging flip (with PER_ACTION_BILLED_STEPS on) proves per-step verdict counts identical to OFF and marker-only iterations drop from ~18.7% to <7% (batch.step-attribution-preserved)",evidence:"batch.step-attribution-preserved unit lane + staging marker-only-iteration % soak measurement",owner:"steering (Alex)",review:"2026-07-25"}},WARNING_CRITERION_BIND:{key:"WARNING_CRITERION_BIND",envVars:["AGENTIQA_WARNING_CRITERION_BIND","AGENTIQA_EXPERIMENT_WARNING_CRITERION_BIND"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"run_complete grade<->criterion binding strips the platform-appended \" (warning only)\" render suffix from the model-echoed check text before the exact-text match, so a failing warning-only (strict:false) criterion binds by text (matchedByText=true) and keeps its own strict:false flag instead of being forced strict:true by the ordinal fallback and hard-failing the run; off restores the raw exact-text compare (a warning-only criterion the model echoed with the suffix escalates to a hard fail). Also the master gate for C1 honoring (2026-07-28): when the model REPHRASED the check so no text tier binds, a FAILING grade may keep an EXPLICIT strict:false only under this switch and only under a STRUCTURAL gate (round 7): the plan step the grade was filed under contains NO strict-or-default criterion at all, i.e. every criterion OF THAT STEP is an EXPLICIT strict:false, so there is nothing WITHIN THE STEP a mis-bound failure could be laundered out of. A MISSING strict counts as strict-or-default (fail-closed). A second condition \u2014 no unbound grade of the entry is itself a failure or un-adjudicated (a benign PASSING surplus grade does not close the gate) \u2014 is retained as DEFENCE-IN-DEPTH and is NOT a containment condition: mutating it away is verdict-inert, because an unbound grade already takes strict:true and a failing strict grade already fails the step. Diag `residual_strict_honoring:structural` records reason text-bound or sole-warning-entry when honored, and names the blocker otherwise. NOTHING ABOUT THE GRADE TEXT IS MEASURED. Rounds 3-6 all tried to identify the grade lexically \u2014 a shared-token threshold, then a generic-UI stopword list to stop it over-firing, then the same token measure read purely comparatively \u2014 and every one failed verification in BOTH directions; the comparative form was broken by ONE added word (appending the warning slot own noun to a confirmed false-PASS rewrite flips it open, dropping a distinctive token from a legitimate rephrase flips it shut). A grader-authored sentence is an unclosed class, so a restatement of a strict criterion and a rephrase of a warning-only one are not separable by any function of the two strings; the structural question reads the PLAN, which is authored data and cannot be gamed by wording. HONEST SCOPE: the honoring now covers ONLY all-warning steps (the shape of the incident step itself), and the guarantee it buys is a WITHIN-THE-STEP one \u2014 the gate reads one step's criteria and says nothing about a grade the model filed under the wrong step. Two documented boundaries, neither closed here: (A) false-FAIL side \u2014 a legitimate failing rephrase of a warning-only criterion that sits BESIDE a strict sibling fails closed to strict:true, the same verdict origin/staging produces, an unclosed class rather than a regression; (B) false-PASS side, CROSS-STEP MISFILE \u2014 a failing grade about step N's strict criterion, filed by the model under an all-warning step M, is honored as a warning, so a run that pre-#1898 staging (6fa6cb4b9) FAILED can PASS. (B) is a real new-vs-staging false-PASS channel and is bounded: it needs a COMPOSITE model error (the misfile AND a wrong pass on the real criterion in its own step \u2014 a lone misfile still fails through step N), the misfiled failure stays visible as a step-level WARNING rather than being dropped, and no WORDING reaches it (a grade filed under its own strict-carrying step is refused as before). Pinned by RunnerRuntime.residualHonoring.falsePassProbes.test.ts. Full closure of BOTH boundaries needs AUTHORING-TIME criterion identity (a stable criterion id echoed by the grader), not grading-time text comparison. Off forces strict:true on every fallback-bound failing grade \u2014 byte-identical pre-C1.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-16"},CRITERION_BIND_RESIDUAL:{key:"CRITERION_BIND_RESIDUAL",envVars:["AGENTIQA_CRITERION_BIND_RESIDUAL","AGENTIQA_EXPERIMENT_CRITERION_BIND_RESIDUAL"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Order-independent run_complete grade<->criterion binding (`bindGradesToPlanSlots`): every grade that matches a criterion by TEXT claims its slot in a first pass, and only then do the still-unbound grades take the still-unclaimed criteria in relative order. The sequential binder it replaces let an EARLIER rephrased grade's ordinal fallback steal the slot a LATER grade matched by exact text, so the same two grades hard-failed or warned depending purely on the order the model listed them (verified: criteria [address strict, title strict:false] + a rephrased failing title grade listed first booked that failure onto the STRICT address slot). With no text bindings the residual pass IS the old absolute ordinal (the round-6 reshuffle shape is byte-identical), and a SURPLUS grade beyond the criteria count still binds to nothing \u2192 fail-closed strict:true. A residual binding never licenses an explicit strict:false on its own: a FAILING residual grade keeps the criterion's strict:false only if the plan step it was filed under carries NO strict-or-default criterion at all (round 7 structural gate \u2014 see WARNING_CRITERION_BIND; a verdict-inert defence-in-depth guard additionally refuses an entry holding an unidentified FAILING or un-adjudicated grade). That single question covers every WITHIN-THE-STEP laundering shape the earlier lexical screens chased, because a step with a strict criterion to launder into is exactly a step where honoring is refused; no grade text is read. It does NOT cover a grade the model filed under the WRONG step \u2014 the documented cross-step boundary (B) on WARNING_CRITERION_BIND. This switch is NOT a containment lever for any of those shapes and never was (verified 2026-07-28: with CRITERION_BIND_RESIDUAL=0 a synonym restatement still false-PASSed on round-4 code); it only chooses HOW grades bind to slots. Containment comes from the honoring gate itself, which contains the class on the default path. Off restores the slot-stealing sequential binder; WARNING_CRITERION_BIND=0 overrides both with origin/staging's raw-exact-then-ordinal bind and turns the honoring off entirely.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-28"},CRITERIA_CONTAINMENT:{key:"CRITERIA_CONTAINMENT",envVars:["AGENTIQA_CRITERIA_CONTAINMENT","AGENTIQA_EXPERIMENT_CRITERIA_CONTAINMENT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Closed-world containment on run_complete: a step\'s verdict is decided ONLY by criteria the PLAN authored. A graded criterion result that binds to NO authored slot of its step (the grading model invented it) is still persisted \u2014 marked `unauthored: true` for forensics \u2014 but `deriveStepStatusFromCriteria` skips it, so a fabricated strict failure can no longer decide a step. Live prod-shaped defect (canary tp_vrgate_offer_upload_retry step 13, ~2/9 replicates): the step authors exactly 2 criteria (Description "Montage und Einweisung", Unit "St\xFCck"), both graded PASS with correct grounding, and the model additionally graded a THIRD criterion \u2014 `Order line 2 Quantity is "St\xFCck"`, strict:true, observed "1" \u2014 that exists in neither the plan nor the DB; that invented failure hard-failed the run. Detection ALWAYS runs (shadow-first): with the flag OFF every verdict is byte-identical and the engine only logs `criteria_containment:would_exclude` {stepIndex, criterionText, strict, observed, wouldFlipStep}; ON it excludes and logs `criteria_containment:excluded` with the same payload. `wouldFlipStep` IS the graduation evidence \u2014 it is true only where the exclusion actually moves the step status. TWO DELIBERATE NARROWINGS keep this rescue-polarity gate from opening a false-PASS channel: (1) it fires only on a step that AUTHORED \u22651 criterion \u2014 grades filed under a criteria-less action/setup step are the cross-step MISFILE class, where today\'s fail-closed treatment of the unbound grade is the only adjudication that failure gets; and (2) only when EVERY authored criterion of that entry received a grade, so an unbound grade can never be excluded while an authored slot went unadjudicated (it would then plausibly BE that slot\'s grade under a heavy rephrase). Identification reuses the ONE authoritative binder \u2014 `bindGradesToPlanSlots` per-entry output (text tiers incl. the platform\'s " (warning only)" rewrite, then residual positional) \u2014 never a new text comparison: measured over 76 persisted corpus runs, 58 of 60 text-unbound results were exactly that legal rewrite, so a text-equality containment rule would be ~97% false positives. A THIRD narrowing closes the DUPLICATE-READ false-PASS channel (review round 2026-07-29): the binder claims slots EXCLUSIVELY, so a SECOND grade of the SAME authored criterion binds to nothing and unguarded containment would discard it \u2014 and when the two reads contradict ([passed:true, then passed:false observed "\u20AC35.00"] for one authored total) the discarded one is the FAILING one, passing the step on a record whose "unauthored" criterionText is byte-identical to the authored check. Before excluding, `findDuplicateReadCriterionIdx` re-runs the binder\'s own text tiers over ALL authored criteria with the claimed set IGNORED; a match means duplicate READ, containment REFUSES to exclude, the grade keeps its flag-OFF effect (the step can still fail \u2014 the correct polarity for a contradicting observation), and the engine logs `criteria_containment:duplicate_read` {stepIndex, criterionIndex, criterionText, passed, wouldHaveExcluded} in BOTH flag states. RESIDUAL: identification is a TEXT relation, so a REPHRASED contradicting second read ("Der Gesamtbetrag lautet \u2026") matches no tier and is still excluded under the flag \u2014 the shadow soak\'s would_exclude population must be reviewed for that shape before graduation. Gate half (detector, no verdict effect): `criteria_over_grading` in e2e/scripts/verdict-replay-gate.mjs, PR #1934.',designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-29",notes:"Default OFF in code; detection runs in shadow always \u2014 the PIN_PAGE_GROUNDING / TYPED_ATOM_FLOOR shadow-first precedent, applied here because the polarity is RESCUE (removes a fail), which per docs/VERDICT-GATES.md carries the higher burden. Rides on the binder flags: with WARNING_CRITERION_BIND=0 or CRITERION_BIND_RESIDUAL=0 the binder is the sequential one, which leaves grades unbound in shapes that are NOT surplus \u2014 narrowing (2) is what keeps containment inert there rather than excluding a legitimately-graded criterion. Runner lane only (RunnerRuntime run_complete). Scope is step-status derivation: the rescue-eligibility gates that read `criteriaResults.every(passed)` (absence oracle, VERIFY_REOBSERVE_WITHHOLD, verify-conflict reconcile) still see the full persisted array, so a fabricated failing result can still BLOCK a rescue \u2014 the fail-closed direction, left deliberately.",graduation:{status:"gated",gate:"Staging/canary shadow soak shows `criteria_containment:would_exclude` with `wouldFlipStep: true` reproducing the tp_vrgate_offer_upload_retry step-13 fabrication class AND zero would_exclude events on steps whose authored criteria were all legitimately graded (no exclusion of a real verdict), plus a clean verdict-replay gate run with the #1934 `criteria_over_grading` detector agreeing on the same steps. MANDATORY before graduation: the soak's would_exclude population must be reviewed grade-by-grade for the REPHRASED-DUPLICATE shape (a paraphrased second read of an authored criterion, which the text tiers cannot distinguish from a fabrication and which the duplicate-read guard therefore does NOT catch); any such event is a false-PASS candidate and blocks the flip until it is either closed or explicitly waived.",evidence:"engine `criteria_containment:would_exclude` / `:excluded` / `:duplicate_read` diag events + the RunnerRuntime.criteriaContainment unit suite (claim verify.containment.authored-criteria-only) + the #1934 replay-gate `criteria_over_grading` violations on the persisted corpus",owner:"steering (Alex)",review:"2026-08-12"}},PLAN_OBEDIENCE:{key:"PLAN_OBEDIENCE",envVars:["AGENTIQA_PLAN_OBEDIENCE","AGENTIQA_EXPERIMENT_PLAN_OBEDIENCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Enforces the active plan step: rejects off-plan label clicks, records deviations, and lets run_complete fail on them; off makes the pre-check, deviation recording, and verdict gate all inert (pre-#1294 behavior).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-07"},LOOP_VISION_ESCALATION:{key:"LOOP_VISION_ESCALATION",envVars:["AGENTIQA_LOOP_VISION_ESCALATION","AGENTIQA_EXPERIMENT_LOOP_VISION_ESCALATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Master gate (Runner/Explorer lanes) for consulting the vision supervisor once before an ambiguous screenshot-blind force-block terminates the run; off keeps the deterministic hard-block.",designDoc:"docs/plans/2026-07-07-loop-detection-vision-supervisor-design.md",status:"active",added:"2026-07-07"},LOOP_VISION_DIFFERENTIAL:{key:"LOOP_VISION_DIFFERENTIAL",envVars:["AGENTIQA_LOOP_VISION_DIFFERENTIAL","AGENTIQA_EXPERIMENT_LOOP_VISION_DIFFERENTIAL"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Phase-2 differential-grant refinement of loop-vision escalation: grants 2..K need a concrete task-unit delta and the per-step ceiling rises to 12; off reverts to Phase-1 (absolute judgment, 4-grant ceiling).",designDoc:"docs/plans/2026-07-09-loop-vision-differential-extension-design.md",status:"active",added:"2026-07-09"},CANVAS_PIXEL_PROGRESS:{key:"CANVAS_PIXEL_PROGRESS",envVars:["AGENTIQA_CANVAS_PIXEL_PROGRESS","AGENTIQA_EXPERIMENT_CANVAS_PIXEL_PROGRESS"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Canvas-aware loop progress: on a canvas-dominant screen (a <canvas> covers >=40% of the viewport) the LoopDetector novel_screen milestone is driven by a coarse screenshot pixel-diff hash (own NOVEL_SCREEN_BUDGET) instead of the static DOM/a11y hash, and the loop-vision differential delta gate accepts a qualitative delta_evidence string when countable task units are unavailable. Off drops both so a canvas build behaves exactly as before (structural breaker climbs on the static DOM hash, delta gate stays countable-only).",designDoc:"docs/plans/2026-07-14-canvas-chat-failure-class-design.md",status:"active",added:"2026-07-14"},LOOP_URL_NOVELTY_REARM:{key:"LOOP_URL_NOVELTY_REARM",envVars:["AGENTIQA_LOOP_URL_NOVELTY_REARM","AGENTIQA_EXPERIMENT_LOOP_URL_NOVELTY_REARM"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Re-arms the structural loop breaker in the chat/explorer (assistant_v2) lane. URL-ONLY (narrow-safe): only the novel-URL seen-set, its NOVEL_URL_BUDGET=40/turn budget, and actionsSinceProgress become TURN-scoped (resetForNewStep no longer wipes them), so a recycled URL revisited across many declared steps stops re-counting as novel and actionsSinceProgress climbs to the 30-action structural threshold. The novel-REF and novel-SCREEN budgets stay PER-DECLARED-STEP in both states \u2014 turn-scoping them was reverted because it starved a legit long single-stable-URL SPA turn producing genuinely-new screen content each action (force-block ~action 53). A genuinely-new URL each step still resets (multi-page wizards unaffected); a wander that also mints novel screens escapes this deterministic re-arm and the run backstop is the net. Off restores the per-step reset (recycled URLs re-count as novel forever, unbudgeted novel_url) \u2014 today's prod behavior. Runner (test_run) lane never opts in.",designDoc:"docs/plans/2026-07-20-loop-safety-rearm-and-backstop-design.md",status:"active",added:"2026-07-20"},RUN_PROGRESS_BACKSTOP:{key:"RUN_PROGRESS_BACKSTOP",envVars:["AGENTIQA_RUN_PROGRESS_BACKSTOP","AGENTIQA_EXPERIMENT_RUN_PROGRESS_BACKSTOP"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Judge-gated run backstop in the chat/explorer (assistant_v2) runLoop: a wall-clock (12 min, primary), iteration (200), and cumulative prompt+completion billed-token (6M) ceiling \u2014 all well above p99 legit chat turns and below the 300-iteration explorer child cap. At a ceiling breach the loop-vision progress judge (the same fail-closed SupervisorService judge the loop breaker uses, temp-0 / thinkingBudget-0) is consulted ONCE with a goal-anchored progress question, rather than blind-terminating: "progressing" grants a BOUNDED extension (each ceiling raised by one window) up to a hard cap of RUN_BACKSTOP_MAX_EXTENSIONS=2 (worst case ~36 min), after which the run terminates regardless of the judge; "wandering" terminates with a judge-confirmed "not getting closer to the objective" message; any no-signal case (no judge wired in this lane, judge error / timeout / unparseable) fails CLOSED to a terminate with a neutral "hit the safety limit" message. Ends with blockKind=backstop / endKind=run_backstop, NOT loop_block, so it is not counted toward the session structural-loop cap. No interactive ask and no cross-turn state (the escalate\u2192ask_user ladder was removed; the judge consult is synchronous and re-derived per breach). Off removes all three ceilings (only bound remains iteration<=maxIterations=300, ~2.5h). Never a crash \u2014 the emit path fails open while the judge fails closed. Runner (test_run) lane never opts in.',designDoc:"docs/plans/2026-07-20-loop-safety-rearm-and-backstop-design.md",status:"active",added:"2026-07-20"},CLICK_AT_INTERACTIVE_DESCEND:{key:"CLICK_AT_INTERACTIVE_DESCEND",envVars:["AGENTIQA_CLICK_AT_INTERACTIVE_DESCEND","AGENTIQA_EXPERIMENT_CLICK_AT_INTERACTIVE_DESCEND"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"A coordinate click_at/double_click_at whose point resolves to a NON-interactive element descends to an interactive descendant within 16px and clicks it via locator, plus a no-effect advisory on a zero-mutation same-URL click; off restores the raw mouse.click(x,y) with no advisory.",designDoc:"docs/plans/2026-07-11-click-at-interactive-descend-design.md",status:"active",added:"2026-07-11"},LOOP_BLOCK_ATTRIBUTION:{key:"LOOP_BLOCK_ATTRIBUTION",envVars:["AGENTIQA_LOOP_BLOCK_ATTRIBUTION","AGENTIQA_EXPERIMENT_LOOP_BLOCK_ATTRIBUTION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:`Evidence-gated loop-block finding attribution: when a force-block's dominant repeated click target is a non-interactive element or a no-op self-anchor, suppress the false "Page appears stuck" auto-issue instead of filing it. Off restores the old unconditional filing (subject only to the AG-6107/AG-6490 gates).`,designDoc:"docs/plans/2026-07-11-loop-block-finding-attribution-design.md",status:"active",added:"2026-07-11"},CLICK_AFFORDANCE_CAPTURE:{key:"CLICK_AFFORDANCE_CAPTURE",envVars:["AGENTIQA_CLICK_AFFORDANCE_CAPTURE","AGENTIQA_EXPERIMENT_CLICK_AFFORDANCE_CAPTURE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Phase-2 of loop-block attribution: captures click-handler affordance evidence onto clickTarget (page-context inline/React/Vue signals + a CDP addEventListener probe on the rare non-interactive branch) so a dominant non-interactive target with a real-but-dead handler files a 'Custom control appears unresponsive' issue instead of being suppressed agent-side. Off \u21D2 no affordance field emitted \u21D2 the custom-control classifier branch can never fire (falls back to the #1477 status quo); it does NOT re-enable filing on a bare non-interactive target.",designDoc:"docs/plans/2026-07-11-custom-control-unresponsive-detection-design.md",status:"active",added:"2026-07-11"},CLICK_EFFECT_SIGNAL:{key:"CLICK_EFFECT_SIGNAL",envVars:["AGENTIQA_CLICK_EFFECT_SIGNAL","AGENTIQA_EXPERIMENT_CLICK_EFFECT_SIGNAL"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Post-click effect signal on EVERY click path (coordinate, retargeted, ref and label \u2014 click_at and double_click_at), SHADOW-FIRST. After the click the engine waits up to a 500ms settle window for the DomObserver to record any DOM/text/attribute mutation (returning the instant one lands), then compares the URL and the auto-accepted-dialog tally. Any movement \u21D2 an effect was observed. No movement \u21D2 the click STILL reports SUCCESS (a click that legitimately changes nothing must never become an error) and the feature's only output is agent STEER. THREE STATES, not two: no env (default) = SHADOW \u2014 detection runs and emits the click_effect:would_signal diag, but no advisory, no effectObserved metadata and no prompt-byte change reach the model; =1 = ENFORCE \u2014 the hedged re-observe advisory rides the successful tool result, effectObserved lands on the ToolCallResult side channel, the wait_for_element "Do NOT retry" coaching softens to its effect-aware wording and the runner prompt gains the re-observe-after-corrective-action line, with a click_effect:signaled diag; =0 = FULLY OFF \u2014 not even the probe runs, so there is zero added latency and click results plus every prompt byte are identical to pre-change behavior. Targets the 2026-07-29 vrgate false-FAIL (run_b72f5099-cee2-4063-b109-1961c55c9898), where a click_at on a rendered React button ~1.3s after a Next.js client navigation reported success while the onClick never fired (painted but not yet hydrated), the agent trusted the success, and the plan FAILED for a defect that did not exist. EXECUTOR-SIDE ONLY: it changes no verdict path, writes no step/criterion/run status, and adds no gate \u2014 it changes what the AGENT is told, and the agent still grades. Fail-safe by construction: an in-page probe that cannot run (CSP, cross-origin frame, document destroyed mid-navigation) yields NO verdict rather than a false "no effect"; navigation/dialog evidence is evaluated BEFORE the mutation counters so the one case where the probe reliably dies is the case the URL alone already proves; canvas-dominant surfaces and native property-only controls (checkbox/radio/select/text input \u2014 where a spurious "re-perform once" would TOGGLE the control back) are advisory-suppressed; and the pre-existing #1476 dead-coordinate peek keeps its exact timing and semantics. Canvas surfaces additionally skip the PROBE (not just the advisory) once a capture has classified the page as canvas-dominant, so a whiteboard/design flow never pays the settle window per click for a verdict that is suppressed on arrival; those clicks are counted as click_effect:probe_skipped.`,designDoc:"packages/engine-core/src/clickEffectSignal.ts",status:"active",added:"2026-07-29",notes:"Default OFF (shadow). Detection runs in shadow always unless explicitly =0 \u2014 the PIN_PAGE_GROUNDING / INTERACTION_CLEARS_PRESENCE_ORACLE shadow-first precedent \u2014 because a shadow that skipped the settle wait would measure a DIFFERENT detector than the one enforcement ships, and its numbers would not predict the ON behavior. The one deliberate non-identity in shadow is therefore TIMING, not tool-result bytes: a click that has mutated nothing yet pays up to 500ms of settle before the state capture that follows it (an effective click returns on the first in-page read and pays one evaluate round-trip). Stated plainly because it is a real, if small, behavior delta in the DEFAULT state \u2014 the post-click screenshot/snapshot of a no-effect click is taken up to 500ms later than before, which is more settled, not less faithful. AGENTIQA_CLICK_EFFECT_SIGNAL=0 removes even that and restores exact timing parity. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add CLICK_EFFECT_SIGNAL to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: packages/engine-core/src/BasePlaywrightService.ts (probeClickEffect / resolveClickEffect on clickAt, clickByRef, clickByLabel), packages/engine-core/src/waitToolCoaching.ts (waitNotFoundError picks the coaching variant), packages/engine-core/src/tools/browserTools.ts (getFailureHandlingPrompt), packages/engine-core/src/RunnerRuntime.ts (buildRunnerPrompt re-observe line); pure decision logic in packages/engine-core/src/clickEffectSignal.ts. Acceptance tests: clickEffectSignal.test.ts (pure verdict matrix incl. every suppression and the unknown-probe degrade), BasePlaywrightService.clickEffectSignal.test.ts (per-path wiring + shadow/enforce/off + the canvas-memo skip + degraded-note preservation on the ref path), clickEffectPromptParity.test.ts (flag-OFF prompt BYTE-parity across all four prompt surfaces). The 500ms settle cost is bounded on canvas-dominant surfaces by the SessionState.lastCaptureCanvasDominant memo: captureState records canvasDominant on every capture and probeClickEffect returns null (emitting click_effect:probe_skipped, reason canvas-memo) while it is set, because the canvas verdict was suppressed anyway.",graduation:{status:"gated",gate:'Staging shadow soak on click_effect:would_signal establishes (a) the no-effect rate per click path, (b) that the fires are dominated by genuinely ineffective clicks rather than by the known effect-free-but-legitimate classes, and (c) that no page class fires it continuously. FOUR NAMED REQUIREMENTS, all of which must be answered before the flag moves past shadow. (1) BLOCKER \u2014 THE NON-IDEMPOTENT SUBMIT. `<button>` and `<a>` are deliberately NOT in the property-only suppression set, so a form submit whose only feedback is a server round-trip (no spinner, no optimistic DOM write) reads as no-effect and, under enforce, receives the "re-perform the action ONCE" advisory. That directly contradicts the failure-handling prompt already shipped in browserTools.getFailureHandlingPrompt, which names "status: ok with url unchanged and no visible DOM change" as a SIGN OF AN IN-FLIGHT WRITE and instructs "do NOT re-click ... Re-clicking the same button while a write is in flight is a no-op for the user and burns retry budget" \u2014 and on a non-idempotent endpoint a second submit is not merely wasted, it can double-charge, double-book or double-post. The soak must show ZERO enforce-mode advisories on non-idempotent submits (classify fires by targetTag/targetRole plus the accessible name against a submit-shaped vocabulary, and cross-check each against pendingRequests at the moment of the fire), OR enforce must first gain a submit-shaped suppression (e.g. withhold the advisory whenever a same-origin request was in flight at probe time, or whenever the target is a submit-shaped control) \u2014 either outcome, and NEITHER may be waived. (2) IFRAME BLIND SPOT. Every counter read (peek / waitForMutation / flush) goes through page.evaluate, which runs in the MAIN frame only, and a top-document MutationObserver does not cross an iframe boundary \u2014 so a click whose whole effect renders inside an embedded frame (payment element, third-party booking/chat widget, embedded editor preview) reads as no-effect however well it worked. There is no target shape to suppress on, so iframe-hosted effects are a KNOWN-LEGITIMATE fire class the soak must be able to account for and subtract, exactly like property-only controls, downloads, clipboard and focus-only clicks; it is enumerated in the clickEffectSignal.ts header for the same reason. (3) SHADOW IS NOT INERT \u2014 READ THE SOAK ACCORDINGLY. The probe delays the post-click captureState by up to the full 500ms settle window on any click that has mutated nothing yet, INCLUDING in the default shadow state. Captured screenshots/snapshots on those clicks are therefore of a MORE SETTLED page than pre-change, so a shadow-vs-baseline comparison that shows different captured content on no-effect clicks is expected and is not evidence of a detector defect; only the =0 state is timing-identical to pre-change. (4) HYDRATION EMPIRICAL CRITERION. The soak must answer "what would run_b72f5099-cee2-4063-b109-1961c55c9898 have produced?" \u2014 i.e. for clicks landing inside a post-navigation hydration window, what fraction show mutationCount > 0 or attrCount > 0 (some other script mutated the page, so the detector stays SILENT and would not have rescued the incident) versus both counters at 0 (the detector fires and the advisory would have reached the agent). Both counters are already in the click_effect payload, so the query is: filter click_effect:would_signal to fires within ~2s of a navigation, then bucket on (mutationCount > 0 || attrCount > 0). A silent-dominated result means this feature does not fix its own motivating incident and enforcement is not justified on that basis. Enforcement additionally needs an inversion showing the advisory does not induce a harmful second click on a toggle.',evidence:"staging click_effect:would_signal diag events (rate + clickPath/suppressReason/targetTag/targetRole breakdown, plus the mutationCount/attrCount split inside the post-navigation hydration window and the submit-shaped-target cross-check against in-flight same-origin requests) + click_effect:probe_skipped counts for the canvas-memo skips + the engine-core clickEffectSignal / BasePlaywrightService.clickEffectSignal / clickEffectPromptParity unit suites",owner:"steering (Alex)",review:"2026-08-08"}},REVISION_CRITERIA_CARRYOVER:{key:"REVISION_CRITERIA_CARRYOVER",envVars:["AGENTIQA_REVISION_CRITERIA_CARRYOVER","AGENTIQA_EXPERIMENT_REVISION_CRITERIA_CARRYOVER"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Backstop that carries prior-draft criteria forward when a plan revision strips ALL criteria across ALL steps; off lets a total criteria-strip through.",designDoc:"packages/engine-core/src/revisionCriteriaCarryOver.ts",status:"active",added:"2026-07-07"},CREDENTIAL_GUARD:{key:"CREDENTIAL_GUARD",envVars:["AGENTIQA_CREDENTIAL_GUARD","AGENTIQA_EXPERIMENT_CREDENTIAL_GUARD"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Credential-fabrication guard: injects the login-prohibition prompt wording and fires the false-premise report_issue gate; off omits both (pre-feature behavior).",designDoc:"packages/engine-core/src/testingEmailPolicy.ts",status:"active",added:"2026-07-06"},CREDENTIAL_BINDING:{key:"CREDENTIAL_BINDING",envVars:["AGENTIQA_CREDENTIAL_BINDING","AGENTIQA_EXPERIMENT_CREDENTIAL_BINDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Runner deterministic credential-step binding (v1.1): when a plan step unambiguously references exactly one non-generic stored credential AND the model's own type_project_credential_at pick was a generic field word, the mismatched credentialName is overridden to the referenced one (credential_binding_override diag) \u2014 a non-generic pick is never rewritten; and when a credential fill is followed within a 3-action adjacency window by a 401/403 while the step-referenced credential is untried and was not the last one filled, ONE report_issue/exploration_blocked per run is deflected toward that specific credential. A genuine 401 of the step's own credential, an unrelated stray 401, or a step naming no credential all proceed to the report. Off restores the model's free credential pick and no auth-failure nudge (pre-feature behavior).",designDoc:"docs/plans/2026-07-19-ag7727-run-fidelity-fixes-design.md",status:"active",added:"2026-07-19"},EMAIL_CODE_PROVENANCE:{key:"EMAIL_CODE_PROVENANCE",envVars:["AGENTIQA_EMAIL_CODE_PROVENANCE","AGENTIQA_EXPERIMENT_EMAIL_CODE_PROVENANCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verification-code write provenance gate: a write the model TYPED as fieldPurpose='verification_code' is refused unless its value equals a whole code token in an email actually fetched via check_email this run (subject + text + html-as-text, token-equality not raw substring). Off passes the write through ungrounded (pre-feature behavior), so a guessed or fabricated code can mutate the page into a false success state.",designDoc:"packages/engine-core/src/emailVerificationGate.ts",status:"active",added:"2026-07-12"},VERBATIM_INPUT_PIN:{key:"VERBATIM_INPUT_PIN",envVars:["AGENTIQA_VERBATIM_INPUT_PIN","AGENTIQA_EXPERIMENT_VERBATIM_INPUT_PIN"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verbatim user-input payload pinning: at test-plan generation a text-entry step's model-emitted verbatimInput is kept ONLY when it provenance-matches user-supplied text (deterministic type-time capture + user chat/attachment corpus, normalized full match), and RunnerRuntime types that pinned string verbatim (slot wins over prose). Off disables both the capture/attach and the runner consumption (pre-feature behavior: payloads paraphrased into step prose and re-improvised at replay).",designDoc:"docs/plans/2026-07-13-verbatim-input-payload-design.md",status:"active",added:"2026-07-13"},VERIFY_ORACLE_FIDELITY:{key:"VERIFY_ORACLE_FIDELITY",envVars:["AGENTIQA_VERIFY_ORACLE_FIDELITY","AGENTIQA_EXPERIMENT_VERIFY_ORACLE_FIDELITY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verify-oracle fidelity (verbatim-input Phase 2): a deterministic post-generation pass at both producer gates (CoordinatorRuntime.handleSaveTestPlan + the Explorer draft path), after pinVerbatimInputSteps, that restores user-authored acceptance criteria the LLM summarized away. It captures verification check-bullets under a high-precision verification-heading line (r2: heading ends with ':' and its core matches a verification PHRASE whole, not merely contains a strong token; each bullet captured unless action-imperative-shaped) plus a bounded single-paragraph anti-false-pass lookback, tests each against the persisted verify-side content (verify-step texts + criteria checks + expectedValue pins) by literal-atom containment (quoted spans + numerals/ranges with EN/RU 0\u201320 spelled-form equivalence; atom-free \u2192 normalized-token containment \u2265 0.6), and APPENDS a verify step for every uncovered item carrying the user's bullet verbatim as both the step text AND a compiled criterion ({check, strict:true}, r2/F7 \u2014 so the appended step passes validateDraftPlanSteps and never hits the runner's criteria-less synthesis path). Append-only (never edits/deletes an existing step), fail-open (any error \u2192 save unchanged). Off restores pure LLM-compliance generation (summarized oracles persist as-is). Emits an oracle_fidelity diag {bullets, covered, appended, lookbackCaptured, looseBullets, disabled} regardless of flag state (looseBullets = diag-only recall telemetry, never appends).",designDoc:"docs/plans/2026-07-15-verify-oracle-fidelity-design.md",status:"active",added:"2026-07-15"},TYPE_NEWLINE_SAFE:{key:"TYPE_NEWLINE_SAFE",envVars:["AGENTIQA_TYPE_NEWLINE_SAFE","AGENTIQA_EXPERIMENT_TYPE_NEWLINE_SAFE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Multi-line text typing: embedded newlines are entered as Shift+Enter soft line breaks (never a raw Enter keypress) so a multi-line prompt does not premature-submit an Enter-to-send composer (e.g. Miro/Slack chat sidekicks). Off restores the raw keyboard.type(text) behavior where each "\\n" fires an Enter keypress. Applies to all four text-typing paths (typeTextAt / typeByRef / typeByLabel / setFocusedInputValue fallback); pressEnter still appends one trailing Enter regardless.',designDoc:"packages/engine-core/src/typeMultiline.ts",status:"active",added:"2026-07-13"},CANVAS_TYPE_GROUNDING:{key:"CANVAS_TYPE_GROUNDING",envVars:["AGENTIQA_CANVAS_TYPE_GROUNDING","AGENTIQA_EXPERIMENT_CANVAS_TYPE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Canvas typed-text grounding: after a coordinate type_text_at whose focus is NOT a text-editable DOM element on a canvas-dominant screen, verify the text actually landed \u2014 a11y/DOM positive check on the reused post-action snapshot, else a pixel route gated by an ambient-animation pre-check (two pre-type full-frame captures a settle apart). If the board is proven static (pre-captures byte-identical) a full-frame before/after compare decides: any change = landed (off-clip renders included), byte-identical = confident negative \u2192 explicit failure (metadata.error + canvasTypeVerification='text_not_found') with a switch-strategy hint. If the board is self-animating (pre-captures differ) the outcome is uncertain_animated: behavior byte-identical to flag-off, recorded via a canvas_type_verify diag event. Every uncertain outcome is fail-open (behavior unchanged); \u22643 verification screenshots per qualifying action. Off restores the pre-feature bare-success canvas type (no verification screenshots, no a11y check).",designDoc:"docs/plans/2026-07-14-canvas-chat-failure-class-design.md",status:"active",added:"2026-07-14"},RESULT_FIRST_DISCOVERY:{key:"RESULT_FIRST_DISCOVERY",envVars:["AGENTIQA_EXPERIMENT_RESULT_FIRST_DISCOVERY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"env-const-disabled",gates:'Result-first discovery (#373): auto-approve discovered scope and run high-risk areas immediately; off restores the "question-first" scope-approval checkpoint that waits.',designDoc:"packages/engine-core/src/resultFirstDiscovery.ts",status:"active",added:"2026-06-01",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_RESULT_FIRST_DISCOVERY (no bare AGENTIQA_ spelling). NOT migrated to killSwitchDisabled \u2014 that would add the bare spelling and change behavior. Also has a per-session config opt-out."},SCOPE_PROVENANCE:{key:"SCOPE_PROVENANCE",envVars:["AGENTIQA_EXPERIMENT_SCOPE_PROVENANCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"env-const-disabled",gates:"Scope-provenance-aware plan selection: user-enumerated medium/low areas still run in the first pass; off falls back to the legacy risk-only split.",designDoc:"packages/engine-core/src/resultFirstDiscovery.ts",status:"active",added:"2026-07-01",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_SCOPE_PROVENANCE. NOT migrated to killSwitch (would add a bare spelling)."},MEMORY_WRITEBACK:{key:"MEMORY_WRITEBACK",envVars:["AGENTIQA_EXPERIMENT_MEMORY_WRITEBACK"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"env-const-enabled",gates:"Verified-memory writeback: offers the save_verified_memory tool and activates the durable write path; off leaves writeback inert.",designDoc:"docs/plans/2026-07-04-verified-memory-writeback-design.md",status:"active",added:"2026-07-04",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_MEMORY_WRITEBACK. NOT migrated to killSwitchEnabled (would add a bare spelling). Also has a per-session config force-on for evals.",graduation:{status:"gated",gate:"Model-elicitation quality gate from the 2026-07-04 verified-memory-writeback design doc closes",evidence:"design-doc gate + eval force-on runs",owner:"steering (Alex)",review:"2026-08-01"}},FAST_START_PROMPT:{key:"FAST_START_PROMPT",envVars:["AGENTIQA_EXPERIMENT_FAST_START_PROMPT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"is-experiment-enabled",gates:"Explorer prompt variant: emits the fast-start initial prompt instead of the standard one.",designDoc:"packages/engine-core/src/ExplorerRuntime.ts",status:"active",added:"2026-06-01",notes:'Single spelling via isExperimentEnabled (exact "1"). NOT a killSwitch flag \u2014 no bare AGENTIQA_ spelling honored.',graduation:{status:"parked",gate:"No rollout intent; delete registry entry + code path if still unused by 2026-09-01"}},MINIMAL_INITIAL_CONTEXT:{key:"MINIMAL_INITIAL_CONTEXT",envVars:["AGENTIQA_EXPERIMENT_MINIMAL_INITIAL_CONTEXT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"is-experiment-enabled",gates:"Explorer context variant: sends a minimal initial context to the model instead of the full one.",designDoc:"packages/engine-core/src/ExplorerRuntime.ts",status:"active",added:"2026-06-01",notes:'Single spelling via isExperimentEnabled (exact "1"). NOT a killSwitch flag \u2014 no bare AGENTIQA_ spelling honored.',graduation:{status:"parked",gate:"No rollout intent; delete registry entry + code path if still unused by 2026-09-01"}},STEERING_VETO:{key:"STEERING_VETO",envVars:["AGENTIQA_STEERING_VETO"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!1,read:"env-direct",gates:"Supervisor steering veto: at a redirect, refuses the recent loop-set of action fingerprints for a bounded TTL/budget; off passes those calls through.",designDoc:"packages/engine-core/src/steeringVeto.ts",status:"active",added:"2026-06-01",notes:'Reads ONLY the bare AGENTIQA_STEERING_VETO (via direct process.env access, "!== 0"). It has NO AGENTIQA_EXPERIMENT_ spelling, so the orchestrator passthrough cannot flip it in a cloud pod (cloud-unreachable \u2014 known limitation). NOT migrated to killSwitchDisabled: that would add the EXPERIMENT_ spelling and change behavior/reachability.'},AUTH_DISABLE_EMAIL_VERIFICATION:{key:"AUTH_DISABLE_EMAIL_VERIFICATION",envVars:["AUTH_DISABLE_EMAIL_VERIFICATION"],polarity:"1-enables",defaultState:"off",surfaces:["web-next-node"],cloudForwarded:!1,read:"env-direct",gates:"On-prem escape hatch: disables signup email verification; IGNORED (fail-safe) on a hosted Vercel deploy where VERCEL/VERCEL_ENV is present.",designDoc:"apps/web-next/lib/auth-flags.ts",status:"active",added:"2026-06-01",notes:"Not AGENTIQA_-prefixed. Static process.env member access (edge-safe). Hosted-platform sentinel forces it off on Vercel.",graduation:{status:"permanent",gate:"On-prem operational escape hatch, not an experiment \u2014 never graduates; forced off on hosted Vercel"}},ORG_ENTITLEMENT_ENABLED:{key:"ORG_ENTITLEMENT_ENABLED",envVars:["ORG_ENTITLEMENT_ENABLED"],polarity:"0-disables",defaultState:"on",surfaces:["web-next-node"],cloudForwarded:!1,read:"env-direct",gates:'Company-plan org entitlement (O0+): when on, an active OrgMembership resolves the billing subject to the org and its plan wins over the personal plan in all entitlement gates; "0" forces the personal subject everywhere (org rows become inert).',designDoc:"docs/plans/2026-07-11-company-plan-access-control-design.md",status:"active",added:"2026-07-11",notes:"Not AGENTIQA_-prefixed. Static process.env member access via isOrgEntitlementEnabled() in apps/web-next/lib/billing-subject.ts (single read point). Dark by data until an Organization row exists \u2014 with zero orgs the flag has no observable effect."},EXTENSION_PROFILE_PERSISTENCE:{key:"EXTENSION_PROFILE_PERSISTENCE",envVars:[],polarity:"1-enables",defaultState:"on",surfaces:["desktop-main","desktop-renderer"],cloudForwarded:!1,read:"compile-const",gates:"Saves/restores a per-project Chrome profile (cookies/storage) across sessions so login can be skipped on replay; a false value skips profile persistence.",designDoc:"apps/desktop-next/src/renderer/featureFlags.ts",status:"active",added:"2026-06-01",notes:"Hardcoded TypeScript boolean (`= true`), no env var \u2014 a compile-time gate flipped by editing the const. Defined twice: apps/desktop-next/src/renderer/featureFlags.ts and apps/desktop-next/src/main/computerUse/DesktopPlaywrightService.ts (the main-process copy is the one actually consumed)."},TRANSIENT_ENV_RETRY:{key:"TRANSIENT_ENV_RETRY",envVars:["AGENTIQA_TRANSIENT_ENV_RETRY","AGENTIQA_EXPERIMENT_TRANSIENT_ENV_RETRY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Transient-environment retry-once policy (RunnerRuntime / test-plan runs only, v1 \u2014 never ExplorerRuntime/chat). Motivating incident: staging run run_9fff560a \u2014 the app's POST to its own API failed transiently (console: CORS block + AxiosError "Network Error"), the agent waited 2\xD730s, then filed report_issue and blocked after ONE attempt; later probing showed the API healthy. When on, a report_issue (or the ensuing exploration_blocked) whose failure is a DETERMINISTIC transient-environment stall \u2014 BOTH a stall/timeout symptom (a wait/wait_for_element in the evidence window, or explicit stall/network phrasing; never a content/assertion mismatch) AND an environment signature in the captured EventDigest (any failedRequests, a console/page error matching the network class \u2014 CORS / "Network Error" / AxiosError / net::ERR_ / "fetch failed" \u2014 or an explicit 5xx write) \u2014 is BOUNCED once with a structured instruction to repeat the triggering action and report only if it reproduces, tracked per step index. The second matching failure at the SAME step passes through and the runtime (not the model) stamps the issue evidence JSON with attempts:2, both attempt timestamps, both EventDigest snapshots, sets category='environment', and appends 'Reproduced on retry \u2014 2 attempts.' to the description. Bounds: exactly 1 retry per step, max 2 retried steps per run; a further environment stall after the budget is spent passes through with attempts:1 and the note 'Environment degraded \u2014 not retried (budget exhausted).'. A run-mode prompt nudge asks the agent to retry proactively; the deterministic gate is the backstop (never trust LLM compliance). Off \u21D2 every environment failure files immediately on the first attempt, byte-identical to pre-change behavior. Non-environment failures are never retried regardless of this flag.`,designDoc:"docs/plans/2026-07-23-transient-env-retry-once-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception (not graduated from an off default) \u2014 the policy is a strict reduction of a confirmed false-block class (one transient blip \u2192 a blocked run + a filed non-defect issue), so there is no pre-change OFF behavior to preserve. Registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED (the tripwire acknowledging the default-ON state deliberately). Deterministic classifier + state machine in packages/engine-core/src/transientEnvRetry.ts; the kill-switch read + wiring live at packages/engine-core/src/RunnerRuntime.ts handleReportIssue / handleBlocked. Runner lane only."},PREDICATE_BASIS_COMPILE:{key:"PREDICATE_BASIS_COMPILE",envVars:["AGENTIQA_PREDICATE_BASIS_COMPILE","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_COMPILE"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Trust-layer predicate basis \u2014 Slice B AUTOFORMALIZATION COMPILER (design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md). "Compile-don't-parse": at AUTHORING an LLM COMPILES a natural-language assertion into a typed Slice-A logical form (Predicate) over named observables \u2014 autoformalization (utterance \u2192 logical form \u2192 executor \u2192 denotation) \u2014 NOT a verdict. Slice A shipped the schema + generic deterministic executor; Slice B produces the forms the executor denotes. TASK-BLIND: the compiler compiles the assertion's MEANING (including any pinned expected value the assertion text itself carries) and never sees the observed screen or pass/fail \u2014 the firewall keeps the LLM out of the DECISION (Slice A's deterministic executor owns pass/fail). GRAMMAR-CONSTRAINED \u2192 MECHANICAL ABSTAIN: the model may only emit an in-grammar kind (count/delta/absence/modification/presence/typed) or the explicit not_groundable escape; compileToPredicate then STRICTLY validates the chosen kind's operands, so an inherently-subjective assertion ("the agent responds correctly", "looks clean") or an in-grammar kind with missing/invalid operands routes to a first-class ABSTAIN (AbstainNode) \u2014 NEVER a forced/invalid form. The grammar's expressiveness IS the verifiable/subjective boundary. v1 = structured output + strict schema validation + a groundability decision; full constrained decoding (PICARD) is a later refinement (TODO). GRADUATED default-ON 2026-07-27 (alongside PREDICATE_BASIS_VERIFY, which is the live consumer that routes a compiled form to a step result); the emergency kill-switch is retained and byte-identical WHEN FORCED OFF: the seam (runAssertionCompile / runRedundantCompile) short-circuits to \`disabled\` (ZERO model calls) when AGENTIQA_PREDICATE_BASIS_COMPILE=0 \u2014 and with COMPILE forced off but VERIFY on the compiler returns a disabled result \u2192 ABSTAIN (safe, never a manufactured verdict). Cost when on: one auxiliary structured-output call per compiled assertion (cost-isolated via emitAuxiliaryLlmUsage \u2014 not a billable step), thinkingBudget:0, hard-capped by a per-call timeout; fail-closed (error/empty/timeout/out-of-grammar \u2192 ABSTAIN).`,designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-26",notes:"GRADUATED 2026-07-27 (default ON) \u2014 the authoring-side ARc compiler that feeds the LIVE verify wiring (PREDICATE_BASIS_VERIFY, graduated in the same PR). Turn-on = BOTH flags ON: with VERIFY on, runPredicateBasisVerify calls runRedundantCompile, which rides THIS flag; on \u21D2 the compiler produces the logical forms the deterministic executor denotes. Slice B (authoring-side compiler) + Slice C (ARc redundant-compile: compile k\xD7 \u2192 ABSTAIN on disagreement/degeneration, attacking the factKind-wrong-kind gap) are the compile consumers of this flag. GRADUATION EVIDENCE: the flagship live-replay benchmark (PR #1879) returned GATE=GO \u2014 zero-regression on the prod Lio (semantic-reference) + Miro (canvas) corpora, the firewall intact (a groundable contradiction FAILS; nothing ungroundable is ever a hard PASS), the vision/canvas path abstains, and the #1876 DOM-reachability fix live-confirmed. TASK-BLIND / FIREWALL (unchanged): the compiler compiles the assertion's MEANING (never sees the observed screen nor pass/fail); Slice A's deterministic executor owns the decision. GRAMMAR-CONSTRAINED \u2192 MECHANICAL ABSTAIN: an inherently-subjective or out-of-grammar assertion routes to a first-class ABSTAIN (AbstainNode), never a forced/invalid form. Off (explicit AGENTIQA_PREDICATE_BASIS_COMPILE=0) is byte-identical to pre-graduation: runAssertionCompile / runRedundantCompile short-circuit to `disabled` with ZERO model calls, and with COMPILE off but VERIFY on the compiler returns a disabled result \u2192 ABSTAIN (safe, never a manufactured verdict) \u2014 the emergency kill-switch still works. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND PREDICATE_BASIS_COMPILE listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/predicateBasis/compile.ts (runAssertionCompile) + packages/engine-core/src/predicateBasis/redundantCompile.ts (runRedundantCompile). Cost when on: one auxiliary structured-output call per compiled assertion, cost-isolated via emitAuxiliaryLlmUsage (not a billable step), thinkingBudget:0, hard-capped, fail-closed (error/empty/timeout/out-of-grammar \u2192 ABSTAIN). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisCompile.test.ts + predicateBasisRedundantCompile.test.ts. Compile-correctness benchmark: e2e/benchmark/compileCorrectness.ts. Binds claims verify.predicate-basis-compile-correctness + verify.predicate-basis-redundant-compile. STAGING-FIRST: merging to staging makes this default-ON on the STAGING engine only; PROD stays OFF until a later staging\u2192main release carries it (a natural staged soak). PREDICATE_BASIS_CONSENSUS (Slice D vision-consensus) stays default-OFF \u2014 vision-consensus is safe ONLY as abstain, not turn-on-ready (the P2 dense-abstain finding)."},PREDICATE_BASIS_CONSENSUS:{key:"PREDICATE_BASIS_CONSENSUS",envVars:["AGENTIQA_PREDICATE_BASIS_CONSENSUS","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_CONSENSUS"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Trust-layer predicate basis \u2014 Slice D: (1) CONSENSUS EXTRACTION/RESOLUTION and (2) the SEMANTIC-TOLERANCE FALLBACK TIER (design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md \u2014 \xA7 three buckets bucket-2 canvas "task-blind extraction + deterministic comparison + consensus-or-abstain", \xA7 the @reference resolution consensus/abstain, \xA7 "Semantic as a fallback tier, not a peer primitive"; north star hard-part #1 "the extractor itself can be wrong: miscount a canvas, misread"). CONSENSUS: task-blindness removes confirmation bias but NOT perception error (the model genuinely miscounts a canvas / mis-resolves "the cart total"); the no-false-positive mitigation is N INDEPENDENT task-blind extractions must AGREE, else ABSTAIN \u2014 one mechanism serving BOTH the vision/canvas path AND the semantic-reference resolution risk. SEMANTIC-TOLERANCE: run the DETERMINISTIC executor FIRST; invoke the task-blind concept classifier ONLY when the deterministic comparison cannot decide (tolerance:semantic OR an inconclusive comparison) \u2014 confident semantic = Verified, ambiguous = Assessed (a lean + confidence, never a grounded badge, never a manufactured pass \u2014 the bucket-3 Assessed slot). SHADOW / behavior-neutral even when ON: NOT wired into any live RunnerRuntime verdict path \u2014 the two drivers are consumed only by the consensus benchmark + unit tests. Off \u21D2 ZERO extractor/classifier calls, byte-identical; Slice-A deterministic parity is UNAFFECTED (the semantic tier COMPOSES the untouched evaluate, only reached on an inconclusive result).',designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-26",notes:"Trust-layer predicate basis Slice D (consensus extraction/resolution + semantic-tolerance fallback tier). Default OFF; SHADOW / behavior-neutral even when ON \u2014 the two drivers produce would-be results and are wired into NO live verdict path (consumers: the consensus benchmark + unit tests). Read sites: packages/engine-core/src/predicateBasis/consensusExtract.ts (runConsensusExtraction \u2192 killSwitchEnabled('PREDICATE_BASIS_CONSENSUS'); zero extractor calls when off) + packages/engine-core/src/predicateBasis/semanticTolerance.ts (runSemanticTolerance \u2192 killSwitchEnabled('PREDICATE_BASIS_CONSENSUS'); zero classifier calls when off). CONSENSUS-EXTRACT: a PURE reducer (reduceNumericConsensus / reduceCategoricalConsensus \u2014 N observations \u2192 accept-on-agreement / ABSTAIN(extraction_disagreement) on numeric-spread-beyond-tolerance or different presence/text; fail-closed extraction_error when no usable sample) + a pure per-frame read (readObservable over count-of / presence-of / value-at) + the thin flag-gated driver over the EXISTING StateExtractor seam (reused, not re-implemented \u2014 N independent samples). SEMANTIC-TOLERANCE: a PURE reducer (resolveSemanticTier \u2014 deterministic-first; decided deterministic \u2192 Verified with no classifier call; inconclusive + eligible + injected classifier \u2192 semanticToSpectrum: confident match/contradiction \u2192 Verified, ambiguous \u2192 Assessed, abstain \u2192 the Inconclusive floor) + the flag-gated driver that COMPOSES the untouched Slice-A evaluate (Slice-A parity byte-identical by construction). Reuses the Slice-2 concept-classifier seam (ConceptClassifier / semanticToSpectrum / renderObservation from groundedStateUnified.ts). Deliberately NOT re-exported from predicateBasis/index.ts (imported directly). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisConsensus.test.ts (deterministic \u2014 injected observations for the consensus reducer; injected classifier RESULT for the semantic tier; flag-OFF zero-calls; fail-closed error\u2192abstain). Consensus benchmark: e2e/benchmark/consensusExtraction.ts (deterministic reducer/tier self-validation always runs; the live N-extraction + classifier measurement is PENDING until a keyed run \u2014 Slice-1/B/C precedent, no fabricated number). Binds claim verify.predicate-basis-consensus-extraction. Slice E (abstain-rate as a first-class COVERAGE metric on a real-assertion corpus) is BUILT: packages/engine-core/src/predicateBasis/coverage.ts (aggregateCoverage \u2014 a PURE reducer folding pipeline-routed assertion outcomes into the Verified/Assessed/Inconclusive distribution + abstain rate + abstain-origin/per-kind breakdown), wired into NO live verdict path (no new flag; the live measurement reuses THIS flag + PREDICATE_BASIS_COMPILE), claim verify.predicate-basis-coverage-abstain-rate, benchmark e2e/benchmark/coverage.ts (deterministic layers real; live full-pipeline number PENDING until keyed). This COMPLETES the predicate-basis v1 build; the remaining work is the KEYED phase (live LLM measurements) + the prod Miro+Lio final gate.",graduation:{status:"gated",gate:"Slice D is shadow / behavior-neutral (two drivers, wired into NO verdict path). Graduation gates on: (1) the consensus benchmark run WITH a model key showing consensus ABSTAINS on genuinely disagreeing/noisy N task-blind extractions and ACCEPTS on agreement (the miscount-a-canvas / mis-resolve-a-reference no-false-positive mechanism), plus a measured abstain-rate on the vision/canvas + semantic-reference corpus; (2) the semantic-tolerance tier measured deterministic-first (a deterministic-decidable case never consulting the classifier) with confident\u2192Verified / ambiguous\u2192Assessed; (3) the engine-core predicateBasisConsensus unit suite green. This is the DEFERRED consensus-extraction that gates ANY vision-path live graduation; the FINAL gate is the prod Miro (canvas) + Lio (semantic-reference) benchmark.",evidence:"e2e/benchmark/artifacts/benchmark-consensus-extraction.{json,md} (consensus abstain/accept + abstain-rate + semantic-tier bands; PENDING until a keyed run) + the engine-core predicateBasisConsensus unit suite + the claim verify.predicate-basis-consensus-extraction",owner:"steering (Alex)",review:"2026-09-05"}},PREDICATE_BASIS_VERIFY:{key:"PREDICATE_BASIS_VERIFY",envVars:["AGENTIQA_PREDICATE_BASIS_VERIFY","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_VERIFY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Trust-layer predicate basis \u2014 Slice F LIVE VERIFY WIRING (the FIRST non-shadow slice; design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md \xA7 three buckets; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md \xA7 the verdict spectrum). Slices A\u2013E built the basis as SHADOW machinery wired into NO verdict path; this is the first wiring that lets a compiled logical form FEED A STEP RESULT (the readiness step toward turn-on). When ON, a verify step's assertion routes through the basis: runRedundantCompile (ARc: compile k\xD7 \u2192 ABSTAIN on disagreement/degeneration) \u2192 classifyVerifyBucket \u2192 the deterministic executor / semantic-tolerance tier \u2192 a verdict in the SPECTRUM (Verified-PASS/FAIL | Assessed | Inconclusive) that feeds the step result. SCOPED to the SAFE paths \u2014 everything else ABSTAINS, never manufactures a verdict: DOM-groundable (deterministic executor over structured extraction) \u2192 Verified-PASS/FAIL LIVE (a grounded contradiction FAILS \u2014 the no-false-positive core); confident-semantic (semantic-tolerance, deterministic-first, task-blind classifier) \u2192 Verified, ambiguous \u2192 Assessed (non-blocking WARNING band, never a hard pass/fail); VISION/CANVAS (bucket 2) \u2192 ABSTAIN (Inconclusive/WARNING), NOT enforced \u2014 the mandatory dense-abstain guard from the P2 finding (consensus does NOT eliminate correlated-miscount false-confirms on dense canvases, so vision must NOT produce a live PASS/FAIL yet; a count tally is treated as vision-grounded \u2192 ABSTAIN unless the caller asserts domGrounded); not-groundable / compile-abstain / consensus-abstain \u2192 Inconclusive/Assessed, NEVER a manufactured pass. FIREWALL INVARIANT: a groundable contradiction MUST FAIL; nothing ungroundable is EVER a hard PASS \u2014 verifyStepAction encodes the DEFAULT consequence policy (only a Verified-FAIL gates; a Verified-PASS confirms but never manufactures/overrides a pass; Assessed is a non-blocking warning; Inconclusive leaves the existing verdict). GRADUATED default-ON 2026-07-27 (alongside PREDICATE_BASIS_COMPILE) after the flagship live-replay gate; the emergency kill-switch is retained and BYTE-IDENTICAL WHEN FORCED OFF (non-negotiable): explicit AGENTIQA_PREDICATE_BASIS_VERIFY=0 makes runPredicateBasisVerify short-circuit to disabled with ZERO compile/executor/classifier calls and the RunnerRuntime enforcement pass early-return before any effect. The compile itself rides PREDICATE_BASIS_COMPILE (also graduated), so full turn-on = both flags ON (with VERIFY on but COMPILE forced off the compiler returns a disabled result \u2192 ABSTAIN, safe). STAGING-FIRST: default-ON reaches the STAGING engine on merge; PROD stays OFF until a later staging\u2192main release carries it.",designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-27",notes:"GRADUATED 2026-07-27 (default ON) \u2014 Slice F LIVE verify wiring, the FIRST live trust-verdict on the predicate basis (turned on alongside PREDICATE_BASIS_COMPILE per Alex's explicit approval after the flagship live-replay gate). When on (and a predicateBasisCompiler is wired at engine boot \u2014 buildDeps.getPredicateBasisCompiler, present whenever a Google key is set), a verify step's assertion routes through the basis: runRedundantCompile (ARc, rides PREDICATE_BASIS_COMPILE) \u2192 classifyVerifyBucket \u2192 the deterministic executor / semantic-tolerance tier \u2192 a SPECTRUM verdict feeding the step result. SCOPED to the SAFE paths \u2014 everything else ABSTAINS, never manufactures a verdict: DOM-groundable \u2192 Verified-PASS/FAIL LIVE (a grounded contradiction FAILS \u2014 the no-false-positive core); confident-semantic \u2192 Verified, ambiguous \u2192 Assessed (non-blocking WARNING); VISION/CANVAS \u2192 ABSTAIN (Inconclusive), NOT enforced \u2014 the mandatory P2 dense-abstain guard (a count tally is vision-grounded \u2192 ABSTAIN unless the caller asserts domGrounded); not-groundable / compile-abstain \u2192 Inconclusive, NEVER a manufactured pass. FIREWALL INVARIANT (unchanged): only a Verified-FAIL gates; a Verified-PASS confirms but never manufactures/overrides a pass; Assessed warns; Inconclusive leaves the existing verdict. GRADUATION EVIDENCE: the flagship live-replay benchmark (PR #1879) returned GATE=GO \u2014 zero-regression on the prod Lio (semantic-reference) + Miro (canvas) corpora, the firewall intact, canvas-abstain intact, and the #1876 DOM-reachability fix live-confirmed; the engine-core predicateBasisVerifyWiring + RunnerRuntime.predicateBasisVerify unit suites are green (flag-OFF byte-identical parity, safe-path enforcement, vision-canvas ABSTAIN, the firewall). BYTE-IDENTICAL WHEN FORCED OFF (emergency kill-switch retained): explicit AGENTIQA_PREDICATE_BASIS_VERIFY=0 restores the pre-graduation behavior \u2014 runPredicateBasisVerify short-circuits to disabled with ZERO compile/executor/classifier calls and the RunnerRuntime enforcement pass early-returns before any effect. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND PREDICATE_BASIS_VERIFY listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: packages/engine-core/src/predicateBasis/verifyWiring.ts (runPredicateBasisVerify) + packages/engine-core/src/RunnerRuntime.ts (predicateBasisVerifyEnabled / the run_complete enforcement pass). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisVerifyWiring.test.ts + RunnerRuntime.predicateBasisVerify.test.ts. E2E proof: e2e/benchmark/predicateBasisVerify.ts. Standing live gate post-graduation: e2e/scenarios/22-verify/01-predicate-basis-dom-enforce.ts asserts the pbv-ON DOM-enforce + canvas-abstain behavior by DEFAULT now (default-ON engine) in the nightly qa-exhaustive path. Binds claim verify.predicate-basis-verify-wiring. STAGING-FIRST: merging to staging makes pbv default-ON on the STAGING engine ONLY (staging deploys from staging); PROD stays OFF until a later staging\u2192main release carries it \u2014 a natural staged soak. VISION-path live PASS/FAIL stays DEFERRED behind PREDICATE_BASIS_CONSENSUS (still default-OFF) regardless of this flag \u2014 vision-consensus is safe ONLY as abstain, not turn-on-ready (the P2 finding)."},ELEMENT_STATE_GROUNDING:{key:"ELEMENT_STATE_GROUNDING",envVars:["AGENTIQA_ELEMENT_STATE_GROUNDING","AGENTIQA_EXPERIMENT_ELEMENT_STATE_GROUNDING"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Trust-layer predicate basis \u2014 ELEMENT-STATE grounding (residual track P2, slice 1: BUILD + SHADOW; design docs/plans/2026-07-27-element-state-grounding-design.md). Closes a groundability gap in the DOM-verify path (routeDomVerify / domExtractionSource): the deterministic a11y-outline extraction grounds PRESENCE / ABSENCE / COUNT / MODIFICATION but STRIPS element STATE \u2014 a `- button "Submit" [disabled]` line\'s `[disabled]`, an `aria-checked` / `[selected]` / `[expanded]` marker, and an input\'s inline value \u2014 so an assertion like "the Submit button is enabled" is NOT DOM-groundable and falls through to flaky model-vision grading (the Lio submission s8 flake: a weak vision-only read of button-enabled that varied run-to-run). The a11y snapshot (Playwright _snapshotForAI) DETERMINISTICALLY carries this state; this track parses it into a new `state-of` observable + `element-state` predicate the Slice-A executor denotes over, so enabled/disabled/checked/selected/expanded/value assertions ground deterministically. FIREWALL PRESERVED: a state that is NOT resolvable from the a11y outline (target element not found, dimension not applicable to the role, mixed/unreadable value) ABSTAINS (Inconclusive) \u2014 never force-fails on unresolvable, never manufactures a pass; enforcement stays force-fail-only (only a grounded CONTRADICTION \u2192 would_fail gates). SLICE 1 = SHADOW / behavior-neutral even when ON: the machinery (extraction + NL parser + mapping + the flag-gated driver runElementStateGrounding) is wired into NO live RunnerRuntime verdict path \u2014 consumed only by unit tests (+ a later graduation benchmark). Off \u21D2 ZERO element-state extraction / parse / evaluate, byte-identical (the new observable/extraction runs only under this flag); the existing pbv DOM/count/absence/modification paths are UNTOUCHED. Graduation (benchmark + gate-review + Alex\'s default-on flip + live wiring) is a LATER slice, mirroring the pbv arc.',designDoc:"docs/plans/2026-07-27-element-state-grounding-design.md",status:"active",added:"2026-07-27",notes:"Residual track P2 (element-state grounding) slice 1 \u2014 BUILD + SHADOW behind a default-OFF killSwitch, mirroring the predicate-basis Slice A\u2013E / Slice-D CONSENSUS shadow precedent (pure machinery + flag-gated driver, wired into NO live verdict path). Read site: packages/engine-core/src/predicateBasis/elementState.ts (runElementStateGrounding \u2192 killSwitchEnabled('ELEMENT_STATE_GROUNDING'); zero element-state work when off). PURE machinery (also in elementState.ts, always safe to call, exercised in the unit suite): extractElementStatesFromAriaSnapshot (per-a11y-line state parse keyed on Playwright's exact role\u2192dimension applicability \u2014 kAriaDisabledRoles / kAriaCheckedRoles / kAriaSelectedRoles / kAriaExpandedRoles \u2014 so absence-of-marker on an applicable role reads as false, and a non-applicable role ABSTAINS rather than guessing), parseElementStateAssertion (deterministic NL \u2192 {ref, dimension, expected}; returns null when no state vocabulary is present so it is additive), elementStateQueryToLogicalForm (\u2192 the `element-state` node), and evaluateElementState (in executor.ts, the Slice-A generic executor's new case \u2014 resolves the target element in frames.after.elementStates, reads the dimension, denotes PASS on confirm / FAIL on a grounded contradiction / INCONCLUSIVE on any unresolvable \u2014 target absent, dimension N/A, mixed/ambiguous). GROUNDABLE STATES: enabled/disabled (fully both directions \u2014 the Lio s8 case), checked/unchecked, selected, expanded (PASS on [expanded] + FAIL on a collapsed-assertion contradiction; absence ABSTAINS \u2014 collapsed vs non-expandable is not distinguishable in the outline), and input value (normalized-equality; typed/locale-tolerant value comparison is a follow-up routing to compareTyped). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisElementState.test.ts (extraction, parser, mapping, executor firewall, flag-OFF zero-work / byte-identical, registry-presence freshness canary). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 GRADUATING = flip defaultState to 'on' AND add ELEMENT_STATE_GROUNDING to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire); slice 1 stays OFF.",graduation:{status:"gated",gate:"Slice 1 is BUILD + SHADOW (pure machinery + a flag-gated driver, wired into NO verdict path). Graduation gates on the LATER slice: (1) an element-state graduation-benchmark run showing enabled/disabled/checked/selected/expanded/value ground deterministically from the a11y outline (a grounded contradiction \u2192 would_fail FIXES the Lio-s8-class vision flake; an unresolvable state \u2192 ABSTAIN, no false-PASS / no false-FAIL) and adversarially proven able to say NO-GO; (2) wiring runElementStateGrounding into the RunnerRuntime run_complete enforcement pass (force-fail-only, alongside applyPredicateBasisVerify); (3) the engine-core predicateBasisElementState unit suite green + flag-OFF byte-identical; then Alex flips the default-on (and lists it in INTENTIONALLY_GRADUATED). Mirrors the pbv graduation arc (shadow \u2192 benchmark \u2192 gate-review \u2192 default-on).",evidence:"e2e/benchmark element-state corpus (grounded PASS/FAIL vs ABSTAIN; Lio-s8 vision flake fixed; PENDING until the graduation slice) + the engine-core predicateBasisElementState unit suite + the (later) claim verify.element-state-grounding",owner:"steering (Alex)",review:"2026-08-15"}},VERIFY_CONFLICT_RECONCILE_SNAPSHOT:{key:"VERIFY_CONFLICT_RECONCILE_SNAPSHOT",envVars:["AGENTIQA_VERIFY_CONFLICT_RECONCILE_SNAPSHOT","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_RECONCILE_SNAPSHOT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Verify-conflict DETERMINISTIC snapshot reconcile \u2014 M1 of the verify-oracle reconcile design (docs/plans/2026-07-28-verify-oracle-reconcile-design.md; GH #1907, root cause of #1813). WHAT IT DECIDES: at the SECOND verification-conflict escalation ONLY (the run_complete pass that would otherwise force-FAIL; the first bounce is untouched, and the bounce alone already resolves ~73% of oracle failures), the runtime takes ONE forced-full a11y snapshot for the whole run and re-checks each conflicted step's recorded wait literal (`_verifyOracleFailureDetails[step].literal`) against it with the SAME whole-token `pinPresentInPage` matcher, under the `waitLiteralHasSignificantTokens` significance floor. ZERO LLM calls \u2014 the model is not in the loop, so a lie about a genuinely broken wait fails constructively. THREE OUTCOMES: (a) literal significant AND present in the fresh snapshot \u2192 CLEARED: the oracle failure is removed from the ledger, the step's own already-passed criteria grades stand, the step passes, and the step is TAINTED via noteStepReopenedForReverify (the runtime consumed a re-observation it demanded, so predicate-basis-verify must not enforce over a basis it cannot attribute \u2014 the same invariant the bounce path carries); (b) literal significant and ABSENT from the fresh snapshot \u2192 GROUNDED NEGATIVE: the hard fail stands and the step is permanently INELIGIBLE for the VERIFY_CONFLICT_WITHHOLD warning band; (c) INAPPLICABLE \u2014 which is the only input VERIFY_CONFLICT_WITHHOLD (M2) ever sees \u2014 for no literal / insignificant literal / capture failed / budget already spent / the plan-derived `pin_page_grounding` oracle (excluded WHOLESALE \u2014 a plan-pin failure is a deterministic contradiction, not an absence of confirmation) / **any negation-or-absence marker on the step text or a criterion check** (`stepCarriesNegationOrAbsenceMarker`, reason `negation_marker`: a presence-clear is INVERTED for an assertion that the target is gone, and the absence lane's routing lexicon is narrow BY DESIGN, so this deliberately broader screen \u2014 not/no/none/without/missing/gone/empty/removed/deleted/closes/hidden/disappear*/vanish*/clear*/away/left-the-list/moves-to-trash/ceases-to/count-drops/zero-rows/fewer/struck-through/back-to-default/\u2026 plus a minimal DE/FR set, read over prose with only the target literal's OCCURRENCES removed (round-3: the earlier strip also deleted every \u22654-char TOKEN of the literal from the whole check, so a destination name like 'Deleted Items' silently disarmed the screen) \u2014 keeps every such step ineligible. HONEST LIMIT: this is a best-effort keyword screen over open-ended NL and completeness is unreachable; a phrasing it misses stays eligible and can be presence-cleared. The guarantee for absence assertions is the ABSENCE_AWARE_VERIFY lane, which decides with evidence rather than vocabulary) / **a literal that is not PLAN-GROUNDED whole-token with \u22652 tokens** (`waitLiteralGroundsSnapshotClear`, reason `literal_not_plan_grounded`: a CLEAR is only sound when the literal is the AUTHOR's expectation, read with the same `pinPresentInPage` matcher against the step text + criteria check/expectedValue \u2014 a model-invented literal that whole-token-matches unrelated chrome on another screen proves nothing, and a one-token literal is never distinctive enough even when the plan does contain it. KNOWN BOUNDARY, documented not fixed (round-3): this gate reads AUTHORSHIP, never PLACE \u2014 an AUTHORED literal that appears in unrelated chrome (a nav item, a help-sidebar link, the header of an Error 500 page) CLEARS exactly as it would in the region the step names; page-state and container binding are the next slice, and until then such clears are only visible in the `verify_conflict_reconcile:would_clear` census the graduation soak reads). Every inapplicable decision is logged per step as `verify_conflict_reconcile:inapplicable` with its reason. DETECTION ALWAYS RUNS (shadow): with the flag OFF the same decision is computed against the RETAINED full-snapshot corpus (`_fullSnapshotByStep`) \u2014 NO fresh capture, so OFF stays byte-identical including ZERO extra browser actions \u2014 and logged as `verify_conflict_reconcile:would_clear` / `:would_fail` with `basis:'retained_snapshot'` and `enforced:false`; ON logs the same events with `basis:'fresh_snapshot'` and `enforced:true`. Exactly ONE reconcile snapshot per run (guarded); a second escalation after the budget is spent decides INAPPLICABLE rather than re-enforcing off a stale page. NOT COVERED BY THIS FLAG (deferred slices, see the design \xA7 4): dropping `wait_for_element` from VERIFY_EVIDENCE_ACTIONS (own flag `VERIFY_EVIDENCE_REQUIRE_CAPTURE`, needs a shadow taint-rate measurement first), and still-running-vs-terminal recognition (a nested run still in flight at run end reads as a grounded negative and correctly stays red in this slice \u2014 the honest known gap). Runner lane only (RunnerRuntime run_complete).",designDoc:"docs/plans/2026-07-28-verify-oracle-reconcile-design.md",status:"active",added:"2026-07-28",notes:"M1 of the verify-oracle reconcile track (design docs/plans/2026-07-28-verify-oracle-reconcile-design.md), default OFF. Fixes the residual verify-conflict FALSE-FAIL that `canReconcileVerificationConflict` deliberately refuses: a PLAN-GROUNDED wait literal (repro run_5a6f0681 step 2, plan tp_vmlio_d1360115, literal 'QA Base \u2014 Draft Completion (do not modify)'; asess_1785247451027 step 1 is the same shape). That refusal is CORRECT as a static rule \u2014 a plan-grounded literal is a real must-pass presence oracle \u2014 so the fix is not to relax the rule but to consult the PAGE one more time: the element rendered late, and a fresh forced-full snapshot proves it. THREE FACTUAL CORRECTIONS to #1907 this design records (staging code, not the issue's reading): (a) evidence is NOT recorded on a timed-out oracle \u2014 the `_verifyEvidenceStepIndexes` add sits in the SUCCESS branch, so a timeout does not satisfy the evidence gate; (b) 'criteria are advisory' is too broad \u2014 `deriveStepStatusFromCriteria` does derive from grades; the real root is that the verify-conflict force-fail OVERRIDES already-passed criteria because `oracleConflictReason` never sees stepResults; (c) an existing valve (`canReconcileVerificationConflict`) already reconciles the non-plan-grounded case to a full PASS \u2014 the residual false-fail is exactly its plan-grounded refusal branch, not the whole mechanism. Read site: packages/engine-core/src/RunnerRuntime.ts (verifyConflictReconcileSnapshotEnabled \u2192 reconcileVerifyConflictsFromSnapshot, called from the second verification-conflict escalation in handleRunComplete). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts (B-R1 repro form + B-C1..B-C9 counter-probes + the flag-OFF parity / one-snapshot-per-run invariants). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 graduating means flipping defaultState to 'on' AND listing the key in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts.",graduation:{status:"gated",gate:"Graduation gates on the LIVE harness, not on units: Chin's ci-first-plan `tp_c0dcd706` run \xD710 against staging with the flag ON \u2014 baseline is 0/10, the target is \u22658/10 on the step-9 mode (post-login redirect), with the cleared-vs-would_fail split reported from the `verify_conflict_reconcile:*` diags. The step-17 mode (nested run still in flight at run end) is EXPECTED to stay red in this slice; if it turns green the significance threshold is leaky and that is a bug to investigate, NOT evidence to graduate on. Plus: a staging shadow soak of `verify_conflict_reconcile:would_clear` / `:would_fail` sizing the cleared rate and confirming no would_clear fires on a genuinely-absent target, and the engine-core verifyConflictReconcile unit suite green with flag-OFF parity over the full runner corpus.",evidence:"staging `verify_conflict_reconcile:would_clear` / `:would_fail` diag events (cleared rate, basis, per-step literals) + the tp_c0dcd706 \xD710 harness pass rate per failure mode + packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts",owner:"steering (Alex)",review:"2026-08-15"}},VERIFY_CONFLICT_WITHHOLD:{key:"VERIFY_CONFLICT_WITHHOLD",envVars:["AGENTIQA_VERIFY_CONFLICT_WITHHOLD","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_WITHHOLD"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Verify-conflict RESIDUAL WARNING policy \u2014 M2 of the verify-oracle reconcile design (docs/plans/2026-07-28-verify-oracle-reconcile-design.md). Strictly downstream of VERIFY_CONFLICT_RECONCILE_SNAPSHOT (M1): it sees ONLY the conflicts M1 could not decide (no captured literal, an insignificant literal, a failed capture, or the reconcile budget already spent) and NEVER a step M1 read as a GROUNDED NEGATIVE \u2014 a target the runtime looked for and did not find always stays a hard FAIL. When ON, such a residual conflict is soft-withheld to a step-level WARNING ('could not be independently confirmed on this run') instead of force-FAILing the run. ALL SEVEN conditions must hold or the existing force-fail stands: (1) the unresolved oracle is a wait-style action, never the plan-derived `pin_page_grounding` oracle; (2) every graded criterion on the step passed with a non-empty substantiation note (the same bar `canReconcileVerificationConflict` uses) AND the step result is still 'passed' with no other deterministic negative on it (no reobserve-withhold, no upstream floor having already flipped it) ; (3) \u22651 STRICT criterion carries an engine-corroborated concrete value \u2014 its `observed` (or, absent that, its pinned `expectedValue`) is whole-token present in the retained page corpus via `pinPresentInPage`; (4) the wait literal's significant tokens are corroborated by the `observed`/note corpus of some passed criterion (this is what links 'what we waited for' to 'what was confirmed', and it is why a short/frequent literal like 'ok' or '3' can never withhold \u2014 the significance floor rejects it); (5) the step is NOT absence-intent (`checkTextAssertsAbsence` \u2014 that shape belongs to ABSENCE_AWARE_VERIFY, which owns its own confirm/abstain ladder) and, since that lexicon is narrow by design, ALSO carries no negation-or-absence marker at all under the broader M1 screen (`stepCarriesNegationOrAbsenceMarker`, reason `negation_marker`) \u2014 a warning there would withdraw a force-fail the engine has no evidence to withdraw; (6) \u2014 folded into (2) \u2014 no other deterministic negative on the step; (7) the step was OBSERVED AGAIN after the conflict bounce (a runtime capture-sequence watermark taken at the bounce; a verbatim resubmit of pre-bounce grades never withholds). DETECTION ALWAYS RUNS (shadow): `verify_conflict_withhold:would_withhold` (and a reasoned `:inapplicable`) is logged with `enforced:` reflecting the flag, so OFF is byte-identical with telemetry only. KNOWN, DELIBERATE SIDE EFFECTS when enforcing (asserted in CI, not accidents): withdrawing the forced conflict fail leaves `terminationReason='completed'`, which makes the run BILLABLE; and no 'Potential Issue Detected' card is synthesized for a withheld step \u2014 one fewer false issue. Runner lane only (RunnerRuntime run_complete).",designDoc:"docs/plans/2026-07-28-verify-oracle-reconcile-design.md",status:"active",added:"2026-07-28",notes:"M2 of the verify-oracle reconcile track, default OFF and inert unless M1's decision for the step is INAPPLICABLE. The honesty floor is the point: a withheld step is a WARNING \u2014 never a pass, never a fail \u2014 so this flag can only ever move a run out of a false RED into an honest AMBER, and it can never manufacture a green. The grounded-negative exclusion is the hard invariant (design \xA7 3): M1 having actually read the page and not found the target is exactly the evidence that the step is genuinely broken, so those never enter this path. Measured coverage of conditions (2)-(4) on the design's corpus is 32/33 steps; the one exception (staging ck-cli_test 2026-07-28 step 17, a genuinely failed criterion) correctly stays red. Read site: packages/engine-core/src/RunnerRuntime.ts (verifyConflictWithholdEnabled \u2192 classifyVerifyConflictWithhold, applied at the second verification-conflict escalation after the M1 pass). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts (B-C2/B-C3/B-C5/B-C6 keep the reds red; B-C8 asserts the billing invariant deliberately). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 graduating means flipping defaultState to 'on' AND listing the key in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts.",graduation:{status:"gated",gate:"Graduation gates on M1 graduating FIRST (M2 is only meaningful over M1's inapplicable residue), then on a staging shadow soak of `verify_conflict_withhold:would_withhold` showing (a) no would_withhold on a step any deterministic oracle reads as a negative, (b) the withheld population is dominated by genuinely unconfirmable captures rather than real failures \u2014 sampled and hand-adjudicated \u2014 and (c) an explicit product decision on the billing consequence (withdrawing the forced fail makes the run terminate 'completed' and therefore BILLABLE) plus the warning-display semantics review (a withheld step must read as a neutral 'could not confirm', not as an alarm-amber defect).",evidence:"staging `verify_conflict_withhold:would_withhold` / `:inapplicable` diag events (rate + hand-adjudicated sample of the withheld population) + the tp_c0dcd706 harness residue after M1 + packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts",owner:"steering (Alex)",review:"2026-08-15"}}},dre=Object.values(sh);var kL=["run","run the test","run the test plan","run test plan"];function Hv(t){let e=t.toLowerCase().trim();return kL.includes(e)}function Wv(t){return t.replace(/\s+/g," ").trim()}function bs(t){let e=t.indexOf(":");return e===-1?{provider:"google",modelName:t}:{provider:t.slice(0,e),modelName:t.slice(e+1)}}var Hn="google:gemini-3-flash-preview",zv="google:gemini-3-flash-preview";var Ec=[{name:"Green",hex:"#4ade80"},{name:"Blue",hex:"#60a5fa"},{name:"Purple",hex:"#a78bfa"},{name:"Amber",hex:"#fbbf24"},{name:"Red",hex:"#f87171"},{name:"Cyan",hex:"#22d3ee"},{name:"Pink",hex:"#f472b6"},{name:"Slate",hex:"#94a3b8"}];function ve(t){return`${t}_${crypto.randomUUID()}`}function So(t,e){return typeof process>"u"||!process.env?!1:process.env[`AGENTIQA_${t}`]===e||process.env[`AGENTIQA_EXPERIMENT_${t}`]===e}function Kv(t){return sh[t]?.defaultState}function Le(t){return So(t,"0")?!0:So(t,"1")?!1:Kv(t)==="off"}function Ge(t){return So(t,"1")?!0:So(t,"0")?!1:Kv(t)==="on"}function Yv(t){return So(t,"0")}function Eo(){return Ge("VALUE_GROUNDING_ENFORCE")}function ih(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}function Jv(t){switch(t){case"message":return"msg";case"tool_call":return"tool";case"llm_usage":return"llm";case"supervisor_verdict":return"sv";case"agent_lifecycle":return"lc";case"user_action":return"ua";case"session_start":case"session_end":case"turn_start":case"turn_end":return"sl";case"log":case"pageSnapshot.structuralStrip":return"diag";default:return"evt"}}var Hi=class{apiUrl;fetchFn;sessions=new Map;queues=new Map;timer=null;isUploading=!1;inFlight=new Set;eventIds=new WeakMap;directUploadFailedSessions=new Set;BATCH_SIZE=25;FLUSH_INTERVAL=6e4;MAX_PAYLOAD_BYTES=35e5;auth;constructor(e,n,r=globalThis.fetch.bind(globalThis)){this.apiUrl=e,this.fetchFn=r,this.auth=typeof n=="string"?{kind:"bearer",token:n}:n,this.timer=setInterval(()=>this.flushAll(),this.FLUSH_INTERVAL)}buildAuthHeaders(e,n=!1){let r={"Content-Type":"application/json"};if(this.auth.kind==="bearer")return r.Authorization=`Bearer ${this.auth.token}`,r;if(n&&this.auth.bearerFallback)return r.Authorization=`Bearer ${this.auth.bearerFallback}`,r;r["x-admin-service-key"]=this.auth.serviceKey;let s=e?.userId??this.auth.fallbackUserId;return s&&(r["x-user-id"]=s),r}hasBearerFallback(){return this.auth.kind==="service"&&!!this.auth.bearerFallback}emit(e){let n=e.sessionId;if(this.eventIds.has(e)||this.eventIds.set(e,ih(Jv(e.kind))),e.kind==="session_start"&&e.sessionMeta&&this.sessions.set(n,{...e.sessionMeta,desktopSessionId:n,status:"active",startedAt:new Date(e.ts).toISOString()}),e.kind==="session_end"){let s=this.sessions.get(n);s&&(s.status=e.status??"completed",s.endedAt=new Date(e.ts).toISOString())}if(this.isProviderLocationUnsupportedEvent(e)){let s=this.sessions.get(n);s&&(s.terminalErrorClass="provider_location_unsupported")}!n&&!this.sessions.has("")&&this.sessions.set("",{desktopSessionId:"global",projectId:"_global",status:"active",startedAt:new Date(e.ts).toISOString()});let r=this.queues.get(n);r||(r=[],this.queues.set(n,r)),r.push(e),r.length>=this.BATCH_SIZE&&this.flushSession(n),e.kind==="session_end"&&this.flushSession(n)}async flush(){await this.flushAll()}destroy(){this.timer&&(clearInterval(this.timer),this.timer=null),this.flushAll()}async flushAll(){let e=[];for(let r of this.queues.keys()){let s=this.flushSession(r);s&&e.push(s)}let n=Array.from(this.inFlight);await Promise.allSettled([...e,...n])}flushSession(e){let n=this.sessions.get(e),r=this.queues.get(e);if(!n||!r||r.length===0)return null;let s=r.splice(0),i=this.uploadWithRetry(n,s).catch(a=>{let o=s.filter(l=>l.kind==="session_end");if(o.length>0){let l=this.queues.get(n.desktopSessionId);l&&l.unshift(...o)}console.error(`[RemoteAnalyticsSink] Failed to upload ${s.length} events:`,a.message)});return this.inFlight.add(i),i.finally(()=>{this.inFlight.delete(i)}),i}async uploadWithRetry(e,n,r=3){let s;for(let i=1;i<=r;i++)try{await this.upload(e,n);return}catch(a){s=a;let o=a?.status;if(o!==void 0&&o>=400&&o<500)throw a;if(i<r){let l=Math.min(1e3*Math.pow(3,i-1),9e3);await new Promise(c=>setTimeout(c,l))}}throw s}async upload(e,n){let r=await this.mapEvents(e.desktopSessionId,n);await this.postIngest(e,r)}async postIngest(e,n,r=!1){if(n.length===0)return;let s=JSON.stringify({session:{...e},events:n});if(s.length>this.MAX_PAYLOAD_BYTES&&n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}let i;try{i=await this.fetchFn(`${this.apiUrl}/api/analytics/ingest`,{method:"POST",headers:this.buildAuthHeaders(e,r),body:s})}catch(l){throw new Error(`analytics upload network error: ${l?.message??String(l)}`)}if(i.ok)return;if((i.status===401||i.status===403)&&!r&&this.hasBearerFallback()){console.warn(`[RemoteAnalyticsSink] service-key auth got ${i.status} for session ${e.desktopSessionId} \u2014 retrying with bearer fallback (AG-169)`),await this.postIngest(e,n,!0);return}if(i.status===413){if(n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}console.warn(`[RemoteAnalyticsSink] Dropping single oversized event (${Math.round(s.length/1024)} KB)`);return}let a=await i.text().catch(()=>`HTTP ${i.status}`);if(a.includes("FUNCTION_PAYLOAD_TOO_LARGE")||a.includes("Request Entity Too Large")){if(n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}console.warn(`[RemoteAnalyticsSink] Dropping single oversized event (${Math.round(s.length/1024)} KB)`);return}(i.status===401||i.status===403)&&console.error(`[RemoteAnalyticsSink] auth_failed status=${i.status} authKind=${this.auth.kind} sessionId=${e.desktopSessionId} userId=${e.userId??"(unset)"} body=${a.slice(0,200)}`);let o=new Error(a);throw o.status=i.status,o}async mapEvents(e,n){let r=[];for(let s of n){let i={timestamp:new Date(s.ts).toISOString(),childId:qi(s.childId)},a=this.eventIds.get(s)??ih(Jv(s.kind));switch(s.kind){case"message":r.push({...i,id:a,eventType:"message",role:s.role,messageText:s.text,toolName:s.actionName,toolArgs:s.actionArgs,url:s.url});break;case"tool_call":{let o;s.screenshotBase64&&(o=await this.uploadScreenshot(e,s.screenshotBase64)),r.push({...i,id:a,eventType:"tool_call",toolName:s.toolName,toolArgs:s.args,toolResult:s.result,screenshotUrl:o,url:s.url,stepIndex:s.stepIndex,actionMetadata:{durationMs:s.durationMs,tokenCount:s.tokenCount}});break}case"llm_usage":r.push({...i,id:a,eventType:"llm_usage",toolName:s.model,promptTokens:s.promptTokens,completionTokens:s.completionTokens,totalTokens:s.totalTokens,runId:s.runId,callKind:s.callKind,keySource:s.keySource,llmProvider:s.llmProvider,billedUnits:s.billedUnits,actionMetadata:{durationMs:s.durationMs,finishReason:s.finishReason,tokenCount:s.tokenCount,messageCount:s.messageCount,systemPromptHash:s.systemPromptHash,lastToolResults:s.lastToolResults,chosenActions:s.chosenActions,textResponse:s.textResponse,cachedInputTokens:s.cachedInputTokens,planStepIndex:s.planStepIndex,planStepType:s.planStepType}});break;case"supervisor_verdict":r.push({...i,id:a,eventType:"supervisor_verdict",actionType:s.verdict,actionMetadata:{verdict:s.verdict,message:s.message,iteration:s.iteration,actionLogSize:s.actionLogSize,stepText:s.stepText,progress:s.progress??null,differential:s.differential??null}});break;case"agent_lifecycle":r.push({...i,id:a,eventType:"agent_lifecycle",actionType:s.event,actionMetadata:{event:s.event,iteration:s.iteration,details:s.details}});break;case"user_action":r.push({...i,id:a,eventType:"user_action",actionType:s.action,actionTargetId:s.targetId,actionMetadata:s.metadata});break;case"session_start":case"session_end":case"turn_start":case"turn_end":r.push({...i,id:a,eventType:"user_action",actionType:s.kind,actionTargetId:s.sessionId,actionMetadata:s.sessionMeta?{...s.sessionMeta}:{status:s.status,...s.kind==="session_end"&&s.endKind?{endKind:s.endKind}:{}}});break;case"log":r.push({...i,id:a,eventType:"diagnostic",actionType:s.level,actionMetadata:{source:s.source,msg:s.msg,...s.data}});break;case"pageSnapshot.structuralStrip":r.push({...i,id:a,eventType:"diagnostic",actionType:s.kind,actionMetadata:{originalLen:s.originalLen,finalLen:s.finalLen,droppedNodeCount:s.droppedNodeCount,foldedRunCount:s.foldedRunCount,capHit:s.capHit}});break;default:{console.warn(`[RemoteAnalyticsSink] dropping unmapped DiagnosticEvent kind=${s.kind}`);break}}}return r}isProviderLocationUnsupportedEvent(e){return e.kind!=="log"?!1:Sr([e.msg,e.source,typeof e.data=="object"&&e.data?JSON.stringify(e.data):""].join(`
|
|
8
|
+
`),n=e.match(/credential\s+'([^']+)'|'([^']+@[^']+)'/i);return n?n[1]??n[2]:e.match(/[\w.+-]+@[\w.-]+\.\w+/)?.[0]}function AL(t){let e=t.map((u,d)=>u.authRole==="login"?d:-1).filter(u=>u>=0);if(e.length<=1)return t;let n=e.map(u=>t[u]),r=IL(n),s=xL(n),i=s?` as '${s}'`:"",o={text:r?`Sign in with ${r}${i}`:`Log in${i}`,type:"setup",authRole:"login"},l=e[0],c=[];for(let u=0;u<t.length;u++){if(t[u].authRole==="login"){u===l&&c.push(o);continue}c.push(t[u])}return c}function wo(t,e){if(e?.authModeHint==="under_test")return{steps:t,authMode:"under_test"};let n=t.filter(o=>o.authRole);if(n.length===0)return{steps:t};let r=n.filter(o=>o.authRole==="probe"),s=n.filter(o=>o.authRole==="login"),i=t.filter(o=>!o.authRole);return{steps:AL([...r,...s,...i]),authMode:"precondition"}}var sh={GROUNDED_EXPECTATIONS:{key:"GROUNDED_EXPECTATIONS",envVars:["AGENTIQA_GROUNDED_EXPECTATIONS","AGENTIQA_EXPERIMENT_GROUNDED_EXPECTATIONS"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"When on, run_complete batch-judges provisionally-passing steps for expectation drift (heal cosmetic, fail-closed critical/judge-unavailable) instead of trusting the model grade verbatim.",designDoc:"docs/plans/2026-07-07-grounded-expectations-phase-b-design.md",status:"active",added:"2026-07-07",notes:"GRADUATED 2026-07-21 (default on): prod ran env-ON (AGENTIQA_EXPERIMENT_GROUNDED_EXPECTATIONS=1 on the orchestrator) since 2026-07-10 with zero grounded-attributable false-FAIL; nightly regressions in the window were all infra/render flake. This flip normalizes code to the already-live prod behavior \u2014 remove the orchestrator env vars (both namespaces) once this reaches each environment."},LOOP_VISION_ESCALATION_CHAT:{key:"LOOP_VISION_ESCALATION_CHAT",envVars:["AGENTIQA_LOOP_VISION_ESCALATION_CHAT","AGENTIQA_EXPERIMENT_LOOP_VISION_ESCALATION_CHAT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Extends loop-detection vision-supervisor escalation to the Coordinator/chat lane; off disables it for chat only (the master LOOP_VISION_ESCALATION still governs the Runner/Explorer lanes).",designDoc:"docs/plans/2026-07-07-loop-detection-vision-supervisor-design.md",status:"active",added:"2026-07-07",notes:"Staged default-OFF originally, flipped default-ON once baked (AG-6995) \u2014 reads via killSwitchDisabled today."},PIN_PAGE_GROUNDING:{key:"PIN_PAGE_GROUNDING",envVars:["AGENTIQA_PIN_PAGE_GROUNDING","AGENTIQA_EXPERIMENT_PIN_PAGE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Runner-lane pin page-grounding: a criterion's pinned expectedValue must appear in the literal full-page a11y text at verify-evidence capture (parroted grade notes no longer suffice). Detection runs in shadow (telemetry) unless VALUE_GROUNDING_ENFORCE is on; '0' disables detection AND the forced full-snapshot capture entirely.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-10"},ISSUE_QUOTE_GROUNDING:{key:"ISSUE_QUOTE_GROUNDING",envVars:["AGENTIQA_ISSUE_QUOTE_GROUNDING","AGENTIQA_EXPERIMENT_ISSUE_QUOTE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Chat-lane hallucinated-quote gate on report_issue: a quoted literal asserted as visible must appear in the freshly captured full a11y snapshot. Detection runs in shadow (telemetry) unless VALUE_GROUNDING_ENFORCE is on; '0' disables detection AND the forced full-snapshot capture entirely.",designDoc:"packages/engine-core/src/negativeStateEvidence.ts",status:"active",added:"2026-07-10"},VALUE_GROUNDING_ENFORCE:{key:"VALUE_GROUNDING_ENFORCE",envVars:["AGENTIQA_VALUE_GROUNDING_ENFORCE","AGENTIQA_EXPERIMENT_VALUE_GROUNDING_ENFORCE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Flips both value-grounding gates (PIN_PAGE_GROUNDING, ISSUE_QUOTE_GROUNDING) from shadow telemetry (would_fail / would_bounce diag logs) to enforcement: pin absence records a real per-step oracle failure that fails run_complete; a hallucinated visible quote rejects the report_issue filing.",designDoc:"packages/engine-core/src/killSwitch.ts",status:"active",added:"2026-07-10",notes:"Shadow-first rollout: two adversarial review rounds each surfaced false-fail classes on a hard-fail gate, so enforcement waited on a staging soak. PARKED 2026-07-21 (steering decision, Alex): VERIFY_REOBSERVE_WITHHOLD (graduated default-ON) strictly dominates this hard-fail path \u2014 it closes the same blind-verdict/pin-absence hole with a soft-withhold that never manufactures the false-FAIL classes both review rounds surfaced. Never graduate the enforcement; the oracle_failure recording branch is a deletion candidate. Detection stays: PIN_PAGE_GROUNDING + ISSUE_QUOTE_GROUNDING (default-ON) keep their shadow would_fail/would_bounce telemetry. Remove the staging orchestrator env var (AGENTIQA_EXPERIMENT_VALUE_GROUNDING_ENFORCE) \u2014 the force-ON soak is moot.",graduation:{status:"parked",gate:"Retired in favor of VERIFY_REOBSERVE_WITHHOLD (soft-withhold successor). Do not graduate; delete the enforcement branch once the successor has a clean prod window.",evidence:"F2b eval proof: enforce cannot catch the abstain{snapshot_incremental} class (identical RED both legs); panel + review-round history of false-fail classes on the hard-fail path",owner:"steering (Alex)",review:"2026-08-15"}},RESUME_INPUT_ASK_USER:{key:"RESUME_INPUT_ASK_USER",envVars:["AGENTIQA_RESUME_INPUT_ASK_USER","AGENTIQA_EXPERIMENT_RESUME_INPUT_ASK_USER"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Coordinator turn-continuity: when on, a child Explorer's ask_user that blocks on a MISSING INPUT (a file to upload, a path/value \u2014 not an email/generic async wait) arms a resumable `input_wait` pause that persists the halted child's OBJECTIVE; the next user turn resumes that SAME objective (re-attaching session attachments) instead of falling through to free re-decomposition, and re-asks for the SAME objective when the required file is still absent. Off = byte-identical to today (missing-input ask_user arms no pause; the email-wait / generic-wait paths are unchanged).",designDoc:"docs/plans/2026-07-20-paused-task-resume-design.md",status:"active",added:"2026-07-20",notes:"GRADUATED 2026-07-21 (default on) via the bound-eval arm of its gate: chat/paused-task-resume green 2/2 replicates on origin/staging (pause armed on the missing-file ask_user; resume carried the SAME objective tokens (upload + filename) with an explicit no-re-plan prompt; text-only reply correctly re-asked for the same file) + the earlier recorded GRADUATION-PASS on the lio replay (asess_1784568697674). Organic staging soak was vacuous (organic chat never hits a missing-input upload ask_user \u2014 0 input_wait events in 12 sessions), so the eval arm is the gate per the evidence-count doctrine. Renderer attachment-drop discriminator stays a SEPARATE open item (PostHog coordinator_started.has_attachments). Remove the staging orchestrator env var once this reaches staging."},VERIFY_REOBSERVE_WITHHOLD:{key:"VERIFY_REOBSERVE_WITHHOLD",envVars:["AGENTIQA_VERIFY_REOBSERVE_WITHHOLD","AGENTIQA_EXPERIMENT_VERIFY_REOBSERVE_WITHHOLD"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Runner-lane grade-time re-observe + soft-withhold (batch.verify-never-blind fix). When a pinned STRICT verify criterion cannot be grounded at grade time \u2014 the snapshot is not full (abstain snapshot_incremental/missing/thin) or the value is absent from a full a11y snapshot (would_fail) \u2014 the runtime takes ONE fresh forced-full a11y re-capture and re-grounds before accepting the verdict. Groundable after re-observe (value was present but the grade-time capture was imageless/incremental) \u2192 the model verdict stands; still ungroundable \u2192 the step is SOFT-withheld to a 'warning'+note (NON-confident, never a hard fail, never routed through the VALUE_GROUNDING_ENFORCE oracle_failure path). Closes the blind-verdict hole (F2a canvas + F2b incremental) WITHOUT manufacturing false-FAILs on values present-to-user but absent from the a11y outline (virtualized/scrolled-off rows).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-21",notes:"GRADUATED 2026-07-21 (default on), same-day evidence gate approved by Alex in lieu of a calendar soak: (1) staging replay-soak on the lio fixture (proj_mqzn31900, 3 sequential replicates of the only expectedValue-pinned plan) \u2014 zero false-withholds across 6 present-pin observations, withholds only on genuinely-absent values, surgical parity (grounded and no-pin verdicts untouched, check-only plans fully inert), no failing run laundered to pass, no material latency delta; (2) the grounded-rescue + Regression A/B legs banked by the fix-gate eval run (F2b re-observe\u2192grounded\u2192pass, healthy batch zero-fire, below-fold DOM value grounds). Product semantics approved by Alex: pinned-strict TRUE-MISMATCH fails also downgrade to warning (observed-value note preserved) until typed-match (AG-7753) restores precise typed fails. The two evals (runner-verify-blind-canvas / -incremental) remain the regression gate: fix OFF must reproduce, ON must resolve. Independent of VALUE_GROUNDING_ENFORCE \u2014 when off, that flag behaves unchanged. Remove the staging orchestrator env var once this reaches staging."},VERIFY_GATED_DONE:{key:"VERIFY_GATED_DONE",envVars:["AGENTIQA_VERIFY_GATED_DONE","AGENTIQA_EXPERIMENT_VERIFY_GATED_DONE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Cross-checks a 'done'/'passed' claim against deterministic completion-time oracle failures (wait-style); off restores trusting the model's completion claim verbatim.",designDoc:"docs/plans/2026-07-06-verification-gated-done-design.md",status:"active",added:"2026-07-06"},VERIFY_CONFLICT_RECONCILE:{key:"VERIFY_CONFLICT_RECONCILE",envVars:["AGENTIQA_VERIFY_CONFLICT_RECONCILE","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_RECONCILE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Downgrades a verification-conflict force-FAIL to a step-level warning (run not failed) when every plan criterion on the conflicted step passed with a substantiated note AND the only unresolved oracle is an agent-invented wait literal absent from the plan; off restores the unconditional bounce-then-fail-closed (false-negative on incident asess_1784155719395_h62evpmp).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-16"},VERIFY_RECONCILE_CLEAN_PASS:{key:"VERIFY_RECONCILE_CLEAN_PASS",envVars:["AGENTIQA_VERIFY_RECONCILE_CLEAN_PASS","AGENTIQA_EXPERIMENT_VERIFY_RECONCILE_CLEAN_PASS"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Presentation of a VERIFY_CONFLICT_RECONCILE-reconciled verify step: on, the reconciled step is a clean PASS and the reconciliation is recorded only in the structured verification_conflict_reconciled diag event (no engine-jargon note on the user-facing step); off restores the legacy step-level WARNING plus the explanatory note. Independent of VERIFY_CONFLICT_RECONCILE, which decides WHETHER a conflict reconciles at all \u2014 this only changes how an already-reconciled step is surfaced.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-22"},VERIFY_PRESENCE_WAIT_FLOOR:{key:"VERIFY_PRESENCE_WAIT_FLOOR",envVars:["AGENTIQA_VERIFY_PRESENCE_WAIT_FLOOR","AGENTIQA_EXPERIMENT_VERIFY_PRESENCE_WAIT_FLOOR"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Raises a verify-step presence oracle wait (wait_for_element on a `verify` plan step) to a minimum budget (20s) so a slow-rendering but PRESENT element \u2014 e.g. Miro\'s Templates carousel "Blank board" card, which paints several seconds after the dashboard is otherwise interactive \u2014 is not falsely failed by the 5s default wait budget (staging step-5 login/dashboard flake, sessions asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1, where the next action successfully CLICKED "Blank board"). Floor-only: never lowers a larger model-supplied timeout; off restores the model-supplied / 5s-default budget. Fail-closed preserved \u2014 a genuinely-absent element still times out at the larger budget and records the same oracle failure, so no false-PASS is introduced. Applied in RunnerRuntime.raiseVerifyPresenceWaitBudget (Runner/test-plan lane only; Explorer/Coordinator have no plan steps).',designDoc:"packages/engine-core/src/verifyPresenceWaitBudget.ts",status:"active",added:"2026-07-25"},ABSENCE_AWARE_VERIFY:{key:"ABSENCE_AWARE_VERIFY",envVars:["AGENTIQA_ABSENCE_AWARE_VERIFY","AGENTIQA_EXPERIMENT_ABSENCE_AWARE_VERIFY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Absence-assertion verify oracle (issue_742c9da8), a BEFORE\u2192AFTER differential. A verify step that asserts a NEGATIVE (the target is GONE) is verified with the presence-only wait_for_element, whose legitimate timeout on the correctly-absent, PLAN-GROUNDED literal is recorded as an oracle failure and force-FAILS the run at run_complete (canReconcileVerificationConflict refuses the plan-grounded literal \u2014 correct for a PRESENCE assertion, wrong for an absence one). Detection ALWAYS runs (shadow): for a conflicted verify step whose step text / any criterion check asserts THIS TARGET's absence (checkTextAssertsAbsence \u2014 the target literal is stripped first, then an EXPLICIT absence lexeme must survive; a negation inside the target NAME or an incidental 'not' cannot route it) and whose unresolved oracle is a wait-style action with a captured target literal, it classifies CONFIRMED vs ABSTAIN and emits an `absence_verify_oracle:shadow` diag. CONFIRMED requires the wait-literal's OWN before\u2192after transition: (a) GENUINELY ABSENT from a FULL, substantive, NON-canvas, non-load-failure AFTER snapshot retained for that step (never the model's note), AND (b) pinPresentInPage-TRUE in an EARLIER full+whole-page+substantive+same-origin BEFORE snapshot (the presence ledger \u2014 reusing the retained full-snapshot maps), AND every graded criterion passed substantiated. The weak container-noun positive anchor is DROPPED as the load-proof (before-presence + whole-page liveness replaces it); a load-failure/retry interstitial AFTER page is REJECTED (snapshotShowsLoadFailure). When this flag is ON it ENFORCES: a CONFIRMED absence reconciles the conflict to a PASS (via the VERIFY_CONFLICT_RECONCILE clean-pass rail), and an ABSTAIN (no full snapshot / canvas / target still present / load-failure after / NO before-presence \u2014 the target was never shown present / unsubstantiated criteria) soft-withholds the step to a WARNING (never a hard fail, never a clean pass). Off leaves every verdict byte-identical (the plan-grounded absence timeout still force-FAILs) with the shadow diag only. Positive (presence) assertions are untouched (checkTextAssertsAbsence false \u2192 inapplicable \u2192 the existing timeout-fails behavior). Runner lane only (RunnerRuntime run_complete).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-25",notes:"GRADUATED 2026-07-26 (default ON) \u2014 the FIRST live trust-verdict graduation. Enforcement (reconcile-to-pass on CONFIRMED / soft-withhold-to-warning on ABSTAIN) is now the no-env default; detection had run in shadow since 2026-07-25 (absence_verify_oracle:shadow diag) \u2014 the PIN_PAGE_GROUNDING / VERIFY_REOBSERVE_WITHHOLD shadow-first precedent. GRADUATION EVIDENCE: the kind-agnostic graduation benchmark (#1857, e2e/benchmark/) returned GATE=GO on the absence corpus (4 false-FAILs fixed \u2192 PASS, 0 regressions, 0 new false-PASS, 0 marginal LLM cost) and is adversarially proven able to say NO-GO; a fresh-build re-confirm held (confirmed-absence\u2192PASS fixes #1816 / unconfirmable\u2192WARNING / still-present\u2192no false-PASS; the full engine-core suite is byte-identical ON vs OFF except the graduated verdicts). HARD CONSTRAINT (unchanged): confirm fires ONLY on the wait-literal's OWN before\u2192after transition (present in an earlier same-origin full+substantive+non-canvas snapshot, absent from the non-load-failure after one) read from real page snapshots \u2014 never the model's note nor a disjoint absence lexeme \u2014 so a hallucinated 'it's gone', a never-loaded presence target (compound presence+absence), and a silently-blank list echoing the container noun all abstain to WARNING rather than confirming; no false-PASS is reintroduced. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND ABSENCE_AWARE_VERIFY listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire); an explicit AGENTIQA_ABSENCE_AWARE_VERIFY=0 still restores the byte-identical pre-graduation force-FAIL behavior. Read site: packages/engine-core/src/RunnerRuntime.ts (absenceAwareVerifyEnabled). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.absenceVerifyFalseFail.test.ts (end-to-end, now green for the right reason) + RunnerRuntime.absenceVerifyHardening.test.ts. Claim runner.absence-assertion-verify is now bound green."},GROUNDED_STATE_VERIFIER:{key:"GROUNDED_STATE_VERIFIER",envVars:["AGENTIQA_GROUNDED_STATE_VERIFIER","AGENTIQA_EXPERIMENT_GROUNDED_STATE_VERIFIER"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S1 escalation gate + shadow instrumentation (Tier-2 vision-extraction cost sizing; design docs/plans/2026-07-25-grounded-state-verifier-design.md). SHADOW-ONLY / MEASUREMENT-ONLY: this slice makes NO model call and NEVER alters a verdict, verdict input, or any other diagnostic. When on, the runner's Tier-1 deterministic pin page-grounding oracle (checkPinPageGrounding), at each GROUNDABILITY abstain on a step carrying a countable expectedValue pin \u2014 canvas_dominant, a non-full/incremental a11y snapshot, or a thin/missing snapshot (NOT the transient/ephemeral-text abstain) \u2014 consults the surface-agnostic capture-groundability signal (captureModeGroundsAbsence, keyed on captureMode, NOT a surface-name check) and emits a structured `verifier_escalated` diag {stepIndex, reason, assertionKind, captureMode, wouldNeedTier2:true} for a capture a vision extractor could ground (the genuine Tier-2 candidate), or `verifier_escalation_abstained` {\u2026, wouldNeedTier2:false, floor:'inconclusive'} when even vision cannot ground it (the fail-closed floor \u2014 abstain, never escalate-and-guess). Off \u21D2 byte-identical to today: the escalation diags are not emitted and nothing else changes. Sizes S2's per-verify vision-extraction cost by measuring how often and WHERE Tier-1 abstains on countable state assertions.",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S1 of the grounded-state verifier (measurement slice). Default OFF; SHADOW-ONLY and verdict-inert even when ON \u2014 this slice only emits verifier_escalated / verifier_escalation_abstained shadow diags at the checkPinPageGrounding abstain points, makes no model call, and changes no verdict. The escalation decision keys on captureModeGroundsAbsence (capture fidelity / checkPinPageGrounding outcome), NOT on canvasDominant/surface identity, so a non-canvas vision-groundable surface escalates through the same path (spec AC-7). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateVerifierEnabled \u2192 maybeEmitVerifierEscalation, called from checkPinPageGrounding); pure logic in packages/engine-core/src/groundedStateVerifier.ts. Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateVerifier.test.ts (wiring, flag-OFF byte-identical) + groundedStateVerifier.test.ts (pure groundability keying). S2 (prompt-only extractor + deterministic comparator) is the next slice and adds the actual Tier-2 call behind this same flag.",graduation:{status:"gated",gate:"S1 is measurement-only (no verdict change), so it graduates by FEEDING S2, not by flipping default-on: a staging shadow soak of verifier_escalated / verifier_escalation_abstained sizes the Tier-1-abstain-on-countable-state rate (per reason + captureMode) that S2 (prompt-only vision extractor + deterministic comparator, same flag) is built against. The flag advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; S1 alone never flips default-on.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events (escalation rate + reason/captureMode breakdown) + the engine-core RunnerRuntime.groundedStateVerifier + groundedStateVerifier unit suites",owner:"steering (Alex)",review:"2026-08-08"}},GROUNDED_STATE_EXTRACT:{key:"GROUNDED_STATE_EXTRACT",envVars:["AGENTIQA_GROUNDED_STATE_EXTRACT","AGENTIQA_EXPERIMENT_GROUNDED_STATE_EXTRACT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S2 prompt-only vision EXTRACTOR + deterministic presence COMPARATOR (design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1's free measurement stays independently runnable). SHADOW-ONLY: when on AND a stateExtractor is wired, each S1 escalation candidate (a Tier-1 checkPinPageGrounding abstain on a vision-groundable capture carrying a PRESENCE assertion, deduped one-call-per-step) gets ONE no-task-stake vision extraction at run_complete that enumerates what is on screen into a FIXED schema (objects/text/labels/counts) \u2014 NEVER a verdict (AC-2: the prompt receives no assertion outcome and no pass/fail framing). A DETERMINISTIC comparator then decides presence of the plan-text-derived target against that extraction, reproducibly from the logged extraction + target without re-calling the model (AC-3), and the runtime LOGS the would-be verdict + its PARITY vs the driver's current grade (grounded_state_extract diag). This slice changes NO live verdict. FAIL-CLOSED (Decision 7): any missing image / extractor abstain / non-answer / error / timeout / ambiguous or thin comparison \u2192 INCONCLUSIVE, never a pass. Off \u21D2 zero extraction calls, no candidate collection, byte-identical behavior (AC-6). Cost: one extraction call per escalated presence step, hard-capped (fork E).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S2 of the grounded-state verifier (prompt-only extractor + deterministic presence comparator). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be presence verdict and its parity vs the driver grade (grounded_state_extract / _start / _done diags), makes at most ONE extraction model call per escalated step (fork-E hard cap), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER so S1 measurement runs without paying S2 cost. Requires deps.stateExtractor wired (getStateExtractor in apps/execution-engine/src/buildDeps.ts) \u2014 absent \u21D2 inert. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateExtractEnabled \u2192 candidate recording in maybeEmitVerifierEscalation, consumed by runGroundedStateExtractions at run_complete); extractor + comparator in packages/engine-core/src/groundedStateExtractor.ts. Acceptance tests: packages/engine-core/src/__tests__/groundedStateExtractor.test.ts (pure prompt/parser/comparator/parity \u2014 AC-2/AC-3) + RunnerRuntime.groundedStateExtract.test.ts (wiring, shadow-no-mutation, fail-closed, one-call cap, seam guard, flag-OFF byte-identical). Binds claim verify.grounded-state-extract-then-compare. S3 (GROUNDED_STATE_DIFFERENTIAL) adds the before\u2192after differential for absence + modification.",graduation:{status:"gated",gate:"S2 is shadow-first (no verdict change). Graduation gates the PRESENCE case only, and only after: (1) a staging verdict-parity shadow soak of grounded_state_extract shows the extract-then-compare would-verdict matching the driver grade on DOM-groundable controls and DISAGREEing (would_fail on a driver-passed step) on the canvas false-pass fixtures (project_canvas_direct_draw_test) that the driver self-grade lets through today; (2) the extractor accuracy on the canvas presence fixtures clears the fork-G bar (else spec the fine-tuned extractor first). Advancing to a LIVE verdict path is a separate step from flipping this flag to shadow-on.",evidence:"staging grounded_state_extract / _start / _done diag events (would-verdict + parity + inconclusive-rate breakdown) + the engine-core groundedStateExtractor + RunnerRuntime.groundedStateExtract unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_DIFFERENTIAL:{key:"GROUNDED_STATE_DIFFERENTIAL",envVars:["AGENTIQA_GROUNDED_STATE_DIFFERENTIAL","AGENTIQA_EXPERIMENT_GROUNDED_STATE_DIFFERENTIAL"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S3 BEFORE\u2192AFTER DIFFERENTIAL (absence \u2282 update) for ABSENCE + MODIFICATION (design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1 measurement) / GROUNDED_STATE_EXTRACT (S2 single-after presence). SHADOW-ONLY: when on AND a stateExtractor is wired, each S1 escalation candidate (a Tier-1 checkPinPageGrounding abstain on a vision-groundable capture carrying an ABSENCE or MODIFICATION assertion, deduped one-call-per-step) runs the S2 no-task-stake vision extraction on BOTH the persisted baseline (before, resolveBaselineMessage) and verify (after, resolveEvidenceMessage) frames \u2014 each with S2's IDENTICAL constant task-blind prompt (AC-2: task-blind on BOTH frames, no assertion / no expected value / no pass/fail framing) \u2014 and a DETERMINISTIC differential comparator decides the verdict from the two extractions + the plan-text-derived target, reproducibly without re-calling the model (AC-3). ABSENCE: target present-before \u2227 absent-after \u2192 would_pass (confirmed_absent); still present-after \u2192 would_fail; before-presence unestablished / after unreadable \u2192 inconclusive. MODIFICATION: a count that changed to the expected value, or a crisp new value that appeared (before-absent + after-present) \u2192 would_pass; unresolvable \u2192 inconclusive. The runtime LOGS the would-be differential verdict + its PARITY vs the driver grade (grounded_state_differential diag); this slice changes NO live verdict. FAIL-CLOSED (Decision 7): any missing-before / unreadable / extractor abstain / error / timeout / ambiguous or unresolvable comparison \u2192 INCONCLUSIVE, never a pass. Canvas is IN scope (the extractor is vision; before/after frames exist via blind-double-read), identified by the plan DESCRIPTOR (fork D1) with an ambiguous match abstaining to inconclusive \u2014 never re-identifying an anonymous object. Off \u21D2 zero candidate collection, zero extraction calls, byte-identical behavior (AC-6). Cost: at most TWO extraction calls per escalated differential step (before + after, fork-E bounded call budget), hard-capped, batched under a deadline.",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:'S3 of the grounded-state verifier (before\u2192after differential; absence \u2282 update). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be differential verdict and its parity vs the driver grade (grounded_state_differential / _start / _done diags), makes at most TWO extraction model calls per escalated step (before + after; fork-E bounded budget, hard-capped, batched under a deadline \u2192 timeout inconclusive), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2). Requires deps.stateExtractor wired (getStateExtractor in apps/execution-engine/src/buildDeps.ts, reused per-frame) \u2014 absent \u21D2 inert. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateDifferentialEnabled \u2192 differential-candidate recording in maybeEmitVerifierEscalation, consumed by runGroundedStateDifferentials at run_complete); pure differential comparator in packages/engine-core/src/groundedStateDifferential.ts (reuses S2 groundedStateExtractor). Acceptance tests: packages/engine-core/src/__tests__/groundedStateDifferential.test.ts (pure differential \u2014 absence/modification/fail-closed, #1816 RED\u2192GREEN comparator soak hook + green-guard, AC-2/AC-3) + RunnerRuntime.groundedStateDifferential.test.ts (wiring, before+after two-frame extraction, shadow-no-mutation, fail-closed on missing-before/unreadable/timeout, one-differential-per-step cap, canvas descriptor-match, flag-OFF byte-identical). Binds claim verify.grounded-state-extract-then-compare. S4 (GROUNDED_STATE_INCONCLUSIVE) maps verifier-abstain \u2192 the inconclusive floor. Trust-layer Slice 1 (routing-gap fix) ALSO gates a STATIC single-frame COUNT comparator on this same flag: a count-intent assertion ("exactly 3 shapes" \u2014 authored factKind:count or an NL count check) escalates a count candidate and, at run_complete, runGroundedStateCounts runs ONE task-blind extraction + the deterministic compareCount (extracted 4 \u2260 expected 3 \u2192 grounded_state_count would_fail(after_count_mismatch); 3 = 3 \u2192 would_pass(confirmed_count)); shadow-only, fail-closed, one-call-per-step. Acceptance: RunnerRuntime.groundedStateCount.test.ts + the compareCount/checkTextAssertsCount cases in groundedStateDifferential.test.ts; end-to-end firewall proof eval runner-verify-count-canvas.',graduation:{status:"gated",gate:"S3 is shadow-first (no verdict change). Graduation gates the ABSENCE + MODIFICATION differential and only after: (1) a staging verdict-parity shadow soak of grounded_state_differential shows the #1816 reproduced-RED absence scenario would flip RED\u2192GREEN under the differential (confirmed_absent \u2192 would_pass on a driver-failed step) WITHOUT regressing the paired green-guard fixture (target-still-present \u2192 would_fail / driver-pass preserved); (2) new MODIFICATION fixtures (count + value-appearance) shadow-soak clean; (3) the extractor accuracy on the canvas absence/modification fixtures clears the fork-G bar. Advancing to a LIVE verdict path is a separate step from flipping this flag to shadow-on.",evidence:"staging grounded_state_differential / _start / _done diag events (would-verdict + parity + inconclusive-rate breakdown, #1816 RED\u2192GREEN) + the engine-core groundedStateDifferential + RunnerRuntime.groundedStateDifferential unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-22"}},GROUNDED_STATE_INCONCLUSIVE:{key:"GROUNDED_STATE_INCONCLUSIVE",envVars:["AGENTIQA_GROUNDED_STATE_INCONCLUSIVE","AGENTIQA_EXPERIMENT_GROUNDED_STATE_INCONCLUSIVE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S4 FAIL-CLOSED INCONCLUSIVE FLOOR wiring (Decision 7 + Fork F2; design docs/plans/2026-07-25-grounded-state-verifier-design.md). The sibling flag to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3). SHADOW-ONLY: when on, each verifier ABSTAIN \u2014 the S1 escalation fail-closed floor (verifier_escalation_abstained, a capture even a vision extractor cannot ground) and every S2 presence / S3 differential `inconclusive` outcome (thin/unreadable capture, extractor refusal/error/timeout, before-presence unestablished, after unreadable, ambiguous match, unresolved count) \u2014 is ALSO mapped to the typed inconclusive floor and LOGGED (grounded_state_inconclusive diag): the DISTINCT `verifier_inconclusive:{reason}` sub-reason + the interim `warning` step status (Fork F2 \u2014 a NEUTRAL 'couldn't tell', NOT an alarm-amber defect per project_warning_display_semantics) + the verifierInconclusive marker + migratesTo:'inconclusive'. This slice mutates NO stepResult and changes NO verdict \u2014 it computes/LOGS the would-be floor mapping only. HONESTY FLOORS: an abstain NEVER maps to `passed` (VERIFIER_INCONCLUSIVE_STEP_STATUS is warning/inconclusive, never passed), and a genuine would_pass/would_fail is never floored (inconclusiveFloorForVerdict returns null on a non-inconclusive verdict; the wiring only fires on the S2/S3 abstain paths + the S1 abstained floor). ONE migration point: flip VERIFIER_INCONCLUSIVE_STEP_STATUS (groundedStateInconclusive.ts) from `warning` to step-level `inconclusive` when Layered-Hybrid Phase-1 lands that status in the step enum. Off \u21D2 zero mapping, zero logs, byte-identical (AC-6).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S4 of the grounded-state verifier (fail-closed inconclusive floor; interim warning-with-distinct-sub-reason, Fork F2). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes and LOGS the would-be inconclusive floor mapping (grounded_state_inconclusive diag), makes NO model call (pure wiring of S1/S2/S3 abstain outcomes), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3); the abstains it maps only exist when those slices run, so S4 is additive telemetry on top of them. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateInconclusiveEnabled \u2192 maybeLogInconclusiveFloor, called at the S1 verifier_escalation_abstained floor in maybeEmitVerifierEscalation + the S2/S3 logInconclusive abstain choke points in runGroundedStateExtractions / runGroundedStateDifferentials); pure mapping in packages/engine-core/src/groundedStateInconclusive.ts (the ONE migration point VERIFIER_INCONCLUSIVE_STEP_STATUS). Acceptance tests: packages/engine-core/src/__tests__/groundedStateInconclusive.test.ts (pure \u2014 each abstain reason \u2192 typed sub-reason \u2192 interim warning-never-passed, distinct-from-product-warning, migration seam, would_pass/would_fail never floored) + RunnerRuntime.groundedStateInconclusive.test.ts (wiring \u2014 flag-OFF byte-identical, shadow-no-mutation, floor logged per S1/S2/S3 abstain, no floor on a would_pass step). Binds claim verify.grounded-state-extract-then-compare. S5 broadens the groundability surface + fine-tune trigger.",graduation:{status:"gated",gate:"S4 is shadow-first (no verdict change) and the INTERIM F2 mapping (warning-with-distinct-sub-reason). Graduation to a LIVE floor is a SEPARATE, later step from flipping this flag shadow-on and requires: (1) a staging shadow soak of grounded_state_inconclusive confirming the abstain\u2192floor breakdown (source / reason / rate) is sane and that no would_pass/would_fail is ever floored (the honesty invariants hold in the field); (2) the S2/S3 verdict-parity soaks having graduated their live-verdict paths (an inconclusive floor is only meaningful once the extract-then-compare verdicts gate); (3) the UI rendering the verifier_inconclusive sub-reason as a NEUTRAL could-not-tell (not alarm-amber). The clean F2\u2192F1 migration (flip VERIFIER_INCONCLUSIVE_STEP_STATUS warning\u2192inconclusive at the ONE point) lands when Layered-Hybrid Phase-1 ships the step-level inconclusive status.",evidence:"staging grounded_state_inconclusive diag events (abstain\u2192floor mapping: source/reason/sub-reason/interim-status breakdown, honesty-invariant field check) + the engine-core groundedStateInconclusive + RunnerRuntime.groundedStateInconclusive unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-08-29"}},GROUNDED_STATE_FINETUNE_METRIC:{key:"GROUNDED_STATE_FINETUNE_METRIC",envVars:["AGENTIQA_GROUNDED_STATE_FINETUNE_METRIC","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FINETUNE_METRIC"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Grounded-state verifier \u2014 S5 FINE-TUNE TRIGGER METRIC (Fork G: DEFINE the trigger, do NOT fine-tune; design docs/plans/2026-07-25-grounded-state-verifier-design.md). The final sibling flag to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) / GROUNDED_STATE_INCONCLUSIVE (S4). SHADOW-ONLY: when on AND an S2/S3 shadow batch runs, the runtime ACCUMULATES per-SURFACE outcome counts from the extract-then-compare batches \u2014 extractor-abstain (the prompt-only extractor produced no facts), comparator-inconclusive (facts extracted but no definite verdict), and parity agree/disagree \u2014 bucketed by the escalation reason \u2192 surface class (canvas_dominant\u2192canvas, thin\u2192image_or_svg, incremental/non_full\u2192partial_capture; a DIAGNOSTIC label over the already-recorded reason, NOT a surface-name gate \u2014 the escalation gate stays keyed on captureModeGroundsAbsence, Fork A1). After both batches it LOGS the evaluated fine-tune trigger report against the STATED bar (grounded_state_finetune_metric diag): per surface the extractor-abstain rate, inconclusive rate, disagreement rate, and a would-trigger-fine-tune flag (Fork-G graduation signal, ADVISORY). This makes the prompt-only\u2192dedicated/fine-tuned graduation a DATA read; prompt-only stays v1 (Decision 6) \u2014 this slice invests in NO model, mutates NO stepResult, and changes NO verdict. The metric only has samples to fold when S2 and/or S3 also run. Off \u21D2 zero accumulation, zero logs, byte-identical (AC-6). The STATED bar: per surface, after live graduation, extractor-abstain rate > 0.20 OR inconclusive rate > 0.40 over \u2265 50 escalated extract-then-compares triggers a dedicated/fine-tuned extractor FOR THAT SURFACE (parity-disagreement is reported but NOT a trigger input \u2014 a high disagreement can be the extractor CATCHING driver false-passes, the desired signal).",designDoc:"docs/plans/2026-07-25-grounded-state-verifier-design.md",status:"active",added:"2026-07-25",notes:"S5 of the grounded-state verifier (fine-tune trigger metric; Fork G define-not-fine-tune) and the LAST vision-tier slice. Default OFF; SHADOW-ONLY \u2014 even when ON it only accumulates the per-surface outcome breakdown from the S2/S3 shadow batches and LOGS the evaluated trigger report (grounded_state_finetune_metric diag), makes NO model call (pure metric over existing S2/S3 outcomes), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_VERIFIER (S1) / GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) / GROUNDED_STATE_INCONCLUSIVE (S4); the outcomes it folds only exist when S2/S3 run, so S5 is additive telemetry on top of them. The companion BROADEN half of S5 (SVG/image coverage, spec AC-7 generalized) needed NO gate change \u2014 the S1/S2/S3 path already keys on captureModeGroundsAbsence (Fork A1), so broadening is a fixture/coverage add, proven by the RunnerRuntime.groundedStateBroaden test. Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateFineTuneMetricEnabled \u2192 the run_complete accumulator threaded into runGroundedStateExtractions / runGroundedStateDifferentials, emitted by emitFineTuneTriggerMetric); pure metric + STATED bar in packages/engine-core/src/groundedStateFineTuneTrigger.ts (FINETUNE_TRIGGER_BAR). Acceptance tests: packages/engine-core/src/__tests__/groundedStateFineTuneTrigger.test.ts (pure surface mapping / fold / rates / bar evaluation) + RunnerRuntime.groundedStateFineTuneMetric.test.ts (wiring \u2014 per-surface fold from S2/S3, flag-OFF byte-identical, shadow-no-mutation) + RunnerRuntime.groundedStateBroaden.test.ts (AC-7 generalized: a non-canvas SVG/image surface escalates + extracts + compares through the identical path). Binds claim verify.grounded-state-extract-then-compare. COMPLETES the S1\u2013S5 vision-tier build; remaining work is soak + graduation flips (Alex).",graduation:{status:"gated",gate:"S5 is shadow-first (no verdict change) and DEFINES the Fork-G fine-tune trigger \u2014 it does not fine-tune. The metric graduates by FEEDING the fine-tune decision, not by flipping default-on: a staging shadow soak of grounded_state_finetune_metric measures each surface (canvas / image_or_svg / partial_capture) extractor-abstain + inconclusive rate against the STATED bar (FINETUNE_TRIGGER_BAR: abstain > 0.20 OR inconclusive > 0.40 over \u2265 50 escalated steps). Investing in a dedicated/fine-tuned extractor for a surface is triggered ONLY when that surface clears the bar AFTER the S2/S3 extract-then-compare has graduated live on it (Decision 6: prompt-only ships regardless). This flag alone never flips default-on.",evidence:"staging grounded_state_finetune_metric diag events (per-surface extractor-abstain / inconclusive / disagreement rate + would-trigger evaluation vs FINETUNE_TRIGGER_BAR) + the engine-core groundedStateFineTuneTrigger + RunnerRuntime.groundedStateFineTuneMetric + RunnerRuntime.groundedStateBroaden unit suites + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-09-05"}},GROUNDED_STATE_NL_TRIGGER:{key:"GROUNDED_STATE_NL_TRIGGER",envVars:["AGENTIQA_GROUNDED_STATE_NL_TRIGGER","AGENTIQA_EXPERIMENT_GROUNDED_STATE_NL_TRIGGER"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 1 \u2014 un-inert the grounded-state verifier for PINLESS criteria (design docs/plans/2026-07-26-groundability-contract-design.md). The Tier-1 pin page-grounding oracle (checkPinPageGrounding) early-returns when a criterion carries no expectedValue pin, so a real/canvas plan's natural-language {check,strict} assertion never reached the S1 escalation path \u2014 the grounded-state verifier was provably INERT on exactly the canvas surfaces (Miro/Figma) it was built for. When on, a PINLESS verify step whose RUNTIME fact-kind (deriveVerifyAssertionKind) is a non-default state-change kind \u2014 `absence` or `modification` \u2014 routes through the SAME capture-groundability abstain\u2192escalate logic the pinned path uses (maybeEmitVerifierEscalation \u2192 buildVerifierEscalation), keyed on the IDENTICAL captureModeGroundsAbsence gate (a capture even a vision extractor cannot ground abstains to the fail-closed inconclusive floor, never escalate-and-guess). F2 ANTI-FLOOD: the DEFAULT `presence` kind is EXCLUDED \u2014 deriveVerifyAssertionKind defaults to presence for everything, so escalating on presence would flood every pinless ungroundable step; only absence/modification (which the classifier returns deliberately) escalate in Slice 1 (authored count/value are Slice 2). ESCALATION-TRIGGER ONLY: matchType/comparison/expectedValue-as-comparator are untouched, this is shadow/verdict-inert like S1\u2013S5, and it emits nothing on its own \u2014 the escalation diag / candidate still requires GROUNDED_STATE_VERIFIER / _EXTRACT / _DIFFERENTIAL / _INCONCLUSIVE. Off \u21D2 byte-identical: the pinless early-return stands, zero new telemetry, zero behavior change (AC-6).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-25",notes:"Groundability-contract Slice 1 (PR-A). Default OFF; SHADOW-ONLY and verdict-inert even when ON \u2014 it only relocates the S1 escalation TRIGGER for pinless criteria off the expectedValue pin onto the existing runtime fact-kind classifier (deriveVerifyAssertionKind). NO schema change (migration-safe). The escalate-vs-abstain disposition stays keyed on the exact captureModeGroundsAbsence gate reused from the pinned path (GUARDRAIL 1: no pinless bypass). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateNlTriggerEnabled \u2192 maybeEmitPinlessNlEscalation, called at the checkPinPageGrounding pinless early-return; routes through the shared maybeEmitVerifierEscalation). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateNlTrigger.test.ts (pinless absence/modification escalates on ungroundable canvas/thin/non_full; groundable-mode capture abstains to the inconclusive floor NOT escalate; presence pinless never escalates \u2014 F2 anti-flood; flag-OFF byte-identical; pinned path unchanged). OVERLAP NOTE: ABSENCE_AWARE_VERIFY (#1818, classifyAbsenceVerifyConflict / wait-oracle literal) is a DISTINCT pin-independent absence route \u2014 both are shadow/verdict-inert, so absence carries a DOUBLE shadow signal; do not double-count in soak evidence. Slice 2 adds authored count/value kinds.",graduation:{status:"gated",gate:"Slice 1 is measurement-only (no verdict change): it graduates by FEEDING the same S2/S3 extract-then-compare shadow soak \u2014 a staging shadow soak of verifier_escalated / verifier_escalation_abstained on PINLESS absence/modification steps (canvas/real plans) sizes the escalation rate the vision tier is built against, previously unmeasurable because pinless steps never escalated. The flag advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; Slice 1 alone never flips default-on. Slice 2 (authored count/value kinds) is a separate gated slice.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events on pinless absence/modification steps (escalation rate + reason/captureMode breakdown, de-duplicated against the ABSENCE_AWARE_VERIFY absence shadow signal) + the engine-core RunnerRuntime.groundedStateNlTrigger unit suite",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_FACTKIND_AUTHORED:{key:"GROUNDED_STATE_FACTKIND_AUTHORED",envVars:["AGENTIQA_GROUNDED_STATE_FACTKIND_AUTHORED","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FACTKIND_AUTHORED"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 2 \u2014 consume the MODEL-authored `factKind` as source-of-truth for the grounded-state escalation trigger's assertion shape (design docs/plans/2026-07-26-groundability-contract-design.md). Builds on Slice 1 (GROUNDED_STATE_NL_TRIGGER, pinless escalation on runtime absence/modification). The new OPTIONAL `factKind` enum (value|count|presence|absence|modification|relation) on TestPlanV2Criterion is authored by the generation model (all three producer schemas) as a deliberate typed choice (spawn_agent authMode/authSurfaceKind precedent). When on, a criterion carrying an AUTHORED factKind (a) OVERRIDES the runtime deriveVerifyAssertionKind inference (mapped 6\u21923 for the escalation branch, Fork F1: absence\u2192absence, modification\u2192modification, value/count/presence/relation\u2192presence) AND (b) LIFTS Slice 1's F2 anti-flood filter for that step so ANY authored kind escalates \u2014 authoring IS the deliberate groundable-fact signal \u2014 still gated by the IDENTICAL captureModeGroundsAbsence floor (a capture even a vision extractor cannot ground abstains to the fail-closed inconclusive floor, NEVER escalate-and-guess), routed per collapsed kind (absence/modification \u2192 S3 differential candidate; value/count/presence/relation \u2192 S2 presence-family extraction candidate). This fixes the count/canvas case (authored count \u2192 escalates to S2 extraction) WITHOUT the runtime-presence flood. UNAUTHORED criteria keep Slice 1's runtime path EXACTLY (only absence/modification escalate; the runtime `presence` default does NOT). matchType/comparison/expectedValue-as-comparator UNTOUCHED; SHADOW-ONLY / verdict-inert like S1\u2013S5; it emits nothing on its own \u2014 the escalation diag / candidate still requires GROUNDED_STATE_VERIFIER / _EXTRACT / _DIFFERENTIAL / _INCONCLUSIVE. Off (or factKind absent) \u21D2 byte-identical: the field is unread, Slice 1's runtime behavior stands (AC-6). The field may be authored + persisted with this flag OFF (harmless, unread).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-25",notes:"Groundability-contract Slice 2 (PR-B). Default OFF; SHADOW-ONLY and verdict-inert even when ON. Read sites: packages/engine-core/src/RunnerRuntime.ts (groundedStateFactKindAuthoredEnabled \u2192 authoredFactKind, consumed by deriveVerifyAssertionKind override + the pinless F2-filter lift in maybeEmitPinlessNlEscalation). Field: packages/shared-types/src/index.ts (FactKind + TestPlanV2Criterion.factKind); producer schemas: coordinatorToolDefs.ts test_plan_criteria_schema, agentToolDefs.ts criteria_schema, runnerToolDefs.ts step_with_criteria_schema (thin inline); generation steer: planStepGuidance.ts buildCriteriaFactKindGuidance; 6\u21923 mapping + type-guard: groundedStateVerifier.ts factKindToAssertionKind / isAuthoredFactKind. DROP-SITES registered (else a plain step-text edit silently wipes the authored field \u2014 the matchType bug): renderer finalizeCriterion (apps/desktop-next/.../testPlanStepsSerde.ts) + server carryCriterionPins (apps/web-next/lib/testPlanSaveNormalize.ts) \u2014 both preserve factKind on an UNCHANGED check, drop it on an EDITED check (\u2192 runtime fallback, safe). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.groundedStateFactKindAuthored.test.ts (authored count/presence on ungroundable canvas \u2192 S2 extraction candidate; authored absence \u2192 S3 differential candidate; authored + degraded capture \u2192 inconclusive floor, no escalate-and-guess; flag OFF \u2192 byte-identical field-unread Slice-1 behavior; field absent \u2192 Slice-1 behavior) + drop-site round-trip tests in testPlanStepsSerde.test.ts / testPlanSaveNormalize.test.ts. The MANDATORY real-runtime generation eval + the qa-box claim verify.groundability-contract-authored are Slice-2b (separate follow-on), NOT this PR. OVERLAP NOTE: composes with GROUNDED_STATE_NL_TRIGGER (Slice 1) via the shared maybeEmitPinlessNlEscalation helper.",graduation:{status:"gated",gate:"Slice 2 is measurement-only (no verdict change): it graduates by FEEDING the same S2/S3 extract-then-compare shadow soak, now widened to authored count/value/presence/relation kinds (the count/canvas case Slice 1 could not reach because runtime presence does not escalate). It advances to a real verdict path only under S2+ with its own verdict-parity shadow-soak; Slice 2 alone never flips default-on. Requires the Slice-2b generation eval (real ExplorerRuntime/CoordinatorRuntime authoring the correct factKind) to gate the authoring quality before any graduation.",evidence:"staging verifier_escalated / verifier_escalation_abstained diag events on PINLESS authored-factKind steps (escalation rate + factKind/reason/captureMode breakdown) + the engine-core RunnerRuntime.groundedStateFactKindAuthored unit suite; graduation additionally blocked on the Slice-2b real-runtime generation eval (authoring-distribution baseline)",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_FACTKIND_TYPING_PASS:{key:"GROUNDED_STATE_FACTKIND_TYPING_PASS",envVars:["AGENTIQA_GROUNDED_STATE_FACTKIND_TYPING_PASS","AGENTIQA_EXPERIMENT_GROUNDED_STATE_FACTKIND_TYPING_PASS"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Groundability-contract Slice 2b \u2014 MODEL-authored focused second-pass factKind typing that FIXES the realistic-authoring gap (design docs/plans/2026-07-26-groundability-contract-design.md). Slice 2 (GROUNDED_STATE_FACTKIND_AUTHORED) consumes an authored `factKind`, but the live ExplorerRuntime authors it on ~0% of criteria produced by a realistic multimodal explore (screenshots + long trace + coordinator\u2192explorer spawn = the load that suppresses a deeply-nested OPTIONAL enum) \u2014 MEASURED 0/8 on e2e/evals/plans/groundability-factkind-explored.ts, and the three natural schema fixes (imperative guidance, required field, field reorder) ALL stayed 0%. But a FOCUSED low-load typing call over JUST the drafted check-texts types factKind at 100% (probe 78/78, real gemini-3-flash-preview). When on, AFTER the Explorer's draftTestCase is finalized (assistant_v2_report accept seam, past every re-prompt gate), a SEPARATE model-authored pass (packages/engine-core/src/factKindTypingPass.ts runFactKindTypingPass) collects the verify criteria that LACK an authored factKind, makes ONE batched Gemini call (the session's own model + the REAL buildCriteriaFactKindGuidance the producer schema ships; generateText + Output.object, thinkingBudget:0) that returns {index,factKind}[], and writes the kind back onto each criterion IN PLACE. It is MODEL-authored (a real Gemini call), NOT the rejected deterministic runtime factKind inference. NO OVERWRITE: only a MISSING factKind is filled (an already-authored kind is skipped at collect + double-guarded at write-back). FAIL-SAFE: any error/empty/timeout/invalid-kind leaves factKind UNSET (falls through to runtime inference) \u2014 never crashes authoring, never writes a garbage kind. SHADOW-SAFE: the written factKind is read ONLY by the separately flag-gated GROUNDED_STATE_FACTKIND_AUTHORED verifier (default-OFF), so verdicts are byte-identical whether or not this pass ran. Off \u21D2 the caller never invokes the module: ZERO new model calls, byte-identical authoring (AC-6).",designDoc:"docs/plans/2026-07-26-groundability-contract-design.md",status:"active",added:"2026-07-26",notes:"Groundability-contract Slice 2b (the realistic-authoring FIX; a flag-gated prototype \u2014 adding a model call to the authoring flow is Alex's architecture/graduation call). Default OFF; when ON adds ONE auxiliary Gemini call per COMPLETED explore that produced untyped verify criteria (batched, text-only, cost-isolated via emitAuxiliaryLlmUsage \u2014 not a billable step). Read site: packages/engine-core/src/ExplorerRuntime.ts assistant_v2_report accept seam (killSwitchEnabled('GROUNDED_STATE_FACTKIND_TYPING_PASS') \u2192 runFactKindTypingPass over draftTestCase.steps, mutating criteria in place BEFORE the report message is persisted/emitted, so the authored factKind rides both the saved plan and the diag). Pure module core (collectUntypedVerifyCriteria / buildFactKindTypingPrompt / mapTypesByIndex / applyFactKindTypes) + the single generateText seam. Unit suite: packages/engine-core/src/__tests__/factKindTypingPass.test.ts (ON fills missing factKind from a mocked typing response; OFF = no call / byte-identical; already-authored factKind never overwritten; error/empty response \u2192 factKind stays unset, fail-safe). RE-MEASURE: e2e/evals/plans/groundability-factkind-explored.ts COMMITTED_BASELINE carries the with-typing-pass authored-rate alongside the without (0/8).",graduation:{status:"gated",gate:"The realistic-authoring re-measure (groundability-factkind-explored with GROUNDED_STATE_FACTKIND_TYPING_PASS ON) shows the authored-factKind rate on the real explore path jump from ~0% to high (target near the probe 100%, \u2265~85%) with CORRECT kinds, AND the engine-core factKindTypingPass unit suite green (fill / no-overwrite / fail-safe / off-byte-identical). Graduation to any verdict path additionally requires GROUNDED_STATE_FACTKIND_AUTHORED (the consumer) to graduate under its own shadow-soak \u2014 this pass only PRODUCES the field.",evidence:"e2e/evals/plans/groundability-factkind-explored.ts with-typing-pass measuredAt entry (authored-rate + kind-correctness) + the engine-core factKindTypingPass unit suite + factkind_typing_pass diag events",owner:"steering (Alex)",review:"2026-08-15"}},GROUNDED_STATE_UNIFIED:{key:"GROUNDED_STATE_UNIFIED",envVars:["AGENTIQA_GROUNDED_STATE_UNIFIED","AGENTIQA_EXPERIMENT_GROUNDED_STATE_UNIFIED"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Trust-layer Slice 2 \u2014 PER-SNAPSHOT UNIFICATION (design docs/plans/2026-07-26-trust-layer-slice-2-per-snapshot-unification-design.md; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md). Collapses the three Slice-1 per-kind run_complete batches (runGroundedStateCounts / runGroundedStateExtractions / runGroundedStateDifferentials \u2014 each re-extracting once PER step/kind) into ONE task-blind extraction PER SNAPSHOT feeding ONE typed-comparator dispatch, and introduces the verdict SPECTRUM (Verified / Assessed / Inconclusive) + semantic matchType. SHADOW-ONLY: when on AND a stateExtractor is wired, it consumes the SAME escalation candidates the per-kind batches do (its flag is OR-ed into the maybeEmitVerifierEscalation candidate-recording seam), groups them by shared captured AFTER-frame (groupCandidatesBySnapshot \u2014 verify-steps sharing a frame with no intervening state-mutating action share ONE extraction; differential candidates additionally share ONE run-start baseline extraction), runs ONE extraction per unique frame, and for each candidate runs its typed comparator (compareCount / comparePresence / compareAbsenceDifferential / compareModificationDifferential) \u2014 or, for a matchType:'semantic' criterion, the task-blind concept classifier (deps.conceptClassifier) \u2014 against that shared extraction. It LOGS grounded_state_unified (band + shadowVerdict + parity vs the driver grade) + grounded_state_unified_start/_done (the extraction-vs-comparison counts that PROVE 1-extraction-per-snapshot); it mutates NO stepResult and changes NO verdict. Part B is a REFACTOR that must be verdict-PARITY with the three per-kind paths: the unified would-verdict equals what the retired per-kind batch logged (same evidence resolution + same target derivation + same deterministic comparator on the same extraction). The verdict spectrum: a deterministic comparator would_pass/would_fail \u2192 Verified (the no-false-positive guarantee); a low-confidence semantic result \u2192 Assessed (the SLOT only \u2014 the independent reasoned judge is a LATER slice); no confident extraction/classification / missing image / extractor abstain / error / timeout / unresolvable comparison / unavailable semantic classifier \u2192 the fail-closed Inconclusive floor, NEVER a pass. Task-blindness preserved: the extraction prompt (buildExtractionQuestion) carries observation targets only and the semantic classifier carries a concept + a neutral observation rendering \u2014 NEVER the expected values or pass/fail framing. It runs ALONGSIDE the per-kind batches (its own flag) so the shadow soak can prove parity BEFORE the per-kind methods are physically retired. Off \u21D2 zero candidate consumption here, zero extraction calls, byte-identical (the per-kind paths, if their flags are on, are untouched) (AC-6). Cost: #snapshots (+1 shared before, if any differential) extraction calls per run \u2014 strictly \u2264 the sum of the three per-kind batches, and 1 for N verify-steps on one screen.",designDoc:"docs/plans/2026-07-26-trust-layer-slice-2-per-snapshot-unification-design.md",status:"active",added:"2026-07-26",notes:"Trust-layer Slice 2 (per-snapshot unification). Default OFF; SHADOW-FIRST \u2014 even when ON it only computes + LOGS the would-be verdict-spectrum result and its parity vs the driver grade (grounded_state_unified / _start / _done diags), makes #snapshots (+1 shared before) extraction calls plus one concept-classifier call per semantic candidate (both cost-isolated Flash-model seams via emitAuxiliaryLlmUsage, hard-capped, batched under the same deadline as the per-kind batches), and changes NO verdict or stepResult. Sibling to GROUNDED_STATE_EXTRACT (S2) / GROUNDED_STATE_DIFFERENTIAL (S3) \u2014 it consumes the SAME candidate maps and reuses the SAME comparators, so its would-verdicts are byte-parity with the three per-kind batches (the Slice-2 acceptance gate). Requires deps.stateExtractor wired; a matchType:'semantic' criterion additionally requires deps.conceptClassifier (absent \u21D2 that candidate floors to Inconclusive). Read site: packages/engine-core/src/RunnerRuntime.ts (groundedStateUnifiedEnabled \u2192 the OR-ed candidate recording in maybeEmitVerifierEscalation + collectUnifiedCandidates + runGroundedStateUnified at run_complete); pure core (snapshot grouping / verdict spectrum / semantic mapping) in packages/engine-core/src/groundedStateUnified.ts. Acceptance tests: packages/engine-core/src/__tests__/groundedStateUnified.test.ts (pure \u2014 grouping, spectrum mapping, semantic mapping) + RunnerRuntime.groundedStateUnified.test.ts (wiring \u2014 verdict-PARITY vs the three per-kind batches, ONE extraction for N\u22653 verify-steps on one snapshot, semantic success\u2192Verified / ambiguous\u2192Assessed / error\u2192Verified-FAIL, shadow-no-mutation, flag-OFF byte-identical). Evals: e2e/evals/plans/trust-unified-parity.ts (runner-trust-unified-parity), trust-unified-batching.ts (runner-trust-unified-batching), trust-unified-semantic.ts (runner-trust-unified-semantic). The three per-kind batch methods are RETAINED in this slice as the parity oracle; their physical removal is the graduation follow-up. Binds claim verify.grounded-state-extract-then-compare.",graduation:{status:"gated",gate:"Slice 2 is shadow-first (no verdict change). Graduation gates on: (1) a staging verdict-PARITY shadow soak of grounded_state_unified vs the per-kind grounded_state_count / _extract / _differential diags showing ZERO would-verdict drift across the count / presence / absence / modification fixtures; (2) grounded_state_unified_done confirming extractions == #snapshots (+ shared before), NOT #comparisons (the batching win) in the field; (3) the semantic-matchType Assessed slot behaving (confident \u2192 Verified, ambiguous \u2192 Assessed, contradiction \u2192 Verified-FAIL) at an acceptable concept-classifier accuracy. ONLY after parity is proven do the three per-kind batch methods get physically retired (a separate refactor PR) and does advancing to a LIVE verdict path get considered \u2014 both separate steps from flipping this flag shadow-on.",evidence:"staging grounded_state_unified / _start / _done diag events (spectrum verdict + parity + extraction-vs-comparison counts) cross-checked against the per-kind diags for parity + the engine-core groundedStateUnified + RunnerRuntime.groundedStateUnified unit suites + the trust-unified-parity / -batching / -semantic evals + the claim verify.grounded-state-extract-then-compare",owner:"steering (Alex)",review:"2026-09-05"}},INTERACTION_CLEARS_PRESENCE_ORACLE:{key:"INTERACTION_CLEARS_PRESENCE_ORACLE",envVars:["AGENTIQA_INTERACTION_CLEARS_PRESENCE_ORACLE","AGENTIQA_EXPERIMENT_INTERACTION_CLEARS_PRESENCE_ORACLE"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Interaction-clears-presence-oracle (rank-2 of the step-5 slow-render flake wave, sibling to VERIFY_PRESENCE_WAIT_FLOOR's rank-1 budget raise). A verify-step PRESENCE wait oracle (wait_for_element) that STILL times out after the raised budget records an unresolved oracle failure that verify-gated-done only lets a fresh successful wait_for_element/run_js clear \u2014 a screenshot or a successful click is refused and the plan-grounded literal blocks canReconcileVerificationConflict \u2014 so a genuinely-present-but-slow element force-FAILs (staging sessions asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1, where the NEXT step's click_at('Blank board') SUCCEEDED and navigated). When on, a subsequent SUCCESSFUL deterministic click_at (or a type_text_at/set_focused_input_value write) on the current verify step or the one immediately preceding it (lookback 1) whose ENGINE-RESOLVED element identity (clickTarget.accessibleName/textContent for a ref/coordinate click, clickedElement.textContent for a label click, or typedIntoField \u2014 the resolved field's accessible name \u2014 for a type write; never the model's narration or the typed VALUE) whole-token-substantiates (citationSubstantiates \u2014 the SAME contiguous-token machinery pinPresentInPage uses, NOT substring) the failed wait's captured target literal CLEARS that step's wait-oracle failure \u2014 engine-observed, un-hallucinable proof of presence, strictly stronger than the screenshot the gate already refuses. HARD CONSTRAINTS (no false-PASS): whole-token resolved-name match only, gated by a SIGNIFICANCE floor (the wait literal must carry a \u22654-char token OR \u22652 tokens \u2014 a bare common single short token like \"ok\"/\"3\" whole-token-matches an unrelated control name too easily, so it can never clear); the #1476 real-hit guard (a coordinate no-op-success \u2014 noObservedEffect side channel \u2014 and a non-interactive pixel landing whose accessibleName merely mirrors a container's textContent are BOTH rejected, so a click that reports success but hit nothing cannot launder a miss); a type only ever clears when it genuinely resolved+focused a named field (typedIntoField populated \u2014 a blind write carries no identity); scope = wait-style presence oracle only (isVerificationOracleAction, NEVER the plan-derived pin-page-grounding oracle) on a Runner verify step; an ABSENCE-intent verify step (checkTextAssertsAbsence over the step text + criteria) is NEVER cleared \u2014 a successful interaction DISPROVES an absence assertion, so clearing would manufacture a pass on a real absence-violation bug; fail-closed (a genuinely-absent element cannot be successfully interacted with, and an ambiguous / non-matching / insignificant-literal / stale-beyond-lookback / absence-intent identity does NOT clear \u2014 the force-fail stands). SHADOW-FIRST: off (default) leaves every verdict identical (the force-fail stands) and only emits an `interaction_clears_presence_oracle:would_clear` diag of what it WOULD have cleared, so a staging soak can confirm it fires only on genuine presence before the flip; on makes the clear live (`\u2026:cleared`).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-25",notes:"Default OFF in code; detection runs in shadow always (interaction_clears_presence_oracle:would_clear diag), the actual clear is gated \u2014 the ABSENCE_AWARE_VERIFY / PIN_PAGE_GROUNDING shadow-first precedent. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add INTERACTION_CLEARS_PRESENCE_ORACLE to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/RunnerRuntime.ts (interactionClearsPresenceOracleEnabled \u2192 maybeInteractionClearsPresenceOracle, called from the browser-action dispatch after recordOffPlanResolvedClick). Resolved-identity sources: label click \u2192 response.clickedElement.text (clickByLabel only populates it after resolving exactly one clickable control by name AND clicking without error \u2014 un-hallucinable); ref/coordinate click \u2192 response.clickTarget.accessibleName/text, admitted ONLY when isInteractiveClickTarget(clickTarget) so a pixel that landed on a text container cannot launder via the accessibleName\u2192textContent fallback; type write (type_text_at / set_focused_input_value) \u2192 response.typedIntoField (getFocusedFieldName \u2014 the accessible name of the field the write actually resolved+focused; the typed VALUE is never an identity). SIGNIFICANCE floor (waitLiteralHasSignificantTokens over the same tokenizeCitation basis the match uses): a bare common single short token (a status word, a lone digit) whole-token-matches an unrelated resolved name too easily, so the wait literal must carry a \u22654-char token OR \u22652 tokens or it never clears. Lookback is intentionally tight (1 step) to keep a stale REAL miss from an earlier step from being laundered by a same-named element that appears much later; a soak may widen it. Absence-intent verify steps are excluded via checkTextAssertsAbsence (a successful interaction disproves an absence assertion \u2192 would be a false-PASS); a suppressed match emits interaction_clears_presence_oracle:absence_skip. Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.interactionClearsPresenceOracle.test.ts (flag-OFF shadow-only + byte-identical for both click and type, flag-ON label + ref + type clear, type resolved-different-field reject, type-with-no-resolved-field reject, significance-floor bare-one-token reject, #1476 no-op reject, non-interactive container-text reject, non-matching-element reject, whole-token-not-substring, genuinely-absent still-fails, absence-intent step NEVER cleared, pin-page-grounding scope guard, cross-step lookback bound).",graduation:{status:"gated",gate:"Staging shadow soak clean (interaction_clears_presence_oracle:would_clear fires ONLY where a successful click genuinely resolved+acted on an element whose engine-resolved identity whole-token-matches the failed wait literal \u2014 never on a #1476 coordinate no-op, a non-interactive container-text mirror, an absence-intent verify step, or a stale failure beyond the 1-step lookback) AND the engine-core interaction-clears-presence-oracle detection-inversion passes (flag OFF \u2192 the timed-out presence step still force-FAILs; flag ON \u2192 a matching successful click clears it to a PASS, a no-op/non-matching/absent/absence-intent element still FAILs)",evidence:"staging interaction_clears_presence_oracle:would_clear / :cleared diag events (clear rate + resolvedVia/literal breakdown) + the RunnerRuntime.interactionClearsPresenceOracle unit suite + the step-5 slow-render rehearsal replay (asess_1784961071757_cqwxon46 / asess_1784960734951_4t0zaxp1)",owner:"steering (Alex)",review:"2026-08-01"}},CANVAS_STRATEGY:{key:"CANVAS_STRATEGY",envVars:["AGENTIQA_CANVAS_STRATEGY","AGENTIQA_EXPERIMENT_CANVAS_STRATEGY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Enables the canvas-app (Miro/Figma/spreadsheet) per-turn strategy prompt injection and the coordinate-action tool-result caveat; off drops both so a false canvas classification cannot alter targeting guidance.",designDoc:"docs/plans/2026-07-06-canvas-capability-design.md",status:"active",added:"2026-07-06"},SCREENSHOT_DIRECT_UPLOAD:{key:"SCREENSHOT_DIRECT_UPLOAD",envVars:["AGENTIQA_SCREENSHOT_DIRECT_UPLOAD","AGENTIQA_EXPERIMENT_SCREENSHOT_DIRECT_UPLOAD"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Analytics-sink screenshot upload path: on, the sink fetches a presigned R2 PUT URL from /api/analytics/presign-screenshot and PUTs the PNG straight to R2 (bytes never transit web-next); "0" forces the legacy base64 /api/analytics/upload-image route. On any presign/PUT failure the sink falls back to the legacy route per-screenshot regardless of this switch.',designDoc:"packages/engine-core/src/sinks/RemoteAnalyticsSink.ts",status:"active",added:"2026-07-19"},SAME_GOAL_ABORT:{key:"SAME_GOAL_ABORT",envVars:["AGENTIQA_SAME_GOAL_ABORT","AGENTIQA_EXPERIMENT_SAME_GOAL_ABORT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Escalates consecutive milestone-free supervisor REDIRECT verdicts into an abort-then-block, bounding a stuck same-goal step; off leaves the supervisor redirecting until the iteration budget runs out.",designDoc:"docs/plans/2026-07-06-canvas-capability-design.md",status:"active",added:"2026-07-06"},TARGET_CONTAINMENT:{key:"TARGET_CONTAINMENT",envVars:["AGENTIQA_TARGET_CONTAINMENT","AGENTIQA_EXPERIMENT_TARGET_CONTAINMENT"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Keeps the agent within the app-under-test origin at every navigation chokepoint; off makes every boundary check return "allow" (pre-containment behavior).',designDoc:"packages/engine-core/src/BasePlaywrightService.ts",status:"active",added:"2026-07-05"},PIN_SUBSTANTIATION:{key:"PIN_SUBSTANTIATION",envVars:["AGENTIQA_PIN_SUBSTANTIATION","AGENTIQA_EXPERIMENT_PIN_SUBSTANTIATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Flips a criterion the model graded "passed" to failed when the pinned expected value is not substantiated; off returns the model grade verbatim (pins still render, enforcement is off).',designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-07"},PIN_CROSS_STEP_SUBSTANTIATION:{key:"PIN_CROSS_STEP_SUBSTANTIATION",envVars:["AGENTIQA_PIN_CROSS_STEP_SUBSTANTIATION","AGENTIQA_EXPERIMENT_PIN_CROSS_STEP_SUBSTANTIATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:`FIX 3 (extends FIX 2 to the cross-STEP misattribution class). Before Amendment 5a synthesizes a strict pinned criterion as "never graded \u2192 unconfirmed \u2192 fail", it searches EARLIER step entries for an ORPHAN grade of the IDENTICAL check \u2014 graded passed=true, bound to NONE of its own step's plan criteria, and whose observed value substantiates THIS pin's expectedValue (the SAME substantiatePinnedCriterion gate). A match means the grading LLM misfiled the pin under a PRECEDING/action step (prod asess_1785211658727: step 2's 3 strict pins graded inside step 1, an action step), so the pin was really evaluated \u2014 the substantiated pass is relocated to its own slot instead of false-failing the step. Off restores FIX 2 behavior verbatim (no cross-step search). The rescue is SCOPED to misattributed grades, not a blanket 'a passing grade exists elsewhere': (1) only orphan grades qualify \u2014 a step's OWN bound verdict is never borrowed, so a still-passing earlier verify cannot mask a later regression; (2) a contradicting FAILING grade for the same check anywhere blocks the rescue; (3) only a STRICTLY EARLIER step's grade qualifies, so a later step's page state is never laundered backward onto an earlier assertion (a backward misattribution stays fail-closed); (4) the caller only rescues a pin unique among plan verify criteria. Outside that envelope the pre-existing fail-closed synthesis stands. EVIDENCE-EPOCH DISPOSITION (steering 2026-07-28): 'strictly earlier' does not mean 'same page state', so a rescue is only a silent PASS when NO state-changing plan step (type action/setup) sits STRICTLY BETWEEN the rescuing entry and the pin's own step \u2014 the confirmed prod shape (verify step k's grades misfiled under the immediately preceding action step k-1) has nothing in between, so it keeps its full PASS rescue. A STALE-FORWARD rescue (an intervening action/setup broke the epoch, so the observation may predate a regression) is instead SOFT-WITHHELD to a step-level 'warning' \u2014 the criterion carries the substantiated pass noted 'substantiated by an earlier-step grade; not re-verified at this step' and the step is demoted passed->warning (never a hard fail, never a clean pass; run status is untouched since only 'failed' steps downgrade a run). This is the ABSENCE_AWARE_VERIFY-ABSTAIN / GROUNDING_EPOCH_FIDELITY withhold rail: the criterion stays passed:true on purpose, because flipping it would route deriveStepStatusFromCriteria to a hard 'failed' on a strict criterion (warning-cap-only). Every accepted rescue emits RunnerRuntime log pin_cross_step_substantiated {stepIndex, sourceStep, expected, orphanCandidates, corpusSize, reason} for prod frequency/provenance, where reason is 'same-epoch-rescue' (PASS) or 'stale-forward-warning' (withheld). SHARED BINDER (round 4): the orphan test (guard 1) READS the already-computed per-entry bindings from bindGradesToPlanSlots \u2014 the ONE authoritative two-pass binder that also drives FIX 2's cross-entry union and the reported criteria results \u2014 and never re-derives them. An earlier revision ran its own SEQUENTIAL bindGradeToPlanIdx loop, which diverges from the two-pass binder wherever a rephrased grade's positional fallback would steal a slot a later grade matches by exact text: the authoritative binder books that grade onto its own step (non-orphan) while the sequential mirror leaves it unbound (orphan) and thus eligible to rescue another step's pin \u2014 an EMERGENT false-PASS reachable only with PIN_CROSS_STEP_SUBSTANTIATION and CRITERION_BIND_RESIDUAL both on, which each flag's own tests miss. Pinned by a 4-cell flag-matrix test. PER-CRITERION FLOOR (round 4): the rescue pushes a synthetic passed result, which switched OFF the whole-step zero-grade 'unsubstantiated verify' floor (that floor tests criteriaResults.length === 0) for the step's OTHER criteria \u2014 and Amendment 5a itself only covers PINNED strict criteria, so a plain strict criterion beside a rescued pin was adjudicated by nothing and rode through on the reported 'passed'. On steps where a rescue fired, each plan criterion that is in neither the FIX 2 union nor Amendment 5a's coverage AND has no matching grade anywhere in the cross-step corpus now synthesizes its own failure (strict) or warning (strict:false), emitting pin_cross_step_sibling_unsubstantiated {stepIndex, check, strict, rescuedPinsOnStep}. Scoped to rescue-touched steps so no untouched verdict moves, and gated on 'ungraded ANYWHERE' so the whole-step misattribution the rescue tolerates is not re-punished.`,designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-28"},CHECK_TEXT_ATOM_PIN:{key:"CHECK_TEXT_ATOM_PIN",envVars:["AGENTIQA_CHECK_TEXT_ATOM_PIN","AGENTIQA_EXPERIMENT_CHECK_TEXT_ATOM_PIN"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"run_complete grade-time atom pinning: a strict verify criterion whose check text pins exactly one URL literal (http(s):// or bare localhost) and carries no expectedValue has that literal promoted to an effective expectedValue so the pin-substantiation / grounding machinery fires on it, plus a deterministic URL-host floor that fails the criterion closed (naming both hosts) when the evidence observes a different-host URL and preserves the pass on a scheme-only / trailing-slash difference \u2014 regardless of what the substantiation/drift judge decided. Off leaves a bare {check, strict} URL criterion ungraded past the model self-grade (pre-feature behavior).",designDoc:"docs/plans/2026-07-19-ag7727-run-fidelity-fixes-design.md",status:"active",added:"2026-07-19"},TYPED_MATCH:{key:"TYPED_MATCH",envVars:["AGENTIQA_TYPED_MATCH","AGENTIQA_EXPERIMENT_TYPED_MATCH"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Routes pin-substantiation's observed-vs-expected comparison through the typed match-comparator registry keyed on a criterion's `matchType` (country ISO-3166 fold DE\u2261Germany, locale numeric equality); a typed match keeps a pass the brittle literal compare would have flipped, a typed mismatch (wrong country) flips closed. Off (or an absent/`literal` matchType) restores the pure literal `citationSubstantiates` behavior verbatim \u2014 inert until a criterion carries a matchType, so this only removes a false-fail class, never changes an untyped verdict (AG-7753).",designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-20"},COUNTRY_EQUIV_RESCUE:{key:"COUNTRY_EQUIV_RESCUE",envVars:["AGENTIQA_COUNTRY_EQUIV_RESCUE","AGENTIQA_EXPERIMENT_COUNTRY_EQUIV_RESCUE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'C2 country-equivalence rescue in run_complete pin substantiation: when an already model-PASSED strict criterion\'s literal citation fails, the citation is retried with every recognized country surface form on BOTH sides folded to its ISO-3166 alpha-3, so an address that differs ONLY by country NAME vs CODE ("\u2026H\xF6henkirchen Germany" pin vs "\u2026H\xF6henkirchen DE" observed, prod Lio tp_5a2a7f4c step 9) substantiates instead of brittle-failing. Narrowly scoped: the rescue runs only for a country-SHAPED pin \u2014 `matchType: \'country\'`, or (untyped/literal/text-normalized/presence) a pin whose TERMINAL token is a full country NAME or alpha-3; a bare terminal alpha-2 pin ("Dover, DE") and every number/currency/url/semantic matchType are excluded. The fold itself only rewrites a country NAME anywhere, and a country CODE only as an uppercase token in the terminal country slot (never before a US zip), with subdivision/unit collisions (CA/NL/GB/CH/IE/PL/PT/SE/IN/CAN/NOR/\u2026) restricted to a sole-token read. That extra ambiguity is FOLD-SCOPED (`FOLD_AMBIGUOUS_ALPHA2`/`FOLD_AMBIGUOUS_ALPHA3`): the shared gazetteer read by citedCountry/compareTyped \u2014 i.e. the typed-atom floor and the predicate-basis typed comparator, neither of which this switch gates \u2014 is untouched BY THIS FLAG, verified by a differential sweep of the whole gazetteer. Off restores the pure literal `citationSubstantiates` verdict, so this flag only ever removes a false-FAIL class and nothing this flag contributes survives turning it off. NOTE (AG-8212, 2026-07-29) \u2014 that is a statement about THIS flag, not about the comparator stack as a whole: the OBSERVED scan has since gained its own ungated guard (the same eight collision-prone alpha-2 codes are now gated in citedCountry too, so a bare code buried in prose resolves a country only when a full NAME corroborates it or when it is the sole token), which this switch does not gate and cannot revert. The fold path and both fold-ambiguity sets remain pre-C2 byte-identical, and the AUTHORED read (`citedCountryAuthored`, what the typed-atom floor recognizes the author\'s check text with) is unchanged. Split out of TYPED_MATCH (which stays inert on untyped criteria) because this rescue fires on criteria that carry NO matchType.',designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-28"},TYPED_ATOM_FLOOR:{key:"TYPED_ATOM_FLOOR",envVars:["AGENTIQA_TYPED_ATOM_FLOOR","AGENTIQA_EXPERIMENT_TYPED_ATOM_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"AG-7753 Phase 2 strict-unpinned typed-atom floor. run_complete detection ALWAYS runs (shadow): for a strict verify criterion the model graded passed that carries NO expectedValue and whose check text names exactly one recognized typed atom (country ISO-3166 / currency ISO-4217 / number \u2014 the generalization of #1685's URL host floor), the page-read observed value (a11y snapshot, else the structured `observed` grade field; disagreement \u2192 abstain) is compared to the recognized expectation via compareTyped. On a same-type MISMATCH (France where Germany expected) it emits a shadow `typed_atom_floor:would_fail` diag; when this flag is ON it ENFORCES \u2014 flipping the criterion passed\u2192false (only-fails, never originates a pass) and emitting `typed_atom_floor:fire`. Off leaves every verdict byte-identical (shadow diag only). URL stays owned by CHECK_TEXT_ATOM_PIN \u2014 a URL-bearing check is not recognized here.",designDoc:"docs/plans/2026-07-20-typed-match-comparator-design.md",status:"active",added:"2026-07-20",notes:"GRADUATED 2026-07-21 (default on) via the evidence-count doctrine: detection-inversion PROVEN twice \u2014 deterministically in RunnerRuntime.typedAtomFloor.test.ts (33 assertions) and live in the runner/typed-atom-country-floor L3 eval (qa-exhaustive 29861680933: seeded wrong-country step correctly failed) after the self-testing fixture deploy was unblocked (productionBranch was pinned to main). Shadow soak was clean but thin (organic staging plans carry no recognizable unpinned atoms \u2014 vacuous-soak class). Enforcement only-fails a same-type mismatch, never originates a pass. Distinct from TYPED_MATCH (Phase 1, default ON, pinned-criterion fold) and CHECK_TEXT_ATOM_PIN (#1685, URL host floor). Runner lane only (RunnerRuntime run_complete)."},COMPLETION_EVIDENCE_FLOOR:{key:"COMPLETION_EVIDENCE_FLOOR",envVars:["AGENTIQA_COMPLETION_EVIDENCE_FLOOR","AGENTIQA_EXPERIMENT_COMPLETION_EVIDENCE_FLOOR"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Completion-evidence floor for the CHAT/CLI objective lane (the ungrounded-ship seam VERIFY_GATED_DONE misses: it fires only on a failed wait-oracle in the last 5 actions, so a fabricated value with no failing wait ships silently). Detection ALWAYS runs (shadow) at ExplorerRuntime.handleReport on a terminal `completed` report: for an evidence-bearing objective (find/copy/extract a named value) it grounds the agent's TYPED CLAIM (the optional `extractedValues` field on the assistant_v2_report payload; free-text is never parsed): a claimed value found nowhere in the runtime a11y-snapshot corpus nor in runtime_observed revealed facts (whole-token `citationSubstantiates` \u2014 free-form; `compareTyped`'s closed grammar does NOT apply) emits a shadow `completion_grounding:would_demote` diag; a completed extraction objective with NO typed claim is shadow-only signal (reason no_typed_claim) and is NEVER enforced. Label-presence in the corpus never substantiates a value (v1.1). When this flag is ON it ENFORCES the typed-claim-fabrication path only \u2014 attaching an Explorer `VerificationConflict` with the NEW source `completion_ungrounded` (own card copy; NO terminal blockKind) that the existing verification-conflict rail (`applyVerificationConflictFindings` / `focusedTaskVerdictRecommendation`) demotes to do_not_ship in BOTH Coordinator producers. ABSTAINS (never demotes) when the objective is not evidence-bearing, the target is undecidable, or the observed corpus is thin/absent (canvas/off-DOM/dynamic value not in the snapshot) \u2014 demote-on-absence must abstain on any evidence-availability gap (blind-double-read precedent). Off leaves every verdict byte-identical (shadow diag only). Distinct from TYPED_ATOM_FLOOR (runner lane, closed-grammar value mismatch); this is the chat-lane grounding net (absence of any observed evidence, not value-correctness).",designDoc:"docs/plans/2026-07-21-completion-evidence-floor-design.md",status:"active",added:"2026-07-21",notes:"Default OFF in code; detection runs in shadow always (would_demote diag), enforcement is gated \u2014 the PIN_PAGE_GROUNDING / TYPED_ATOM_FLOOR shadow-first precedent. Single Explorer-level hook (handleReport) so both Coordinator verdict producers surface it (the cross-producer parity bug class, PR #643). Chat/Explorer lane only (assistant_v2_report). v1.1: enforcement requires a typed extractedValues claim proven absent from corpus+facts (provable fabrication); strict-extraction recognizer with common-UI-word stoplist (generic read/find objectives abstain); no-typed-claim path stays shadow-only so the soak measures claim-population rate. Grounds fabrication of a claimed value, NOT mis-selection of a real-but-wrong on-page value.",graduation:{status:"gated",gate:"Staging shadow soak clean (would_demote fires on the wandering-maze fabricate-and-ship replicates, zero would_demote on legitimately-shipping value-extraction controls) AND the engine-core completion-evidence-floor detection-inversion passes (floor OFF \u2192 fabricate-and-ship rides through as ship, ON \u2192 do_not_ship on the identical input in BOTH producers)",evidence:"staging completion_grounding:would_demote diag events + the engine-core completion-evidence-floor unit suite + the loop-detection/wandering-self-stop flag-ON graduation run",owner:"steering (Alex)",review:"2026-07-23"}},SETUP_NOTE_GROUNDING:{key:"SETUP_NOTE_GROUNDING",envVars:["AGENTIQA_SETUP_NOTE_GROUNDING","AGENTIQA_EXPERIMENT_SETUP_NOTE_GROUNDING"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Setup/action step-note grounding \u2014 surface S-A of the substantiation-fidelity (\"honest words\") track. Detection ALWAYS runs (shadow) at RunnerRuntime run_complete, after substantiation + the typed-atom floor: for each setup/action step (verify steps out of scope) graded passed/warning whose NOTE names a completed UI action (a closed past-tense/gerund verb lexicon \u2014 entered/typed/filled/submitted/clicked/selected/uploaded/dragged/\u2026) it checks the step's own planStepIndex-stamped action-tool window; a note asserting an action with ZERO grounding action tool calls in-window (the census shape asess_1784714866561_jhc34ht9 \u2014 pre-authed login steps graded green with 'Entered the email'/'Submitted the login form' notes and no type_*/click ever fired) emits a shadow `narration_fidelity:would_flag{surface:'setup_note', stepIndex, claim, missing_action, toolCallsInWindow}`. ABSTAINS (never flags) on a verify/read-only step, a note with no action verb, a non-terminal grade, or a window carrying ANY grounding action tool \u2014 ambiguity always abstains (closed allowlist). When this flag is ON it ENFORCES honest note substitution \u2014 the fabricated action clause is replaced with an honest precondition note; the step's verdict/status is UNTOUCHED (never a hard fail \u2014 the precondition was met, just not by the asserted action). Off leaves every stepResults note byte-identical (shadow diag only). Distinct from TYPED_ATOM_FLOOR (verify-criterion value mismatch) and COMPLETION_EVIDENCE_FLOOR (chat-lane claimed-value fabrication); this grounds SETUP/ACTION step NARRATION against the action log.",designDoc:"docs/plans/2026-07-22-substantiation-fidelity-design.md",status:"active",added:"2026-07-22",notes:"Default OFF in code; detection runs in shadow always (would_flag diag), enforcement (honest note substitution) is gated \u2014 the COMPLETION_EVIDENCE_FLOOR / TYPED_ATOM_FLOOR shadow-first precedent. Single RunnerRuntime run_complete pass (mirrors the typed-atom floor shadow). Deterministic \u2014 ~zero marginal LLM cost (reads the already-collected stepResults notes + the planStepIndex-stamped action-message log). P0 of the substantiation-fidelity track (S-A); S-B/S-C/S-D are separate per-phase flags.",graduation:{status:"gated",gate:"Staging shadow soak clean (narration_fidelity:would_flag{surface:'setup_note'} fires on the census-shaped reproduced-RED fixture, zero would_flag on legitimately-honest action notes whose tool call fired) AND the engine-core setupNoteGrounding detection-inversion passes (rip the pass out \u2192 the fixture stops flagging; enforce-ON rewrites the note, verdict untouched, on the identical input)",evidence:"staging narration_fidelity:would_flag diag events + the engine-core setupNoteGrounding + RunnerRuntime.setupNoteGrounding unit suites + the runner/narration-ghost-setup reproduced-RED eval",owner:"steering (Alex)",review:"2026-07-29"}},GROUNDING_EPOCH_FIDELITY:{key:"GROUNDING_EPOCH_FIDELITY",envVars:["AGENTIQA_GROUNDING_EPOCH_FIDELITY","AGENTIQA_EXPERIMENT_GROUNDING_EPOCH_FIDELITY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Criterion grounding-epoch fidelity \u2014 surface S-B of the substantiation-fidelity (\"honest words\") track. Detection ALWAYS runs (shadow) at RunnerRuntime run_complete, after substantiation + grounding + the typed-atom floor: for each verify-step criterion substantiated as PASSED it compares the criterion's grounding epoch (the monotonic capture/generation index at which its pinned value was actually groundable in a full page snapshot) against the step's OWN verify-time epoch. A value groundable ONLY in a STRICTLY-LATER capture \u2014 a subsequent step's / a different entity's snapshot \u2014 is cross-entity-deferred grounding (the census asess_1784714866561_jhc34ht9 step 6: base-draft pins pin_page_grounding:would_fail at the step's own epoch, then matched off the duplicate-draft (e674/e731) and submitted-request (e1337) snapshots, all past the base-draft epoch) and emits a shadow `narration_fidelity:would_flag{surface:'grounding_epoch', stepIndex, criterion, groundingEpoch, stepEpoch, epochDriftRefs}`. ABSTAINS (never flags) on a value grounded at/before the step's own epoch (honest same-epoch grounding, or a legitimately-earlier carried observation), an explicitly carried-forward observation with recorded provenance, a criterion that did not pass, or an UNDETERMINED epoch (a missing epoch never manufactures a flag). When this flag is ON it ENFORCES via the existing VERIFY_REOBSERVE_WITHHOLD soft-withhold rail: the cross-entity-grounded criterion is treated as UNCONFIRMED and routed to a warning (never a red fail \u2014 the values may be correct; the fix removes the false EVIDENCE ATTRIBUTION, not the pass). Off leaves every verdict byte-identical (shadow diag only). Distinct from PIN_PAGE_GROUNDING (value ABSENCE at grade time) and SETUP_NOTE_GROUNDING (setup/action step NARRATION); this grounds a verify criterion's EVIDENCE-EPOCH provenance.",designDoc:"docs/plans/2026-07-22-substantiation-fidelity-design.md",status:"active",added:"2026-07-23",notes:"Default OFF in code; detection runs in shadow always (would_flag diag), enforcement (soft-withhold to warning via VERIFY_REOBSERVE_WITHHOLD) is gated \u2014 the COMPLETION_EVIDENCE_FLOOR / SETUP_NOTE_GROUNDING shadow-first precedent. Single RunnerRuntime run_complete pass (mirrors the setup-note-grounding shadow). Deterministic \u2014 ~zero marginal LLM cost (reconstructs each step's own capture epoch + each pinned value's grounding epoch from the retained per-generation full snapshots collected during the run). P1 of the substantiation-fidelity track (S-B); S-A (SETUP_NOTE_GROUNDING) shipped P0, S-C/S-D are separate flags.",graduation:{status:"gated",gate:"Staging shadow soak clean (narration_fidelity:would_flag{surface:'grounding_epoch'} fires on the census-shaped A\u2192duplicate-B reproduced-RED fixture, zero would_flag on same-epoch honest grounding controls) AND the engine-core groundingEpochFidelity detection-inversion passes (rip the drift out \u2192 the fixture stops flagging; enforce-ON soft-withholds the criterion to warning, never red, on the identical input)",evidence:"staging narration_fidelity:would_flag diag events + the engine-core groundingEpochFidelity + RunnerRuntime.groundingEpoch unit suites + the runner/narration-grounding-epoch reproduced-RED eval",owner:"steering (Alex)",review:"2026-07-30"}},NOTE_CONTRADICTION_FLOOR:{key:"NOTE_CONTRADICTION_FLOOR",envVars:["AGENTIQA_NOTE_CONTRADICTION_FLOOR","AGENTIQA_EXPERIMENT_NOTE_CONTRADICTION_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Terminal-error verdict-honesty Layer A \u2014 the deterministic note-contradiction floor (run_27825c90). Detection ALWAYS runs (pure module) at RunnerRuntime run_complete, LAST \u2014 after every fail gate: for a step the model graded `passed` carrying a passed criterion whose OWN note/groundingObservation text contains a conservative error marker (error/failed/failure/timeout/timed out/aborted/exception/went wrong, word-boundary) that the criterion's own check/expectedValue (or its step text) does NOT license, it caps that step to `warning` with an explanatory note. A marker GOVERNED BY A NEGATOR in the same clause (no/not/never/without/none/zero/didn't/no longer/free of/\u2026 \u2014 see NEGATOR_RE) is BENIGN and never caps ('No error appeared', 'verified no timeout occurred'), so a note that negates every marker is skipped; a note that re-asserts an error after negating one ('no error at first, then Error: timeout appeared') still caps. ONE-DIRECTIONAL \u2014 only caps a passed step (never rescues/escalates a model-failed grade; the criterion result stays passed, the STEP status is soft-withheld like VERIFY_REOBSERVE_WITHHOLD). Check-text licensing is dumb-string (accepts the documented `verify NO error` negation blind spot on the CHECK \u2014 Layer B handles it semantically). This flag ALSO gates the deterministic report_issue verdict-bearing fold (decision 6): a high/medium-severity `logical` issue filed during an otherwise-clean `passed` run caps the run at `warning`. When ON it ENFORCES; off \u21D2 `note_contradiction:would_cap` / `report_issue_contradiction:would_cap` diags and every verdict byte-identical. Distinct from Layer B (TERMINAL_ERROR_FLOOR, a model terminal-screen read). Ships default-ON (the trap eval's warning-cap signature only greens with both floors live).",designDoc:"docs/plans/2026-07-23-terminal-error-verdict-honesty-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception (not graduated from an off default) \u2014 registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED. Deterministic (~zero marginal LLM cost \u2014 scans the already-collected stepResults notes + grounding observations). Pure logic in packages/engine-core/src/noteContradictionFloor.ts; applied at RunnerRuntime run_complete AFTER all fail gates so it only ever touches a still-passed step. Runner lane only. Layer A of the terminal-error wave; TERMINAL_ERROR_FLOOR is Layer B."},TERMINAL_ERROR_FLOOR:{key:"TERMINAL_ERROR_FLOOR",envVars:["AGENTIQA_TERMINAL_ERROR_FLOOR","AGENTIQA_EXPERIMENT_TERMINAL_ERROR_FLOOR"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Terminal-error verdict-honesty Layer B \u2014 one unconditional terminal-screen model read per plan run (run_27825c90). At RunnerRuntime run_complete (LAST, after every fail gate) the terminal capture plus the plan's step texts are sent through the existing `deps.blindReader` seam, asked whether an app error/failure state is visible that no plan step asserts. The terminal frame is selected DELIBERATELY from the in-memory `_screenshots` ledger (NOT R2 \u2014 works in the anonymous eval lane where imageStorage is null): the LAST full-frame capture (crops and post-upload shots are skipped; each push site is kind-tagged), abstaining when none exists or when it predates the last browser action (stale). Licensing is SEMANTIC (the reader sees the step texts, so it handles negation like `verify NO error is shown`). An unlicensed visible error \u21D2 cap the run at `warning` by demoting the highest-index PASSED step (via capRunToWarning \u2014 never a skipped/failed step; when a sibling floor already capped the terminal step, the quote is appended, not double-capped) and quote the error text in the step note + run summary. Reader unavailable / no full-frame / stale frame / non-answer / licensed error \u21D2 abstain no-op (never a new false-fail). ONE-DIRECTIONAL (only caps a still-passed step; the binary run status never flips \u2014 `warning` is the step-level/derived aggregate). When ON it ENFORCES; off \u21D2 `terminal_error:would_cap` shadow, no cap. This is the ONLY layer that fires when the model never transcribes the banner into any note (the incident shape). Distinct from Layer A (NOTE_CONTRADICTION_FLOOR, deterministic note scan). Ships default-ON.",designDoc:"docs/plans/2026-07-23-terminal-error-verdict-honesty-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception \u2014 registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED. Cost \u2248 one cheap Flash vision call per plan run (the cost-isolated blindReader model, same as BLIND_DOUBLE_READ). Detection (the read) runs whenever a reader + final capture are available so the switch shadows (`terminal_error:would_cap`) when off; a later cost-driven change could guard the call on the flag. Pure prompt/interpretation in packages/engine-core/src/terminalErrorFloor.ts. Runner lane only. Layer B of the terminal-error wave; NOTE_CONTRADICTION_FLOOR is Layer A + the report_issue fold."},BLIND_DOUBLE_READ:{key:"BLIND_DOUBLE_READ",envVars:["AGENTIQA_BLIND_DOUBLE_READ","AGENTIQA_EXPERIMENT_BLIND_DOUBLE_READ"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"When on, run_complete independently re-reads the persisted evidence screenshot for each pinned criterion that survived substantiation as passed (a blind LLM read that never sees the expected value) and flips the pass to failed when the observed value does not match the pin; abstains (no-op) on missing image / R2 read failure / reader non-answer / batch timeout. Off makes zero extra LLM calls and leaves every verdict unchanged.",designDoc:"docs/plans/2026-07-15-blind-double-read-design.md",status:"active",added:"2026-07-15",notes:"Default OFF in code; forced ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_BLIND_DOUBLE_READ=1) \u2014 the exact GROUNDED_EXPECTATIONS precedent. Prod enablement is a later explicit flip after nightly baselines. Runner lane only (RunnerRuntime run_complete).",graduation:{status:"gated",gate:"HARDENED 2026-07-21: BDR must actually FIRE (reads>0) and FLIP on runner/blind-read-conflation-trap \u2014 not merely avoid errors. BLOCKED on the evidence-resolution gap: on the conflation trap BDR abstained missing_image (resolveEvidenceMessage found no hasScreenshot+planStepIndex message \u2014 the model graded from the inline tool-result snapshot, which is never persisted as a screenshot message) and the seeded false-pass shipped (qa-exhaustive 29861680933). Fix = guarantee a planStepIndex-stamped verify screenshot (STEP_MARKER_FOLD stamping path is the natural vehicle \u2014 same root as the run-detail evidence-fidelity gap) or broaden resolveEvidenceMessage fallback. Plus: no new false-FAIL class on nightly runner baselines (MET as of 07-21; abstains acceptable). tp_00b325d5 confirm-path re-verified 07-21 (2 reads/2 confirms/0 flips).",evidence:"runner/blind-read-{parroting,conflation}-trap eval verdicts (conflation must flip) + blind_double_read diag events + nightly runner baselines",owner:"steering (Alex)",review:"2026-07-28"}},NEVER_GRADED_RETRY:{key:"NEVER_GRADED_RETRY",envVars:["AGENTIQA_NEVER_GRADED_RETRY","AGENTIQA_EXPERIMENT_NEVER_GRADED_RETRY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'When on (and a criterionRegrader is wired at engine boot), run_complete re-asks the grader ONCE for a STRICT pinned required criterion that NO stepResults entry graded (genuine model-omission \u2014 absent from the FIX 2 cross-entry union) before Amendment 5a synthesizes its "never graded \u2192 unconfirmed \u2192 fail". The returned grade is fed through the SAME substantiatePinnedCriterion gate, so only a re-grade that independently CITES the pinned value rescues the pin to passed; a returned FAIL, an unsubstantiated pass, or an abstain (no image / read failure / non-answer / error / batch timeout) leaves the "never graded" fail byte-identical. Cap ONE retry per pin, no loops. Off makes zero extra LLM calls and leaves every verdict unchanged.',designDoc:"docs/plans/2026-07-27-never-graded-retry-design.md",status:"active",added:"2026-07-27",notes:"Default OFF in code; force ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_NEVER_GRADED_RETRY=1) \u2014 the BLIND_DOUBLE_READ / GROUNDED_EXPECTATIONS shadow-first precedent. Prod enablement is a later explicit flip after a benchmark + staging soak. Runner lane only (RunnerRuntime run_complete, buildRunnerDeps.getCriterionRegrader \u2014 the SAME cost-isolated Flash model as blindReader; child Runners on the web-coordinator lane do not receive it yet, mirroring blindReader's own coordinator-forward gap). COMPOSES with (does not regress) PR #1884 FIX 2: the retry fires ONLY on pins genuinely absent from the cross-entry union FIX 2 computes, i.e. exactly the omission FIX 2 deliberately left as a fail. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add NEVER_GRADED_RETRY to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/RunnerRuntime.ts (neverGradedRetryEnabled \u2192 runNeverGradedRetries). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.neverGradedRetry.test.ts.",graduation:{status:"gated",gate:"FIRST SLICE = build + unit (this PR): shadow behind the default-OFF flag, byte-identical when off, fail-closed-safe (retry never manufactures a pass; a genuinely-ungraded-after-retry pin still fails). GRADUATION (later, separate slices) needs: (1) a kind-agnostic graduation benchmark (e2e/benchmark/, the ABSENCE_AWARE_VERIFY #1857 precedent) showing the Lio-s2 omission false-FAIL class is rescued to PASS with 0 new false-PASS and 0 regressions on the runner corpus, adversarially proven able to say NO-GO; (2) a staging shadow/force-ON soak measuring re-grade fire rate + rescue vs abstain vs still-fail; (3) parity when BLIND_DOUBLE_READ is also on; (4) gate-review sign-off (Alex).",evidence:"never_graded_retry:{start,rescue,abstain,still_fail} diag events + the graduation benchmark verdict + a staging soak on re-grade outcomes",owner:"steering (Alex)",review:"2026-08-03"}},EVIDENCE_FIDELITY:{key:"EVIDENCE_FIDELITY",envVars:["AGENTIQA_EVIDENCE_FIDELITY","AGENTIQA_EXPERIMENT_EVIDENCE_FIDELITY"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"P0 of the evidence-fidelity ('honest pictures') design: makes full_page_screenshot honest. When on, BasePlaywrightService.fullPageScreenshot climbs a capture ladder (document_full \u2192 cdp_full \u2192 scroll_stitch \u2192 viewport_degraded) so an inner-overflow layout (asklio line-items, where the document is viewport-height but the scrollable content lives in an inner overflow:auto container) is captured at its true extent instead of a silent viewport crop; the ONLY non-full path stamps EnvState.captureMode 'viewport_degraded' and emits the full_page_capture:degraded marker \u2014 never a silent lie. Off is byte-identical to today EXCEPT the geometry measurement + a shadow degradation marker still run (detect-only) so staging can measure the lie's live frequency before the capture behavior flips. EnvState.captureMode is set in BOTH states.",designDoc:"docs/plans/2026-07-22-verify-evidence-fidelity-design.md",status:"active",added:"2026-07-22",notes:"Default OFF in code; force ON in staging via the orchestrator env (AGENTIQA_EXPERIMENT_EVIDENCE_FIDELITY=1) \u2014 the GROUNDED_EXPECTATIONS / BLIND_DOUBLE_READ precedent. Prod flip is a later explicit step after nightly baselines + a shadow soak on the degradation marker. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add EVIDENCE_FIDELITY to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: (P0) packages/engine-core/src/BasePlaywrightService.ts fullPageScreenshot \u2192 the honest capture ladder; (P1) packages/engine-core/src/RunnerRuntime.ts \u2192 per settled static-verify batch, capture ONE canonical honest full_page_screenshot, derive planStepIndex-stamped per-criterion crops (region resolved off the graded node; uncropped fallback), and persist a StepEvidenceRef on each TestPlanV2StepResult/CriterionResult at run_complete. Flag OFF is byte-identical to today EXCEPT the P0 shadow degradation marker: no canonical capture, no refs. P1 supersedes the run-detail findStepEvidenceIndex heuristic on runs that carry refs (legacy no-ref runs fall back). P2 (flip BLIND_DOUBLE_READ on the planStepIndex-stamped evidence P1 now produces) is the remaining follow-up gated on this.",graduation:{status:"gated",gate:"P0/P1 reproduced-RED evals green with the flag ON (runner-fullpage-honesty capture-mode/height/marker facts; degraded-abstain unit; P1 wrong-region + stamping-integrity) AND a staging shadow soak on the full_page_capture:degraded marker showing the expected live frequency with NO capture regression on batch.verify-never-blind",evidence:"full_page_capture:degraded diag events (staging shadow soak) + the engine-core capture-honesty integration test + the captureFidelity unit suite + the batch.verify-never-blind regression",owner:"steering (Alex)",review:"2026-07-29"}},PER_ACTION_BILLED_STEPS:{key:"PER_ACTION_BILLED_STEPS",envVars:["AGENTIQA_PER_ACTION_BILLED_STEPS","AGENTIQA_EXPERIMENT_PER_ACTION_BILLED_STEPS"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Decouples the billed step count from the LLM-iteration count (W1 of the batched-actions design, Decision 6). When on, the main-loop agent_step llm_usage event carries an additive billedUnits integer = executed browser actions + verify captures this turn (a marker-only signal_step turn earns 0); ingest sums it into run_billing.step_count. Off omits the field entirely, so ingest bills one step per agent_step event \u2014 byte-identical behavior AND billing to pre-change. The only intended billing delta when on (today, one-action-per-turn) is that marker-only iterations bill 0 instead of 1; a batched turn executing k actions will bill k (W3).",designDoc:"docs/plans/2026-07-18-batched-actions-design.md",status:"active",added:"2026-07-18",notes:"GRADUATED 2026-07-21 (default on): staging run_billing parity check over the force-ON window (since 07-18) held exactly \u2014 116/116 flag-ON runs with step_count == executed actions + verify captures, 99/99 marker-only iterations billed 0; billing.batched-steps-parity unit lane green. Billing substrate for the batched-actions family (W1). Read site: packages/engine-core/src/billedUnits.ts (perActionBilledStepsEnabled). Remove the staging orchestrator env var once this reaches staging."},STEP_MARKER_FOLD:{key:"STEP_MARKER_FOLD",envVars:["AGENTIQA_STEP_MARKER_FOLD","AGENTIQA_EXPERIMENT_STEP_MARKER_FOLD"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Phase 1 of the batched-actions design (Decision 3): when on, the RunnerRuntime run-mode prompt instructs the model to emit the signal_step boundary marker TOGETHER with the signaled step's FIRST action in the SAME turn \u2014 but ONLY for setup/action steps; VERIFY steps keep the separate marker turn so evidence is never captured blind. This collapses the ~18.7% of runner iterations that are marker-only today. HARD COUPLING: inert unless PER_ACTION_BILLED_STEPS is ALSO enabled \u2014 a folded turn under iteration-billing would bill 1 where marker+action should bill 2, breaking billing parity. The code guard (stepMarkerFold.ts::stepMarkerFoldEnabled = STEP_MARKER_FOLD && PER_ACTION_BILLED_STEPS) makes the fold prompt byte-identical to pre-change whenever PER_ACTION_BILLED_STEPS is off, so this flag alone changes nothing. No engine dispatch change: the multi-call loop already runs signal_step before the folded action in order (both in one generation the model saw the same screen), and billedUnits (W1) already counts marker+action as 1 billed unit.",designDoc:"docs/plans/2026-07-18-batched-actions-design.md",status:"active",added:"2026-07-18",notes:"Default OFF in code. Prompt-only change (no engine dispatch or verify-flow change). Read site: packages/engine-core/src/stepMarkerFold.ts (stepMarkerFoldEnabled), consumed in RunnerRuntime.buildRunnerPrompt run-mode signal_step cadence directive. The AND-coupling with PER_ACTION_BILLED_STEPS lives in code, not just here: flipping STEP_MARKER_FOLD=1 while PER_ACTION_BILLED_STEPS stays off is a no-op.",graduation:{status:"gated",gate:"Default-off soak on staging, then a staging flip (with PER_ACTION_BILLED_STEPS on) proves per-step verdict counts identical to OFF and marker-only iterations drop from ~18.7% to <7% (batch.step-attribution-preserved)",evidence:"batch.step-attribution-preserved unit lane + staging marker-only-iteration % soak measurement",owner:"steering (Alex)",review:"2026-07-25"}},WARNING_CRITERION_BIND:{key:"WARNING_CRITERION_BIND",envVars:["AGENTIQA_WARNING_CRITERION_BIND","AGENTIQA_EXPERIMENT_WARNING_CRITERION_BIND"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"run_complete grade<->criterion binding strips the platform-appended \" (warning only)\" render suffix from the model-echoed check text before the exact-text match, so a failing warning-only (strict:false) criterion binds by text (matchedByText=true) and keeps its own strict:false flag instead of being forced strict:true by the ordinal fallback and hard-failing the run; off restores the raw exact-text compare (a warning-only criterion the model echoed with the suffix escalates to a hard fail). Also the master gate for C1 honoring (2026-07-28): when the model REPHRASED the check so no text tier binds, a FAILING grade may keep an EXPLICIT strict:false only under this switch and only under a STRUCTURAL gate (round 7): the plan step the grade was filed under contains NO strict-or-default criterion at all, i.e. every criterion OF THAT STEP is an EXPLICIT strict:false, so there is nothing WITHIN THE STEP a mis-bound failure could be laundered out of. A MISSING strict counts as strict-or-default (fail-closed). A second condition \u2014 no unbound grade of the entry is itself a failure or un-adjudicated (a benign PASSING surplus grade does not close the gate) \u2014 is retained as DEFENCE-IN-DEPTH and is NOT a containment condition: mutating it away is verdict-inert, because an unbound grade already takes strict:true and a failing strict grade already fails the step. Diag `residual_strict_honoring:structural` records reason text-bound or sole-warning-entry when honored, and names the blocker otherwise. NOTHING ABOUT THE GRADE TEXT IS MEASURED. Rounds 3-6 all tried to identify the grade lexically \u2014 a shared-token threshold, then a generic-UI stopword list to stop it over-firing, then the same token measure read purely comparatively \u2014 and every one failed verification in BOTH directions; the comparative form was broken by ONE added word (appending the warning slot own noun to a confirmed false-PASS rewrite flips it open, dropping a distinctive token from a legitimate rephrase flips it shut). A grader-authored sentence is an unclosed class, so a restatement of a strict criterion and a rephrase of a warning-only one are not separable by any function of the two strings; the structural question reads the PLAN, which is authored data and cannot be gamed by wording. HONEST SCOPE: the honoring now covers ONLY all-warning steps (the shape of the incident step itself), and the guarantee it buys is a WITHIN-THE-STEP one \u2014 the gate reads one step's criteria and says nothing about a grade the model filed under the wrong step. Two documented boundaries, neither closed here: (A) false-FAIL side \u2014 a legitimate failing rephrase of a warning-only criterion that sits BESIDE a strict sibling fails closed to strict:true, the same verdict origin/staging produces, an unclosed class rather than a regression; (B) false-PASS side, CROSS-STEP MISFILE \u2014 a failing grade about step N's strict criterion, filed by the model under an all-warning step M, is honored as a warning, so a run that pre-#1898 staging (6fa6cb4b9) FAILED can PASS. (B) is a real new-vs-staging false-PASS channel and is bounded: it needs a COMPOSITE model error (the misfile AND a wrong pass on the real criterion in its own step \u2014 a lone misfile still fails through step N), the misfiled failure stays visible as a step-level WARNING rather than being dropped, and no WORDING reaches it (a grade filed under its own strict-carrying step is refused as before). Pinned by RunnerRuntime.residualHonoring.falsePassProbes.test.ts. Full closure of BOTH boundaries needs AUTHORING-TIME criterion identity (a stable criterion id echoed by the grader), not grading-time text comparison. Off forces strict:true on every fallback-bound failing grade \u2014 byte-identical pre-C1.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-16"},CRITERION_BIND_RESIDUAL:{key:"CRITERION_BIND_RESIDUAL",envVars:["AGENTIQA_CRITERION_BIND_RESIDUAL","AGENTIQA_EXPERIMENT_CRITERION_BIND_RESIDUAL"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Order-independent run_complete grade<->criterion binding (`bindGradesToPlanSlots`): every grade that matches a criterion by TEXT claims its slot in a first pass, and only then do the still-unbound grades take the still-unclaimed criteria in relative order. The sequential binder it replaces let an EARLIER rephrased grade's ordinal fallback steal the slot a LATER grade matched by exact text, so the same two grades hard-failed or warned depending purely on the order the model listed them (verified: criteria [address strict, title strict:false] + a rephrased failing title grade listed first booked that failure onto the STRICT address slot). With no text bindings the residual pass IS the old absolute ordinal (the round-6 reshuffle shape is byte-identical), and a SURPLUS grade beyond the criteria count still binds to nothing \u2192 fail-closed strict:true. A residual binding never licenses an explicit strict:false on its own: a FAILING residual grade keeps the criterion's strict:false only if the plan step it was filed under carries NO strict-or-default criterion at all (round 7 structural gate \u2014 see WARNING_CRITERION_BIND; a verdict-inert defence-in-depth guard additionally refuses an entry holding an unidentified FAILING or un-adjudicated grade). That single question covers every WITHIN-THE-STEP laundering shape the earlier lexical screens chased, because a step with a strict criterion to launder into is exactly a step where honoring is refused; no grade text is read. It does NOT cover a grade the model filed under the WRONG step \u2014 the documented cross-step boundary (B) on WARNING_CRITERION_BIND. This switch is NOT a containment lever for any of those shapes and never was (verified 2026-07-28: with CRITERION_BIND_RESIDUAL=0 a synonym restatement still false-PASSed on round-4 code); it only chooses HOW grades bind to slots. Containment comes from the honoring gate itself, which contains the class on the default path. Off restores the slot-stealing sequential binder; WARNING_CRITERION_BIND=0 overrides both with origin/staging's raw-exact-then-ordinal bind and turns the honoring off entirely.",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-28"},CRITERIA_CONTAINMENT:{key:"CRITERIA_CONTAINMENT",envVars:["AGENTIQA_CRITERIA_CONTAINMENT","AGENTIQA_EXPERIMENT_CRITERIA_CONTAINMENT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Closed-world containment on run_complete: a step\'s verdict is decided ONLY by criteria the PLAN authored. A graded criterion result that binds to NO authored slot of its step (the grading model invented it) is still persisted \u2014 marked `unauthored: true` for forensics \u2014 but `deriveStepStatusFromCriteria` skips it, so a fabricated strict failure can no longer decide a step. Live prod-shaped defect (canary tp_vrgate_offer_upload_retry step 13, ~2/9 replicates): the step authors exactly 2 criteria (Description "Montage und Einweisung", Unit "St\xFCck"), both graded PASS with correct grounding, and the model additionally graded a THIRD criterion \u2014 `Order line 2 Quantity is "St\xFCck"`, strict:true, observed "1" \u2014 that exists in neither the plan nor the DB; that invented failure hard-failed the run. Detection ALWAYS runs (shadow-first): with the flag OFF every verdict is byte-identical and the engine only logs `criteria_containment:would_exclude` {stepIndex, criterionText, strict, observed, wouldFlipStep}; ON it excludes and logs `criteria_containment:excluded` with the same payload. `wouldFlipStep` IS the graduation evidence \u2014 it is true only where the exclusion actually moves the step status. TWO DELIBERATE NARROWINGS keep this rescue-polarity gate from opening a false-PASS channel: (1) it fires only on a step that AUTHORED \u22651 criterion \u2014 grades filed under a criteria-less action/setup step are the cross-step MISFILE class, where today\'s fail-closed treatment of the unbound grade is the only adjudication that failure gets; and (2) only when EVERY authored criterion of that entry received a grade, so an unbound grade can never be excluded while an authored slot went unadjudicated (it would then plausibly BE that slot\'s grade under a heavy rephrase). Identification reuses the ONE authoritative binder \u2014 `bindGradesToPlanSlots` per-entry output (text tiers incl. the platform\'s " (warning only)" rewrite, then residual positional) \u2014 never a new text comparison: measured over 76 persisted corpus runs, 58 of 60 text-unbound results were exactly that legal rewrite, so a text-equality containment rule would be ~97% false positives. A THIRD narrowing closes the DUPLICATE-READ false-PASS channel (review round 2026-07-29): the binder claims slots EXCLUSIVELY, so a SECOND grade of the SAME authored criterion binds to nothing and unguarded containment would discard it \u2014 and when the two reads contradict ([passed:true, then passed:false observed "\u20AC35.00"] for one authored total) the discarded one is the FAILING one, passing the step on a record whose "unauthored" criterionText is byte-identical to the authored check. Before excluding, `findDuplicateReadCriterionIdx` re-runs the binder\'s own text tiers over ALL authored criteria with the claimed set IGNORED; a match means duplicate READ, containment REFUSES to exclude, the grade keeps its flag-OFF effect (the step can still fail \u2014 the correct polarity for a contradicting observation), and the engine logs `criteria_containment:duplicate_read` {stepIndex, criterionIndex, criterionText, passed, wouldHaveExcluded} in BOTH flag states. RESIDUAL: identification is a TEXT relation, so a REPHRASED contradicting second read ("Der Gesamtbetrag lautet \u2026") matches no tier and is still excluded under the flag \u2014 the shadow soak\'s would_exclude population must be reviewed for that shape before graduation. Gate half (detector, no verdict effect): `criteria_over_grading` in e2e/scripts/verdict-replay-gate.mjs, PR #1934.',designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-29",notes:"Default OFF in code; detection runs in shadow always \u2014 the PIN_PAGE_GROUNDING / TYPED_ATOM_FLOOR shadow-first precedent, applied here because the polarity is RESCUE (removes a fail), which per docs/VERDICT-GATES.md carries the higher burden. Rides on the binder flags: with WARNING_CRITERION_BIND=0 or CRITERION_BIND_RESIDUAL=0 the binder is the sequential one, which leaves grades unbound in shapes that are NOT surplus \u2014 narrowing (2) is what keeps containment inert there rather than excluding a legitimately-graded criterion. Runner lane only (RunnerRuntime run_complete). Scope is step-status derivation: the rescue-eligibility gates that read `criteriaResults.every(passed)` (absence oracle, VERIFY_REOBSERVE_WITHHOLD, verify-conflict reconcile) still see the full persisted array, so a fabricated failing result can still BLOCK a rescue \u2014 the fail-closed direction, left deliberately.",graduation:{status:"gated",gate:"Staging/canary shadow soak shows `criteria_containment:would_exclude` with `wouldFlipStep: true` reproducing the tp_vrgate_offer_upload_retry step-13 fabrication class AND zero would_exclude events on steps whose authored criteria were all legitimately graded (no exclusion of a real verdict), plus a clean verdict-replay gate run with the #1934 `criteria_over_grading` detector agreeing on the same steps. MANDATORY before graduation: the soak's would_exclude population must be reviewed grade-by-grade for the REPHRASED-DUPLICATE shape (a paraphrased second read of an authored criterion, which the text tiers cannot distinguish from a fabrication and which the duplicate-read guard therefore does NOT catch); any such event is a false-PASS candidate and blocks the flip until it is either closed or explicitly waived.",evidence:"engine `criteria_containment:would_exclude` / `:excluded` / `:duplicate_read` diag events + the RunnerRuntime.criteriaContainment unit suite (claim verify.containment.authored-criteria-only) + the #1934 replay-gate `criteria_over_grading` violations on the persisted corpus",owner:"steering (Alex)",review:"2026-08-12"}},PLAN_OBEDIENCE:{key:"PLAN_OBEDIENCE",envVars:["AGENTIQA_PLAN_OBEDIENCE","AGENTIQA_EXPERIMENT_PLAN_OBEDIENCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Enforces the active plan step: rejects off-plan label clicks, records deviations, and lets run_complete fail on them; off makes the pre-check, deviation recording, and verdict gate all inert (pre-#1294 behavior).",designDoc:"packages/engine-core/src/RunnerRuntime.ts",status:"active",added:"2026-07-07"},LOOP_VISION_ESCALATION:{key:"LOOP_VISION_ESCALATION",envVars:["AGENTIQA_LOOP_VISION_ESCALATION","AGENTIQA_EXPERIMENT_LOOP_VISION_ESCALATION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Master gate (Runner/Explorer lanes) for consulting the vision supervisor once before an ambiguous screenshot-blind force-block terminates the run; off keeps the deterministic hard-block.",designDoc:"docs/plans/2026-07-07-loop-detection-vision-supervisor-design.md",status:"active",added:"2026-07-07"},LOOP_VISION_DIFFERENTIAL:{key:"LOOP_VISION_DIFFERENTIAL",envVars:["AGENTIQA_LOOP_VISION_DIFFERENTIAL","AGENTIQA_EXPERIMENT_LOOP_VISION_DIFFERENTIAL"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Phase-2 differential-grant refinement of loop-vision escalation: grants 2..K need a concrete task-unit delta and the per-step ceiling rises to 12; off reverts to Phase-1 (absolute judgment, 4-grant ceiling).",designDoc:"docs/plans/2026-07-09-loop-vision-differential-extension-design.md",status:"active",added:"2026-07-09"},CANVAS_PIXEL_PROGRESS:{key:"CANVAS_PIXEL_PROGRESS",envVars:["AGENTIQA_CANVAS_PIXEL_PROGRESS","AGENTIQA_EXPERIMENT_CANVAS_PIXEL_PROGRESS"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Canvas-aware loop progress: on a canvas-dominant screen (a <canvas> covers >=40% of the viewport) the LoopDetector novel_screen milestone is driven by a coarse screenshot pixel-diff hash (own NOVEL_SCREEN_BUDGET) instead of the static DOM/a11y hash, and the loop-vision differential delta gate accepts a qualitative delta_evidence string when countable task units are unavailable. Off drops both so a canvas build behaves exactly as before (structural breaker climbs on the static DOM hash, delta gate stays countable-only).",designDoc:"docs/plans/2026-07-14-canvas-chat-failure-class-design.md",status:"active",added:"2026-07-14"},LOOP_URL_NOVELTY_REARM:{key:"LOOP_URL_NOVELTY_REARM",envVars:["AGENTIQA_LOOP_URL_NOVELTY_REARM","AGENTIQA_EXPERIMENT_LOOP_URL_NOVELTY_REARM"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Re-arms the structural loop breaker in the chat/explorer (assistant_v2) lane. URL-ONLY (narrow-safe): only the novel-URL seen-set, its NOVEL_URL_BUDGET=40/turn budget, and actionsSinceProgress become TURN-scoped (resetForNewStep no longer wipes them), so a recycled URL revisited across many declared steps stops re-counting as novel and actionsSinceProgress climbs to the 30-action structural threshold. The novel-REF and novel-SCREEN budgets stay PER-DECLARED-STEP in both states \u2014 turn-scoping them was reverted because it starved a legit long single-stable-URL SPA turn producing genuinely-new screen content each action (force-block ~action 53). A genuinely-new URL each step still resets (multi-page wizards unaffected); a wander that also mints novel screens escapes this deterministic re-arm and the run backstop is the net. Off restores the per-step reset (recycled URLs re-count as novel forever, unbudgeted novel_url) \u2014 today's prod behavior. Runner (test_run) lane never opts in.",designDoc:"docs/plans/2026-07-20-loop-safety-rearm-and-backstop-design.md",status:"active",added:"2026-07-20"},RUN_PROGRESS_BACKSTOP:{key:"RUN_PROGRESS_BACKSTOP",envVars:["AGENTIQA_RUN_PROGRESS_BACKSTOP","AGENTIQA_EXPERIMENT_RUN_PROGRESS_BACKSTOP"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Judge-gated run backstop in the chat/explorer (assistant_v2) runLoop: a wall-clock (12 min, primary), iteration (200), and cumulative prompt+completion billed-token (6M) ceiling \u2014 all well above p99 legit chat turns and below the 300-iteration explorer child cap. At a ceiling breach the loop-vision progress judge (the same fail-closed SupervisorService judge the loop breaker uses, temp-0 / thinkingBudget-0) is consulted ONCE with a goal-anchored progress question, rather than blind-terminating: "progressing" grants a BOUNDED extension (each ceiling raised by one window) up to a hard cap of RUN_BACKSTOP_MAX_EXTENSIONS=2 (worst case ~36 min), after which the run terminates regardless of the judge; "wandering" terminates with a judge-confirmed "not getting closer to the objective" message; any no-signal case (no judge wired in this lane, judge error / timeout / unparseable) fails CLOSED to a terminate with a neutral "hit the safety limit" message. Ends with blockKind=backstop / endKind=run_backstop, NOT loop_block, so it is not counted toward the session structural-loop cap. No interactive ask and no cross-turn state (the escalate\u2192ask_user ladder was removed; the judge consult is synchronous and re-derived per breach). Off removes all three ceilings (only bound remains iteration<=maxIterations=300, ~2.5h). Never a crash \u2014 the emit path fails open while the judge fails closed. Runner (test_run) lane never opts in.',designDoc:"docs/plans/2026-07-20-loop-safety-rearm-and-backstop-design.md",status:"active",added:"2026-07-20"},CLICK_AT_INTERACTIVE_DESCEND:{key:"CLICK_AT_INTERACTIVE_DESCEND",envVars:["AGENTIQA_CLICK_AT_INTERACTIVE_DESCEND","AGENTIQA_EXPERIMENT_CLICK_AT_INTERACTIVE_DESCEND"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"A coordinate click_at/double_click_at whose point resolves to a NON-interactive element descends to an interactive descendant within 16px and clicks it via locator, plus a no-effect advisory on a zero-mutation same-URL click; off restores the raw mouse.click(x,y) with no advisory.",designDoc:"docs/plans/2026-07-11-click-at-interactive-descend-design.md",status:"active",added:"2026-07-11"},LOOP_BLOCK_ATTRIBUTION:{key:"LOOP_BLOCK_ATTRIBUTION",envVars:["AGENTIQA_LOOP_BLOCK_ATTRIBUTION","AGENTIQA_EXPERIMENT_LOOP_BLOCK_ATTRIBUTION"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:`Evidence-gated loop-block finding attribution: when a force-block's dominant repeated click target is a non-interactive element or a no-op self-anchor, suppress the false "Page appears stuck" auto-issue instead of filing it. Off restores the old unconditional filing (subject only to the AG-6107/AG-6490 gates).`,designDoc:"docs/plans/2026-07-11-loop-block-finding-attribution-design.md",status:"active",added:"2026-07-11"},CLICK_AFFORDANCE_CAPTURE:{key:"CLICK_AFFORDANCE_CAPTURE",envVars:["AGENTIQA_CLICK_AFFORDANCE_CAPTURE","AGENTIQA_EXPERIMENT_CLICK_AFFORDANCE_CAPTURE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Phase-2 of loop-block attribution: captures click-handler affordance evidence onto clickTarget (page-context inline/React/Vue signals + a CDP addEventListener probe on the rare non-interactive branch) so a dominant non-interactive target with a real-but-dead handler files a 'Custom control appears unresponsive' issue instead of being suppressed agent-side. Off \u21D2 no affordance field emitted \u21D2 the custom-control classifier branch can never fire (falls back to the #1477 status quo); it does NOT re-enable filing on a bare non-interactive target.",designDoc:"docs/plans/2026-07-11-custom-control-unresponsive-detection-design.md",status:"active",added:"2026-07-11"},CLICK_EFFECT_SIGNAL:{key:"CLICK_EFFECT_SIGNAL",envVars:["AGENTIQA_CLICK_EFFECT_SIGNAL","AGENTIQA_EXPERIMENT_CLICK_EFFECT_SIGNAL"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Post-click effect signal on EVERY click path (coordinate, retargeted, ref and label \u2014 click_at and double_click_at), SHADOW-FIRST. After the click the engine waits up to a 500ms settle window for the DomObserver to record any DOM/text/attribute mutation (returning the instant one lands), then compares the URL and the auto-accepted-dialog tally. Any movement \u21D2 an effect was observed. No movement \u21D2 the click STILL reports SUCCESS (a click that legitimately changes nothing must never become an error) and the feature's only output is agent STEER. THREE STATES, not two: no env (default) = SHADOW \u2014 detection runs and emits the click_effect:would_signal diag, but no advisory, no effectObserved metadata and no prompt-byte change reach the model; =1 = ENFORCE \u2014 the hedged re-observe advisory rides the successful tool result, effectObserved lands on the ToolCallResult side channel, the wait_for_element "Do NOT retry" coaching softens to its effect-aware wording and the runner prompt gains the re-observe-after-corrective-action line, with a click_effect:signaled diag; =0 = FULLY OFF \u2014 not even the probe runs, so there is zero added latency and click results plus every prompt byte are identical to pre-change behavior. Targets the 2026-07-29 vrgate false-FAIL (run_b72f5099-cee2-4063-b109-1961c55c9898), where a click_at on a rendered React button ~1.3s after a Next.js client navigation reported success while the onClick never fired (painted but not yet hydrated), the agent trusted the success, and the plan FAILED for a defect that did not exist. EXECUTOR-SIDE ONLY: it changes no verdict path, writes no step/criterion/run status, and adds no gate \u2014 it changes what the AGENT is told, and the agent still grades. Fail-safe by construction: an in-page probe that cannot run (CSP, cross-origin frame, document destroyed mid-navigation) yields NO verdict rather than a false "no effect"; navigation/dialog evidence is evaluated BEFORE the mutation counters so the one case where the probe reliably dies is the case the URL alone already proves; canvas-dominant surfaces and native property-only controls (checkbox/radio/select/text input \u2014 where a spurious "re-perform once" would TOGGLE the control back) are advisory-suppressed; and the pre-existing #1476 dead-coordinate peek keeps its exact timing and semantics. Canvas surfaces additionally skip the PROBE (not just the advisory) once a capture has classified the page as canvas-dominant, so a whiteboard/design flow never pays the settle window per click for a verdict that is suppressed on arrival; those clicks are counted as click_effect:probe_skipped. A SECOND probe skip covers the unobservable case: in SHADOW, where the diag is the feature's only output, a platform with no BasePlaywrightService.diagLog wired skips the probe entirely rather than pay the settle window for a measurement nothing can read (ENFORCE always probes \u2014 its output is agent-visible behavior, not telemetry).`,designDoc:"packages/engine-core/src/clickEffectSignal.ts",status:"active",added:"2026-07-29",notes:"Default OFF (shadow). Detection runs in shadow always unless explicitly =0 \u2014 the PIN_PAGE_GROUNDING / INTERACTION_CLEARS_PRESENCE_ORACLE shadow-first precedent \u2014 because a shadow that skipped the settle wait would measure a DIFFERENT detector than the one enforcement ships, and its numbers would not predict the ON behavior. The one deliberate non-identity in shadow is therefore TIMING, not tool-result bytes: a click that has mutated nothing yet pays up to 500ms of settle before the state capture that follows it (an effective click returns on the first in-page read and pays one evaluate round-trip). Stated plainly because it is a real, if small, behavior delta in the DEFAULT state \u2014 the post-click screenshot/snapshot of a no-effect click is taken up to 500ms later than before, which is more settled, not less faithful. AGENTIQA_CLICK_EFFECT_SIGNAL=0 removes even that and restores exact timing parity. killSwitch resolves the no-env value from this defaultState (#1729), so GRADUATING = flip defaultState to 'on' AND add CLICK_EFFECT_SIGNAL to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: packages/engine-core/src/BasePlaywrightService.ts (probeClickEffect / resolveClickEffect on clickAt, clickByRef, clickByLabel), packages/engine-core/src/waitToolCoaching.ts (waitNotFoundError picks the coaching variant), packages/engine-core/src/tools/browserTools.ts (getFailureHandlingPrompt), packages/engine-core/src/RunnerRuntime.ts (buildRunnerPrompt re-observe line); pure decision logic in packages/engine-core/src/clickEffectSignal.ts. Acceptance tests: clickEffectSignal.test.ts (pure verdict matrix incl. every suppression and the unknown-probe degrade), BasePlaywrightService.clickEffectSignal.test.ts (per-path wiring + shadow/enforce/off + the canvas-memo skip + degraded-note preservation on the ref path), clickEffectPromptParity.test.ts (flag-OFF prompt BYTE-parity across all four prompt surfaces). The 500ms settle cost is bounded on canvas-dominant surfaces by the SessionState.lastCaptureCanvasDominant memo: captureState records canvasDominant on every capture and probeClickEffect returns null (emitting click_effect:probe_skipped, reason canvas-memo) while it is set, because the canvas verdict was suppressed anyway. It is bounded a second way by the OBSERVER check: in shadow, where the diag is the only output, probeClickEffect returns null before the settle window when this.diagLog is unwired \u2014 an unobservable measurement is pure latency. Enforce is exempt (its verdict is agent-visible behavior). Acceptance: the shadow/enforce no-observer pair in BasePlaywrightService.clickEffectSignal.test.ts.",graduation:{status:"gated",gate:'SOAK SOURCE \u2014 read this first. click_effect:* rides BasePlaywrightService.diagLog, which was wired ONLY in DesktopPlaywrightService until the CloudPlaywrightService sink resolver landed (2026-07-30), so before that commit desktop runs were the ONLY source and a census of 0 from a cloud/staging replay lane is NON-EVIDENCE (the events were structurally unemittable there, not absent). Any soak reading must therefore be taken from engine builds that carry the cloud diagLog wiring; older cloud replays cannot be counted, and in shadow an unwired lane now skips the probe outright so it contributes no fires by construction. Staging shadow soak on click_effect:would_signal establishes (a) the no-effect rate per click path, (b) that the fires are dominated by genuinely ineffective clicks rather than by the known effect-free-but-legitimate classes, and (c) that no page class fires it continuously. FOUR NAMED REQUIREMENTS, all of which must be answered before the flag moves past shadow. (1) BLOCKER \u2014 THE NON-IDEMPOTENT SUBMIT. `<button>` and `<a>` are deliberately NOT in the property-only suppression set, so a form submit whose only feedback is a server round-trip (no spinner, no optimistic DOM write) reads as no-effect and, under enforce, receives the "re-perform the action ONCE" advisory. That directly contradicts the failure-handling prompt already shipped in browserTools.getFailureHandlingPrompt, which names "status: ok with url unchanged and no visible DOM change" as a SIGN OF AN IN-FLIGHT WRITE and instructs "do NOT re-click ... Re-clicking the same button while a write is in flight is a no-op for the user and burns retry budget" \u2014 and on a non-idempotent endpoint a second submit is not merely wasted, it can double-charge, double-book or double-post. The soak must show ZERO enforce-mode advisories on non-idempotent submits (classify fires by targetTag/targetRole plus the accessible name against a submit-shaped vocabulary, and cross-check each against pendingRequests at the moment of the fire), OR enforce must first gain a submit-shaped suppression (e.g. withhold the advisory whenever a same-origin request was in flight at probe time, or whenever the target is a submit-shaped control) \u2014 either outcome, and NEITHER may be waived. (2) IFRAME BLIND SPOT. Every counter read (peek / waitForMutation / flush) goes through page.evaluate, which runs in the MAIN frame only, and a top-document MutationObserver does not cross an iframe boundary \u2014 so a click whose whole effect renders inside an embedded frame (payment element, third-party booking/chat widget, embedded editor preview) reads as no-effect however well it worked. There is no target shape to suppress on, so iframe-hosted effects are a KNOWN-LEGITIMATE fire class the soak must be able to account for and subtract, exactly like property-only controls, downloads, clipboard and focus-only clicks; it is enumerated in the clickEffectSignal.ts header for the same reason. (3) SHADOW IS NOT INERT \u2014 READ THE SOAK ACCORDINGLY. The probe delays the post-click captureState by up to the full 500ms settle window on any click that has mutated nothing yet, INCLUDING in the default shadow state. Captured screenshots/snapshots on those clicks are therefore of a MORE SETTLED page than pre-change, so a shadow-vs-baseline comparison that shows different captured content on no-effect clicks is expected and is not evidence of a detector defect; only the =0 state is timing-identical to pre-change. (4) HYDRATION EMPIRICAL CRITERION. The soak must answer "what would run_b72f5099-cee2-4063-b109-1961c55c9898 have produced?" \u2014 i.e. for clicks landing inside a post-navigation hydration window, what fraction show mutationCount > 0 or attrCount > 0 (some other script mutated the page, so the detector stays SILENT and would not have rescued the incident) versus both counters at 0 (the detector fires and the advisory would have reached the agent). Both counters are already in the click_effect payload, so the query is: filter click_effect:would_signal to fires within ~2s of a navigation, then bucket on (mutationCount > 0 || attrCount > 0). A silent-dominated result means this feature does not fix its own motivating incident and enforcement is not justified on that basis. Enforcement additionally needs an inversion showing the advisory does not induce a harmful second click on a toggle.',evidence:"staging click_effect:would_signal diag events FROM AN ENGINE BUILD THAT CARRIES THE CLOUD diagLog WIRING (rate + clickPath/suppressReason/targetTag/targetRole breakdown, plus the mutationCount/attrCount split inside the post-navigation hydration window and the submit-shaped-target cross-check against in-flight same-origin requests) + click_effect:probe_skipped counts for the canvas-memo skips + the engine-core clickEffectSignal / BasePlaywrightService.clickEffectSignal / clickEffectPromptParity unit suites + apps/execution-engine/__tests__/CloudPlaywrightService.diagLog.test.ts for the cloud emit path itself",owner:"steering (Alex)",review:"2026-08-08"}},REVISION_CRITERIA_CARRYOVER:{key:"REVISION_CRITERIA_CARRYOVER",envVars:["AGENTIQA_REVISION_CRITERIA_CARRYOVER","AGENTIQA_EXPERIMENT_REVISION_CRITERIA_CARRYOVER"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Backstop that carries prior-draft criteria forward when a plan revision strips ALL criteria across ALL steps; off lets a total criteria-strip through.",designDoc:"packages/engine-core/src/revisionCriteriaCarryOver.ts",status:"active",added:"2026-07-07"},CREDENTIAL_GUARD:{key:"CREDENTIAL_GUARD",envVars:["AGENTIQA_CREDENTIAL_GUARD","AGENTIQA_EXPERIMENT_CREDENTIAL_GUARD"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Credential-fabrication guard: injects the login-prohibition prompt wording and fires the false-premise report_issue gate; off omits both (pre-feature behavior).",designDoc:"packages/engine-core/src/testingEmailPolicy.ts",status:"active",added:"2026-07-06"},CREDENTIAL_BINDING:{key:"CREDENTIAL_BINDING",envVars:["AGENTIQA_CREDENTIAL_BINDING","AGENTIQA_EXPERIMENT_CREDENTIAL_BINDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Runner deterministic credential-step binding (v1.1): when a plan step unambiguously references exactly one non-generic stored credential AND the model's own type_project_credential_at pick was a generic field word, the mismatched credentialName is overridden to the referenced one (credential_binding_override diag) \u2014 a non-generic pick is never rewritten; and when a credential fill is followed within a 3-action adjacency window by a 401/403 while the step-referenced credential is untried and was not the last one filled, ONE report_issue/exploration_blocked per run is deflected toward that specific credential. A genuine 401 of the step's own credential, an unrelated stray 401, or a step naming no credential all proceed to the report. Off restores the model's free credential pick and no auth-failure nudge (pre-feature behavior).",designDoc:"docs/plans/2026-07-19-ag7727-run-fidelity-fixes-design.md",status:"active",added:"2026-07-19"},EMAIL_CODE_PROVENANCE:{key:"EMAIL_CODE_PROVENANCE",envVars:["AGENTIQA_EMAIL_CODE_PROVENANCE","AGENTIQA_EXPERIMENT_EMAIL_CODE_PROVENANCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verification-code write provenance gate: a write the model TYPED as fieldPurpose='verification_code' is refused unless its value equals a whole code token in an email actually fetched via check_email this run (subject + text + html-as-text, token-equality not raw substring). Off passes the write through ungrounded (pre-feature behavior), so a guessed or fabricated code can mutate the page into a false success state.",designDoc:"packages/engine-core/src/emailVerificationGate.ts",status:"active",added:"2026-07-12"},VERBATIM_INPUT_PIN:{key:"VERBATIM_INPUT_PIN",envVars:["AGENTIQA_VERBATIM_INPUT_PIN","AGENTIQA_EXPERIMENT_VERBATIM_INPUT_PIN"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verbatim user-input payload pinning: at test-plan generation a text-entry step's model-emitted verbatimInput is kept ONLY when it provenance-matches user-supplied text (deterministic type-time capture + user chat/attachment corpus, normalized full match), and RunnerRuntime types that pinned string verbatim (slot wins over prose). Off disables both the capture/attach and the runner consumption (pre-feature behavior: payloads paraphrased into step prose and re-improvised at replay).",designDoc:"docs/plans/2026-07-13-verbatim-input-payload-design.md",status:"active",added:"2026-07-13"},VERIFY_ORACLE_FIDELITY:{key:"VERIFY_ORACLE_FIDELITY",envVars:["AGENTIQA_VERIFY_ORACLE_FIDELITY","AGENTIQA_EXPERIMENT_VERIFY_ORACLE_FIDELITY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Verify-oracle fidelity (verbatim-input Phase 2): a deterministic post-generation pass at both producer gates (CoordinatorRuntime.handleSaveTestPlan + the Explorer draft path), after pinVerbatimInputSteps, that restores user-authored acceptance criteria the LLM summarized away. It captures verification check-bullets under a high-precision verification-heading line (r2: heading ends with ':' and its core matches a verification PHRASE whole, not merely contains a strong token; each bullet captured unless action-imperative-shaped) plus a bounded single-paragraph anti-false-pass lookback, tests each against the persisted verify-side content (verify-step texts + criteria checks + expectedValue pins) by literal-atom containment (quoted spans + numerals/ranges with EN/RU 0\u201320 spelled-form equivalence; atom-free \u2192 normalized-token containment \u2265 0.6), and APPENDS a verify step for every uncovered item carrying the user's bullet verbatim as both the step text AND a compiled criterion ({check, strict:true}, r2/F7 \u2014 so the appended step passes validateDraftPlanSteps and never hits the runner's criteria-less synthesis path). Append-only (never edits/deletes an existing step), fail-open (any error \u2192 save unchanged). Off restores pure LLM-compliance generation (summarized oracles persist as-is). Emits an oracle_fidelity diag {bullets, covered, appended, lookbackCaptured, looseBullets, disabled} regardless of flag state (looseBullets = diag-only recall telemetry, never appends).",designDoc:"docs/plans/2026-07-15-verify-oracle-fidelity-design.md",status:"active",added:"2026-07-15"},TYPE_NEWLINE_SAFE:{key:"TYPE_NEWLINE_SAFE",envVars:["AGENTIQA_TYPE_NEWLINE_SAFE","AGENTIQA_EXPERIMENT_TYPE_NEWLINE_SAFE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:'Multi-line text typing: embedded newlines are entered as Shift+Enter soft line breaks (never a raw Enter keypress) so a multi-line prompt does not premature-submit an Enter-to-send composer (e.g. Miro/Slack chat sidekicks). Off restores the raw keyboard.type(text) behavior where each "\\n" fires an Enter keypress. Applies to all four text-typing paths (typeTextAt / typeByRef / typeByLabel / setFocusedInputValue fallback); pressEnter still appends one trailing Enter regardless.',designDoc:"packages/engine-core/src/typeMultiline.ts",status:"active",added:"2026-07-13"},CANVAS_TYPE_GROUNDING:{key:"CANVAS_TYPE_GROUNDING",envVars:["AGENTIQA_CANVAS_TYPE_GROUNDING","AGENTIQA_EXPERIMENT_CANVAS_TYPE_GROUNDING"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-disabled",gates:"Canvas typed-text grounding: after a coordinate type_text_at whose focus is NOT a text-editable DOM element on a canvas-dominant screen, verify the text actually landed \u2014 a11y/DOM positive check on the reused post-action snapshot, else a pixel route gated by an ambient-animation pre-check (two pre-type full-frame captures a settle apart). If the board is proven static (pre-captures byte-identical) a full-frame before/after compare decides: any change = landed (off-clip renders included), byte-identical = confident negative \u2192 explicit failure (metadata.error + canvasTypeVerification='text_not_found') with a switch-strategy hint. If the board is self-animating (pre-captures differ) the outcome is uncertain_animated: behavior byte-identical to flag-off, recorded via a canvas_type_verify diag event. Every uncertain outcome is fail-open (behavior unchanged); \u22643 verification screenshots per qualifying action. Off restores the pre-feature bare-success canvas type (no verification screenshots, no a11y check).",designDoc:"docs/plans/2026-07-14-canvas-chat-failure-class-design.md",status:"active",added:"2026-07-14"},RESULT_FIRST_DISCOVERY:{key:"RESULT_FIRST_DISCOVERY",envVars:["AGENTIQA_EXPERIMENT_RESULT_FIRST_DISCOVERY"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"env-const-disabled",gates:'Result-first discovery (#373): auto-approve discovered scope and run high-risk areas immediately; off restores the "question-first" scope-approval checkpoint that waits.',designDoc:"packages/engine-core/src/resultFirstDiscovery.ts",status:"active",added:"2026-06-01",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_RESULT_FIRST_DISCOVERY (no bare AGENTIQA_ spelling). NOT migrated to killSwitchDisabled \u2014 that would add the bare spelling and change behavior. Also has a per-session config opt-out."},SCOPE_PROVENANCE:{key:"SCOPE_PROVENANCE",envVars:["AGENTIQA_EXPERIMENT_SCOPE_PROVENANCE"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"env-const-disabled",gates:"Scope-provenance-aware plan selection: user-enumerated medium/low areas still run in the first pass; off falls back to the legacy risk-only split.",designDoc:"packages/engine-core/src/resultFirstDiscovery.ts",status:"active",added:"2026-07-01",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_SCOPE_PROVENANCE. NOT migrated to killSwitch (would add a bare spelling)."},MEMORY_WRITEBACK:{key:"MEMORY_WRITEBACK",envVars:["AGENTIQA_EXPERIMENT_MEMORY_WRITEBACK"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"env-const-enabled",gates:"Verified-memory writeback: offers the save_verified_memory tool and activates the durable write path; off leaves writeback inert.",designDoc:"docs/plans/2026-07-04-verified-memory-writeback-design.md",status:"active",added:"2026-07-04",notes:"Single spelling: reads ONLY AGENTIQA_EXPERIMENT_MEMORY_WRITEBACK. NOT migrated to killSwitchEnabled (would add a bare spelling). Also has a per-session config force-on for evals.",graduation:{status:"gated",gate:"Model-elicitation quality gate from the 2026-07-04 verified-memory-writeback design doc closes",evidence:"design-doc gate + eval force-on runs",owner:"steering (Alex)",review:"2026-08-01"}},FAST_START_PROMPT:{key:"FAST_START_PROMPT",envVars:["AGENTIQA_EXPERIMENT_FAST_START_PROMPT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"is-experiment-enabled",gates:"Explorer prompt variant: emits the fast-start initial prompt instead of the standard one.",designDoc:"packages/engine-core/src/ExplorerRuntime.ts",status:"active",added:"2026-06-01",notes:'Single spelling via isExperimentEnabled (exact "1"). NOT a killSwitch flag \u2014 no bare AGENTIQA_ spelling honored.',graduation:{status:"parked",gate:"No rollout intent; delete registry entry + code path if still unused by 2026-09-01"}},MINIMAL_INITIAL_CONTEXT:{key:"MINIMAL_INITIAL_CONTEXT",envVars:["AGENTIQA_EXPERIMENT_MINIMAL_INITIAL_CONTEXT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"is-experiment-enabled",gates:"Explorer context variant: sends a minimal initial context to the model instead of the full one.",designDoc:"packages/engine-core/src/ExplorerRuntime.ts",status:"active",added:"2026-06-01",notes:'Single spelling via isExperimentEnabled (exact "1"). NOT a killSwitch flag \u2014 no bare AGENTIQA_ spelling honored.',graduation:{status:"parked",gate:"No rollout intent; delete registry entry + code path if still unused by 2026-09-01"}},STEERING_VETO:{key:"STEERING_VETO",envVars:["AGENTIQA_STEERING_VETO"],polarity:"0-disables",defaultState:"on",surfaces:["engine"],cloudForwarded:!1,read:"env-direct",gates:"Supervisor steering veto: at a redirect, refuses the recent loop-set of action fingerprints for a bounded TTL/budget; off passes those calls through.",designDoc:"packages/engine-core/src/steeringVeto.ts",status:"active",added:"2026-06-01",notes:'Reads ONLY the bare AGENTIQA_STEERING_VETO (via direct process.env access, "!== 0"). It has NO AGENTIQA_EXPERIMENT_ spelling, so the orchestrator passthrough cannot flip it in a cloud pod (cloud-unreachable \u2014 known limitation). NOT migrated to killSwitchDisabled: that would add the EXPERIMENT_ spelling and change behavior/reachability.'},AUTH_DISABLE_EMAIL_VERIFICATION:{key:"AUTH_DISABLE_EMAIL_VERIFICATION",envVars:["AUTH_DISABLE_EMAIL_VERIFICATION"],polarity:"1-enables",defaultState:"off",surfaces:["web-next-node"],cloudForwarded:!1,read:"env-direct",gates:"On-prem escape hatch: disables signup email verification; IGNORED (fail-safe) on a hosted Vercel deploy where VERCEL/VERCEL_ENV is present.",designDoc:"apps/web-next/lib/auth-flags.ts",status:"active",added:"2026-06-01",notes:"Not AGENTIQA_-prefixed. Static process.env member access (edge-safe). Hosted-platform sentinel forces it off on Vercel.",graduation:{status:"permanent",gate:"On-prem operational escape hatch, not an experiment \u2014 never graduates; forced off on hosted Vercel"}},ORG_ENTITLEMENT_ENABLED:{key:"ORG_ENTITLEMENT_ENABLED",envVars:["ORG_ENTITLEMENT_ENABLED"],polarity:"0-disables",defaultState:"on",surfaces:["web-next-node"],cloudForwarded:!1,read:"env-direct",gates:'Company-plan org entitlement (O0+): when on, an active OrgMembership resolves the billing subject to the org and its plan wins over the personal plan in all entitlement gates; "0" forces the personal subject everywhere (org rows become inert).',designDoc:"docs/plans/2026-07-11-company-plan-access-control-design.md",status:"active",added:"2026-07-11",notes:"Not AGENTIQA_-prefixed. Static process.env member access via isOrgEntitlementEnabled() in apps/web-next/lib/billing-subject.ts (single read point). Dark by data until an Organization row exists \u2014 with zero orgs the flag has no observable effect."},EXTENSION_PROFILE_PERSISTENCE:{key:"EXTENSION_PROFILE_PERSISTENCE",envVars:[],polarity:"1-enables",defaultState:"on",surfaces:["desktop-main","desktop-renderer"],cloudForwarded:!1,read:"compile-const",gates:"Saves/restores a per-project Chrome profile (cookies/storage) across sessions so login can be skipped on replay; a false value skips profile persistence.",designDoc:"apps/desktop-next/src/renderer/featureFlags.ts",status:"active",added:"2026-06-01",notes:"Hardcoded TypeScript boolean (`= true`), no env var \u2014 a compile-time gate flipped by editing the const. Defined twice: apps/desktop-next/src/renderer/featureFlags.ts and apps/desktop-next/src/main/computerUse/DesktopPlaywrightService.ts (the main-process copy is the one actually consumed)."},TRANSIENT_ENV_RETRY:{key:"TRANSIENT_ENV_RETRY",envVars:["AGENTIQA_TRANSIENT_ENV_RETRY","AGENTIQA_EXPERIMENT_TRANSIENT_ENV_RETRY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Transient-environment retry-once policy (RunnerRuntime / test-plan runs only, v1 \u2014 never ExplorerRuntime/chat). Motivating incident: staging run run_9fff560a \u2014 the app's POST to its own API failed transiently (console: CORS block + AxiosError "Network Error"), the agent waited 2\xD730s, then filed report_issue and blocked after ONE attempt; later probing showed the API healthy. When on, a report_issue (or the ensuing exploration_blocked) whose failure is a DETERMINISTIC transient-environment stall \u2014 BOTH a stall/timeout symptom (a wait/wait_for_element in the evidence window, or explicit stall/network phrasing; never a content/assertion mismatch) AND an environment signature in the captured EventDigest (any failedRequests, a console/page error matching the network class \u2014 CORS / "Network Error" / AxiosError / net::ERR_ / "fetch failed" \u2014 or an explicit 5xx write) \u2014 is BOUNCED once with a structured instruction to repeat the triggering action and report only if it reproduces, tracked per step index. The second matching failure at the SAME step passes through and the runtime (not the model) stamps the issue evidence JSON with attempts:2, both attempt timestamps, both EventDigest snapshots, sets category='environment', and appends 'Reproduced on retry \u2014 2 attempts.' to the description. Bounds: exactly 1 retry per step, max 2 retried steps per run; a further environment stall after the budget is spent passes through with attempts:1 and the note 'Environment degraded \u2014 not retried (budget exhausted).'. A run-mode prompt nudge asks the agent to retry proactively; the deterministic gate is the backstop (never trust LLM compliance). Off \u21D2 every environment failure files immediately on the first attempt, byte-identical to pre-change behavior. Non-environment failures are never retried regardless of this flag.`,designDoc:"docs/plans/2026-07-23-transient-env-retry-once-design.md",status:"active",added:"2026-07-23",notes:"Ships default-ON from inception (not graduated from an off default) \u2014 the policy is a strict reduction of a confirmed false-block class (one transient blip \u2192 a blocked run + a filed non-defect issue), so there is no pre-change OFF behavior to preserve. Registered in killSwitchDefaultState.test.ts INTENTIONALLY_GRADUATED (the tripwire acknowledging the default-ON state deliberately). Deterministic classifier + state machine in packages/engine-core/src/transientEnvRetry.ts; the kill-switch read + wiring live at packages/engine-core/src/RunnerRuntime.ts handleReportIssue / handleBlocked. Runner lane only."},PREDICATE_BASIS_COMPILE:{key:"PREDICATE_BASIS_COMPILE",envVars:["AGENTIQA_PREDICATE_BASIS_COMPILE","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_COMPILE"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:`Trust-layer predicate basis \u2014 Slice B AUTOFORMALIZATION COMPILER (design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md). "Compile-don't-parse": at AUTHORING an LLM COMPILES a natural-language assertion into a typed Slice-A logical form (Predicate) over named observables \u2014 autoformalization (utterance \u2192 logical form \u2192 executor \u2192 denotation) \u2014 NOT a verdict. Slice A shipped the schema + generic deterministic executor; Slice B produces the forms the executor denotes. TASK-BLIND: the compiler compiles the assertion's MEANING (including any pinned expected value the assertion text itself carries) and never sees the observed screen or pass/fail \u2014 the firewall keeps the LLM out of the DECISION (Slice A's deterministic executor owns pass/fail). GRAMMAR-CONSTRAINED \u2192 MECHANICAL ABSTAIN: the model may only emit an in-grammar kind (count/delta/absence/modification/presence/typed) or the explicit not_groundable escape; compileToPredicate then STRICTLY validates the chosen kind's operands, so an inherently-subjective assertion ("the agent responds correctly", "looks clean") or an in-grammar kind with missing/invalid operands routes to a first-class ABSTAIN (AbstainNode) \u2014 NEVER a forced/invalid form. The grammar's expressiveness IS the verifiable/subjective boundary. v1 = structured output + strict schema validation + a groundability decision; full constrained decoding (PICARD) is a later refinement (TODO). GRADUATED default-ON 2026-07-27 (alongside PREDICATE_BASIS_VERIFY, which is the live consumer that routes a compiled form to a step result); the emergency kill-switch is retained and byte-identical WHEN FORCED OFF: the seam (runAssertionCompile / runRedundantCompile) short-circuits to \`disabled\` (ZERO model calls) when AGENTIQA_PREDICATE_BASIS_COMPILE=0 \u2014 and with COMPILE forced off but VERIFY on the compiler returns a disabled result \u2192 ABSTAIN (safe, never a manufactured verdict). Cost when on: one auxiliary structured-output call per compiled assertion (cost-isolated via emitAuxiliaryLlmUsage \u2014 not a billable step), thinkingBudget:0, hard-capped by a per-call timeout; fail-closed (error/empty/timeout/out-of-grammar \u2192 ABSTAIN).`,designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-26",notes:"GRADUATED 2026-07-27 (default ON) \u2014 the authoring-side ARc compiler that feeds the LIVE verify wiring (PREDICATE_BASIS_VERIFY, graduated in the same PR). Turn-on = BOTH flags ON: with VERIFY on, runPredicateBasisVerify calls runRedundantCompile, which rides THIS flag; on \u21D2 the compiler produces the logical forms the deterministic executor denotes. Slice B (authoring-side compiler) + Slice C (ARc redundant-compile: compile k\xD7 \u2192 ABSTAIN on disagreement/degeneration, attacking the factKind-wrong-kind gap) are the compile consumers of this flag. GRADUATION EVIDENCE: the flagship live-replay benchmark (PR #1879) returned GATE=GO \u2014 zero-regression on the prod Lio (semantic-reference) + Miro (canvas) corpora, the firewall intact (a groundable contradiction FAILS; nothing ungroundable is ever a hard PASS), the vision/canvas path abstains, and the #1876 DOM-reachability fix live-confirmed. TASK-BLIND / FIREWALL (unchanged): the compiler compiles the assertion's MEANING (never sees the observed screen nor pass/fail); Slice A's deterministic executor owns the decision. GRAMMAR-CONSTRAINED \u2192 MECHANICAL ABSTAIN: an inherently-subjective or out-of-grammar assertion routes to a first-class ABSTAIN (AbstainNode), never a forced/invalid form. Off (explicit AGENTIQA_PREDICATE_BASIS_COMPILE=0) is byte-identical to pre-graduation: runAssertionCompile / runRedundantCompile short-circuit to `disabled` with ZERO model calls, and with COMPILE off but VERIFY on the compiler returns a disabled result \u2192 ABSTAIN (safe, never a manufactured verdict) \u2014 the emergency kill-switch still works. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND PREDICATE_BASIS_COMPILE listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read site: packages/engine-core/src/predicateBasis/compile.ts (runAssertionCompile) + packages/engine-core/src/predicateBasis/redundantCompile.ts (runRedundantCompile). Cost when on: one auxiliary structured-output call per compiled assertion, cost-isolated via emitAuxiliaryLlmUsage (not a billable step), thinkingBudget:0, hard-capped, fail-closed (error/empty/timeout/out-of-grammar \u2192 ABSTAIN). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisCompile.test.ts + predicateBasisRedundantCompile.test.ts. Compile-correctness benchmark: e2e/benchmark/compileCorrectness.ts. Binds claims verify.predicate-basis-compile-correctness + verify.predicate-basis-redundant-compile. STAGING-FIRST: merging to staging makes this default-ON on the STAGING engine only; PROD stays OFF until a later staging\u2192main release carries it (a natural staged soak). PREDICATE_BASIS_CONSENSUS (Slice D vision-consensus) stays default-OFF \u2014 vision-consensus is safe ONLY as abstain, not turn-on-ready (the P2 dense-abstain finding)."},PREDICATE_BASIS_CONSENSUS:{key:"PREDICATE_BASIS_CONSENSUS",envVars:["AGENTIQA_PREDICATE_BASIS_CONSENSUS","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_CONSENSUS"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Trust-layer predicate basis \u2014 Slice D: (1) CONSENSUS EXTRACTION/RESOLUTION and (2) the SEMANTIC-TOLERANCE FALLBACK TIER (design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md \u2014 \xA7 three buckets bucket-2 canvas "task-blind extraction + deterministic comparison + consensus-or-abstain", \xA7 the @reference resolution consensus/abstain, \xA7 "Semantic as a fallback tier, not a peer primitive"; north star hard-part #1 "the extractor itself can be wrong: miscount a canvas, misread"). CONSENSUS: task-blindness removes confirmation bias but NOT perception error (the model genuinely miscounts a canvas / mis-resolves "the cart total"); the no-false-positive mitigation is N INDEPENDENT task-blind extractions must AGREE, else ABSTAIN \u2014 one mechanism serving BOTH the vision/canvas path AND the semantic-reference resolution risk. SEMANTIC-TOLERANCE: run the DETERMINISTIC executor FIRST; invoke the task-blind concept classifier ONLY when the deterministic comparison cannot decide (tolerance:semantic OR an inconclusive comparison) \u2014 confident semantic = Verified, ambiguous = Assessed (a lean + confidence, never a grounded badge, never a manufactured pass \u2014 the bucket-3 Assessed slot). SHADOW / behavior-neutral even when ON: NOT wired into any live RunnerRuntime verdict path \u2014 the two drivers are consumed only by the consensus benchmark + unit tests. Off \u21D2 ZERO extractor/classifier calls, byte-identical; Slice-A deterministic parity is UNAFFECTED (the semantic tier COMPOSES the untouched evaluate, only reached on an inconclusive result).',designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-26",notes:"Trust-layer predicate basis Slice D (consensus extraction/resolution + semantic-tolerance fallback tier). Default OFF; SHADOW / behavior-neutral even when ON \u2014 the two drivers produce would-be results and are wired into NO live verdict path (consumers: the consensus benchmark + unit tests). Read sites: packages/engine-core/src/predicateBasis/consensusExtract.ts (runConsensusExtraction \u2192 killSwitchEnabled('PREDICATE_BASIS_CONSENSUS'); zero extractor calls when off) + packages/engine-core/src/predicateBasis/semanticTolerance.ts (runSemanticTolerance \u2192 killSwitchEnabled('PREDICATE_BASIS_CONSENSUS'); zero classifier calls when off). CONSENSUS-EXTRACT: a PURE reducer (reduceNumericConsensus / reduceCategoricalConsensus \u2014 N observations \u2192 accept-on-agreement / ABSTAIN(extraction_disagreement) on numeric-spread-beyond-tolerance or different presence/text; fail-closed extraction_error when no usable sample) + a pure per-frame read (readObservable over count-of / presence-of / value-at) + the thin flag-gated driver over the EXISTING StateExtractor seam (reused, not re-implemented \u2014 N independent samples). SEMANTIC-TOLERANCE: a PURE reducer (resolveSemanticTier \u2014 deterministic-first; decided deterministic \u2192 Verified with no classifier call; inconclusive + eligible + injected classifier \u2192 semanticToSpectrum: confident match/contradiction \u2192 Verified, ambiguous \u2192 Assessed, abstain \u2192 the Inconclusive floor) + the flag-gated driver that COMPOSES the untouched Slice-A evaluate (Slice-A parity byte-identical by construction). Reuses the Slice-2 concept-classifier seam (ConceptClassifier / semanticToSpectrum / renderObservation from groundedStateUnified.ts). Deliberately NOT re-exported from predicateBasis/index.ts (imported directly). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisConsensus.test.ts (deterministic \u2014 injected observations for the consensus reducer; injected classifier RESULT for the semantic tier; flag-OFF zero-calls; fail-closed error\u2192abstain). Consensus benchmark: e2e/benchmark/consensusExtraction.ts (deterministic reducer/tier self-validation always runs; the live N-extraction + classifier measurement is PENDING until a keyed run \u2014 Slice-1/B/C precedent, no fabricated number). Binds claim verify.predicate-basis-consensus-extraction. Slice E (abstain-rate as a first-class COVERAGE metric on a real-assertion corpus) is BUILT: packages/engine-core/src/predicateBasis/coverage.ts (aggregateCoverage \u2014 a PURE reducer folding pipeline-routed assertion outcomes into the Verified/Assessed/Inconclusive distribution + abstain rate + abstain-origin/per-kind breakdown), wired into NO live verdict path (no new flag; the live measurement reuses THIS flag + PREDICATE_BASIS_COMPILE), claim verify.predicate-basis-coverage-abstain-rate, benchmark e2e/benchmark/coverage.ts (deterministic layers real; live full-pipeline number PENDING until keyed). This COMPLETES the predicate-basis v1 build; the remaining work is the KEYED phase (live LLM measurements) + the prod Miro+Lio final gate.",graduation:{status:"gated",gate:"Slice D is shadow / behavior-neutral (two drivers, wired into NO verdict path). Graduation gates on: (1) the consensus benchmark run WITH a model key showing consensus ABSTAINS on genuinely disagreeing/noisy N task-blind extractions and ACCEPTS on agreement (the miscount-a-canvas / mis-resolve-a-reference no-false-positive mechanism), plus a measured abstain-rate on the vision/canvas + semantic-reference corpus; (2) the semantic-tolerance tier measured deterministic-first (a deterministic-decidable case never consulting the classifier) with confident\u2192Verified / ambiguous\u2192Assessed; (3) the engine-core predicateBasisConsensus unit suite green. This is the DEFERRED consensus-extraction that gates ANY vision-path live graduation; the FINAL gate is the prod Miro (canvas) + Lio (semantic-reference) benchmark.",evidence:"e2e/benchmark/artifacts/benchmark-consensus-extraction.{json,md} (consensus abstain/accept + abstain-rate + semantic-tier bands; PENDING until a keyed run) + the engine-core predicateBasisConsensus unit suite + the claim verify.predicate-basis-consensus-extraction",owner:"steering (Alex)",review:"2026-09-05"}},PREDICATE_BASIS_VERIFY:{key:"PREDICATE_BASIS_VERIFY",envVars:["AGENTIQA_PREDICATE_BASIS_VERIFY","AGENTIQA_EXPERIMENT_PREDICATE_BASIS_VERIFY"],polarity:"1-enables",defaultState:"on",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Trust-layer predicate basis \u2014 Slice F LIVE VERIFY WIRING (the FIRST non-shadow slice; design docs/plans/2026-07-26-trust-layer-predicate-basis-design.md \xA7 three buckets; north star docs/plans/2026-07-26-trust-layer-verification-architecture.md \xA7 the verdict spectrum). Slices A\u2013E built the basis as SHADOW machinery wired into NO verdict path; this is the first wiring that lets a compiled logical form FEED A STEP RESULT (the readiness step toward turn-on). When ON, a verify step's assertion routes through the basis: runRedundantCompile (ARc: compile k\xD7 \u2192 ABSTAIN on disagreement/degeneration) \u2192 classifyVerifyBucket \u2192 the deterministic executor / semantic-tolerance tier \u2192 a verdict in the SPECTRUM (Verified-PASS/FAIL | Assessed | Inconclusive) that feeds the step result. SCOPED to the SAFE paths \u2014 everything else ABSTAINS, never manufactures a verdict: DOM-groundable (deterministic executor over structured extraction) \u2192 Verified-PASS/FAIL LIVE (a grounded contradiction FAILS \u2014 the no-false-positive core); confident-semantic (semantic-tolerance, deterministic-first, task-blind classifier) \u2192 Verified, ambiguous \u2192 Assessed (non-blocking WARNING band, never a hard pass/fail); VISION/CANVAS (bucket 2) \u2192 ABSTAIN (Inconclusive/WARNING), NOT enforced \u2014 the mandatory dense-abstain guard from the P2 finding (consensus does NOT eliminate correlated-miscount false-confirms on dense canvases, so vision must NOT produce a live PASS/FAIL yet; a count tally is treated as vision-grounded \u2192 ABSTAIN unless the caller asserts domGrounded); not-groundable / compile-abstain / consensus-abstain \u2192 Inconclusive/Assessed, NEVER a manufactured pass. FIREWALL INVARIANT: a groundable contradiction MUST FAIL; nothing ungroundable is EVER a hard PASS \u2014 verifyStepAction encodes the DEFAULT consequence policy (only a Verified-FAIL gates; a Verified-PASS confirms but never manufactures/overrides a pass; Assessed is a non-blocking warning; Inconclusive leaves the existing verdict). GRADUATED default-ON 2026-07-27 (alongside PREDICATE_BASIS_COMPILE) after the flagship live-replay gate; the emergency kill-switch is retained and BYTE-IDENTICAL WHEN FORCED OFF (non-negotiable): explicit AGENTIQA_PREDICATE_BASIS_VERIFY=0 makes runPredicateBasisVerify short-circuit to disabled with ZERO compile/executor/classifier calls and the RunnerRuntime enforcement pass early-return before any effect. The compile itself rides PREDICATE_BASIS_COMPILE (also graduated), so full turn-on = both flags ON (with VERIFY on but COMPILE forced off the compiler returns a disabled result \u2192 ABSTAIN, safe). STAGING-FIRST: default-ON reaches the STAGING engine on merge; PROD stays OFF until a later staging\u2192main release carries it.",designDoc:"docs/plans/2026-07-26-trust-layer-predicate-basis-design.md",status:"active",added:"2026-07-27",notes:"GRADUATED 2026-07-27 (default ON) \u2014 Slice F LIVE verify wiring, the FIRST live trust-verdict on the predicate basis (turned on alongside PREDICATE_BASIS_COMPILE per Alex's explicit approval after the flagship live-replay gate). When on (and a predicateBasisCompiler is wired at engine boot \u2014 buildDeps.getPredicateBasisCompiler, present whenever a Google key is set), a verify step's assertion routes through the basis: runRedundantCompile (ARc, rides PREDICATE_BASIS_COMPILE) \u2192 classifyVerifyBucket \u2192 the deterministic executor / semantic-tolerance tier \u2192 a SPECTRUM verdict feeding the step result. SCOPED to the SAFE paths \u2014 everything else ABSTAINS, never manufactures a verdict: DOM-groundable \u2192 Verified-PASS/FAIL LIVE (a grounded contradiction FAILS \u2014 the no-false-positive core); confident-semantic \u2192 Verified, ambiguous \u2192 Assessed (non-blocking WARNING); VISION/CANVAS \u2192 ABSTAIN (Inconclusive), NOT enforced \u2014 the mandatory P2 dense-abstain guard (a count tally is vision-grounded \u2192 ABSTAIN unless the caller asserts domGrounded); not-groundable / compile-abstain \u2192 Inconclusive, NEVER a manufactured pass. FIREWALL INVARIANT (unchanged): only a Verified-FAIL gates; a Verified-PASS confirms but never manufactures/overrides a pass; Assessed warns; Inconclusive leaves the existing verdict. GRADUATION EVIDENCE: the flagship live-replay benchmark (PR #1879) returned GATE=GO \u2014 zero-regression on the prod Lio (semantic-reference) + Miro (canvas) corpora, the firewall intact, canvas-abstain intact, and the #1876 DOM-reachability fix live-confirmed; the engine-core predicateBasisVerifyWiring + RunnerRuntime.predicateBasisVerify unit suites are green (flag-OFF byte-identical parity, safe-path enforcement, vision-canvas ABSTAIN, the firewall). BYTE-IDENTICAL WHEN FORCED OFF (emergency kill-switch retained): explicit AGENTIQA_PREDICATE_BASIS_VERIFY=0 restores the pre-graduation behavior \u2014 runPredicateBasisVerify short-circuits to disabled with ZERO compile/executor/classifier calls and the RunnerRuntime enforcement pass early-returns before any effect. killSwitch resolves the no-env value from this defaultState (#1729), so graduation = defaultState 'on' AND PREDICATE_BASIS_VERIFY listed in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire). Read sites: packages/engine-core/src/predicateBasis/verifyWiring.ts (runPredicateBasisVerify) + packages/engine-core/src/RunnerRuntime.ts (predicateBasisVerifyEnabled / the run_complete enforcement pass). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisVerifyWiring.test.ts + RunnerRuntime.predicateBasisVerify.test.ts. E2E proof: e2e/benchmark/predicateBasisVerify.ts. Standing live gate post-graduation: e2e/scenarios/22-verify/01-predicate-basis-dom-enforce.ts asserts the pbv-ON DOM-enforce + canvas-abstain behavior by DEFAULT now (default-ON engine) in the nightly qa-exhaustive path. Binds claim verify.predicate-basis-verify-wiring. STAGING-FIRST: merging to staging makes pbv default-ON on the STAGING engine ONLY (staging deploys from staging); PROD stays OFF until a later staging\u2192main release carries it \u2014 a natural staged soak. VISION-path live PASS/FAIL stays DEFERRED behind PREDICATE_BASIS_CONSENSUS (still default-OFF) regardless of this flag \u2014 vision-consensus is safe ONLY as abstain, not turn-on-ready (the P2 finding)."},ELEMENT_STATE_GROUNDING:{key:"ELEMENT_STATE_GROUNDING",envVars:["AGENTIQA_ELEMENT_STATE_GROUNDING","AGENTIQA_EXPERIMENT_ELEMENT_STATE_GROUNDING"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:'Trust-layer predicate basis \u2014 ELEMENT-STATE grounding (residual track P2, slice 1: BUILD + SHADOW; design docs/plans/2026-07-27-element-state-grounding-design.md). Closes a groundability gap in the DOM-verify path (routeDomVerify / domExtractionSource): the deterministic a11y-outline extraction grounds PRESENCE / ABSENCE / COUNT / MODIFICATION but STRIPS element STATE \u2014 a `- button "Submit" [disabled]` line\'s `[disabled]`, an `aria-checked` / `[selected]` / `[expanded]` marker, and an input\'s inline value \u2014 so an assertion like "the Submit button is enabled" is NOT DOM-groundable and falls through to flaky model-vision grading (the Lio submission s8 flake: a weak vision-only read of button-enabled that varied run-to-run). The a11y snapshot (Playwright _snapshotForAI) DETERMINISTICALLY carries this state; this track parses it into a new `state-of` observable + `element-state` predicate the Slice-A executor denotes over, so enabled/disabled/checked/selected/expanded/value assertions ground deterministically. FIREWALL PRESERVED: a state that is NOT resolvable from the a11y outline (target element not found, dimension not applicable to the role, mixed/unreadable value) ABSTAINS (Inconclusive) \u2014 never force-fails on unresolvable, never manufactures a pass; enforcement stays force-fail-only (only a grounded CONTRADICTION \u2192 would_fail gates). SLICE 1 = SHADOW / behavior-neutral even when ON: the machinery (extraction + NL parser + mapping + the flag-gated driver runElementStateGrounding) is wired into NO live RunnerRuntime verdict path \u2014 consumed only by unit tests (+ a later graduation benchmark). Off \u21D2 ZERO element-state extraction / parse / evaluate, byte-identical (the new observable/extraction runs only under this flag); the existing pbv DOM/count/absence/modification paths are UNTOUCHED. Graduation (benchmark + gate-review + Alex\'s default-on flip + live wiring) is a LATER slice, mirroring the pbv arc.',designDoc:"docs/plans/2026-07-27-element-state-grounding-design.md",status:"active",added:"2026-07-27",notes:"Residual track P2 (element-state grounding) slice 1 \u2014 BUILD + SHADOW behind a default-OFF killSwitch, mirroring the predicate-basis Slice A\u2013E / Slice-D CONSENSUS shadow precedent (pure machinery + flag-gated driver, wired into NO live verdict path). Read site: packages/engine-core/src/predicateBasis/elementState.ts (runElementStateGrounding \u2192 killSwitchEnabled('ELEMENT_STATE_GROUNDING'); zero element-state work when off). PURE machinery (also in elementState.ts, always safe to call, exercised in the unit suite): extractElementStatesFromAriaSnapshot (per-a11y-line state parse keyed on Playwright's exact role\u2192dimension applicability \u2014 kAriaDisabledRoles / kAriaCheckedRoles / kAriaSelectedRoles / kAriaExpandedRoles \u2014 so absence-of-marker on an applicable role reads as false, and a non-applicable role ABSTAINS rather than guessing), parseElementStateAssertion (deterministic NL \u2192 {ref, dimension, expected}; returns null when no state vocabulary is present so it is additive), elementStateQueryToLogicalForm (\u2192 the `element-state` node), and evaluateElementState (in executor.ts, the Slice-A generic executor's new case \u2014 resolves the target element in frames.after.elementStates, reads the dimension, denotes PASS on confirm / FAIL on a grounded contradiction / INCONCLUSIVE on any unresolvable \u2014 target absent, dimension N/A, mixed/ambiguous). GROUNDABLE STATES: enabled/disabled (fully both directions \u2014 the Lio s8 case), checked/unchecked, selected, expanded (PASS on [expanded] + FAIL on a collapsed-assertion contradiction; absence ABSTAINS \u2014 collapsed vs non-expandable is not distinguishable in the outline), and input value (normalized-equality; typed/locale-tolerant value comparison is a follow-up routing to compareTyped). Acceptance tests: packages/engine-core/src/__tests__/predicateBasisElementState.test.ts (extraction, parser, mapping, executor firewall, flag-OFF zero-work / byte-identical, registry-presence freshness canary). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 GRADUATING = flip defaultState to 'on' AND add ELEMENT_STATE_GROUNDING to INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts (the tripwire); slice 1 stays OFF.",graduation:{status:"gated",gate:"Slice 1 is BUILD + SHADOW (pure machinery + a flag-gated driver, wired into NO verdict path). Graduation gates on the LATER slice: (1) an element-state graduation-benchmark run showing enabled/disabled/checked/selected/expanded/value ground deterministically from the a11y outline (a grounded contradiction \u2192 would_fail FIXES the Lio-s8-class vision flake; an unresolvable state \u2192 ABSTAIN, no false-PASS / no false-FAIL) and adversarially proven able to say NO-GO; (2) wiring runElementStateGrounding into the RunnerRuntime run_complete enforcement pass (force-fail-only, alongside applyPredicateBasisVerify); (3) the engine-core predicateBasisElementState unit suite green + flag-OFF byte-identical; then Alex flips the default-on (and lists it in INTENTIONALLY_GRADUATED). Mirrors the pbv graduation arc (shadow \u2192 benchmark \u2192 gate-review \u2192 default-on).",evidence:"e2e/benchmark element-state corpus (grounded PASS/FAIL vs ABSTAIN; Lio-s8 vision flake fixed; PENDING until the graduation slice) + the engine-core predicateBasisElementState unit suite + the (later) claim verify.element-state-grounding",owner:"steering (Alex)",review:"2026-08-15"}},VERIFY_CONFLICT_RECONCILE_SNAPSHOT:{key:"VERIFY_CONFLICT_RECONCILE_SNAPSHOT",envVars:["AGENTIQA_VERIFY_CONFLICT_RECONCILE_SNAPSHOT","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_RECONCILE_SNAPSHOT"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Verify-conflict DETERMINISTIC snapshot reconcile \u2014 M1 of the verify-oracle reconcile design (docs/plans/2026-07-28-verify-oracle-reconcile-design.md; GH #1907, root cause of #1813). WHAT IT DECIDES: at the SECOND verification-conflict escalation ONLY (the run_complete pass that would otherwise force-FAIL; the first bounce is untouched, and the bounce alone already resolves ~73% of oracle failures), the runtime takes ONE forced-full a11y snapshot for the whole run and re-checks each conflicted step's recorded wait literal (`_verifyOracleFailureDetails[step].literal`) against it with the SAME whole-token `pinPresentInPage` matcher, under the `waitLiteralHasSignificantTokens` significance floor. ZERO LLM calls \u2014 the model is not in the loop, so a lie about a genuinely broken wait fails constructively. THREE OUTCOMES: (a) literal significant AND present in the fresh snapshot \u2192 CLEARED: the oracle failure is removed from the ledger, the step's own already-passed criteria grades stand, the step passes, and the step is TAINTED via noteStepReopenedForReverify (the runtime consumed a re-observation it demanded, so predicate-basis-verify must not enforce over a basis it cannot attribute \u2014 the same invariant the bounce path carries); (b) literal significant and ABSENT from the fresh snapshot \u2192 GROUNDED NEGATIVE: the hard fail stands and the step is permanently INELIGIBLE for the VERIFY_CONFLICT_WITHHOLD warning band; (c) INAPPLICABLE \u2014 which is the only input VERIFY_CONFLICT_WITHHOLD (M2) ever sees \u2014 for no literal / insignificant literal / capture failed / budget already spent / the plan-derived `pin_page_grounding` oracle (excluded WHOLESALE \u2014 a plan-pin failure is a deterministic contradiction, not an absence of confirmation) / **any negation-or-absence marker on the step text or a criterion check** (`stepCarriesNegationOrAbsenceMarker`, reason `negation_marker`: a presence-clear is INVERTED for an assertion that the target is gone, and the absence lane's routing lexicon is narrow BY DESIGN, so this deliberately broader screen \u2014 not/no/none/without/missing/gone/empty/removed/deleted/closes/hidden/disappear*/vanish*/clear*/away/left-the-list/moves-to-trash/ceases-to/count-drops/zero-rows/fewer/struck-through/back-to-default/\u2026 plus a minimal DE/FR set, read over prose with only the target literal's OCCURRENCES removed (round-3: the earlier strip also deleted every \u22654-char TOKEN of the literal from the whole check, so a destination name like 'Deleted Items' silently disarmed the screen) \u2014 keeps every such step ineligible. HONEST LIMIT: this is a best-effort keyword screen over open-ended NL and completeness is unreachable; a phrasing it misses stays eligible and can be presence-cleared. The guarantee for absence assertions is the ABSENCE_AWARE_VERIFY lane, which decides with evidence rather than vocabulary) / **a literal that is not PLAN-GROUNDED whole-token with \u22652 tokens** (`waitLiteralGroundsSnapshotClear`, reason `literal_not_plan_grounded`: a CLEAR is only sound when the literal is the AUTHOR's expectation, read with the same `pinPresentInPage` matcher against the step text + criteria check/expectedValue \u2014 a model-invented literal that whole-token-matches unrelated chrome on another screen proves nothing, and a one-token literal is never distinctive enough even when the plan does contain it. KNOWN BOUNDARY, documented not fixed (round-3): this gate reads AUTHORSHIP, never PLACE \u2014 an AUTHORED literal that appears in unrelated chrome (a nav item, a help-sidebar link, the header of an Error 500 page) CLEARS exactly as it would in the region the step names; page-state and container binding are the next slice, and until then such clears are only visible in the `verify_conflict_reconcile:would_clear` census the graduation soak reads). Every inapplicable decision is logged per step as `verify_conflict_reconcile:inapplicable` with its reason. DETECTION ALWAYS RUNS (shadow): with the flag OFF the same decision is computed against the RETAINED full-snapshot corpus (`_fullSnapshotByStep`) \u2014 NO fresh capture, so OFF stays byte-identical including ZERO extra browser actions \u2014 and logged as `verify_conflict_reconcile:would_clear` / `:would_fail` with `basis:'retained_snapshot'` and `enforced:false`; ON logs the same events with `basis:'fresh_snapshot'` and `enforced:true`. Exactly ONE reconcile snapshot per run (guarded); a second escalation after the budget is spent decides INAPPLICABLE rather than re-enforcing off a stale page. NOT COVERED BY THIS FLAG (deferred slices, see the design \xA7 4): dropping `wait_for_element` from VERIFY_EVIDENCE_ACTIONS (own flag `VERIFY_EVIDENCE_REQUIRE_CAPTURE`, needs a shadow taint-rate measurement first), and still-running-vs-terminal recognition (a nested run still in flight at run end reads as a grounded negative and correctly stays red in this slice \u2014 the honest known gap). Runner lane only (RunnerRuntime run_complete).",designDoc:"docs/plans/2026-07-28-verify-oracle-reconcile-design.md",status:"active",added:"2026-07-28",notes:"M1 of the verify-oracle reconcile track (design docs/plans/2026-07-28-verify-oracle-reconcile-design.md), default OFF. Fixes the residual verify-conflict FALSE-FAIL that `canReconcileVerificationConflict` deliberately refuses: a PLAN-GROUNDED wait literal (repro run_5a6f0681 step 2, plan tp_vmlio_d1360115, literal 'QA Base \u2014 Draft Completion (do not modify)'; asess_1785247451027 step 1 is the same shape). That refusal is CORRECT as a static rule \u2014 a plan-grounded literal is a real must-pass presence oracle \u2014 so the fix is not to relax the rule but to consult the PAGE one more time: the element rendered late, and a fresh forced-full snapshot proves it. THREE FACTUAL CORRECTIONS to #1907 this design records (staging code, not the issue's reading): (a) evidence is NOT recorded on a timed-out oracle \u2014 the `_verifyEvidenceStepIndexes` add sits in the SUCCESS branch, so a timeout does not satisfy the evidence gate; (b) 'criteria are advisory' is too broad \u2014 `deriveStepStatusFromCriteria` does derive from grades; the real root is that the verify-conflict force-fail OVERRIDES already-passed criteria because `oracleConflictReason` never sees stepResults; (c) an existing valve (`canReconcileVerificationConflict`) already reconciles the non-plan-grounded case to a full PASS \u2014 the residual false-fail is exactly its plan-grounded refusal branch, not the whole mechanism. Read site: packages/engine-core/src/RunnerRuntime.ts (verifyConflictReconcileSnapshotEnabled \u2192 reconcileVerifyConflictsFromSnapshot, called from the second verification-conflict escalation in handleRunComplete). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts (B-R1 repro form + B-C1..B-C9 counter-probes + the flag-OFF parity / one-snapshot-per-run invariants). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 graduating means flipping defaultState to 'on' AND listing the key in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts.",graduation:{status:"gated",gate:"Graduation gates on the LIVE harness, not on units: Chin's ci-first-plan `tp_c0dcd706` run \xD710 against staging with the flag ON \u2014 baseline is 0/10, the target is \u22658/10 on the step-9 mode (post-login redirect), with the cleared-vs-would_fail split reported from the `verify_conflict_reconcile:*` diags. The step-17 mode (nested run still in flight at run end) is EXPECTED to stay red in this slice; if it turns green the significance threshold is leaky and that is a bug to investigate, NOT evidence to graduate on. Plus: a staging shadow soak of `verify_conflict_reconcile:would_clear` / `:would_fail` sizing the cleared rate and confirming no would_clear fires on a genuinely-absent target, and the engine-core verifyConflictReconcile unit suite green with flag-OFF parity over the full runner corpus.",evidence:"staging `verify_conflict_reconcile:would_clear` / `:would_fail` diag events (cleared rate, basis, per-step literals) + the tp_c0dcd706 \xD710 harness pass rate per failure mode + packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts",owner:"steering (Alex)",review:"2026-08-15"}},VERIFY_CONFLICT_WITHHOLD:{key:"VERIFY_CONFLICT_WITHHOLD",envVars:["AGENTIQA_VERIFY_CONFLICT_WITHHOLD","AGENTIQA_EXPERIMENT_VERIFY_CONFLICT_WITHHOLD"],polarity:"1-enables",defaultState:"off",surfaces:["engine"],cloudForwarded:!0,read:"killSwitch-enabled",gates:"Verify-conflict RESIDUAL WARNING policy \u2014 M2 of the verify-oracle reconcile design (docs/plans/2026-07-28-verify-oracle-reconcile-design.md). Strictly downstream of VERIFY_CONFLICT_RECONCILE_SNAPSHOT (M1): it sees ONLY the conflicts M1 could not decide (no captured literal, an insignificant literal, a failed capture, or the reconcile budget already spent) and NEVER a step M1 read as a GROUNDED NEGATIVE \u2014 a target the runtime looked for and did not find always stays a hard FAIL. When ON, such a residual conflict is soft-withheld to a step-level WARNING ('could not be independently confirmed on this run') instead of force-FAILing the run. ALL SEVEN conditions must hold or the existing force-fail stands: (1) the unresolved oracle is a wait-style action, never the plan-derived `pin_page_grounding` oracle; (2) every graded criterion on the step passed with a non-empty substantiation note (the same bar `canReconcileVerificationConflict` uses) AND the step result is still 'passed' with no other deterministic negative on it (no reobserve-withhold, no upstream floor having already flipped it) ; (3) \u22651 STRICT criterion carries an engine-corroborated concrete value \u2014 its `observed` (or, absent that, its pinned `expectedValue`) is whole-token present in the retained page corpus via `pinPresentInPage`; (4) the wait literal's significant tokens are corroborated by the `observed`/note corpus of some passed criterion (this is what links 'what we waited for' to 'what was confirmed', and it is why a short/frequent literal like 'ok' or '3' can never withhold \u2014 the significance floor rejects it); (5) the step is NOT absence-intent (`checkTextAssertsAbsence` \u2014 that shape belongs to ABSENCE_AWARE_VERIFY, which owns its own confirm/abstain ladder) and, since that lexicon is narrow by design, ALSO carries no negation-or-absence marker at all under the broader M1 screen (`stepCarriesNegationOrAbsenceMarker`, reason `negation_marker`) \u2014 a warning there would withdraw a force-fail the engine has no evidence to withdraw; (6) \u2014 folded into (2) \u2014 no other deterministic negative on the step; (7) the step was OBSERVED AGAIN after the conflict bounce (a runtime capture-sequence watermark taken at the bounce; a verbatim resubmit of pre-bounce grades never withholds). DETECTION ALWAYS RUNS (shadow): `verify_conflict_withhold:would_withhold` (and a reasoned `:inapplicable`) is logged with `enforced:` reflecting the flag, so OFF is byte-identical with telemetry only. KNOWN, DELIBERATE SIDE EFFECTS when enforcing (asserted in CI, not accidents): withdrawing the forced conflict fail leaves `terminationReason='completed'`, which makes the run BILLABLE; and no 'Potential Issue Detected' card is synthesized for a withheld step \u2014 one fewer false issue. Runner lane only (RunnerRuntime run_complete).",designDoc:"docs/plans/2026-07-28-verify-oracle-reconcile-design.md",status:"active",added:"2026-07-28",notes:"M2 of the verify-oracle reconcile track, default OFF and inert unless M1's decision for the step is INAPPLICABLE. The honesty floor is the point: a withheld step is a WARNING \u2014 never a pass, never a fail \u2014 so this flag can only ever move a run out of a false RED into an honest AMBER, and it can never manufacture a green. The grounded-negative exclusion is the hard invariant (design \xA7 3): M1 having actually read the page and not found the target is exactly the evidence that the step is genuinely broken, so those never enter this path. Measured coverage of conditions (2)-(4) on the design's corpus is 32/33 steps; the one exception (staging ck-cli_test 2026-07-28 step 17, a genuinely failed criterion) correctly stays red. Read site: packages/engine-core/src/RunnerRuntime.ts (verifyConflictWithholdEnabled \u2192 classifyVerifyConflictWithhold, applied at the second verification-conflict escalation after the M1 pass). Acceptance tests: packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts (B-C2/B-C3/B-C5/B-C6 keep the reds red; B-C8 asserts the billing invariant deliberately). killSwitch resolves the no-env value from this defaultState (#1729) \u2014 graduating means flipping defaultState to 'on' AND listing the key in INTENTIONALLY_GRADUATED in killSwitchDefaultState.test.ts.",graduation:{status:"gated",gate:"Graduation gates on M1 graduating FIRST (M2 is only meaningful over M1's inapplicable residue), then on a staging shadow soak of `verify_conflict_withhold:would_withhold` showing (a) no would_withhold on a step any deterministic oracle reads as a negative, (b) the withheld population is dominated by genuinely unconfirmable captures rather than real failures \u2014 sampled and hand-adjudicated \u2014 and (c) an explicit product decision on the billing consequence (withdrawing the forced fail makes the run terminate 'completed' and therefore BILLABLE) plus the warning-display semantics review (a withheld step must read as a neutral 'could not confirm', not as an alarm-amber defect).",evidence:"staging `verify_conflict_withhold:would_withhold` / `:inapplicable` diag events (rate + hand-adjudicated sample of the withheld population) + the tp_c0dcd706 harness residue after M1 + packages/engine-core/src/__tests__/RunnerRuntime.verifyConflictReconcile.test.ts",owner:"steering (Alex)",review:"2026-08-15"}}},dre=Object.values(sh);var kL=["run","run the test","run the test plan","run test plan"];function Hv(t){let e=t.toLowerCase().trim();return kL.includes(e)}function Wv(t){return t.replace(/\s+/g," ").trim()}function bs(t){let e=t.indexOf(":");return e===-1?{provider:"google",modelName:t}:{provider:t.slice(0,e),modelName:t.slice(e+1)}}var Hn="google:gemini-3-flash-preview",zv="google:gemini-3-flash-preview";var Ec=[{name:"Green",hex:"#4ade80"},{name:"Blue",hex:"#60a5fa"},{name:"Purple",hex:"#a78bfa"},{name:"Amber",hex:"#fbbf24"},{name:"Red",hex:"#f87171"},{name:"Cyan",hex:"#22d3ee"},{name:"Pink",hex:"#f472b6"},{name:"Slate",hex:"#94a3b8"}];function ve(t){return`${t}_${crypto.randomUUID()}`}function So(t,e){return typeof process>"u"||!process.env?!1:process.env[`AGENTIQA_${t}`]===e||process.env[`AGENTIQA_EXPERIMENT_${t}`]===e}function Kv(t){return sh[t]?.defaultState}function Le(t){return So(t,"0")?!0:So(t,"1")?!1:Kv(t)==="off"}function Ge(t){return So(t,"1")?!0:So(t,"0")?!1:Kv(t)==="on"}function Yv(t){return So(t,"0")}function Eo(){return Ge("VALUE_GROUNDING_ENFORCE")}function ih(t){return`${t}_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}function Jv(t){switch(t){case"message":return"msg";case"tool_call":return"tool";case"llm_usage":return"llm";case"supervisor_verdict":return"sv";case"agent_lifecycle":return"lc";case"user_action":return"ua";case"session_start":case"session_end":case"turn_start":case"turn_end":return"sl";case"log":case"pageSnapshot.structuralStrip":return"diag";default:return"evt"}}var Hi=class{apiUrl;fetchFn;sessions=new Map;queues=new Map;timer=null;isUploading=!1;inFlight=new Set;eventIds=new WeakMap;directUploadFailedSessions=new Set;BATCH_SIZE=25;FLUSH_INTERVAL=6e4;MAX_PAYLOAD_BYTES=35e5;auth;constructor(e,n,r=globalThis.fetch.bind(globalThis)){this.apiUrl=e,this.fetchFn=r,this.auth=typeof n=="string"?{kind:"bearer",token:n}:n,this.timer=setInterval(()=>this.flushAll(),this.FLUSH_INTERVAL)}buildAuthHeaders(e,n=!1){let r={"Content-Type":"application/json"};if(this.auth.kind==="bearer")return r.Authorization=`Bearer ${this.auth.token}`,r;if(n&&this.auth.bearerFallback)return r.Authorization=`Bearer ${this.auth.bearerFallback}`,r;r["x-admin-service-key"]=this.auth.serviceKey;let s=e?.userId??this.auth.fallbackUserId;return s&&(r["x-user-id"]=s),r}hasBearerFallback(){return this.auth.kind==="service"&&!!this.auth.bearerFallback}emit(e){let n=e.sessionId;if(this.eventIds.has(e)||this.eventIds.set(e,ih(Jv(e.kind))),e.kind==="session_start"&&e.sessionMeta&&this.sessions.set(n,{...e.sessionMeta,desktopSessionId:n,status:"active",startedAt:new Date(e.ts).toISOString()}),e.kind==="session_end"){let s=this.sessions.get(n);s&&(s.status=e.status??"completed",s.endedAt=new Date(e.ts).toISOString())}if(this.isProviderLocationUnsupportedEvent(e)){let s=this.sessions.get(n);s&&(s.terminalErrorClass="provider_location_unsupported")}!n&&!this.sessions.has("")&&this.sessions.set("",{desktopSessionId:"global",projectId:"_global",status:"active",startedAt:new Date(e.ts).toISOString()});let r=this.queues.get(n);r||(r=[],this.queues.set(n,r)),r.push(e),r.length>=this.BATCH_SIZE&&this.flushSession(n),e.kind==="session_end"&&this.flushSession(n)}async flush(){await this.flushAll()}destroy(){this.timer&&(clearInterval(this.timer),this.timer=null),this.flushAll()}async flushAll(){let e=[];for(let r of this.queues.keys()){let s=this.flushSession(r);s&&e.push(s)}let n=Array.from(this.inFlight);await Promise.allSettled([...e,...n])}flushSession(e){let n=this.sessions.get(e),r=this.queues.get(e);if(!n||!r||r.length===0)return null;let s=r.splice(0),i=this.uploadWithRetry(n,s).catch(a=>{let o=s.filter(l=>l.kind==="session_end");if(o.length>0){let l=this.queues.get(n.desktopSessionId);l&&l.unshift(...o)}console.error(`[RemoteAnalyticsSink] Failed to upload ${s.length} events:`,a.message)});return this.inFlight.add(i),i.finally(()=>{this.inFlight.delete(i)}),i}async uploadWithRetry(e,n,r=3){let s;for(let i=1;i<=r;i++)try{await this.upload(e,n);return}catch(a){s=a;let o=a?.status;if(o!==void 0&&o>=400&&o<500)throw a;if(i<r){let l=Math.min(1e3*Math.pow(3,i-1),9e3);await new Promise(c=>setTimeout(c,l))}}throw s}async upload(e,n){let r=await this.mapEvents(e.desktopSessionId,n);await this.postIngest(e,r)}async postIngest(e,n,r=!1){if(n.length===0)return;let s=JSON.stringify({session:{...e},events:n});if(s.length>this.MAX_PAYLOAD_BYTES&&n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}let i;try{i=await this.fetchFn(`${this.apiUrl}/api/analytics/ingest`,{method:"POST",headers:this.buildAuthHeaders(e,r),body:s})}catch(l){throw new Error(`analytics upload network error: ${l?.message??String(l)}`)}if(i.ok)return;if((i.status===401||i.status===403)&&!r&&this.hasBearerFallback()){console.warn(`[RemoteAnalyticsSink] service-key auth got ${i.status} for session ${e.desktopSessionId} \u2014 retrying with bearer fallback (AG-169)`),await this.postIngest(e,n,!0);return}if(i.status===413){if(n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}console.warn(`[RemoteAnalyticsSink] Dropping single oversized event (${Math.round(s.length/1024)} KB)`);return}let a=await i.text().catch(()=>`HTTP ${i.status}`);if(a.includes("FUNCTION_PAYLOAD_TOO_LARGE")||a.includes("Request Entity Too Large")){if(n.length>1){let l=Math.floor(n.length/2);await this.postIngest(e,n.slice(0,l),r),await this.postIngest(e,n.slice(l),r);return}console.warn(`[RemoteAnalyticsSink] Dropping single oversized event (${Math.round(s.length/1024)} KB)`);return}(i.status===401||i.status===403)&&console.error(`[RemoteAnalyticsSink] auth_failed status=${i.status} authKind=${this.auth.kind} sessionId=${e.desktopSessionId} userId=${e.userId??"(unset)"} body=${a.slice(0,200)}`);let o=new Error(a);throw o.status=i.status,o}async mapEvents(e,n){let r=[];for(let s of n){let i={timestamp:new Date(s.ts).toISOString(),childId:qi(s.childId)},a=this.eventIds.get(s)??ih(Jv(s.kind));switch(s.kind){case"message":r.push({...i,id:a,eventType:"message",role:s.role,messageText:s.text,toolName:s.actionName,toolArgs:s.actionArgs,url:s.url});break;case"tool_call":{let o;s.screenshotBase64&&(o=await this.uploadScreenshot(e,s.screenshotBase64)),r.push({...i,id:a,eventType:"tool_call",toolName:s.toolName,toolArgs:s.args,toolResult:s.result,screenshotUrl:o,url:s.url,stepIndex:s.stepIndex,actionMetadata:{durationMs:s.durationMs,tokenCount:s.tokenCount}});break}case"llm_usage":r.push({...i,id:a,eventType:"llm_usage",toolName:s.model,promptTokens:s.promptTokens,completionTokens:s.completionTokens,totalTokens:s.totalTokens,runId:s.runId,callKind:s.callKind,keySource:s.keySource,llmProvider:s.llmProvider,billedUnits:s.billedUnits,actionMetadata:{durationMs:s.durationMs,finishReason:s.finishReason,tokenCount:s.tokenCount,messageCount:s.messageCount,systemPromptHash:s.systemPromptHash,lastToolResults:s.lastToolResults,chosenActions:s.chosenActions,textResponse:s.textResponse,cachedInputTokens:s.cachedInputTokens,planStepIndex:s.planStepIndex,planStepType:s.planStepType}});break;case"supervisor_verdict":r.push({...i,id:a,eventType:"supervisor_verdict",actionType:s.verdict,actionMetadata:{verdict:s.verdict,message:s.message,iteration:s.iteration,actionLogSize:s.actionLogSize,stepText:s.stepText,progress:s.progress??null,differential:s.differential??null}});break;case"agent_lifecycle":r.push({...i,id:a,eventType:"agent_lifecycle",actionType:s.event,actionMetadata:{event:s.event,iteration:s.iteration,details:s.details}});break;case"user_action":r.push({...i,id:a,eventType:"user_action",actionType:s.action,actionTargetId:s.targetId,actionMetadata:s.metadata});break;case"session_start":case"session_end":case"turn_start":case"turn_end":r.push({...i,id:a,eventType:"user_action",actionType:s.kind,actionTargetId:s.sessionId,actionMetadata:s.sessionMeta?{...s.sessionMeta}:{status:s.status,...s.kind==="session_end"&&s.endKind?{endKind:s.endKind}:{}}});break;case"log":r.push({...i,id:a,eventType:"diagnostic",actionType:s.level,actionMetadata:{source:s.source,msg:s.msg,...s.data}});break;case"pageSnapshot.structuralStrip":r.push({...i,id:a,eventType:"diagnostic",actionType:s.kind,actionMetadata:{originalLen:s.originalLen,finalLen:s.finalLen,droppedNodeCount:s.droppedNodeCount,foldedRunCount:s.foldedRunCount,capHit:s.capHit}});break;default:{console.warn(`[RemoteAnalyticsSink] dropping unmapped DiagnosticEvent kind=${s.kind}`);break}}}return r}isProviderLocationUnsupportedEvent(e){return e.kind!=="log"?!1:Sr([e.msg,e.source,typeof e.data=="object"&&e.data?JSON.stringify(e.data):""].join(`
|
|
9
9
|
`))}async uploadScreenshot(e,n){let r=ih("img"),s=this.sessions.get(e)??null;if(!Le("SCREENSHOT_DIRECT_UPLOAD")&&!this.directUploadFailedSessions.has(e)){let i=await this.uploadScreenshotDirect(e,s,r,n);if(i)return i;this.directUploadFailedSessions.add(e),console.warn(`[RemoteAnalyticsSink] direct screenshot upload failed for session ${e} \u2014 falling back to legacy base64 upload for this session`)}return this.uploadScreenshotLegacy(e,s,r,n)}async uploadScreenshotDirect(e,n,r,s){let i;try{let d=s.includes(",")?s.split(",")[1]:s;if(d=d.replace(/\s/g,""),d.length===0)return;i=Uint8Array.from(atob(d),f=>f.charCodeAt(0))}catch{return}let a=JSON.stringify({sessionId:e,eventId:r,sizeBytes:i.byteLength}),o=d=>this.fetchFn(`${this.apiUrl}/api/analytics/presign-screenshot`,{method:"POST",headers:this.buildAuthHeaders(n,d),body:a}),l;try{l=await o(!1),(l.status===401||l.status===403)&&this.hasBearerFallback()&&(l=await o(!0))}catch{return}if(!l.ok)return;let c=await l.json().catch(()=>null);if(!c||!c.putUrl||!c.publicUrl)return;let u;try{u=await this.fetchFn(c.putUrl,{method:"PUT",headers:{"content-type":"image/png"},body:i})}catch{return}if(u.ok)return c.publicUrl}async uploadScreenshotLegacy(e,n,r,s){let i=JSON.stringify({sessionId:e,eventId:r,imageBase64:s}),a=o=>this.fetchFn(`${this.apiUrl}/api/analytics/upload-image`,{method:"POST",headers:this.buildAuthHeaders(n,o),body:i});try{let o=await a(!1);if((o.status===401||o.status===403)&&this.hasBearerFallback()&&(console.warn(`[RemoteAnalyticsSink] upload-image service-key auth got ${o.status} for session ${e} \u2014 retrying with bearer fallback (AG-388)`),o=await a(!0)),!o.ok){let c=await o.text().catch(()=>`HTTP ${o.status}`);console.error(`[RemoteAnalyticsSink] upload-image failed status=${o.status} authKind=${this.auth.kind} sessionId=${e} userId=${n?.userId??"(unset)"} body=${c.slice(0,200)}`);return}let l=await o.json().catch(()=>null);if(!l||!l.url){console.warn(`[RemoteAnalyticsSink] upload-image returned no url (success=${l?.success??"(none)"}) for session ${e} \u2014 screenshot_url will be null`);return}return l.url}catch(o){console.error(`[RemoteAnalyticsSink] upload-image network error for session ${e}:`,o.message);return}}};function Ze(t,e){return t.replace(/\{\{timestamp\}\}/g,String(e)).replace(/\{\{unique\}\}/g,RL(e))}function RL(t){let e="abcdefghijklmnopqrstuvwxyz",n="",r=t;for(;r>0;)n=e[r%26]+n,r=Math.floor(r/26);return n||"a"}var Tc=500;function Ic(){return Yv("CLICK_EFFECT_SIGNAL")?"off":Ge("CLICK_EFFECT_SIGNAL")?"enforce":"shadow"}function Wi(){return Ic()==="enforce"}var CL=new Set(["input","select","textarea","option"]),NL=new Set(["checkbox","radio","switch","textbox","searchbox","combobox","listbox","option","spinbutton","slider","menuitemcheckbox","menuitemradio"]);function OL(t){if(!t)return!1;let e=(t.tag??"").toLowerCase(),n=(t.role??"").toLowerCase();return CL.has(e)||NL.has(n)}var PL=`The click was dispatched but no page change was observed within ${Tc}ms (no DOM, text or attribute change, no navigation, no dialog). The target may not have been interactive yet \u2014 for example a freshly navigated page that is still hydrating, where a control is already painted but its handler is not attached. Re-check the element state in the latest screenshot/snapshot and re-perform the action ONCE if it did not take effect; do not assume it succeeded just because it was dispatched.`;function Xv(t,e={}){return t.urlBefore!==t.urlAfter?{effectObserved:!0}:t.dialogsAfter>t.dialogsBefore?{effectObserved:!0}:t.mutationCount==null||t.attrCount==null?{}:t.mutationCount>0||t.attrCount>0?{effectObserved:!0}:OL(e.target)?{effectObserved:!1,suppressedBy:"property-only-control"}:e.canvasDominant?{effectObserved:!1,suppressedBy:"canvas"}:e.suppressAdvisory?{effectObserved:!1,suppressedBy:"caller-note"}:{effectObserved:!1,note:PL}}var ML={type:"string",description:'Brief explanation of what you are doing and why (e.g., "Clicking Login button to access account", "Scrolling to find pricing section")'},DL={type:"string",description:'Name of the screen you are currently looking at (e.g., "Login Page", "Dashboard", "Settings > Billing"). Use consistent names across actions on the same screen.'},LL={type:"array",description:"On the FIRST action of each new screen, list the main navigation elements visible (links, buttons, tabs that lead to other screens). Omit on subsequent actions on the same screen.",items:{type:"object",properties:{label:{type:"string",description:"Text label of the navigation element"},element:{type:"string",description:'Element type: "nav-link", "button", "tab", "menu-item", "sidebar-link", etc.'}},required:["label","element"]}},ah=[{name:"open_web_browser",description:"Open the web browser session.",parameters:{type:"object",properties:{},required:[]}},{name:"screenshot",description:"Capture a screenshot of the current viewport.",parameters:{type:"object",properties:{},required:[]}},{name:"full_page_screenshot",description:"Capture a full-page screenshot (entire scrollable content). Use this for page exploration/verification to see all content at once.",parameters:{type:"object",properties:{},required:[]}},{name:"switch_layout",description:"Switch browser viewport to a different layout/device size. Presets: mobile (390x844), tablet (834x1112), small_laptop (1366x768), big_laptop (1440x900).",parameters:{type:"object",properties:{width:{type:"number",description:"Viewport width in pixels"},height:{type:"number",description:"Viewport height in pixels"}},required:["width","height"]}},{name:"navigate",description:"Navigate to a URL.",parameters:{type:"object",properties:{url:{type:"string"}},required:["url"]}},{name:"click_at",description:'Click a control by its visible name (label), by element ref from the page snapshot, or by normalized coordinates (0-1000 scale). Prefer label for buttons and links that have a clear visible name \u2014 especially on login pages where a "Forgot your password?" link sits right next to the "Sign in" button: naming the control you SEE clicks that exact control on the live page and never the adjacent one. If the target is a <select>, the response returns elementType="select" with availableOptions \u2014 use set_focused_input_value to pick an option. For multi-select, use modifiers: ["Control"] (Windows/Linux) or ["Meta"] (Mac). If the target is a file input, the response returns elementType="file" with accept and multiple \u2014 use upload_file to set files.',parameters:{type:"object",properties:{label:{type:"string",description:'Visible or accessibility name of the control to click (e.g. "Sign in"). When provided, label is preferred over ref/x/y. It resolves against the live page, so it clicks what you see even after a page re-renders and ref numbers change.'},ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"},modifiers:{type:"array",items:{type:"string",enum:["Control","Shift","Alt","Meta"]},description:"Modifier keys to hold during click. Use Control for Ctrl+click (multi-select on Windows/Linux), Meta for Cmd+click (Mac), Shift for range selection."}},required:[]}},{name:"double_click_at",description:"Double-click a control by its visible name (label), by element ref from the page snapshot, or by normalized coordinates (0-1000 scale). Same targeting as click_at. Use to enter edit mode on a cell or shape (a single click only selects) \u2014 the primary way to edit cells/shapes in canvas apps like Miro, Figma, or online spreadsheets, where you target by coordinates.",parameters:{type:"object",properties:{label:{type:"string",description:"Visible or accessibility name of the control to double-click. When provided, label is preferred over ref/x/y."},ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"}},required:[]}},{name:"right_click_at",description:"Right-click (context menu click) at normalized coordinates (0-1000 scale) or by element ref from page snapshot.",parameters:{type:"object",properties:{ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"}},required:[]}},{name:"hover_at",description:"Hover at normalized coordinates (0-1000 scale) or by element ref from page snapshot.",parameters:{type:"object",properties:{ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"}},required:[]}},{name:"type_text_at",description:"Type text into a text input field by visible label, element ref, or coordinates. Prefer label for adjacent form fields with visible labels (for example Contract # vs Booking #). Use ONLY for text inputs (input, textarea, contenteditable). Do NOT use for <select> dropdowns - use click_at to open the dropdown, then click_at again on the option. Coordinates are normalized (0-1000). The response includes typedIntoField with the accessible/visible name of the field that received input.",parameters:{type:"object",properties:{ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},label:{type:"string",description:"Visible or accessibility label of the target text field. When provided, label is preferred over ref/x/y."},x:{type:"number"},y:{type:"number"},text:{type:"string",description:'The text to type. Newlines ("\\n") in this text are entered as soft line breaks (Shift+Enter) and will NOT submit the form \u2014 a multi-line message stays in the composer intact. To submit after typing, set pressEnter: true.'},pressEnter:{type:"boolean",default:!1,description:"When true, presses Enter once after the full text is typed, to submit/confirm. Newlines inside `text` never submit on their own \u2014 set this to send."},clearBeforeTyping:{type:"boolean",default:!0}},required:["text"]}},{name:"type_project_credential_at",description:"Type the hidden SECRET/PASSWORD of a stored project credential into a form field by element ref or coordinates. The credential name shown in PROJECT MEMORY is visible to you \u2014 type it as plain text with type_text_at for username/email fields. This tool ONLY types the hidden secret value. ONLY use credential names explicitly listed in PROJECT MEMORY. Do NOT guess or assume credential names exist.",parameters:{type:"object",properties:{ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"},credentialName:{type:"string",description:"Exact name of a credential from PROJECT MEMORY"},pressEnter:{type:"boolean",default:!1},clearBeforeTyping:{type:"boolean",default:!0}},required:["credentialName"]}},{name:"scroll_document",description:"Scroll the document.",parameters:{type:"object",properties:{direction:{type:"string",enum:["up","down","left","right"]}},required:["direction"]}},{name:"scroll_to_bottom",description:"Scroll to the bottom of the page.",parameters:{type:"object",properties:{},required:[]}},{name:"scroll_at",description:"Scroll at coordinates or element ref with direction and magnitude (normalized).",parameters:{type:"object",properties:{ref:{type:"string",description:'Element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},x:{type:"number"},y:{type:"number"},direction:{type:"string",enum:["up","down","left","right"]},magnitude:{type:"number"}},required:["direction"]}},{name:"wait",description:"Wait for a specified number of seconds before taking a screenshot. Use after clicks that trigger loading states (spinners, progress bars). Choose duration based on expected load time. For content-specific waits, prefer wait_for_element.",parameters:{type:"object",properties:{seconds:{type:"number",description:"Seconds to wait (1-30, default 2)"}},required:[]}},{name:"wait_for_element",description:'Wait for specific text to become visible on the page. Use when you know what content should appear (loading spinner resolves to results, success message appears, tab content loads). Matches as a case-sensitive substring \u2014 be specific to avoid matching loading indicators. For generated identifiers, prefer the concrete visible value (for example DOC-77310) over label prose like "reference number". Returns a screenshot once the text is found. If not found within the timeout, returns current page state with a timeout error.',parameters:{type:"object",properties:{textContent:{type:"string",description:'Text the element should contain (substring match). Be specific \u2014 "Order confirmed" not just "Order".'},timeoutSeconds:{type:"number",description:"Max seconds to wait (default 5, max 30)"}},required:["textContent"]}},{name:"go_back",description:"Go back.",parameters:{type:"object",properties:{},required:[]}},{name:"go_forward",description:"Go forward.",parameters:{type:"object",properties:{},required:[]}},{name:"key_combination",description:'Press a key combination. Provide keys as an array of strings (e.g., ["Command","L"]).',parameters:{type:"object",properties:{keys:{type:"array",items:{type:"string"}}},required:["keys"]}},{name:"set_focused_input_value",description:"Set value on the currently focused input or select. Call click_at first to focus the element, then this tool. Works for all input types including date/time and select dropdowns. Returns elementType, valueBefore, valueAfter in the response. For selects: also returns availableOptions. For date: YYYY-MM-DD. For time: HH:MM (24h). For datetime-local: YYYY-MM-DDTHH:MM.",parameters:{type:"object",properties:{value:{type:"string",description:'Value to set. For select/dropdown elements: use the visible option text (e.g., "Damage deposit"). For date/time inputs: use ISO format (date: "2026-02-15", time: "14:30", datetime-local: "2026-02-15T14:30"). For text inputs: plain text.'}},required:["value"]}},{name:"drag_and_drop",description:"Drag and drop using element refs from page snapshot (ref, destinationRef) or normalized coords (x, y, destinationX, destinationY, 0-1000 scale).",parameters:{type:"object",properties:{ref:{type:"string",description:'Source element reference from page snapshot (e.g. "e5"). When provided, x/y are ignored.'},destinationRef:{type:"string",description:"Destination element reference from page snapshot. When provided, destinationX/destinationY are ignored."},x:{type:"number"},y:{type:"number"},destinationX:{type:"number"},destinationY:{type:"number"}},required:[]}},{name:"upload_file",description:'Upload file(s) to a file input. PREREQUISITE: click_at on the file input first \u2014 the response will show elementType="file" with accept types and multiple flag. Then call this tool with absolute file paths. The files must exist on the local filesystem.',parameters:{type:"object",properties:{filePaths:{type:"array",items:{type:"string"},description:'Absolute paths to files to upload (e.g., ["/Users/alex/Desktop/photo.png"]).'}},required:["filePaths"]}},{name:"switch_tab",description:"Switch between browser tabs. Tab 1 is the original page, tab 2 is opened by links or popups.",parameters:{type:"object",properties:{tab:{type:"string",enum:["tab1","tab2"],description:"Which tab to switch to"}},required:["tab"]}},{name:"close_tab",description:"Close the current tab and switch to the other. Cannot close tab 1.",parameters:{type:"object",properties:{},required:[]}},{name:"http_request",description:"Make an HTTP request. Shares the browser session's cookies and auth context (including httpOnly cookies) but is NOT subject to CORS \u2014 can reach any URL. Use this to verify API state after UI actions, set up test data, or test API endpoints directly. Response body is truncated to 50KB.",parameters:{type:"object",properties:{url:{type:"string",description:"The URL to send the request to"},method:{type:"string",enum:["GET","POST","PUT","PATCH","DELETE"],description:"HTTP method. Defaults to GET."},headers:{type:"object",description:'Optional request headers as key-value pairs (e.g., {"Content-Type": "application/json"})'},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH). Send JSON as a string."}},required:["url"]}},{name:"run_js",description:"Execute arbitrary JavaScript in the page context via Playwright page.evaluate. Use ONLY as a last resort when normal UI actions cannot make progress \u2014 e.g. clearing browser-side persistent storage (cookies plus the standard Web Storage APIs) to recover from a sticky rejection state, reading hidden DOM state, or force-setting form values that do not accept normal click/type. Prefer typed UI actions whenever possible. Each call is logged. Returns the JSON-serialized return value (or undefined), capped at 5KB.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript expression or statement to evaluate in the page context. Capped at 4000 characters."}},required:["code"]}}];function Qv(t){return t.map(e=>({...e,parameters:{...e.parameters,properties:{intent:ML,screen:DL,visible_navigation:LL,...e.parameters.properties},required:["intent","screen",...e.parameters.required]}}))}var zi=Qv(ah),FL=new Set(["screenshot","full_page_screenshot"]),UL=ah.filter(t=>!FL.has(t.name));var Ki=Qv(UL),oh=new Set(ah.map(t=>t.name));function xc(t){return oh.has(t)}function Yi(t){return{open_web_browser:"Opening browser",screenshot:"Taking screenshot",full_page_screenshot:"Capturing full page",switch_layout:"Switching viewport",navigate:"Navigating",click_at:"Clicking",double_click_at:"Double-clicking",right_click_at:"Right-clicking",hover_at:"Hovering",type_text_at:"Typing text",type_project_credential_at:"Entering credentials",scroll_document:"Scrolling page",scroll_to_bottom:"Scrolling to bottom",scroll_at:"Scrolling",wait:"Waiting",wait_for_element:"Waiting for element",go_back:"Going back",go_forward:"Going forward",key_combination:"Pressing keys",set_focused_input_value:"Setting input value",drag_and_drop:"Dragging element",upload_file:"Uploading file",switch_tab:"Switching tab",close_tab:"Closing tab",http_request:"Making HTTP request",run_js:"Running JavaScript"}[t]??t.replace(/_/g," ")}function To(t){return t==="type_project_credential_at"||t==="mobile_type_credential"}function Ac(t,e,n){return To(t)?{...e,projectId:n}:e}var Ji=`Screenshot Click Indicator:
|
|
10
10
|
A red circle may appear in screenshots marking the previous click location. Note: the circle won't appear if the page navigated or refreshed after clicking.
|
|
11
11
|
`;function Xi({snapshotOnly:t}){return t?`\u2550\u2550\u2550 BROWSER TARGETING POLICY \u2550\u2550\u2550
|
|
@@ -471,7 +471,7 @@ Create a structured summary that preserves:
|
|
|
471
471
|
Be concise but preserve critical details like URLs, credentials used, and test data.
|
|
472
472
|
Output ONLY the structured summary, no preamble.`;try{let a=Date.now(),o=await st({model:this.model,messages:[{role:"user",content:i}],temperature:.1,maxOutputTokens:2048,maxRetries:2});return ft(this.sessionAuxMeter(),this.model,o,{durationMs:Date.now()-a}),(o.text??"").trim()}catch(a){return this.log("error","BaseRuntime","Summarization failed",{error:a?.message}),s}}async maybeSummarizeContext(e,n){let r=n.tokenCount??e.lastTokenCount??this.tokenCount;if(r<=2e5||this.conversationTrace.length===0)return!1;let s=Math.floor(2e5*.25);if(this.lastContextSummaryMessageId&&this.lastContextSummaryTokenCount>0&&r<this.lastContextSummaryTokenCount+s)return!1;let i=await this.baseDeps.chatRepo.listMessages(e.id);if(this.countUserMessages(this.conversationTrace)<=jf)return!1;let o=i.slice(0,Math.max(0,i.length-jf*3));if(o.length===0)return!1;this.log("info",n.source,"Token count exceeds threshold",{tokenCount:r,iteration:n.iteration}),this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:e.id,event:"context_summarized",iteration:n.iteration,details:`tokenCount=${r}`});let l=await this.summarizeContext(e,o),c=o[o.length-1]?.id;e.contextSummary=l,e.summarizedUpToMessageId=c,await this.baseDeps.chatRepo.updateSessionFields(e.id,{contextSummary:l,summarizedUpToMessageId:c});let u=this.conversationTrace,d=!!this.systemPromptText&&u[0]?.role==="user"&&u[0]?.parts?.[0]?.text===this.systemPromptText,f=d?u[0]:void 0,p=(d?u.slice(1):u.slice()).slice(-jf*2),g={role:"user",parts:[{text:`[CONTEXT SUMMARY from earlier in conversation]
|
|
473
473
|
${l}
|
|
474
|
-
[END SUMMARY]`}]},m=f?[f,g,...p]:[g,...p];u.length=0,u.push(...m),this.conversationTrace=u,await this.persistConversationTrace(e,u);let S={sessionId:e.id,id:ve("msg"),role:"system",actionName:"context_summarized",text:"Chat context summarized",timestamp:Date.now()};return await this.persistMessage(S),this.emit("message:added",{sessionId:e.id,message:S}),this.lastContextSummaryTokenCount=r,this.lastContextSummaryMessageId=c,!0}async persistConversationTrace(e,n){await this.baseDeps.chatRepo.updateSessionFields(e.id,{conversationTrace:n})}currentPlanStepIndex(){}currentPlanStepType(){}planStepAttribution(){let e=this.currentPlanStepType();return e===void 0?{}:{planStepIndex:this.currentPlanStepIndex(),planStepType:e}}hasTypedCredentialThisRun(){return this._credentialTypedThisRun}async executeBrowserAction(e,n){if(!this.browserActionExecutor)throw new Error("[BaseRuntime] Browser actions not available \u2014 no computerUseService");let r=e.args??{},s=typeof r.intent=="string"?r.intent.trim():void 0;if(cb({config:n.session.config,actionName:e.name,text:r.text,value:r.value,inputType:r.inputType,label:r.label,matchedLabel:r.matchedLabel,intent:r.intent,screen:r.screen,stepText:r.stepText}))return this.log("info","BaseRuntime","executeBrowserAction: refusing email write in discovery run (AG-3588)",{sessionId:n.session.id,action:e.name,label:r.label}),{response:{status:"error",error:"Refused: discovery runs must not submit credentials, sign up, or fill email/login fields. This is expected \u2014 signup / authenticated flows belong in the post-scope Explorer, not in discovery. Treat this signup surface as a discovered area: call log_observation to record the form fields, validation rules, and what the surface offers (including requires_auth=true), then continue mapping other public/unauthenticated pages. When discovery is complete, finish with assistant_v2_report including the signup gate in discoveredAreas. Do NOT call exploration_blocked \u2014 a signup/auth gate is normal discovery output, not a failure. The Coordinator presents the scope checkpoint from your partial discovery (AG-3588)."},isMetaTool:!0};this.recordStartupMilestone("first_browser_tool_dispatched",{toolName:e.name,isMobile:!1,iteration:n.iteration}),n.session.config.extensionPath&&this.log("info","BaseRuntime","executeBrowserAction with extension",{sessionId:n.session.id,projectId:n.session.projectId,extensionPath:n.session.config.extensionPath,action:e.name});let i=this.drainAbortControllers.get(n.session.id);(!i||i.signal.aborted)&&(i=new AbortController,this.drainAbortControllers.set(n.session.id,i));let a=await this.browserActionExecutor.execute(n.session.id,e.name,r,n.session.projectId,n.session.config,{intent:s,stepIndex:n.stepIndex,planStepIndex:this.currentPlanStepIndex(),turnTimestamp:n.turnTimestamp,signal:i.signal});this.recordStartupMilestone("first_browser_tool_completed",{toolName:e.name,isMobile:!1,iteration:n.iteration});let{result:o,response:l,message:c}=a;if(o.captureMode==="viewport_degraded"&&this.log("info","BaseRuntime","full_page_capture:degraded",{captureMode:o.captureMode,url:o.url,planStepIndex:this.currentPlanStepIndex(),action:e.name}),this.captureVerbatimTypedValue(e,l),l&&typeof l=="object"&&l.status==="error"&&typeof l.error=="string"&&this.onBrowserActionError(e.name,l.error),To(e.name)){let p=l??{};p.status==="error"||p.error!=null||p.valueMismatch===!0||(this._credentialTypedThisRun=!0)}a.drainResult&&a.drainResult.pendingAtStart>0&&this.log("info","BrowserActionExecutor","drain",{sessionId:n.session.id,actionName:e.name,iteration:n.iteration,pendingAtStart:a.drainResult.pendingAtStart,pendingAtEnd:a.drainResult.pendingAtEnd,waitedMs:a.drainResult.waitedMs,timedOut:a.drainResult.timedOut,aborted:a.drainResult.aborted,oldestAgeMs:a.drainResult.oldestAgeMs,projectId:n.session.projectId});let u=r.ref?`ref=${r.ref}`:r.x!=null?`(${r.x},${r.y})`:void 0,d={action:e.name,intent:s,screen:typeof r.screen=="string"?r.screen:void 0,target:u,activeTab:o?.metadata?.activeTab,drainMs:a.drainResult?.waitedMs},f=!n.snapshotOnly&&o.screenshot?[{inlineData:{mimeType:"image/png",data:o.screenshot}}]:void 0;o.metadata?.pageSettled!==void 0&&(this._lastNavPageSettled=o.metadata.pageSettled),this._lastCanvasDominant=o.canvasDominant===!0;let h=o.metadata?.navigateMeta;if(h?.originChanged===!0&&l){let p=mu(h);if(p){let g=p.redirectChain.length>0?p.redirectChain.join(" -> "):"(direct)";l.navigateNote=`navigate: requested ${p.requestedUrl}, redirected cross-origin to ${p.finalUrl} via ${g}. This destination looks like an authentication bridge (path matches ${p.matchedPattern}). The requested URL likely requires credentials Agentiqa does not have. Do NOT retry navigate to ${p.requestedUrl} in this turn \u2014 instead, surface this to the user (ask whether they have credentials for the preview, or want to provide a different URL).`,this.baseDeps.sink.emit({kind:"log",ts:Date.now(),sessionId:n.session.id,level:"info",source:"PreviewAuthDetector",msg:"preview_requires_auth",data:p})}else l.navigateNote=wf(h)}return{response:l,parts:f,message:c,supervisorEntry:d,loopDetectorUpdate:{url:o.url,screenContent:l?.pageSnapshot,screenshotSize:n.skipScreenshotSet.has(n.callIndex)?void 0:o.screenshot?.length,canvasDominant:o.canvasDominant===!0,drainTimedOut:a.drainResult?.timedOut??!1},screenshotBase64:o.screenshot,...o.captureMode&&{captureMode:o.captureMode},...o.aiSnapshot&&{groundingSnapshot:o.aiSnapshot,groundingCanvasDominant:o.canvasDominant===!0},...o.snapshotKind&&{groundingSnapshotKind:o.snapshotKind},...o.metadata?.noObservedEffect&&{noObservedEffect:!0},...o.metadata?.effectObserved!==void 0&&{effectObserved:o.metadata.effectObserved},...o.metadata?.elementFingerprint&&{writeElementFingerprint:o.metadata.elementFingerprint},...o.metadata?.verbatimGuardMismatch&&{writeGuardMismatch:!0}}}onBrowserActionError(e,n){}async executeMobileAction(e,n){if(!this.mobileActionExecutor)return{response:{status:"error",error:"Mobile executor not available"}};let r=e.args??{},s=typeof r.intent=="string"?r.intent.trim():void 0;this.recordStartupMilestone("first_browser_tool_dispatched",{toolName:e.name,isMobile:!0,iteration:n.iteration});let i=await this.mobileActionExecutor.execute(n.session.id,e.name,r,n.session.projectId,n.session.config,{intent:s,stepIndex:n.stepIndex,skipScreenshot:n.skipScreenshotSet.has(n.callIndex),turnTimestamp:n.turnTimestamp});this.recordStartupMilestone("first_browser_tool_completed",{toolName:e.name,isMobile:!0,iteration:n.iteration});let{result:a,response:o,message:l}=i,c=r.ref?`ref=${r.ref}`:r.x!=null?`(${r.x},${r.y})`:void 0,u={action:e.name,intent:s,screen:typeof r.screen=="string"?r.screen:void 0,target:c,activeTab:a?.metadata?.activeTab},d=!n.snapshotOnly&&a.screenshot?[{inlineData:{mimeType:"image/png",data:a.screenshot}}]:void 0;return{response:o,parts:d,message:l,supervisorEntry:u,loopDetectorUpdate:{url:a.url,screenContent:o?.pageSnapshot,screenshotSize:n.skipScreenshotSet.has(n.callIndex)?void 0:a.screenshot?.length},screenshotBase64:a.screenshot}}captureVerbatimTypedValue(e,n){if(!ns()||e.name!=="type_text_at"&&e.name!=="set_focused_input_value"||e.args?.fieldPurpose==="verification_code")return;let r=n;if(r?.status==="error"||typeof r?.inputType=="string"&&r.inputType.toLowerCase()==="password")return;let s=e.name==="type_text_at"?e.args?.text:e.args?.value;if(typeof s!="string")return;let i=s.slice(0,4e3);i.trim().length!==0&&(ku(i)||this._capturedTypedValues.includes(i)||(this._capturedTypedValues.push(i),this._capturedTypedValues.length>50&&this._capturedTypedValues.shift()))}getCapturedTypedValues(){return this._capturedTypedValues}async executeAction(e,n){if((e.name==="type_text_at"||e.name==="set_focused_input_value")&&ta({config:n.session?.config,text:e.name==="type_text_at"?e.args?.text:e.args?.value,inputType:typeof e.args?.inputType=="string"?e.args.inputType:void 0,label:e.args?.label,intent:e.args?.intent,screen:e.args?.screen,stepText:e.args?.stepText})&&(this._canonicalEmailWritten=!0,!this._emailVerificationExpected&&ib(e.args?.intent,e.args?.screen,e.args?.stepText)&&(this._emailVerificationExpected=!0),!this._canonicalEmailUsedForSignup&&ab(e.args?.intent,e.args?.screen,e.args?.stepText)&&(this._canonicalEmailUsedForSignup=!0)),!Le("EMAIL_CODE_PROVENANCE")&&this._emailVerificationExpected&&e.args?.fieldPurpose==="verification_code"&&(e.name==="type_text_at"||e.name==="set_focused_input_value")){let o=String(e.name==="type_text_at"?e.args?.text??"":e.args?.value??""),l=FT({value:o,fetchedEmailTexts:this._fetchedEmailTexts});if(!l.allowed)return this.log("warn","BaseRuntime","email_verification_gate: ungrounded code write refused",{toolName:e.name,grounded:this._fetchedEmailTexts.length>0}),{response:{status:"error",error:l.reason},isMetaTool:!0}}let r=this.maybeBlockForObservationCheckpoint(e,n);if(r)return r;let s=n.isMobile&&_s(e.name)?await this.executeMobileAction(e,n):await this.executeBrowserAction(e,n);this._canonicalEmailWritten&&ob(s.loopDetectorUpdate?.screenContent)&&(this._emailVerificationExpected||(this._emailVerificationExpected=!0),this.recordRuntimeRevealedFact({kind:"capability_required",provenance:"runtime_observed",confidence:"high",source:"testingEmailPolicy.screenIndicatesVerificationPending",message:"The product screen indicates email verification is pending.",data:{capability:"email_verification",...typeof s.loopDetectorUpdate?.url=="string"?{url:s.loopDetectorUpdate.url}:{}}}));let a=HT({scope:n.session?.config?.browserNavigationScope,currentUrl:s.loopDetectorUpdate?.url,screenContent:s.loopDetectorUpdate?.screenContent});return a&&this.recordRuntimeRevealedFact(a),this.updateObservationScreenState(s.loopDetectorUpdate?.url,s.loopDetectorUpdate?.screenContent),s}isObservationCheckpointEnabled(e){return!1}updateObservationScreenState(e,n){let r=typeof e=="string"?e.trim():"",s=typeof n=="string"?n.trim():"";if(!r&&!s)return;let i=s?s.slice(0,2e3):"",a=`${r}|${this.quickHash(i)}`;a!==this.currentObservationScreenKey&&(this.currentObservationScreenKey=a)}markObservationCheckpoint(){this.currentObservationScreenKey&&this.checkpointedObservationScreenKeys.add(this.currentObservationScreenKey)}maybeBlockForObservationCheckpoint(e,n){return!this.isObservationCheckpointEnabled(n)||!this.currentObservationScreenKey||!this.isObservationStateChangingAction(e,n)||this.checkpointedObservationScreenKeys.has(this.currentObservationScreenKey)?null:{response:{status:"observation_required",reason:"checkpoint current screen before leaving or changing it; requested action was not executed",instruction:'Call log_observation now. Use decision="capture" for exact facts required as future inputs, stable locators, expected outcomes, or fixed prices/amounts; use context_only for screen inventory/current-state notes; use decision="none" only if nothing durable needs to be preserved. Then retry the same action.'},isMetaTool:!0}}isObservationStateChangingAction(e,n){if(n.isMobile&&_s(e.name)){if(e.name!=="mobile_press_button")return Jq.has(e.name);let r=String(e.args?.button??"").toUpperCase();return r==="BACK"||r==="HOME"}return Yq.has(e.name)}updateLoopDetector(e,n,r,s){let i=n.loopDetectorUpdate;if(i){if(i.url&&e.updateUrl(i.url),!r){let a=Ef()&&i.canvasDominant===!0&&typeof n.screenshotBase64=="string"&&n.screenshotBase64.length>0?{pixelHash:uT(n.screenshotBase64)}:void 0;e.updateScreenContent(i.screenContent,i.screenshotSize,s!==void 0&&Lb.has(s),a)}if(i.drainTimedOut!==void 0){let a={url:i.url,drainTimedOut:i.drainTimedOut};e.recordDrainResult(a),this.progressBus.recordDrainResult(a)}}}async trackTapRetry(e,n,r,s,i,a,o){let l=n.args??{};if(n.name==="mobile_tap"||n.name==="mobile_long_press"){let c=e.recordTap(typeof l.screen=="string"?l.screen:"",Number(l.x??0),Number(l.y??0),typeof l.intent=="string"?l.intent:"",r.result.screenshot?.length??0);c.memoryProposal&&s.upsert&&(Po(c.memoryProposal,a.map(u=>u.text))||(await s.upsert({id:ve("mem"),projectId:i,text:c.memoryProposal,source:"system",createdAt:Date.now(),updatedAt:Date.now()}),a.push({id:ve("mem"),projectId:i,text:c.memoryProposal,source:"system",createdAt:Date.now(),updatedAt:Date.now()}),this.log("info","TapRetryTracker","Memory saved",{text:c.memoryProposal.slice(0,120)})))}else o&&_s(n.name)&&e.reset()}async setupScreencast(e){let n=[],r=Date.now(),s={count:0},i=null,a=this.baseDeps.createVideoRecorder?.();a?.start(this.sessionId);let o=f=>{f.action.status==="started"&&n.push({timestamp:Date.now()-r,actionName:f.action.actionName,label:f.action.intent,planStepIndex:f.action.planStepIndex})},l=f=>{this.baseDeps.screencastService?.showTapIndicator?.(f.normX,f.normY)},c=()=>{this.baseDeps.screencastService?.pausePolling?.()},u=()=>{this.baseDeps.screencastService?.resumePolling?.()};if(this.baseDeps.screencastService&&!e.config?.extensionPath)try{let f=!1,h=()=>{f||(f=!0,this.emit("screencast:started",{sessionId:this.sessionId}))};i=this.baseDeps.screencastService.onFrame(this.sessionId,p=>{s.count++,a?.addFrame(p.data,p.timestamp),h(),this.emit("screencast:frame",{sessionId:this.sessionId,data:p.data,timestamp:p.timestamp})}),await this.baseDeps.screencastService.startScreencast(this.sessionId),h(),this.log("info","VideoPipeline","recording_started",{sessionId:this.sessionId,hasRecorder:!!a}),this.on("action:progress",o),this.on("tap:indicator",l),this.on("screencast:pause-polling",c),this.on("screencast:resume-polling",u)}catch{}let d={unsubscribe:i,actionProgressHandler:o,tapIndicatorHandler:l,pausePollingHandler:c,resumePollingHandler:u,actionMarkers:n,screencastStartTime:r,projectId:e.projectId,frameCounter:s,videoRecorder:a};return this.activeScreencastState=d,this.screencastStopSignaled=!1,d}signalActiveScreencastStopped(e){!this.activeScreencastState||this.screencastStopSignaled||(this.screencastStopSignaled=!0,this.emit("screencast:stopped",{sessionId:this.sessionId,turnId:e,actionMarkers:this.activeScreencastState.actionMarkers}))}async teardownScreencast(e,n){if(!e)return;this.activeScreencastState!==e&&(this.activeScreencastState=e,this.screencastStopSignaled=!1);let{unsubscribe:r,actionProgressHandler:s,tapIndicatorHandler:i,pausePollingHandler:a,resumePollingHandler:o,actionMarkers:l,projectId:c,frameCounter:u,videoRecorder:d}=e;if(this.removeListener("action:progress",s),this.removeListener("tap:indicator",i),this.removeListener("screencast:pause-polling",a),this.removeListener("screencast:resume-polling",o),r?.(),this.baseDeps.screencastService){try{await this.baseDeps.screencastService.stopScreencast(this.sessionId),this.baseDeps.screencastService.stopDeviceRecording&&await this.baseDeps.screencastService.stopDeviceRecording(this.sessionId),this.baseDeps.screencastService.setActionMarkers?.(l)}catch{}this.signalActiveScreencastStopped(n);let f=u?.count??0;this.log(f>0?"info":"warn","VideoPipeline",f>0?"frames_captured":"frames_none",{sessionId:this.sessionId,turnId:n,framesReceived:f});let h;if(d&&d.isUnavailable?.())this.log("info","VideoPipeline","ffmpeg_unavailable",{sessionId:this.sessionId,turnId:n,framesReceived:f});else if(d&&this.baseDeps.uploadVideo)try{let p=await d.stop(),g=d.getLastError?.();if(this.log(p?"info":"warn","VideoPipeline",p?"ffmpeg_produced_file":"ffmpeg_no_file",{sessionId:this.sessionId,turnId:n,framesReceived:f,sizeBytes:p?.sizeBytes,...g?{ffmpegError:g}:{}}),p){let m=`videos/${c}/${this.sessionId}/${n}.mp4`;h=await this.baseDeps.uploadVideo(p.filePath,m)??void 0,d.cleanup(),this.log(h?"info":"warn","VideoPipeline",h?"upload_ok":"upload_failed",{sessionId:this.sessionId,turnId:n,...h?{videoUrl:h}:{}})}}catch(p){this.log("warn","VideoPipeline","video_finalize_error",{sessionId:this.sessionId,turnId:n,error:p instanceof Error?p.message:String(p)})}return h&&this.emit("screencast:stopped",{sessionId:this.sessionId,turnId:n,actionMarkers:l,videoUrl:h}),this.activeScreencastState=null,this.screencastStopSignaled=!1,h}}async consultLoopBreaker(e,n,r,s,i,a,o,l){if(!n||!Of(n))return{extend:!1};if(!this.loopVisionEscalationActive())return this.log("info","BaseRuntime","loop_vision: breaker skipped (lane disabled)",{mechanism:n,iteration:i,skipReason:"kill_switch_off",spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),{extend:!1};if(!this.baseDeps.supervisorService?.evaluateLoopBreaker)return this.log("warn","BaseRuntime","loop_vision: breaker skipped (no supervisor judge wired)",{mechanism:n,iteration:i,skipReason:"no_supervisor_service",spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),{extend:!1};let c=kT(),u=c?xT:Iu;if(this.loopVisionEscalation.decide(n,u)==="ceiling")return this.log("warn","BaseRuntime","loop_vision: extension ceiling reached, hard-blocking",{mechanism:n,grantsUsed:this.loopVisionEscalation.grantsUsed,maxGrants:u,iteration:i}),{extend:!1};let d=c&&this.loopVisionEscalation.grantsUsed>=1,f=this.loopVisionPrevProgress,h=d?{priorScreenshot:this.loopVisionPrevScreenshot,priorProgress:f}:void 0,p=CT(n,r,this.supervisorActionLog,l),g=await this.baseDeps.supervisorService.evaluateLoopBreaker([...this.supervisorActionLog],this.getSupervisorTaskDescription(o??""),a,p,void 0,h,this.sessionAuxMeter()),m=g.progress??null,S=g.decision==="continue",E=g.decision==="continue"?void 0:g.reason;this._lastLoopBreakerConsult={consulted:!0,keepBlockReason:E,deltaEvidence:m?.delta_evidence};let v=d&&this.loopVisionEscalation.grantsUsed>=Iu,x=Ef()&&this._lastCanvasDominant,b=d&&RT(f,m,x),_=v&&S&&!b,w=S&&!_,A=d?{grantIndex:this.loopVisionEscalation.grantsUsed+1,priorDone:f?.done??null,done:m?.done??null,delta:f&&m?m.done-f.done:null,deltaPresent:b}:void 0;return this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:s.id,verdict:w?"continue":"block",message:w?`loop_vision CONTINUE (${n}) \u2014 false-block rescued`:_?"loop_vision keep_block (no_delta)":`loop_vision keep_block (${n}: ${E})`,iteration:i,actionLogSize:this.supervisorActionLog.length,progress:m,...A?{differential:A}:{}}),w?(this.loopVisionEscalation.recordGrant(),e.grantExtension(n,Nf),c&&(this.loopVisionPrevScreenshot=a,this.loopVisionPrevProgress=m),this.log("info","BaseRuntime","loop_vision: judge CONTINUE granted extension",{mechanism:n,grantsUsed:this.loopVisionEscalation.grantsUsed,extensionActions:Nf,iteration:i,progress:m,...A?{differential:A}:{}}),{extend:!0}):_?(this.log("info","BaseRuntime","loop_vision: keep_block no_delta (differential)",{mechanism:n,iteration:i,priorProgress:f,progress:m,differential:A}),{extend:!1}):(this.log("warn","BaseRuntime","loop_vision: judge kept block (fail-closed)",{mechanism:n,reason:E,iteration:i,progress:m,...A?{differential:A}:{}}),{extend:!1})}async applySupervisorVerdict(e,n,r,s){let i=IT()?this.sameGoalAbort.observeVerdict(e.action):null;if(i){let o=e.action==="redirect"?e.message:void 0;this.log("warn","Supervisor","Same-goal abort escalation",{iteration:r,escalation:i,strike:this.sameGoalAbort.fires,consecutiveRedirects:Zo,originalMessage:o}),e=i==="block"?{action:"block",reason:`${Zo*2} consecutive supervisor corrections produced no progress milestone; the agent ignored the abort steer, ending the run`,rawText:e.rawText}:{action:"abort",reason:`${Zo} consecutive supervisor corrections produced no progress milestone`,rawText:e.rawText}}this.log("info","Supervisor","Applying verdict",{action:e.action,iteration:r}),this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:n.id,verdict:e.action,message:e.action==="block"||e.action==="abort"?e.reason:e.message,iteration:r,actionLogSize:this.supervisorActionLog.length});let a=bf(e);if(e.action==="redirect"){this.log("info","Supervisor","REDIRECT",{message:e.message}),this.steeringVeto.recordRedirect(e.message??"Change approach.");let o=s[s.length-1];return o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}}),{done:a.done}}if(e.action==="block"){this.log("warn","Supervisor","BLOCK",{reason:e.reason});let o=a.blockedReason,l={sessionId:n.id,id:ve("msg"),role:"model",text:`We stopped this run because the agent got stuck: ${o}. No usage charged.`,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`Supervisor intervention after ${this.supervisorActionLog.length} actions`,obstacle:o,question:"The supervisor stopped this session. Please review and retry."}};return await this.persistMessage(l),this.emit("message:added",{sessionId:n.id,message:l}),s.push({name:"exploration_blocked",response:{status:"awaiting_user_guidance"}}),{done:a.done,blockedReason:o}}if(e.action==="wrap_up"){this.log("info","Supervisor","WRAP_UP",{message:e.message});let o=s[s.length-1];o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}})}if(e.action==="abort"){this.steeringVeto.recordRedirect(a.injectedFunctionResponseError??e.reason);let o=s[s.length-1];o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}})}return{done:a.done}}onIterationStart(e,n,r){}onIterationEnd(e){}withCanvasStrategy(e,n,r){if(!Cc()||(n!==this._canvasStrategyActive&&(this.log("info","BaseRuntime",n?"canvas_strategy: injected (page is canvas-dominant)":"canvas_strategy: retracted (page no longer canvas-dominant)",{iteration:r,canvasDominant:n}),this._canvasStrategyActive=n),!n))return e;let s=e[e.length-1],i=s?.parts?.some(a=>a!=null&&typeof a=="object"&&"functionResponse"in a);if(s?.role==="user"&&!i){let a={...s,parts:[...s.parts??[],{text:lh}]};return[...e.slice(0,-1),a]}return[...e,{role:"user",parts:[{text:lh}]}]}getSupervisorTaskDescription(e){return e}hasBackgroundWork(){return!1}waitForBackgroundWork(){return Promise.resolve()}async onLoopExhausted(e,n){let r={sessionId:e.id,id:ve("msg"),role:"model",text:`I paused before finishing this run (step limit of ${n} reached). Reply "continue" to let me proceed, or clarify the exact target page/expected behavior.`,timestamp:Date.now()};await this.persistMessage(r),this.emit("message:added",{sessionId:e.id,message:r})}async consultRunBackstopJudge(e,n,r,s,i){let a=this.baseDeps.supervisorService;if(!a?.evaluateLoopBreaker)return this.log("warn","BaseRuntime","backstop:judge_unavailable (no supervisor judge wired)",{iteration:n,ceiling:i.ceiling,spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),"unavailable";try{let l=`RUN BACKSTOP PROGRESS CHECK \u2014 this run has hit a safety ceiling (${vu(i.elapsedMs,i.iteration)}, ${i.ceiling}). Judge ONE thing: given the objective and the recent actions + current screenshot, is the agent GENUINELY PROGRESSING toward the objective \u2014 measurably closer than several steps ago \u2014 or WANDERING / not getting closer (recycling the same screens/URLs, repeating failed attempts, or off on an unrelated tangent)? Answer CONTINUE ONLY if you can point to concrete forward progress toward the objective; if it is not clearly getting closer, answer BLOCK. When unsure, answer BLOCK.`,c=await a.evaluateLoopBreaker([...this.supervisorActionLog],this.getSupervisorTaskDescription(s??""),r,l,void 0,void 0,this.sessionAuxMeter());return c.decision==="continue"?"progressing":c.reason==="block"||c.reason==="redirect"||c.reason==="wrap_up"?"wandering":"unavailable"}catch(o){return this.log("warn","BaseRuntime","backstop:judge_error \u2014 failing closed",{iteration:n,ceiling:i.ceiling,error:o?.message}),"unavailable"}}async handleRunBackstop(e,n,r,s,i="ceiling_cap"){let a=yu(e),o=s&&s.trim().length>0?`"${s.trim().slice(0,160)}"`:"this task",l="a series of navigation and interaction steps";try{let f=new Set,h=[];for(let p of[...this.supervisorActionLog].reverse())if(!(!p?.action||f.has(p.action))&&(f.add(p.action),h.push(p.intent?`${p.action} (${p.intent.slice(0,40)})`:p.action),h.length>=4))break;h.length>0&&(l=h.reverse().join(", "))}catch{}this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"run_backstop",iteration:r,details:`terminate on ${e.ceiling} (${a}); reason=${i}; cumulativeTokens=${e.cumulativeTokens}`}),this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:n.id,verdict:"block",message:`run_backstop terminate (${e.ceiling}: ${a}; reason=${i})`,iteration:r,actionLogSize:this.supervisorActionLog.length});let u=`${i==="wander"?lT(o,e.elapsedMs,e.iteration):cT(e.elapsedMs,e.iteration)} What I tried: ${l}. Send a new message with a more specific target or expected result and I'll try again.`,d={sessionId:n.id,id:ve("msg"),role:"model",text:u,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`${this.supervisorActionLog.length} actions; ${a}`,obstacle:i==="wander"?`Run backstop: not getting closer to ${o} (${e.ceiling}).`:`Run backstop: hit the safety limit (${e.ceiling}; ${i}).`,question:"The run stopped at a safety limit. Adjust the target or steps and reply to try again."}};return await this.persistMessage(d),this.emit("message:added",{sessionId:n.id,message:d}),this.log("warn","BaseRuntime","run_backstop fired (terminate)",{ceiling:e.ceiling,reason:i,iteration:r,elapsedMs:e.elapsedMs,cumulativeTokens:e.cumulativeTokens}),!0}onLoopForceBlock(e,n,r){}async recordLoopBlockIssue(e,n,r){}async runLoop(e){let{session:n,maxIterations:r,snapshotOnly:s,isMobile:i,devicePlatform:a,taskDescription:o,supervisorHints:l,preserveAllPageSnapshots:c,runJsLoopRecoveryPolicy:u="warn_response"}=e,d=this.conversationTrace;this._endMechanism=void 0,this._lastLoopBreakerConsult=void 0,this._currentTaskDescription=o;let f=!1,h=!1,p,g,m=0,S=Math.floor(Date.now()/1e3),E=0,v=0,x=sT()&&n.kind==="assistant_v2",b=Date.now(),_=0,w=0,A=2,k=new Do(P=>{this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"progress_milestone",iteration:E,details:{source:"LoopDetector",signal:P}}),this.sameGoalAbort.recordMilestone(),this.supervisorVerdictFreshness.recordProgress()},{trackNovelScreenContent:!0,...n.config?.loopDetector??{},rearmUrlNovelty:Db()&&n.kind==="assistant_v2"},P=>{this.baseDeps.sink.emit({kind:"log",ts:Date.now(),sessionId:n.id,level:"info",source:"LoopDetector",msg:"structural_force_block_diagnostics",data:P})});this.isExplorationMode()&&k.setMode("exploration"),this._activeLoopDetector=k,this._lastNavPageSettled=null,this._lastCanvasDominant=!1,this._canvasStrategyActive=!1;let T=new Lo,R;this.steeringVeto.reset(),this.sameGoalAbort.reset(),this.resetLoopVisionState(),this.progressBus.resetSupervisorLog(),this.pendingSupervisorVerdict=null,this.resolvedSupervisorVerdict=null,this.supervisorVerdictFreshness.reset(),this.recentActionsForEvidence=[],this.recentClickTargets=[];let O=[];for(let P=1;P<=r;P++){if(E=P,!this._isRunning)throw new Error("cancelled");if(x){let ae=iT({elapsedMs:b>0?Date.now()-b:0,iteration:P,cumulativeTokens:_},aT(Sf,w));if(ae.kind==="terminate"){this.log("info","BaseRuntime","backstop:ceiling_reached",{ceiling:ae.ceiling,iteration:P,elapsedMs:ae.elapsedMs,cumulativeTokens:ae.cumulativeTokens,extensionsGranted:w});let ee="unavailable";w<gu&&(ee=await this.consultRunBackstopJudge(n,P,R,o,ae),this.log("info","BaseRuntime","backstop:judge_verdict",{verdict:ee,ceiling:ae.ceiling,iteration:P,extensionsGranted:w}));let le=oT(ee,w);if(le.action==="extend")w+=1,this.log("info","BaseRuntime","backstop:extended",{extensionsGranted:w,maxExtensions:gu,ceiling:ae.ceiling,iteration:P});else{let fe=!1;try{fe=await this.handleRunBackstop(ae,n,P,o,le.reason)}catch(oe){this.log("warn","BaseRuntime","run_backstop emit failed \u2014 failing open",{error:oe?.message,iteration:P}),fe=!1}if(fe){this.log("info","BaseRuntime","backstop:terminated",{reason:le.reason,verdict:ee,ceiling:ae.ceiling,iteration:P,extensionsGranted:w}),f=!0,h=!0,g="backstop",p=le.reason==="wander"?`Stopped: not getting closer to the objective (${yu(ae)}).`:`Stopped: hit the safety limit (${yu(ae)}).`,this.recordEndMechanism("run_backstop");break}}}}if(typeof process<"u"&&typeof process.memoryUsage=="function")try{let ae=process.memoryUsage();this.log("info","Runtime","iteration_memory",{iteration:P,rssMb:Math.round(ae.rss/1024/1024),heapUsedMb:Math.round(ae.heapUsed/1024/1024),heapTotalMb:Math.round(ae.heapTotal/1024/1024),externalMb:Math.round(ae.external/1024/1024),arrayBuffersMb:Math.round(ae.arrayBuffers/1024/1024)})}catch{}await this.onIterationStart(d,n,P),c||this.stripOldPageSnapshots(d,s);let L=this.getToolSet({isMobile:i,snapshotOnly:s,devicePlatform:a}),V=this.withCanvasStrategy(this.systemPromptText?d.slice(1):d,this._lastCanvasDominant,P),X=Sa(V),z=V.reduce((ae,ee)=>ae+(ee.parts??[]).reduce((le,fe)=>{let oe=fe.text?.length??0,Ie=fe.functionCall?JSON.stringify(fe.functionCall).length:0,ye=fe.functionResponse?JSON.stringify(fe.functionResponse.response??{}).length:0;return le+oe+Ie+ye},0),0);this.log("info","BaseRuntime","llm_call_preflight",{iteration:P,traceMsgCount:V.length,estimatedTraceChars:z});let U=Date.now(),j;try{j=await st({model:this.model,system:this.systemPromptText??void 0,messages:X,tools:L,temperature:.2,topP:.95,topK:40,maxOutputTokens:8192,maxRetries:this._isRunning?7:0,abortSignal:this._abortController?.signal})}catch(ae){let ee=String(ae?.message||ae?.data?.error?.message||"");if(ee.includes("Unable to process input image")||ee.includes("INVALID_ARGUMENT")){this.log("warn","BaseRuntime","Gemini rejected image \u2014 retrying without screenshots",{error:ee.slice(0,200)});let le=V.map(oe=>({...oe,parts:(oe.parts||[]).filter(Ie=>!Ie.inlineData)})),fe=Sa(le);j=await st({model:this.model,system:this.systemPromptText??void 0,messages:fe,tools:L,temperature:.2,topP:.95,topK:40,maxOutputTokens:8192,maxRetries:this._isRunning?7:0,abortSignal:this._abortController?.signal})}else throw ae}let K=Date.now()-U;P===1&&this.recordStartupMilestone("first_llm_completed",{iteration:P,toolCallCount:j.toolCalls.length,textLength:j.text?.length??0});let q=j.usage,Z=(q?.inputTokens??0)+(q?.outputTokens??0);_+=(q?.inputTokens??0)+(q?.outputTokens??0);let ne=q?.inputTokenDetails?.cacheReadTokens??q?.cachedInputTokens??j.providerMetadata?.google?.usageMetadata?.cachedContentTokenCount??0;if(Z>0&&(this.tokenCount=Z,this.emit("context:updated",{sessionId:n.id,tokenCount:Z}),await this.baseDeps.chatRepo.updateSessionFields(n.id,{lastTokenCount:Z}),this.baseDeps.sink.emit({kind:"llm_usage",ts:Date.now(),sessionId:n.id,runId:this.getCurrentRunId(),callKind:"agent_step",...this.planStepAttribution(),...this.llmSourceMeta(),...UT(j.toolCalls.map(ae=>ae.toolName),Au()),model:n.config.model||"unknown",promptTokens:q?.inputTokens??0,completionTokens:q?.outputTokens??0,cachedInputTokens:ne,totalTokens:Z,durationMs:K,finishReason:j.finishReason??void 0,tokenCount:Z,messageCount:d.length,systemPromptHash:this.systemPromptText?this.quickHash(this.systemPromptText):void 0,lastToolResults:O.map(ae=>({toolName:ae.name,status:ae.response?.status??"unknown"})),chosenActions:j.toolCalls.map(ae=>({toolName:ae.toolName,intent:typeof ae.input?.intent=="string"?ae.input.intent:void 0})),textResponse:typeof j.text=="string"?j.text.slice(0,200):void 0})),!this._isRunning)throw new Error("cancelled");let G=j.response.messages,D=If(G);for(let ae of D)d.push(ae);let Y=j.toolCalls.map(ae=>({name:ae.toolName,args:ae.input??{},toolCallId:ae.toolCallId})),B=j.text;if(Y.length===0){let ae=B?.replace(/[\x00-\x1f\x7f-\x9f]|<ctrl\d+>/g,"").trim();if(B&&!ae&&this.log("warn","BaseRuntime","Model returned garbage text, treating as empty response",{charCount:B.length}),ae){let le={sessionId:n.id,id:ve("msg"),role:"model",text:B.slice(0,6e3),timestamp:Date.now()};if(await this.persistMessage(le),this.emit("message:added",{sessionId:n.id,message:le}),f=!0,this.hasBackgroundWork()){this.log("info","BaseRuntime","Text-only response but background work pending \u2014 waiting silently (not persisting LLM text)",{text:B?.slice(0,100)}),await this.waitForBackgroundWork();continue}this.log("info","BaseRuntime","Text-only response, no background work \u2014 exiting loop",{text:B?.slice(0,100)});break}if(v++,this.hasBackgroundWork()){this.log("info","BaseRuntime","Empty response but background work pending \u2014 waiting silently"),await this.waitForBackgroundWork(),v=0;continue}if(this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"empty_response",iteration:P,details:`attempt ${v}/${A}`}),m>0&&v<=A){this.log("info","BaseRuntime","Model returned empty response, nudging to continue",{stepIndex:m,attempt:v,maxAttempts:A});let le;if(i)le=(await this.baseDeps.mobileMcpService.takeScreenshot(this.sessionId)).base64;else{if(!this.baseDeps.computerUseService)throw new Error("[BaseRuntime] Browser nudge not available \u2014 no computerUseService");le=(await this.baseDeps.computerUseService.invoke({sessionId:n.id,action:"screenshot",args:{},config:{...n.config,projectId:n.projectId}})).screenshot}let oe=[{text:"You stopped without responding. Here is the current page state. Please continue with your task, or if you are done, call assistant_v2_report with a summary."}];s||oe.push({inlineData:{mimeType:"image/png",data:le}}),d.push({role:"user",parts:oe});continue}this.log("warn","BaseRuntime","Model returned consecutive empty responses, giving up",{emptyResponseCount:v});let ee={sessionId:n.id,id:ve("msg"),role:"model",text:m>0?`Model returned empty responses after ${m} action(s). This may be caused by rate limiting or a temporary API issue. You can retry by sending another message.`:"Model returned an empty response and could not start. This may be caused by rate limiting or a temporary API issue. You can retry by sending another message.",timestamp:Date.now()};await this.persistMessage(ee),this.emit("message:added",{sessionId:n.id,message:ee}),f=!0;break}if(v=0,B){let ae={sessionId:n.id,id:ve("msg"),role:"system",actionName:"assistant_v2_text",actionArgs:{iteration:P},text:B.slice(0,6e3),timestamp:Date.now()};await this.persistMessage(ae),this.emit("message:added",{sessionId:n.id,message:ae})}let H=[],$=null,N=!1,M=new Set;if(i)for(let ae=0;ae<Y.length-1;ae++)_s(Y[ae].name)&&Y[ae].name!=="mobile_screenshot"&&_s(Y[ae+1].name)&&Y[ae+1].name!=="mobile_screenshot"&&M.add(ae);let F=-1;for(let ae of Y){if(F++,!this._isRunning)break;m++;let ee={iteration:P,sessionId:this.sessionId,session:n,isMobile:i,snapshotOnly:s,devicePlatform:a,callIndex:F,totalCalls:Y.length,skipScreenshotSet:M,lastScreenshotBase64:R,stepIndex:m,turnTimestamp:S},le=fT()?this.steeringVeto.maybeVeto(ae.name,ae.args??{}):null;if(le!==null){this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"steering_veto",iteration:P,details:`${ae.name} refused: ${le.slice(0,160)}`}),H.push({name:ae.name,response:mT(ae.name,le)});continue}let fe=Date.now(),oe=await this.handleToolCall(ae,ee),Ie=Date.now()-fe;if(oe.isMetaTool||this.steeringVeto.recordExecuted(ae.name,ae.args??{}),oe.resetLoopDetector&&(k.resetForNewStep(),T.reset(),this.steeringVeto.reset(),this.sameGoalAbort.reset(),this.resetLoopVisionState()),this.updateLoopDetector(k,oe,M.has(F),ae.name),!oe.isMetaTool&&!Fq(oe)){let ye=k.check(ae.name,ae.args??{},P,!0);if(ye.action==="force_block")if((await this.consultLoopBreaker(k,ye.mechanism,ye.message,n,P,R,o,l)).extend)this.log("info","BaseRuntime","loop_vision: proceeding past force-block (extension granted)",{mechanism:ye.mechanism,iteration:P});else{this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"loop_block",iteration:P,details:ye.message}),this.log("warn","BaseRuntime","Force-blocking loop",{message:ye.message,iteration:P}),this.onLoopForceBlock(n,ye.message,P),await this.recordLoopBlockIssue(n,ye.message,m),this.recordEndMechanism("loop_block");let Pe=PT({mechanism:ye.mechanism,actionCount:this.supervisorActionLog.length,judge:this._lastLoopBreakerConsult}),he={sessionId:n.id,id:ve("msg"),role:"model",text:Pe,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`Repeated "${ae.name}" on the same target (${OT[ye.mechanism]})`,obstacle:ye.message,question:"The run stopped because it was no longer making visible progress. Adjust the target or steps and reply to continue."}};await this.persistMessage(he),this.emit("message:added",{sessionId:n.id,message:he}),H.push({name:"exploration_blocked",response:{status:"awaiting_user_guidance"}}),N=!0,f=!0,h=!0,p=ye.message,g="loop";break}if(ye.action==="warn"){if(this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"loop_warning",iteration:P,details:ye.message}),this.log("warn","BaseRuntime","Loop warning",{message:ye.message,iteration:P}),ae.name==="run_js"&&u==="partial_sitemap_salvage"){let he="",Ce="",ie="";if(this.baseDeps.computerUseService){let Te=await this.baseDeps.computerUseService.invoke({sessionId:n.id,action:"screenshot",args:{},config:n.config});he=Te.screenshot,Ce=Te.url??"",ie=[Te.aiSnapshot,Te.domChanges].filter(Boolean).join(`
|
|
474
|
+
[END SUMMARY]`}]},m=f?[f,g,...p]:[g,...p];u.length=0,u.push(...m),this.conversationTrace=u,await this.persistConversationTrace(e,u);let S={sessionId:e.id,id:ve("msg"),role:"system",actionName:"context_summarized",text:"Chat context summarized",timestamp:Date.now()};return await this.persistMessage(S),this.emit("message:added",{sessionId:e.id,message:S}),this.lastContextSummaryTokenCount=r,this.lastContextSummaryMessageId=c,!0}async persistConversationTrace(e,n){await this.baseDeps.chatRepo.updateSessionFields(e.id,{conversationTrace:n})}currentPlanStepIndex(){}currentPlanStepType(){}planStepAttribution(){let e=this.currentPlanStepType();return e===void 0?{}:{planStepIndex:this.currentPlanStepIndex(),planStepType:e}}hasTypedCredentialThisRun(){return this._credentialTypedThisRun}async executeBrowserAction(e,n){if(!this.browserActionExecutor)throw new Error("[BaseRuntime] Browser actions not available \u2014 no computerUseService");let r=e.args??{},s=typeof r.intent=="string"?r.intent.trim():void 0;if(cb({config:n.session.config,actionName:e.name,text:r.text,value:r.value,inputType:r.inputType,label:r.label,matchedLabel:r.matchedLabel,intent:r.intent,screen:r.screen,stepText:r.stepText}))return this.log("info","BaseRuntime","executeBrowserAction: refusing email write in discovery run (AG-3588)",{sessionId:n.session.id,action:e.name,label:r.label}),{response:{status:"error",error:"Refused: discovery runs must not submit credentials, sign up, or fill email/login fields. This is expected \u2014 signup / authenticated flows belong in the post-scope Explorer, not in discovery. Treat this signup surface as a discovered area: call log_observation to record the form fields, validation rules, and what the surface offers (including requires_auth=true), then continue mapping other public/unauthenticated pages. When discovery is complete, finish with assistant_v2_report including the signup gate in discoveredAreas. Do NOT call exploration_blocked \u2014 a signup/auth gate is normal discovery output, not a failure. The Coordinator presents the scope checkpoint from your partial discovery (AG-3588)."},isMetaTool:!0};this.recordStartupMilestone("first_browser_tool_dispatched",{toolName:e.name,isMobile:!1,iteration:n.iteration}),n.session.config.extensionPath&&this.log("info","BaseRuntime","executeBrowserAction with extension",{sessionId:n.session.id,projectId:n.session.projectId,extensionPath:n.session.config.extensionPath,action:e.name});let i=this.drainAbortControllers.get(n.session.id);(!i||i.signal.aborted)&&(i=new AbortController,this.drainAbortControllers.set(n.session.id,i));let a=await this.browserActionExecutor.execute(n.session.id,e.name,r,n.session.projectId,n.session.config,{intent:s,stepIndex:n.stepIndex,planStepIndex:this.currentPlanStepIndex(),turnTimestamp:n.turnTimestamp,signal:i.signal});this.recordStartupMilestone("first_browser_tool_completed",{toolName:e.name,isMobile:!1,iteration:n.iteration});let{result:o,response:l,message:c}=a;if(this.captureVerbatimTypedValue(e,l),l&&typeof l=="object"&&l.status==="error"&&typeof l.error=="string"&&this.onBrowserActionError(e.name,l.error),To(e.name)){let p=l??{};p.status==="error"||p.error!=null||p.valueMismatch===!0||(this._credentialTypedThisRun=!0)}a.drainResult&&a.drainResult.pendingAtStart>0&&this.log("info","BrowserActionExecutor","drain",{sessionId:n.session.id,actionName:e.name,iteration:n.iteration,pendingAtStart:a.drainResult.pendingAtStart,pendingAtEnd:a.drainResult.pendingAtEnd,waitedMs:a.drainResult.waitedMs,timedOut:a.drainResult.timedOut,aborted:a.drainResult.aborted,oldestAgeMs:a.drainResult.oldestAgeMs,projectId:n.session.projectId});let u=r.ref?`ref=${r.ref}`:r.x!=null?`(${r.x},${r.y})`:void 0,d={action:e.name,intent:s,screen:typeof r.screen=="string"?r.screen:void 0,target:u,activeTab:o?.metadata?.activeTab,drainMs:a.drainResult?.waitedMs},f=!n.snapshotOnly&&o.screenshot?[{inlineData:{mimeType:"image/png",data:o.screenshot}}]:void 0;o.metadata?.pageSettled!==void 0&&(this._lastNavPageSettled=o.metadata.pageSettled),this._lastCanvasDominant=o.canvasDominant===!0;let h=o.metadata?.navigateMeta;if(h?.originChanged===!0&&l){let p=mu(h);if(p){let g=p.redirectChain.length>0?p.redirectChain.join(" -> "):"(direct)";l.navigateNote=`navigate: requested ${p.requestedUrl}, redirected cross-origin to ${p.finalUrl} via ${g}. This destination looks like an authentication bridge (path matches ${p.matchedPattern}). The requested URL likely requires credentials Agentiqa does not have. Do NOT retry navigate to ${p.requestedUrl} in this turn \u2014 instead, surface this to the user (ask whether they have credentials for the preview, or want to provide a different URL).`,this.baseDeps.sink.emit({kind:"log",ts:Date.now(),sessionId:n.session.id,level:"info",source:"PreviewAuthDetector",msg:"preview_requires_auth",data:p})}else l.navigateNote=wf(h)}return{response:l,parts:f,message:c,supervisorEntry:d,loopDetectorUpdate:{url:o.url,screenContent:l?.pageSnapshot,screenshotSize:n.skipScreenshotSet.has(n.callIndex)?void 0:o.screenshot?.length,canvasDominant:o.canvasDominant===!0,drainTimedOut:a.drainResult?.timedOut??!1},screenshotBase64:o.screenshot,...o.captureMode&&{captureMode:o.captureMode},...o.aiSnapshot&&{groundingSnapshot:o.aiSnapshot,groundingCanvasDominant:o.canvasDominant===!0},...o.snapshotKind&&{groundingSnapshotKind:o.snapshotKind},...o.metadata?.noObservedEffect&&{noObservedEffect:!0},...o.metadata?.effectObserved!==void 0&&{effectObserved:o.metadata.effectObserved},...o.metadata?.elementFingerprint&&{writeElementFingerprint:o.metadata.elementFingerprint},...o.metadata?.verbatimGuardMismatch&&{writeGuardMismatch:!0}}}onBrowserActionError(e,n){}async executeMobileAction(e,n){if(!this.mobileActionExecutor)return{response:{status:"error",error:"Mobile executor not available"}};let r=e.args??{},s=typeof r.intent=="string"?r.intent.trim():void 0;this.recordStartupMilestone("first_browser_tool_dispatched",{toolName:e.name,isMobile:!0,iteration:n.iteration});let i=await this.mobileActionExecutor.execute(n.session.id,e.name,r,n.session.projectId,n.session.config,{intent:s,stepIndex:n.stepIndex,skipScreenshot:n.skipScreenshotSet.has(n.callIndex),turnTimestamp:n.turnTimestamp});this.recordStartupMilestone("first_browser_tool_completed",{toolName:e.name,isMobile:!0,iteration:n.iteration});let{result:a,response:o,message:l}=i,c=r.ref?`ref=${r.ref}`:r.x!=null?`(${r.x},${r.y})`:void 0,u={action:e.name,intent:s,screen:typeof r.screen=="string"?r.screen:void 0,target:c,activeTab:a?.metadata?.activeTab},d=!n.snapshotOnly&&a.screenshot?[{inlineData:{mimeType:"image/png",data:a.screenshot}}]:void 0;return{response:o,parts:d,message:l,supervisorEntry:u,loopDetectorUpdate:{url:a.url,screenContent:o?.pageSnapshot,screenshotSize:n.skipScreenshotSet.has(n.callIndex)?void 0:a.screenshot?.length},screenshotBase64:a.screenshot}}captureVerbatimTypedValue(e,n){if(!ns()||e.name!=="type_text_at"&&e.name!=="set_focused_input_value"||e.args?.fieldPurpose==="verification_code")return;let r=n;if(r?.status==="error"||typeof r?.inputType=="string"&&r.inputType.toLowerCase()==="password")return;let s=e.name==="type_text_at"?e.args?.text:e.args?.value;if(typeof s!="string")return;let i=s.slice(0,4e3);i.trim().length!==0&&(ku(i)||this._capturedTypedValues.includes(i)||(this._capturedTypedValues.push(i),this._capturedTypedValues.length>50&&this._capturedTypedValues.shift()))}getCapturedTypedValues(){return this._capturedTypedValues}async executeAction(e,n){if((e.name==="type_text_at"||e.name==="set_focused_input_value")&&ta({config:n.session?.config,text:e.name==="type_text_at"?e.args?.text:e.args?.value,inputType:typeof e.args?.inputType=="string"?e.args.inputType:void 0,label:e.args?.label,intent:e.args?.intent,screen:e.args?.screen,stepText:e.args?.stepText})&&(this._canonicalEmailWritten=!0,!this._emailVerificationExpected&&ib(e.args?.intent,e.args?.screen,e.args?.stepText)&&(this._emailVerificationExpected=!0),!this._canonicalEmailUsedForSignup&&ab(e.args?.intent,e.args?.screen,e.args?.stepText)&&(this._canonicalEmailUsedForSignup=!0)),!Le("EMAIL_CODE_PROVENANCE")&&this._emailVerificationExpected&&e.args?.fieldPurpose==="verification_code"&&(e.name==="type_text_at"||e.name==="set_focused_input_value")){let o=String(e.name==="type_text_at"?e.args?.text??"":e.args?.value??""),l=FT({value:o,fetchedEmailTexts:this._fetchedEmailTexts});if(!l.allowed)return this.log("warn","BaseRuntime","email_verification_gate: ungrounded code write refused",{toolName:e.name,grounded:this._fetchedEmailTexts.length>0}),{response:{status:"error",error:l.reason},isMetaTool:!0}}let r=this.maybeBlockForObservationCheckpoint(e,n);if(r)return r;let s=n.isMobile&&_s(e.name)?await this.executeMobileAction(e,n):await this.executeBrowserAction(e,n);this._canonicalEmailWritten&&ob(s.loopDetectorUpdate?.screenContent)&&(this._emailVerificationExpected||(this._emailVerificationExpected=!0),this.recordRuntimeRevealedFact({kind:"capability_required",provenance:"runtime_observed",confidence:"high",source:"testingEmailPolicy.screenIndicatesVerificationPending",message:"The product screen indicates email verification is pending.",data:{capability:"email_verification",...typeof s.loopDetectorUpdate?.url=="string"?{url:s.loopDetectorUpdate.url}:{}}}));let a=HT({scope:n.session?.config?.browserNavigationScope,currentUrl:s.loopDetectorUpdate?.url,screenContent:s.loopDetectorUpdate?.screenContent});return a&&this.recordRuntimeRevealedFact(a),this.updateObservationScreenState(s.loopDetectorUpdate?.url,s.loopDetectorUpdate?.screenContent),s}isObservationCheckpointEnabled(e){return!1}updateObservationScreenState(e,n){let r=typeof e=="string"?e.trim():"",s=typeof n=="string"?n.trim():"";if(!r&&!s)return;let i=s?s.slice(0,2e3):"",a=`${r}|${this.quickHash(i)}`;a!==this.currentObservationScreenKey&&(this.currentObservationScreenKey=a)}markObservationCheckpoint(){this.currentObservationScreenKey&&this.checkpointedObservationScreenKeys.add(this.currentObservationScreenKey)}maybeBlockForObservationCheckpoint(e,n){return!this.isObservationCheckpointEnabled(n)||!this.currentObservationScreenKey||!this.isObservationStateChangingAction(e,n)||this.checkpointedObservationScreenKeys.has(this.currentObservationScreenKey)?null:{response:{status:"observation_required",reason:"checkpoint current screen before leaving or changing it; requested action was not executed",instruction:'Call log_observation now. Use decision="capture" for exact facts required as future inputs, stable locators, expected outcomes, or fixed prices/amounts; use context_only for screen inventory/current-state notes; use decision="none" only if nothing durable needs to be preserved. Then retry the same action.'},isMetaTool:!0}}isObservationStateChangingAction(e,n){if(n.isMobile&&_s(e.name)){if(e.name!=="mobile_press_button")return Jq.has(e.name);let r=String(e.args?.button??"").toUpperCase();return r==="BACK"||r==="HOME"}return Yq.has(e.name)}updateLoopDetector(e,n,r,s){let i=n.loopDetectorUpdate;if(i){if(i.url&&e.updateUrl(i.url),!r){let a=Ef()&&i.canvasDominant===!0&&typeof n.screenshotBase64=="string"&&n.screenshotBase64.length>0?{pixelHash:uT(n.screenshotBase64)}:void 0;e.updateScreenContent(i.screenContent,i.screenshotSize,s!==void 0&&Lb.has(s),a)}if(i.drainTimedOut!==void 0){let a={url:i.url,drainTimedOut:i.drainTimedOut};e.recordDrainResult(a),this.progressBus.recordDrainResult(a)}}}async trackTapRetry(e,n,r,s,i,a,o){let l=n.args??{};if(n.name==="mobile_tap"||n.name==="mobile_long_press"){let c=e.recordTap(typeof l.screen=="string"?l.screen:"",Number(l.x??0),Number(l.y??0),typeof l.intent=="string"?l.intent:"",r.result.screenshot?.length??0);c.memoryProposal&&s.upsert&&(Po(c.memoryProposal,a.map(u=>u.text))||(await s.upsert({id:ve("mem"),projectId:i,text:c.memoryProposal,source:"system",createdAt:Date.now(),updatedAt:Date.now()}),a.push({id:ve("mem"),projectId:i,text:c.memoryProposal,source:"system",createdAt:Date.now(),updatedAt:Date.now()}),this.log("info","TapRetryTracker","Memory saved",{text:c.memoryProposal.slice(0,120)})))}else o&&_s(n.name)&&e.reset()}async setupScreencast(e){let n=[],r=Date.now(),s={count:0},i=null,a=this.baseDeps.createVideoRecorder?.();a?.start(this.sessionId);let o=f=>{f.action.status==="started"&&n.push({timestamp:Date.now()-r,actionName:f.action.actionName,label:f.action.intent,planStepIndex:f.action.planStepIndex})},l=f=>{this.baseDeps.screencastService?.showTapIndicator?.(f.normX,f.normY)},c=()=>{this.baseDeps.screencastService?.pausePolling?.()},u=()=>{this.baseDeps.screencastService?.resumePolling?.()};if(this.baseDeps.screencastService&&!e.config?.extensionPath)try{let f=!1,h=()=>{f||(f=!0,this.emit("screencast:started",{sessionId:this.sessionId}))};i=this.baseDeps.screencastService.onFrame(this.sessionId,p=>{s.count++,a?.addFrame(p.data,p.timestamp),h(),this.emit("screencast:frame",{sessionId:this.sessionId,data:p.data,timestamp:p.timestamp})}),await this.baseDeps.screencastService.startScreencast(this.sessionId),h(),this.log("info","VideoPipeline","recording_started",{sessionId:this.sessionId,hasRecorder:!!a}),this.on("action:progress",o),this.on("tap:indicator",l),this.on("screencast:pause-polling",c),this.on("screencast:resume-polling",u)}catch{}let d={unsubscribe:i,actionProgressHandler:o,tapIndicatorHandler:l,pausePollingHandler:c,resumePollingHandler:u,actionMarkers:n,screencastStartTime:r,projectId:e.projectId,frameCounter:s,videoRecorder:a};return this.activeScreencastState=d,this.screencastStopSignaled=!1,d}signalActiveScreencastStopped(e){!this.activeScreencastState||this.screencastStopSignaled||(this.screencastStopSignaled=!0,this.emit("screencast:stopped",{sessionId:this.sessionId,turnId:e,actionMarkers:this.activeScreencastState.actionMarkers}))}async teardownScreencast(e,n){if(!e)return;this.activeScreencastState!==e&&(this.activeScreencastState=e,this.screencastStopSignaled=!1);let{unsubscribe:r,actionProgressHandler:s,tapIndicatorHandler:i,pausePollingHandler:a,resumePollingHandler:o,actionMarkers:l,projectId:c,frameCounter:u,videoRecorder:d}=e;if(this.removeListener("action:progress",s),this.removeListener("tap:indicator",i),this.removeListener("screencast:pause-polling",a),this.removeListener("screencast:resume-polling",o),r?.(),this.baseDeps.screencastService){try{await this.baseDeps.screencastService.stopScreencast(this.sessionId),this.baseDeps.screencastService.stopDeviceRecording&&await this.baseDeps.screencastService.stopDeviceRecording(this.sessionId),this.baseDeps.screencastService.setActionMarkers?.(l)}catch{}this.signalActiveScreencastStopped(n);let f=u?.count??0;this.log(f>0?"info":"warn","VideoPipeline",f>0?"frames_captured":"frames_none",{sessionId:this.sessionId,turnId:n,framesReceived:f});let h;if(d&&d.isUnavailable?.())this.log("info","VideoPipeline","ffmpeg_unavailable",{sessionId:this.sessionId,turnId:n,framesReceived:f});else if(d&&this.baseDeps.uploadVideo)try{let p=await d.stop(),g=d.getLastError?.();if(this.log(p?"info":"warn","VideoPipeline",p?"ffmpeg_produced_file":"ffmpeg_no_file",{sessionId:this.sessionId,turnId:n,framesReceived:f,sizeBytes:p?.sizeBytes,...g?{ffmpegError:g}:{}}),p){let m=`videos/${c}/${this.sessionId}/${n}.mp4`;h=await this.baseDeps.uploadVideo(p.filePath,m)??void 0,d.cleanup(),this.log(h?"info":"warn","VideoPipeline",h?"upload_ok":"upload_failed",{sessionId:this.sessionId,turnId:n,...h?{videoUrl:h}:{}})}}catch(p){this.log("warn","VideoPipeline","video_finalize_error",{sessionId:this.sessionId,turnId:n,error:p instanceof Error?p.message:String(p)})}return h&&this.emit("screencast:stopped",{sessionId:this.sessionId,turnId:n,actionMarkers:l,videoUrl:h}),this.activeScreencastState=null,this.screencastStopSignaled=!1,h}}async consultLoopBreaker(e,n,r,s,i,a,o,l){if(!n||!Of(n))return{extend:!1};if(!this.loopVisionEscalationActive())return this.log("info","BaseRuntime","loop_vision: breaker skipped (lane disabled)",{mechanism:n,iteration:i,skipReason:"kill_switch_off",spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),{extend:!1};if(!this.baseDeps.supervisorService?.evaluateLoopBreaker)return this.log("warn","BaseRuntime","loop_vision: breaker skipped (no supervisor judge wired)",{mechanism:n,iteration:i,skipReason:"no_supervisor_service",spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),{extend:!1};let c=kT(),u=c?xT:Iu;if(this.loopVisionEscalation.decide(n,u)==="ceiling")return this.log("warn","BaseRuntime","loop_vision: extension ceiling reached, hard-blocking",{mechanism:n,grantsUsed:this.loopVisionEscalation.grantsUsed,maxGrants:u,iteration:i}),{extend:!1};let d=c&&this.loopVisionEscalation.grantsUsed>=1,f=this.loopVisionPrevProgress,h=d?{priorScreenshot:this.loopVisionPrevScreenshot,priorProgress:f}:void 0,p=CT(n,r,this.supervisorActionLog,l),g=await this.baseDeps.supervisorService.evaluateLoopBreaker([...this.supervisorActionLog],this.getSupervisorTaskDescription(o??""),a,p,void 0,h,this.sessionAuxMeter()),m=g.progress??null,S=g.decision==="continue",E=g.decision==="continue"?void 0:g.reason;this._lastLoopBreakerConsult={consulted:!0,keepBlockReason:E,deltaEvidence:m?.delta_evidence};let v=d&&this.loopVisionEscalation.grantsUsed>=Iu,x=Ef()&&this._lastCanvasDominant,b=d&&RT(f,m,x),_=v&&S&&!b,w=S&&!_,A=d?{grantIndex:this.loopVisionEscalation.grantsUsed+1,priorDone:f?.done??null,done:m?.done??null,delta:f&&m?m.done-f.done:null,deltaPresent:b}:void 0;return this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:s.id,verdict:w?"continue":"block",message:w?`loop_vision CONTINUE (${n}) \u2014 false-block rescued`:_?"loop_vision keep_block (no_delta)":`loop_vision keep_block (${n}: ${E})`,iteration:i,actionLogSize:this.supervisorActionLog.length,progress:m,...A?{differential:A}:{}}),w?(this.loopVisionEscalation.recordGrant(),e.grantExtension(n,Nf),c&&(this.loopVisionPrevScreenshot=a,this.loopVisionPrevProgress=m),this.log("info","BaseRuntime","loop_vision: judge CONTINUE granted extension",{mechanism:n,grantsUsed:this.loopVisionEscalation.grantsUsed,extensionActions:Nf,iteration:i,progress:m,...A?{differential:A}:{}}),{extend:!0}):_?(this.log("info","BaseRuntime","loop_vision: keep_block no_delta (differential)",{mechanism:n,iteration:i,priorProgress:f,progress:m,differential:A}),{extend:!1}):(this.log("warn","BaseRuntime","loop_vision: judge kept block (fail-closed)",{mechanism:n,reason:E,iteration:i,progress:m,...A?{differential:A}:{}}),{extend:!1})}async applySupervisorVerdict(e,n,r,s){let i=IT()?this.sameGoalAbort.observeVerdict(e.action):null;if(i){let o=e.action==="redirect"?e.message:void 0;this.log("warn","Supervisor","Same-goal abort escalation",{iteration:r,escalation:i,strike:this.sameGoalAbort.fires,consecutiveRedirects:Zo,originalMessage:o}),e=i==="block"?{action:"block",reason:`${Zo*2} consecutive supervisor corrections produced no progress milestone; the agent ignored the abort steer, ending the run`,rawText:e.rawText}:{action:"abort",reason:`${Zo} consecutive supervisor corrections produced no progress milestone`,rawText:e.rawText}}this.log("info","Supervisor","Applying verdict",{action:e.action,iteration:r}),this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:n.id,verdict:e.action,message:e.action==="block"||e.action==="abort"?e.reason:e.message,iteration:r,actionLogSize:this.supervisorActionLog.length});let a=bf(e);if(e.action==="redirect"){this.log("info","Supervisor","REDIRECT",{message:e.message}),this.steeringVeto.recordRedirect(e.message??"Change approach.");let o=s[s.length-1];return o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}}),{done:a.done}}if(e.action==="block"){this.log("warn","Supervisor","BLOCK",{reason:e.reason});let o=a.blockedReason,l={sessionId:n.id,id:ve("msg"),role:"model",text:`We stopped this run because the agent got stuck: ${o}. No usage charged.`,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`Supervisor intervention after ${this.supervisorActionLog.length} actions`,obstacle:o,question:"The supervisor stopped this session. Please review and retry."}};return await this.persistMessage(l),this.emit("message:added",{sessionId:n.id,message:l}),s.push({name:"exploration_blocked",response:{status:"awaiting_user_guidance"}}),{done:a.done,blockedReason:o}}if(e.action==="wrap_up"){this.log("info","Supervisor","WRAP_UP",{message:e.message});let o=s[s.length-1];o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}})}if(e.action==="abort"){this.steeringVeto.recordRedirect(a.injectedFunctionResponseError??e.reason);let o=s[s.length-1];o&&a.injectedFunctionResponseError&&(o.response={...o.response,status:"error",metadata:{...o.response?.metadata??{},error:a.injectedFunctionResponseError}})}return{done:a.done}}onIterationStart(e,n,r){}onIterationEnd(e){}withCanvasStrategy(e,n,r){if(!Cc()||(n!==this._canvasStrategyActive&&(this.log("info","BaseRuntime",n?"canvas_strategy: injected (page is canvas-dominant)":"canvas_strategy: retracted (page no longer canvas-dominant)",{iteration:r,canvasDominant:n}),this._canvasStrategyActive=n),!n))return e;let s=e[e.length-1],i=s?.parts?.some(a=>a!=null&&typeof a=="object"&&"functionResponse"in a);if(s?.role==="user"&&!i){let a={...s,parts:[...s.parts??[],{text:lh}]};return[...e.slice(0,-1),a]}return[...e,{role:"user",parts:[{text:lh}]}]}getSupervisorTaskDescription(e){return e}hasBackgroundWork(){return!1}waitForBackgroundWork(){return Promise.resolve()}async onLoopExhausted(e,n){let r={sessionId:e.id,id:ve("msg"),role:"model",text:`I paused before finishing this run (step limit of ${n} reached). Reply "continue" to let me proceed, or clarify the exact target page/expected behavior.`,timestamp:Date.now()};await this.persistMessage(r),this.emit("message:added",{sessionId:e.id,message:r})}async consultRunBackstopJudge(e,n,r,s,i){let a=this.baseDeps.supervisorService;if(!a?.evaluateLoopBreaker)return this.log("warn","BaseRuntime","backstop:judge_unavailable (no supervisor judge wired)",{iteration:n,ceiling:i.ceiling,spawnedByCoordinator:this.baseDeps.spawnedByCoordinator===!0}),"unavailable";try{let l=`RUN BACKSTOP PROGRESS CHECK \u2014 this run has hit a safety ceiling (${vu(i.elapsedMs,i.iteration)}, ${i.ceiling}). Judge ONE thing: given the objective and the recent actions + current screenshot, is the agent GENUINELY PROGRESSING toward the objective \u2014 measurably closer than several steps ago \u2014 or WANDERING / not getting closer (recycling the same screens/URLs, repeating failed attempts, or off on an unrelated tangent)? Answer CONTINUE ONLY if you can point to concrete forward progress toward the objective; if it is not clearly getting closer, answer BLOCK. When unsure, answer BLOCK.`,c=await a.evaluateLoopBreaker([...this.supervisorActionLog],this.getSupervisorTaskDescription(s??""),r,l,void 0,void 0,this.sessionAuxMeter());return c.decision==="continue"?"progressing":c.reason==="block"||c.reason==="redirect"||c.reason==="wrap_up"?"wandering":"unavailable"}catch(o){return this.log("warn","BaseRuntime","backstop:judge_error \u2014 failing closed",{iteration:n,ceiling:i.ceiling,error:o?.message}),"unavailable"}}async handleRunBackstop(e,n,r,s,i="ceiling_cap"){let a=yu(e),o=s&&s.trim().length>0?`"${s.trim().slice(0,160)}"`:"this task",l="a series of navigation and interaction steps";try{let f=new Set,h=[];for(let p of[...this.supervisorActionLog].reverse())if(!(!p?.action||f.has(p.action))&&(f.add(p.action),h.push(p.intent?`${p.action} (${p.intent.slice(0,40)})`:p.action),h.length>=4))break;h.length>0&&(l=h.reverse().join(", "))}catch{}this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"run_backstop",iteration:r,details:`terminate on ${e.ceiling} (${a}); reason=${i}; cumulativeTokens=${e.cumulativeTokens}`}),this.baseDeps.sink.emit({kind:"supervisor_verdict",ts:Date.now(),sessionId:n.id,verdict:"block",message:`run_backstop terminate (${e.ceiling}: ${a}; reason=${i})`,iteration:r,actionLogSize:this.supervisorActionLog.length});let u=`${i==="wander"?lT(o,e.elapsedMs,e.iteration):cT(e.elapsedMs,e.iteration)} What I tried: ${l}. Send a new message with a more specific target or expected result and I'll try again.`,d={sessionId:n.id,id:ve("msg"),role:"model",text:u,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`${this.supervisorActionLog.length} actions; ${a}`,obstacle:i==="wander"?`Run backstop: not getting closer to ${o} (${e.ceiling}).`:`Run backstop: hit the safety limit (${e.ceiling}; ${i}).`,question:"The run stopped at a safety limit. Adjust the target or steps and reply to try again."}};return await this.persistMessage(d),this.emit("message:added",{sessionId:n.id,message:d}),this.log("warn","BaseRuntime","run_backstop fired (terminate)",{ceiling:e.ceiling,reason:i,iteration:r,elapsedMs:e.elapsedMs,cumulativeTokens:e.cumulativeTokens}),!0}onLoopForceBlock(e,n,r){}async recordLoopBlockIssue(e,n,r){}async runLoop(e){let{session:n,maxIterations:r,snapshotOnly:s,isMobile:i,devicePlatform:a,taskDescription:o,supervisorHints:l,preserveAllPageSnapshots:c,runJsLoopRecoveryPolicy:u="warn_response"}=e,d=this.conversationTrace;this._endMechanism=void 0,this._lastLoopBreakerConsult=void 0,this._currentTaskDescription=o;let f=!1,h=!1,p,g,m=0,S=Math.floor(Date.now()/1e3),E=0,v=0,x=sT()&&n.kind==="assistant_v2",b=Date.now(),_=0,w=0,A=2,k=new Do(P=>{this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"progress_milestone",iteration:E,details:{source:"LoopDetector",signal:P}}),this.sameGoalAbort.recordMilestone(),this.supervisorVerdictFreshness.recordProgress()},{trackNovelScreenContent:!0,...n.config?.loopDetector??{},rearmUrlNovelty:Db()&&n.kind==="assistant_v2"},P=>{this.baseDeps.sink.emit({kind:"log",ts:Date.now(),sessionId:n.id,level:"info",source:"LoopDetector",msg:"structural_force_block_diagnostics",data:P})});this.isExplorationMode()&&k.setMode("exploration"),this._activeLoopDetector=k,this._lastNavPageSettled=null,this._lastCanvasDominant=!1,this._canvasStrategyActive=!1;let T=new Lo,R;this.steeringVeto.reset(),this.sameGoalAbort.reset(),this.resetLoopVisionState(),this.progressBus.resetSupervisorLog(),this.pendingSupervisorVerdict=null,this.resolvedSupervisorVerdict=null,this.supervisorVerdictFreshness.reset(),this.recentActionsForEvidence=[],this.recentClickTargets=[];let O=[];for(let P=1;P<=r;P++){if(E=P,!this._isRunning)throw new Error("cancelled");if(x){let ae=iT({elapsedMs:b>0?Date.now()-b:0,iteration:P,cumulativeTokens:_},aT(Sf,w));if(ae.kind==="terminate"){this.log("info","BaseRuntime","backstop:ceiling_reached",{ceiling:ae.ceiling,iteration:P,elapsedMs:ae.elapsedMs,cumulativeTokens:ae.cumulativeTokens,extensionsGranted:w});let ee="unavailable";w<gu&&(ee=await this.consultRunBackstopJudge(n,P,R,o,ae),this.log("info","BaseRuntime","backstop:judge_verdict",{verdict:ee,ceiling:ae.ceiling,iteration:P,extensionsGranted:w}));let le=oT(ee,w);if(le.action==="extend")w+=1,this.log("info","BaseRuntime","backstop:extended",{extensionsGranted:w,maxExtensions:gu,ceiling:ae.ceiling,iteration:P});else{let fe=!1;try{fe=await this.handleRunBackstop(ae,n,P,o,le.reason)}catch(oe){this.log("warn","BaseRuntime","run_backstop emit failed \u2014 failing open",{error:oe?.message,iteration:P}),fe=!1}if(fe){this.log("info","BaseRuntime","backstop:terminated",{reason:le.reason,verdict:ee,ceiling:ae.ceiling,iteration:P,extensionsGranted:w}),f=!0,h=!0,g="backstop",p=le.reason==="wander"?`Stopped: not getting closer to the objective (${yu(ae)}).`:`Stopped: hit the safety limit (${yu(ae)}).`,this.recordEndMechanism("run_backstop");break}}}}if(typeof process<"u"&&typeof process.memoryUsage=="function")try{let ae=process.memoryUsage();this.log("info","Runtime","iteration_memory",{iteration:P,rssMb:Math.round(ae.rss/1024/1024),heapUsedMb:Math.round(ae.heapUsed/1024/1024),heapTotalMb:Math.round(ae.heapTotal/1024/1024),externalMb:Math.round(ae.external/1024/1024),arrayBuffersMb:Math.round(ae.arrayBuffers/1024/1024)})}catch{}await this.onIterationStart(d,n,P),c||this.stripOldPageSnapshots(d,s);let L=this.getToolSet({isMobile:i,snapshotOnly:s,devicePlatform:a}),V=this.withCanvasStrategy(this.systemPromptText?d.slice(1):d,this._lastCanvasDominant,P),X=Sa(V),z=V.reduce((ae,ee)=>ae+(ee.parts??[]).reduce((le,fe)=>{let oe=fe.text?.length??0,Ie=fe.functionCall?JSON.stringify(fe.functionCall).length:0,ye=fe.functionResponse?JSON.stringify(fe.functionResponse.response??{}).length:0;return le+oe+Ie+ye},0),0);this.log("info","BaseRuntime","llm_call_preflight",{iteration:P,traceMsgCount:V.length,estimatedTraceChars:z});let U=Date.now(),j;try{j=await st({model:this.model,system:this.systemPromptText??void 0,messages:X,tools:L,temperature:.2,topP:.95,topK:40,maxOutputTokens:8192,maxRetries:this._isRunning?7:0,abortSignal:this._abortController?.signal})}catch(ae){let ee=String(ae?.message||ae?.data?.error?.message||"");if(ee.includes("Unable to process input image")||ee.includes("INVALID_ARGUMENT")){this.log("warn","BaseRuntime","Gemini rejected image \u2014 retrying without screenshots",{error:ee.slice(0,200)});let le=V.map(oe=>({...oe,parts:(oe.parts||[]).filter(Ie=>!Ie.inlineData)})),fe=Sa(le);j=await st({model:this.model,system:this.systemPromptText??void 0,messages:fe,tools:L,temperature:.2,topP:.95,topK:40,maxOutputTokens:8192,maxRetries:this._isRunning?7:0,abortSignal:this._abortController?.signal})}else throw ae}let K=Date.now()-U;P===1&&this.recordStartupMilestone("first_llm_completed",{iteration:P,toolCallCount:j.toolCalls.length,textLength:j.text?.length??0});let q=j.usage,Z=(q?.inputTokens??0)+(q?.outputTokens??0);_+=(q?.inputTokens??0)+(q?.outputTokens??0);let ne=q?.inputTokenDetails?.cacheReadTokens??q?.cachedInputTokens??j.providerMetadata?.google?.usageMetadata?.cachedContentTokenCount??0;if(Z>0&&(this.tokenCount=Z,this.emit("context:updated",{sessionId:n.id,tokenCount:Z}),await this.baseDeps.chatRepo.updateSessionFields(n.id,{lastTokenCount:Z}),this.baseDeps.sink.emit({kind:"llm_usage",ts:Date.now(),sessionId:n.id,runId:this.getCurrentRunId(),callKind:"agent_step",...this.planStepAttribution(),...this.llmSourceMeta(),...UT(j.toolCalls.map(ae=>ae.toolName),Au()),model:n.config.model||"unknown",promptTokens:q?.inputTokens??0,completionTokens:q?.outputTokens??0,cachedInputTokens:ne,totalTokens:Z,durationMs:K,finishReason:j.finishReason??void 0,tokenCount:Z,messageCount:d.length,systemPromptHash:this.systemPromptText?this.quickHash(this.systemPromptText):void 0,lastToolResults:O.map(ae=>({toolName:ae.name,status:ae.response?.status??"unknown"})),chosenActions:j.toolCalls.map(ae=>({toolName:ae.toolName,intent:typeof ae.input?.intent=="string"?ae.input.intent:void 0})),textResponse:typeof j.text=="string"?j.text.slice(0,200):void 0})),!this._isRunning)throw new Error("cancelled");let G=j.response.messages,D=If(G);for(let ae of D)d.push(ae);let Y=j.toolCalls.map(ae=>({name:ae.toolName,args:ae.input??{},toolCallId:ae.toolCallId})),B=j.text;if(Y.length===0){let ae=B?.replace(/[\x00-\x1f\x7f-\x9f]|<ctrl\d+>/g,"").trim();if(B&&!ae&&this.log("warn","BaseRuntime","Model returned garbage text, treating as empty response",{charCount:B.length}),ae){let le={sessionId:n.id,id:ve("msg"),role:"model",text:B.slice(0,6e3),timestamp:Date.now()};if(await this.persistMessage(le),this.emit("message:added",{sessionId:n.id,message:le}),f=!0,this.hasBackgroundWork()){this.log("info","BaseRuntime","Text-only response but background work pending \u2014 waiting silently (not persisting LLM text)",{text:B?.slice(0,100)}),await this.waitForBackgroundWork();continue}this.log("info","BaseRuntime","Text-only response, no background work \u2014 exiting loop",{text:B?.slice(0,100)});break}if(v++,this.hasBackgroundWork()){this.log("info","BaseRuntime","Empty response but background work pending \u2014 waiting silently"),await this.waitForBackgroundWork(),v=0;continue}if(this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"empty_response",iteration:P,details:`attempt ${v}/${A}`}),m>0&&v<=A){this.log("info","BaseRuntime","Model returned empty response, nudging to continue",{stepIndex:m,attempt:v,maxAttempts:A});let le;if(i)le=(await this.baseDeps.mobileMcpService.takeScreenshot(this.sessionId)).base64;else{if(!this.baseDeps.computerUseService)throw new Error("[BaseRuntime] Browser nudge not available \u2014 no computerUseService");le=(await this.baseDeps.computerUseService.invoke({sessionId:n.id,action:"screenshot",args:{},config:{...n.config,projectId:n.projectId}})).screenshot}let oe=[{text:"You stopped without responding. Here is the current page state. Please continue with your task, or if you are done, call assistant_v2_report with a summary."}];s||oe.push({inlineData:{mimeType:"image/png",data:le}}),d.push({role:"user",parts:oe});continue}this.log("warn","BaseRuntime","Model returned consecutive empty responses, giving up",{emptyResponseCount:v});let ee={sessionId:n.id,id:ve("msg"),role:"model",text:m>0?`Model returned empty responses after ${m} action(s). This may be caused by rate limiting or a temporary API issue. You can retry by sending another message.`:"Model returned an empty response and could not start. This may be caused by rate limiting or a temporary API issue. You can retry by sending another message.",timestamp:Date.now()};await this.persistMessage(ee),this.emit("message:added",{sessionId:n.id,message:ee}),f=!0;break}if(v=0,B){let ae={sessionId:n.id,id:ve("msg"),role:"system",actionName:"assistant_v2_text",actionArgs:{iteration:P},text:B.slice(0,6e3),timestamp:Date.now()};await this.persistMessage(ae),this.emit("message:added",{sessionId:n.id,message:ae})}let H=[],$=null,N=!1,M=new Set;if(i)for(let ae=0;ae<Y.length-1;ae++)_s(Y[ae].name)&&Y[ae].name!=="mobile_screenshot"&&_s(Y[ae+1].name)&&Y[ae+1].name!=="mobile_screenshot"&&M.add(ae);let F=-1;for(let ae of Y){if(F++,!this._isRunning)break;m++;let ee={iteration:P,sessionId:this.sessionId,session:n,isMobile:i,snapshotOnly:s,devicePlatform:a,callIndex:F,totalCalls:Y.length,skipScreenshotSet:M,lastScreenshotBase64:R,stepIndex:m,turnTimestamp:S},le=fT()?this.steeringVeto.maybeVeto(ae.name,ae.args??{}):null;if(le!==null){this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"steering_veto",iteration:P,details:`${ae.name} refused: ${le.slice(0,160)}`}),H.push({name:ae.name,response:mT(ae.name,le)});continue}let fe=Date.now(),oe=await this.handleToolCall(ae,ee),Ie=Date.now()-fe;if(oe.isMetaTool||this.steeringVeto.recordExecuted(ae.name,ae.args??{}),oe.resetLoopDetector&&(k.resetForNewStep(),T.reset(),this.steeringVeto.reset(),this.sameGoalAbort.reset(),this.resetLoopVisionState()),this.updateLoopDetector(k,oe,M.has(F),ae.name),!oe.isMetaTool&&!Fq(oe)){let ye=k.check(ae.name,ae.args??{},P,!0);if(ye.action==="force_block")if((await this.consultLoopBreaker(k,ye.mechanism,ye.message,n,P,R,o,l)).extend)this.log("info","BaseRuntime","loop_vision: proceeding past force-block (extension granted)",{mechanism:ye.mechanism,iteration:P});else{this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"loop_block",iteration:P,details:ye.message}),this.log("warn","BaseRuntime","Force-blocking loop",{message:ye.message,iteration:P}),this.onLoopForceBlock(n,ye.message,P),await this.recordLoopBlockIssue(n,ye.message,m),this.recordEndMechanism("loop_block");let Pe=PT({mechanism:ye.mechanism,actionCount:this.supervisorActionLog.length,judge:this._lastLoopBreakerConsult}),he={sessionId:n.id,id:ve("msg"),role:"model",text:Pe,timestamp:Date.now(),actionName:"exploration_blocked",actionArgs:{attempted:`Repeated "${ae.name}" on the same target (${OT[ye.mechanism]})`,obstacle:ye.message,question:"The run stopped because it was no longer making visible progress. Adjust the target or steps and reply to continue."}};await this.persistMessage(he),this.emit("message:added",{sessionId:n.id,message:he}),H.push({name:"exploration_blocked",response:{status:"awaiting_user_guidance"}}),N=!0,f=!0,h=!0,p=ye.message,g="loop";break}if(ye.action==="warn"){if(this.baseDeps.sink.emit({kind:"agent_lifecycle",ts:Date.now(),sessionId:n.id,event:"loop_warning",iteration:P,details:ye.message}),this.log("warn","BaseRuntime","Loop warning",{message:ye.message,iteration:P}),ae.name==="run_js"&&u==="partial_sitemap_salvage"){let he="",Ce="",ie="";if(this.baseDeps.computerUseService){let Te=await this.baseDeps.computerUseService.invoke({sessionId:n.id,action:"screenshot",args:{},config:n.config});he=Te.screenshot,Ce=Te.url??"",ie=[Te.aiSnapshot,Te.domChanges].filter(Boolean).join(`
|
|
475
475
|
|
|
476
476
|
`)}let C=ie||oe.response?.pageSnapshot||oe.message?.a11ySnapshotText||"",Q=$q(C),Ae=Ce||oe.response?.url||"current page",me=Q.length>0?`Visible controls left as navigation gaps: ${Q.join(", ")}.`:"Visible controls left as navigation gaps: no labeled actionable controls were available in the captured snapshot.",Fe=`Partial sitemap recovered before repeated JavaScript extraction was suppressed.
|
|
477
477
|
Captured page: ${Ae}.
|
|
@@ -1883,7 +1883,7 @@ x-amz-content-sha256:${n}
|
|
|
1883
1883
|
x-amz-date:${c}
|
|
1884
1884
|
`,p="host;x-amz-content-sha256;x-amz-date",g=["GET",o,"",h,p,n].join(`
|
|
1885
1885
|
`),m="AWS4-HMAC-SHA256",S=`${u}/${d}/${f}/aws4_request`,E=[m,c,S,_p(g)].join(`
|
|
1886
|
-
`),v=mP(e.secretAccessKey,u,d,f),x=Za(v,E).toString("hex"),b=`${m} Credential=${e.accessKeyId}/${S}, SignedHeaders=${p}, Signature=${x}`;try{let _=await fetch(s,{method:"GET",headers:{Host:a,"x-amz-date":c,"x-amz-content-sha256":n,Authorization:b}});if(_.ok)return Buffer.from(await _.arrayBuffer());if(_.status===404)return null;if(yP.has(_.status)&&r<Vr){console.warn(`[R2Upload] GET ${_.status} on attempt ${r+1}, retrying in ${eo}ms...`),await new Promise(w=>setTimeout(w,eo));continue}return console.error(`[R2Upload] Download failed: ${_.status} ${_.statusText} (attempt ${r+1}/${Vr+1})`),null}catch(_){if(r<Vr){console.warn(`[R2Upload] Network error on attempt ${r+1}, retrying: ${_.message}`),await new Promise(w=>setTimeout(w,eo));continue}return console.error(`[R2Upload] Download failed after ${Vr+1} attempts: ${_.message}`),null}}return null}async function qQ(t,e,n){let r=await fP(t);return Cy(r,e,n)}async function to(t,e,n){return Cy(t,e,n)}function GQ(){let t=process.env.SIGNED_VIDEO_URLS?.trim().toLowerCase();return t==="1"||t==="true"}function HQ(){let t=process.env.VIDEO_PROXY_BASE?.trim();if(t)return t.replace(/\/+$/,"");let e=process.env.API_URL?.trim();if(e)return e.replace(/\/+$/,"")}function WQ(t,e){return`${t}/api/videos/stream?key=${encodeURIComponent(e)}`}async function Ny(t,e,n="video/mp4"){if(!GQ())return qQ(t,e,n);let r=process.env.R2_PRIVATE_BUCKET?.trim();if(!r)return console.error("[R2Upload] SIGNED_VIDEO_URLS is enabled but R2_PRIVATE_BUCKET is unset \u2014 refusing to upload the recording to the public bucket (fail-closed, no video URL)"),null;let s=HQ();if(!s)return console.error("[R2Upload] SIGNED_VIDEO_URLS is enabled but neither VIDEO_PROXY_BASE nor API_URL is set \u2014 cannot build a durable video-proxy URL (fail-closed, no video URL)"),null;let i=process.env.R2_PRIVATE_PREFIX?.trim().replace(/^\/+|\/+$/g,""),a=i?`${i}/${e}`:e,o=await fP(t);return await Cy(o,a,n,{bucket:r})?WQ(s,a):null}async function vP(t,e){let n=await Zt(`${t.apiUrl}/api/chat-videos/${encodeURIComponent(e.chatSessionId)}`,{method:"PUT",body:JSON.stringify({childId:e.childId,projectId:e.projectId,videoUrl:e.videoUrl,markers:e.markers??null})},{userId:t.userId,userToken:t.userToken});if(!n.ok){let r=await n.text().catch(()=>`HTTP ${n.status}`);console.error(`[chatVideoPersist] Failed to persist chat video for ${e.chatSessionId}/${e.childId} (status ${n.status}):`,r)}}var rc=class{constructor(e){this.userId=e}async save(e){let n=this.decodeBase64(e.base64);if(!n)return{};let r=this.buildKey(e.projectId,e.type,e.issueId??e.messageId);try{let s=await to(n,r,"image/png");return s?{url:s}:{}}catch(s){return console.warn(`[R2ImageStorage] upload failed: ${s.message}`),{}}}async get(e){let n=e.type==="issue"?e.issueId:e.messageId;if(!n)return null;let r=this.buildKey(e.projectId,e.type,n);try{let s=await wp(r);return s?s.toString("base64"):null}catch(s){return console.warn(`[R2ImageStorage] download failed: ${s.message}`),null}}buildKey(e,n,r){return`${["analytics",this.userId,e,n,r??"unknown"].map(i=>i.replace(/:/g,"--")).join("/")}.png`}async delete(){}async deleteSession(){}async clearProject(){}decodeBase64(e){let n=e.includes(",")?e.split(",")[1]:e;if(!n)return null;try{return Buffer.from(n.replace(/\s/g,""),"base64")}catch{return null}}};function bP(t,e){return fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}})}var Sp=class{constructor(e,n,r){this.apiUrl=e;this.userId=n;this.userToken=r}async fetchRecentEmails(e){let n=!!process.env.ADMIN_SERVICE_KEY;if(!n&&!this.userToken)throw new Error("email fetch: no ADMIN_SERVICE_KEY and no user token");let r=n?await Zt((()=>{let i=new URL("/api/admin/email/fetch",this.apiUrl);return i.searchParams.set("targetEmail",e),i.toString()})(),{method:"GET"},{userId:this.userId,userToken:this.userToken}):await bP((()=>{let i=new URL("/api/email/fetch",this.apiUrl);return i.searchParams.set("targetEmail",e),i.toString()})(),this.userToken);if(!r.ok){let i=await r.text().catch(()=>`HTTP ${r.status}`);throw new Error(`email fetch failed: ${i}`)}let s=await r.json();return Array.isArray(s.emails)?s.emails:[]}};async function _P(t,e,n){let r=!!process.env.ADMIN_SERVICE_KEY;if(!t||!r&&!n)return console.error("[ApiEmailService] readiness auth unavailable",{apiUrl:t??null,userId:e,reason:t?"no ADMIN_SERVICE_KEY and no user token":"API_URL not set"}),{available:!1,reason:"email service auth unavailable"};try{let s=r?await Zt(new URL("/api/admin/email/readiness",t).toString(),{method:"GET"},{userId:e,userToken:n}):await bP(new URL("/api/email/readiness",t).toString(),n);if(!s.ok){let a=`readiness returned ${s.status}`;return console.error("[ApiEmailService] readiness non-2xx",{apiUrl:t,userId:e,status:s.status,usedAuth:r?"admin":"user-bearer",reason:a}),{available:!1,reason:a}}let i=await s.json();return i?.available&&i.email?{available:!0,email:i.email}:{available:!1,reason:i?.reason??"email inbox unavailable"}}catch(s){let i=s?.message??"readiness failed";return console.error("[ApiEmailService] readiness threw",{apiUrl:t,userId:e,reason:i}),{available:!1,reason:i}}}var Ep=()=>process.env.API_URL,tr=new cp,SP=new up,EP=new hp,KQ=new fp,TP=new mp,IP=new gp,YQ=new rp,JQ=new yp,xP={async store(){throw new Error("Not supported on cloud")},async read(t){let e=wP(t,"utf-8");return{content:e,sizeBytes:Buffer.byteLength(e)}},async readBinary(t){let e=wP(t);return{data:new Uint8Array(e),sizeBytes:e.length}},async getAbsolutePath(t){if(zQ(t))return t;throw new Error(`Cannot resolve attachment path: ${t}`)},async addRef(){},async removeRef(){},async deleteUnreferenced(){return 0}};function Uy(t){return{platform:t?.platform??"web",userId:t?.userId,...t?.appVersion?{appVersion:t.appVersion}:{},...t?.retryOfSessionId?{retryOfSessionId:t.retryOfSessionId}:{}}}function $y(t){if(process.env.DIAG_FILE_SINK)return new sp(process.env.DIAG_FILE_SINK);if(process.env.DIAG_LOCAL==="true")return new Gi;let e=Ep(),n=process.env.ADMIN_SERVICE_KEY;if(e&&n)return new Hi(e,{kind:"service",serviceKey:n,fallbackUserId:t?.userId,bearerFallback:t?.userToken});let r=t?.userToken;return e&&r?new Hi(e,{kind:"bearer",token:r}):process.env.NODE_ENV!=="production"?new Gi:new bo}function XQ(t){return t?.platform==="cli"&&!!t.userId}function QQ(t,e){let n=e.engineSessionKind==="runner"?"test_run":void 0;return{kind:"session_start",ts:Date.now(),sessionId:t.id,sessionMeta:Kr(t,{...Uy(e),...n?{sessionKind:n}:{},eagerSeed:!0})}}function AP(t,e,n=$y,r=1e4){if(!XQ(e))return;let s=n(e);s.emit(QQ(t,e));let i=!1,a=()=>{i||(i=!0,s.destroy?.())},o,l=new Promise(u=>{o=setTimeout(u,r)}),c=s.flush().catch(()=>{});Promise.race([c,l]).then(()=>{o&&clearTimeout(o),a()})}function kP(t){let e=Ep();return!e||!process.env.ADMIN_SERVICE_KEY&&!t?.userToken?null:new Sp(e,t?.userId??"local-cli",t?.userToken)}var Oy;function RP(){if(Oy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Oy=e?jr(Hn,{google:e}):null}let t=Oy;return t?(e,n)=>cy(t,e,n):null}var Py;function ZQ(){if(Py===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Py=e?jr(Hn,{google:e}):null}let t=Py;return t?(e,n)=>Am(t,e,n):null}var My;function eZ(){if(My===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;My=e?jr(Hn,{google:e}):null}let t=My;return t?(e,n)=>Rm(t,e,n):null}var Dy;function tZ(){if(Dy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Dy=e?jr(Hn,{google:e}):null}let t=Dy;return t?(e,n)=>cm(t,e,n):null}var Ly;function nZ(){if(Ly===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Ly=e?jr(Hn,{google:e}):null}let t=Ly;return t?(e,n)=>hm(t,e,n):null}var Fy;function rZ(){if(Fy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Fy=e?jr(Hn,{google:e}):null}let t=Fy;return t?(e,n)=>uP({model:t,assertion:e,meter:n}).then(r=>r.result):null}function sc(t,e,n,r,s){let i=$y(n),a=tr,o=n?.userToken,l=Ep(),c=l&&(n?.userId||o)?new Qa(l,n?.userId??"",o,n?.memoryItems?.length?{projectId:n.projectId,items:n.memoryItems}:void 0,void 0,n?.sessionId):(()=>{let g=new Ql;return n?.memoryItems?.length&&g.seed(n.projectId,n.memoryItems),g})(),u=l&&(n?.userId||o)?new ec(l,n?.userId??"",o):(()=>{let g=new Xl;return n?.issues?.length&&g.seed(n.issues),g})(),d=l&&(n?.userId||o)?new Zl(l,n?.userId??"",o):SP,f=new tc(n?.credentials??[]),h=n?.userId?new rc(n.userId):null,p=kP(n);return{chatRepo:a,issuesRepo:u,memoryRepo:c,testPlanV2RunRepo:d,secretsService:f,model:t,computerUseService:e,mobileMcpService:r,authService:EP,sink:i,sessionMetaExtras:Uy(n),sampleFilesService:YQ,attachmentStorageService:xP,imageStorageService:h,notificationService:KQ,emailService:p,llmAccessService:TP,errorReporter:IP,supervisorService:new wa(t),screencastService:s??void 0,createVideoRecorder:()=>new nc,uploadVideo:(g,m)=>Ny(g,m,"video/mp4"),driftJudge:RP(),blindReader:ZQ(),criterionRegrader:eZ(),stateExtractor:tZ(),conceptClassifier:nZ(),predicateBasisCompiler:rZ()}}function sZ(t,e,n=process.env){return{...n.AGENTIQA_DISABLE_MODEL_FALLBACK==="1"?{fallbackModelIds:[]}:{},onFallback:r=>{t.emit({kind:"log",ts:Date.now(),sessionId:e??"unknown",level:"warn",source:"ManagedModelRouting",msg:"provider_location_fallback",data:{reason:r.reason,primaryModelId:r.primaryModelId,fallbackModelId:r.fallbackModelId,role:"coordinator"}})}}}function CP(t,e,n,r,s,i){let a=$y(n),o=tr,l=n?.userToken,c=Ep(),u=c&&(n?.userId||l)?new Qa(c,n?.userId??"",l,n?.memoryItems?.length?{projectId:n.projectId,items:n.memoryItems}:void 0,void 0,n?.sessionId):(()=>{let _=new Ql;return n?.memoryItems?.length&&_.seed(n.projectId,n.memoryItems),_})(),d=c&&(n?.userId||l)?new ec(c,n?.userId??"",l):(()=>{let _=new Xl;return n?.issues?.length&&_.seed(n.issues),_})(),f=new tc(n?.credentials??[]),h=c&&(n?.userId||l)?new Zl(c,n?.userId??"",l):SP,p=n?.testPlans?.length?(()=>{let _=new dp;return _.seed(n.testPlans),_})():void 0,g=process.env.COORDINATOR_MODEL?.trim()||zv,m=i?Ka(g,i,sZ(a,n?.sessionId)):void 0,S=c&&l?new op(c,l,n?.userId??"",n?.sessionId):(()=>{let _=new ip;return n?.appMap&&_.seed(n.projectId,n.appMap),_})(),E=c&&l?new lp(c,l,n?.userId??""):(()=>{let _=new ap;return n?.journalEntries?.length&&_.seed(n.projectId,n.journalEntries),_})(),v=c&&l?new pp(c,l):JQ,x=n?.userId?new rc(n.userId):null,b=kP(n);return{chatRepo:o,model:t,coordinatorModel:m,computerUseService:e,authService:EP,sink:a,sessionMetaExtras:Uy(n),memoryRepo:u,secretsService:f,issuesRepo:d,mobileMcpService:r,screencastService:s??void 0,errorReporter:IP,llmAccessService:TP,supervisorService:new wa(t),testPlanV2RunRepo:h,testPlanV2Repo:p,appMapRepo:S,journalRepo:E,projectsRepo:v,imageStorageService:x,emailService:b,attachmentStorageService:xP,createVideoRecorder:()=>new nc,uploadVideo:(_,w)=>Ny(_,w,"video/mp4"),persistChildVideo:c&&(n?.userId||l)?async _=>vP({apiUrl:c,userId:n?.userId??"",userToken:l},_):void 0,driftJudge:RP()}}async function ic(t,e,n,r){try{let[s,i,a]=await Promise.all([r.memoryRepo instanceof Qa?r.memoryRepo.listDetailed(n).catch(()=>({items:[],source:"empty"})):r.memoryRepo.list(n).then(l=>({items:l,source:"inmemory"})).catch(()=>({items:[],source:"inmemory"})),r.appMapRepo?r.appMapRepo.get(n).catch(()=>null):Promise.resolve(null),r.journalRepo?r.journalRepo.list(n).catch(()=>[]):Promise.resolve([])]),o={projectId:n,memoryItems:s.items.length,memorySource:s.source,appMapPresent:!!i&&((i.surfaces?.length??0)>0||(i.entities?.length??0)>0),appMapSurfaces:i?.surfaces?.length??0,journalEntries:a.length};t.emit({kind:"log",ts:Date.now(),sessionId:e,level:"info",source:"MemorySeed",msg:"seed_context",data:{...o}})}catch{}}import NP from"express-rate-limit";var OP=NP({windowMs:6e4,max:60,standardHeaders:!0,legacyHeaders:!1,skip:t=>t.path==="/health",message:{error:"Too many requests, please try again later"}}),PP=NP({windowMs:6e4,max:5,standardHeaders:!0,legacyHeaders:!1,message:{error:"Too many session creation requests, please try again later"}}),MP=20;import{z as re}from"zod";function Gs(t){return(e,n,r)=>{let s=t.safeParse(e.body);if(!s.success){let i=s.error.issues.map(a=>({path:a.path.join("."),message:a.message}));console.error("[Validation] Failed:",e.method,e.path,JSON.stringify(i)),n.status(400).json({error:"Validation failed",details:i});return}e.body=s.data,r()}}var DP=re.union([re.number(),re.string()]).transform(t=>typeof t=="string"?new Date(t).getTime():t),LP=re.object({sessionId:re.string().max(100).optional(),sessionKind:re.string().max(50).optional(),sessionTitle:re.string().max(200).optional(),projectId:re.string().max(100).optional(),userId:re.string().max(100).optional(),userToken:re.string().max(4e3).optional(),model:re.string().max(100).optional(),screenWidth:re.number().int().min(320).max(3840).optional(),screenHeight:re.number().int().min(320).max(3840).optional(),initialUrl:re.string().max(2048).optional(),routingContext:re.object({bootstrapSource:re.enum(["welcome_url_form","chat_message"]).optional(),routingMode:re.enum(["mapper_then_coordinator","specific_task_via_coordinator"]).optional(),bootstrapStartedAt:re.number().optional(),bootstrapCompletedAt:re.number().optional()}).optional(),snapshotOnly:re.boolean().optional(),memoryItems:re.union([re.array(re.object({id:re.string().max(100).optional(),text:re.string().max(5e3),category:re.string().max(100).nullable().optional()}).passthrough()).max(100),re.array(re.string().max(5e3)).max(100)]).optional(),testPlans:re.array(re.object({id:re.string().max(100),projectId:re.string().max(100),title:re.string().max(500),steps:re.array(re.record(re.string(),re.unknown())).max(200)}).passthrough()).max(20).optional(),issues:re.array(re.record(re.string(),re.unknown())).max(200).optional(),credentials:re.array(re.object({name:re.string().max(500),secret:re.string().max(500)}).passthrough()).max(20).optional(),messages:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),role:re.enum(["user","model","system"]),text:re.string().max(5e4).optional(),timestamp:re.number(),actionName:re.string().max(200).optional(),actionArgs:re.unknown().optional(),url:re.string().max(2048).optional(),hasScreenshot:re.boolean().optional(),runId:re.string().max(200).optional()}).passthrough()).max(200).optional(),engineSessionKind:re.enum(["agent","runner"]).optional(),platform:re.string().max(50).optional(),autoApprove:re.boolean().optional(),resultFirstDiscovery:re.boolean().optional(),memoryWriteback:re.boolean().optional(),persistBrowserProfile:re.boolean().optional(),availableCapabilities:re.object({capabilities:re.array(re.enum(["email_verification","oauth_redirect","sms_verification"])).max(10)}).optional(),goal:re.string().max(2e3).optional(),verbose:re.boolean().optional(),knownIssueTitles:re.array(re.string()).optional(),mobileConfig:re.object({platform:re.enum(["android","ios"]),deviceId:re.string().max(200).optional(),appIdentifier:re.string().max(500).optional()}).optional(),seedCookies:re.array(re.object({name:re.string().max(200),value:re.string().max(4096),domain:re.string().max(200),path:re.string().max(200).optional(),expires:re.number().optional(),httpOnly:re.boolean().optional(),secure:re.boolean().optional(),sameSite:re.enum(["Strict","Lax","None"]).optional()}).passthrough()).max(50).optional(),seedLocalStorage:re.array(re.object({url:re.string().max(2048),items:re.record(re.string().max(200),re.string().max(4096))})).max(20).optional()}).passthrough(),FP=re.object({text:re.string().min(1,"text is required").max(5e4),entryId:re.string().max(200).optional(),attachments:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),originalName:re.string().max(500),mimeType:re.string().max(200),sizeBytes:re.number(),category:re.enum(["text","image","binary"]),r2Key:re.string().max(1e3),r2Url:re.string().max(2048)}).passthrough()).max(20).optional()});function iZ(t){if(t==null)return;if(t==="setup"||t==="action"||t==="verify")return t;let e=String(t).toLowerCase();return e.includes("verify")?"verify":e.includes("setup")?"setup":"action"}var aZ=re.object({text:re.string().max(5e3),type:re.preprocess(iZ,re.enum(["setup","action","verify"]).optional()),criteria:re.array(re.object({check:re.string().max(2e3),strict:re.boolean().default(!0),expectedValue:re.string().max(2e3).optional(),grounding:re.object({value:re.string().max(2e3),evidence:re.string().max(2e3),envKey:re.string().max(500),status:re.enum(["candidate","confirmed"]),observedAt:re.string().max(100),runId:re.string().max(200),greens:re.number()}).passthrough().optional()})).max(50).optional(),fileAssets:re.array(re.object({storedPath:re.string().max(1e3),originalName:re.string().max(500),r2Url:re.string().max(2e3).optional()})).max(10).optional()}).passthrough(),jy=re.object({id:re.string().max(100),projectId:re.string().max(100),title:re.string().max(500),steps:re.array(aZ).min(1).max(100),createdAt:DP,updatedAt:DP,sourceSessionId:re.string().max(100).nullish(),chatSessionId:re.string().max(100).nullish(),config:re.record(re.string(),re.unknown()).nullish(),labels:re.array(re.string().max(100)).max(50).nullish()}).passthrough(),UP=re.object({testPlan:jy,initialMemory:re.record(re.string().max(200),re.string().max(2e3)).optional()}),$P=re.object({plans:re.array(jy).min(1).max(20),mode:re.enum(["sequential","parallel"]),concurrency:re.number().int().min(1).max(5).optional(),initialMemory:re.record(re.string().max(200),re.string().max(2e3)).optional(),batchRunId:re.string().optional(),planSessions:re.array(re.object({id:re.string().max(200),testPlanId:re.string().max(200).optional()})).max(20).optional()}),jP=re.object({text:re.string().min(1,"text is required").max(5e4),testPlan:jy,attachments:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),originalName:re.string().max(500),mimeType:re.string().max(200),sizeBytes:re.number(),category:re.enum(["text","image","binary"]),r2Key:re.string().max(1e3),r2Url:re.string().max(2048)}).passthrough()).max(20).optional()}),BP=re.object({expression:re.string().min(1,"expression is required").max(1e4)}),VP=re.object({text:re.string().min(1,"text is required").max(2e3)});process.on("uncaughtException",t=>{console.error("[Engine] Uncaught exception:",t)});process.on("unhandledRejection",t=>{console.error("[Engine] Unhandled rejection:",t)});var dZ=120*1e3;function pZ(){let t=Number(process.env.RUNNER_STALL_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:dZ}function hZ(t){let e=typeof t.type=="string"?t.type:"event";if(e==="action:progress"){let n=t.action,r=typeof n?.actionName=="string"?n.actionName:"unknown action",s=typeof n?.status=="string"?n.status:"unknown status",i=typeof n?.stepIndex=="number"?` step ${n.stepIndex}`:"";return`${e}${i}: ${r} ${s}`}if(e==="supervisor_verdict"){let n=typeof t.verdict=="string"?t.verdict:"unknown",r=typeof t.message=="string"&&t.message?` (${t.message})`:"";return`${e}: ${n}${r}`}if(e==="message:added"){let n=t.message,r=typeof n?.actionName=="string"?n.actionName:typeof n?.role=="string"?n.role:"message";return`${e}: ${r}`}if(e==="session:error"){let n=typeof t.error=="string"?`: ${t.error}`:"";return`${e}${n}`}return e}function fZ(t,e=Date.now(),n=pZ()){let r=0;for(let[s,i]of t){if(!i.runner?.isRunning||i.lastRunOutcome)continue;let a=e-i.lastActivityAt;if(a<=n)continue;let o=i.lastBroadcastSummary??"no engine events after run start",l=`Run stalled after ${Math.round(a/1e3)}s without engine events or run_complete. Last event: ${o}.`;console.error(`[Engine] Failing stalled runner session ${s}: ${l}`),i.sink?.emit({kind:"log",ts:e,sessionId:s,level:"error",source:"ExecutionEngine",msg:"runner_stall_timeout",data:{idleMs:a,timeoutMs:n,lastEvent:o}}),i.runner.failStalledRun(l),r++}return r}function GP(t,e,n,r,s,i){let a=oc(t,r,s,i),o=new Vs(e),l=CP(a,e,t.seed,n,o,r);t.secretsService=l.secretsService,t.sink=l.sink,t.type="agent",t.seed?.credentials?.length&&l.sink.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"Engine",msg:"modeA.activated",data:{credCount:t.seed.credentials.length,credNames:t.seed.credentials.map(u=>u.name),trigger:"project_creds_existed"}});let c=new Ll(t.id,l);if(ic(l.sink,t.id,t.chatSession.projectId,{memoryRepo:l.memoryRepo,appMapRepo:l.appMapRepo,journalRepo:l.journalRepo}),t.seed?.credentials?.length&&!t.chatSession.config?.userProvidedTestEmail){let u=t.seed.credentials.find(d=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.name));if(u){let d=u.name.trim().toLowerCase();t.chatSession.config.userProvidedTestEmail=d,t.chatSession.config.testingEmailPolicy=void 0,l.sink.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"Engine",msg:"modeA.activated",data:{email:d,trigger:"project_creds_derived_email",policyNulled:!0}})}}return t._cleanupListeners=gZ(t,c),c}function Vy(){return process.env.DEFAULT_MODEL?.trim()||Hn}function oc(t,e,n,r){let s=t.chatSession.config?.model??Vy(),i=process.env.AGENTIQA_DISABLE_MODEL_FALLBACK==="1",a=Ka(s,e,{...i?{fallbackModelIds:[]}:{},onFallback:o=>{t.sink?.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"warn",source:"ManagedModelRouting",msg:"provider_location_fallback",data:{reason:o.reason,primaryModelId:o.primaryModelId,fallbackModelId:o.fallbackModelId}})}});return n&&(a=Ty(a,r,!0,(o,l,c)=>{t.sink?.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"LLMCache",message:`${o?"HIT":"MISS"} ${l.slice(0,8)} (msgs=${c})`})})),a}function ac(t,e,n){return t.engineSessionKind&&t.engineSessionKind!==e?(n.status(409).json({error:`Session "${t.engineSessionKind}" cannot use "${e}" endpoint`}),!1):!0}function lt(t,e){t.lastActivityAt=Date.now(),t.lastBroadcastSummary=hZ(e);let{screenshotBase64:n,...r}=e;if(t.events.push(r),n&&e.message&&e.message.id){let i=e.message.id,o=`screenshots/${t.chatSession.projectId||"unknown"}/${t.id}/${i}.png`,l=Buffer.from(n,"base64");t.screenshotUrls||(t.screenshotUrls=new Map),t.pendingScreenshotUploads||(t.pendingScreenshotUploads=[]);let c=to(l,o,"image/png").then(u=>{u?t.screenshotUrls.set(i,u):console.warn(`[Engine] Screenshot upload returned null for ${i}`)}).catch(u=>{console.warn(`[Engine] Screenshot upload error for ${i}: ${u.message}`)});t.pendingScreenshotUploads.push(c)}let s=JSON.stringify(e);for(let i of t.ws)i.readyState===ki.OPEN&&i.send(s)}async function mZ(t){if(!t.r2Url)return t;let e=await import("node:os"),n=await import("node:fs"),r=await import("node:path"),s=r.join(e.tmpdir(),"agentiqa-attachments");n.existsSync(s)||n.mkdirSync(s,{recursive:!0});let i=r.join(s,`${Date.now()}-${t.originalName}`),a=await fetch(t.r2Url);if(!a.ok)throw new Error(`Failed to download attachment: ${a.status}`);let o=new Uint8Array(await a.arrayBuffer());return n.writeFileSync(i,o),{...t,localPath:i}}function gZ(t,e){return e.on("action:progress",n=>{lt(t,{type:"action:progress",...n})}),e.on("message:added",n=>{n?.message?.actionName==="ask_user"&&(t.awaitingUserSince=Date.now()),lt(t,{type:"message:added",...n})}),e.on("session:stopped",n=>{t.awaitingUserSince=void 0,lt(t,{type:"session:stopped",...n})}),e.on("session:blocked",n=>{t.awaitingUserSince=Date.now(),lt(t,{type:"session:blocked",...n})}),e.on("session:error",n=>{lt(t,{type:"session:error",...n})}),e.on("session:status-changed",n=>{lt(t,{type:"session:status-changed",...n})}),e.on("context:updated",n=>{lt(t,{type:"context:updated",...n})}),e.on("test_plan:saved",n=>{lt(t,{type:"test_plan:saved",...n})}),e.on("benchmark:milestone",n=>{lt(t,{type:"benchmark:milestone",...n})}),e.on("session:coverage-requested",n=>{lt(t,{type:"session:coverage-requested",...n})}),e.on("session:interrupt-requested",n=>{lt(t,{type:"session:interrupt-requested",...n})}),e.on("screencast:frame",n=>{HP(t,{type:"screencast:frame",...n})}),e.on("screencast:started",n=>{lt(t,{type:"screencast:started",...n})}),e.on("screencast:stopped",n=>{lt(t,{type:"screencast:stopped",...n})}),()=>e.removeAllListeners()}function By(t,e){return e.on("action:progress",n=>{lt(t,{type:"action:progress",...n})}),e.on("message:added",n=>{lt(t,{type:"message:added",...n})}),e.on("session:stopped",n=>{lt(t,{type:"session:stopped",...n})}),e.on("session:error",n=>{lt(t,{type:"session:error",...n})}),e.on("run:completed",async n=>{lt(t,{type:"run:completed",...n}),t.lastRunOutcome={type:"run:completed",run:n.run,runMemory:n.runMemory};try{t.pendingScreenshotUploads?.length&&await Promise.allSettled(t.pendingScreenshotUploads);let r=n.run;if(r?.id&&t.seed?.userId&&process.env.API_URL){let s=r.sessionId??t.chatSession.id,i=await tr.listMessages(s),{messages:a,usedFallback:o}=fl(i,r.id);o&&console.warn(`[Engine] run ${r.id}: strict runId filter empty on session ${s}, falling back to permissive (${a.length} of ${i.length})`);let l=new Set(["upload_file"]),c=a.filter(h=>h.role==="user"||h.role==="model"&&(h.actionName||h.text&&!/^(<ctrl\d+>\s*)+$/.test(h.text))||h.role==="system"&&(h.hasScreenshot||t.screenshotUrls?.has(h.id)||l.has(h.actionName??"")));console.log(`[Engine] Persisting messages for run ${r.id}: ${c.length} visible of ${a.length} run / ${i.length} total`);let u=(h,p)=>{if(!h)return;let g={};if(h.stepText&&(g.stepText=h.stepText),typeof h.planStepIndex=="number"&&(g.planStepIndex=h.planStepIndex),h.status&&(g.status=h.status),p==="report_issue")for(let m of["title","description","severity","confidence","issueId","issueConfirmed","issueDismissed"])h[m]!==void 0&&(g[m]=h[m]);return p==="propose_update"&&h.updates&&(g.updates=h.updates),p==="spawn_agent"&&h.childAgent&&(g.childAgent=h.childAgent),p==="child_completed"&&h.childAgent&&(g.childAgent=h.childAgent,h.status&&(g.status=h.status),h.summary&&(g.summary=h.summary)),p==="run_complete"&&Array.isArray(h.screenshots)&&(g.screenshots=h.screenshots.map(({base64:m,...S})=>S)),Object.keys(g).length>0?g:void 0},d=c.map(h=>({id:h.id,role:h.role,text:h.text,timestamp:h.timestamp,actionName:h.actionName,actionArgs:u(h.actionArgs,h.actionName),url:h.url,hasScreenshot:h.hasScreenshot||t.screenshotUrls?.has(h.id)||!1,screenshotUrl:t.screenshotUrls?.get(h.id)??void 0,runId:h.runId})),f=await fetch(`${process.env.API_URL}/api/sync/entities/test-plan-runs/${r.id}`,{method:"PUT",headers:Xa(t.seed?.userId??"",t.seed?.userToken),body:JSON.stringify({testPlanId:r.testPlanId,projectId:r.projectId,status:r.status,terminationReason:r.terminationReason,messages:d,updatedAt:Date.now()})});f.ok||console.error(`[Engine] Message persist API error for run ${r.id}: ${f.status} ${f.statusText}`)}}catch(r){console.error("[Engine] Error persisting run messages:",r.message)}finally{t.pendingScreenshotUploads=[]}}),e.on("session:status-changed",n=>{lt(t,{type:"session:status-changed",...n})}),e.on("run:started",n=>{lt(t,{type:"run:started",...n})}),e.on("benchmark:milestone",n=>{lt(t,{type:"benchmark:milestone",...n})}),e.on("session:coverage-requested",n=>{lt(t,{type:"session:coverage-requested",...n})}),e.on("session:interrupt-requested",n=>{lt(t,{type:"session:interrupt-requested",...n})}),e.on("screencast:frame",n=>{HP(t,{type:"screencast:frame",...n})}),e.on("screencast:started",n=>{lt(t,{type:"screencast:started",...n})}),e.on("screencast:stopped",n=>{lt(t,{type:"screencast:stopped",...n})}),()=>e.removeAllListeners()}function HP(t,e){t.lastActivityAt=Date.now();let n=JSON.stringify(e);for(let r of t.ws)r.readyState===ki.OPEN&&r.send(n)}function WP(t,e){let n={google:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,anthropic:process.env.ANTHROPIC_API_KEY,openai:process.env.OPENAI_API_KEY,openaiBaseURL:process.env.OPENAI_BASE_URL},r=process.env.NODE_ENV!=="production"&&process.env.LLM_CACHE!=="0",s=lZ.join(oZ.tmpdir(),"agentiqa-llm-cache"),i=qP(),a=process.env.ENGINE_API_TOKEN;i.use((p,g,m)=>{if(g.header("Access-Control-Allow-Origin","*"),g.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),g.header("Access-Control-Allow-Headers","Content-Type, Authorization, X-Session-Token"),p.method==="OPTIONS"){g.sendStatus(204);return}m()}),i.use(qP.json({limit:"1mb"})),i.use(OP),i.use((p,g,m)=>{if(p.path==="/health"){m();return}if(!a){m();return}if(p.headers.authorization===`Bearer ${a}`){m();return}g.status(401).json({error:"Unauthorized"})});let o=cZ.createServer(i),l=new uZ({server:o,path:"/ws",perMessageDeflate:!1}),c=new Map,u=600*1e3,d=(()=>{let p=Number(process.env.ENGINE_PAUSE_HOLD_MS);return Number.isFinite(p)&&p>0?p:1200*1e3})(),f=setInterval(()=>{let p=Date.now();fZ(c,p);for(let[g,m]of c){let S=!m.agent?.isRunning&&!m.runner?.isRunning,E=m.ws.size===0,v=p-m.lastActivityAt>u,x=m.awaitingUserSince!==void 0&&p-m.awaitingUserSince<d;if(S&&E&&v&&!x){let b=p-m.lastActivityAt,_=m.lastRunOutcome!==void 0;console.log(JSON.stringify({event:"session_idle_reap",sessionId:g,idleMs:b,hadAgentActivity:_})),console.log(`[Engine] Reaping idle session ${g} (age: ${Math.round((p-m.startedAt)/1e3)}s)`),m.agent?.stop(),m.runner?.stop(),m._cleanupListeners?.(),m.sink?.destroy?.(),lt(m,{type:"session:error",error:"Session expired due to inactivity"});for(let w of m.ws)w.readyState===ki.OPEN&&w.close(1e3,"Session expired");t.clearCredentials(g),t.cleanupSession(g).catch(()=>{}),t.cleanupSession(`${g}:child-browser`).catch(()=>{}),tr.deleteSession(g),c.delete(g)}}},6e4);o.on("close",()=>clearInterval(f)),t.onBrowserDisconnected=()=>{if(!t.isBrowserShutdownExpected()){console.error("[Engine] Browser crashed \u2014 stopping all active sessions");for(let[p,g]of c){g.agent?.stop(),g.runner?.stop(),g._cleanupListeners?.(),g.sink?.destroy?.(),lt(g,{type:"session:error",error:"Browser process crashed"});for(let m of g.ws)m.close();t.clearCredentials(p),tr.deleteSession(p),c.delete(p)}}},i.post("/api/engine/session",PP,Gs(LP),async(p,g)=>{if(c.size>=MP){g.status(503).json({error:"Server at capacity, try again later"});return}let{sessionId:m,sessionKind:S,sessionTitle:E,projectId:v,userId:x,userToken:b,model:_,screenWidth:w,screenHeight:A,initialUrl:k,routingContext:T,snapshotOnly:R,memoryItems:O,testPlans:P,issues:L,credentials:V,engineSessionKind:X,mobileConfig:z,goal:U,verbose:j,knownIssueTitles:K,autoApprove:q,parallelChildren:Z,resultFirstDiscovery:ne,memoryWriteback:G,platform:D,appVersion:Y,persistBrowserProfile:B,seedCookies:H,seedLocalStorage:$,availableCapabilities:N,messages:M,browserNavigationScope:F,retryOfSessionId:te}=p.body,se=m||ve("session"),pe;if(typeof k=="string"&&k.length>0&&k!=="about:blank")try{let he=/^https?:\/\//i.test(k)?k:`https://${k}`;pe=new URL(he).origin}catch{pe=void 0}let ke=c.get(se);if(ke){if(X&&ke.engineSessionKind&&X!==ke.engineSessionKind){g.status(409).json({error:`Session ${se} exists with kind '${ke.engineSessionKind}', cannot reuse as '${X}'`});return}console.log(`[Engine] Session ${se} already exists (running: ${ke.agent?.isRunning??ke.runner?.isRunning??!1}), returning existing`),g.json({sessionId:se,config:ke.chatSession.config,existing:!0});return}let ae=v??ve("project"),ee=await _P(process.env.API_URL,x??"local-cli",b),le=ee.available&&ee.email?uh(ee.email,se,{canCheckInbox:!0}):null,fe=Array.isArray(V)&&V.length>0,oe=iP({requestedCapabilities:N,canCheckInbox:le?.canCheckInbox,hasCredentials:fe}),Ie={screenWidth:w??1280,screenHeight:A??720,model:_??Vy(),initialUrl:k,...pe?{appUnderTestOrigin:pe}:{},...Array.isArray(F)&&F.length>0?{browserNavigationScope:F.map(String)}:{},snapshotOnly:R??!1,...oe.length>0?{availableCapabilities:{capabilities:oe}}:{},...le?{testingEmailPolicy:le}:{},...z?{platform:"mobile",mobileConfig:z}:{},...q!=null&&{autoApprove:q},...Z!=null&&{parallelChildren:Z},...ne!=null&&{resultFirstDiscovery:ne},...G!=null&&{memoryWriteback:G},...B!=null&&{persistBrowserProfile:B},...Array.isArray(H)&&H.length>0?{seedCookies:H}:{},...Array.isArray($)&&$.length>0?{seedLocalStorage:$}:{}};if(k&&Js(k).matched){let Ce=Ie.maxIterationsPerTurn;Ie.maxIterationsPerTurn=Math.min(Ce??300,5),(Ce===void 0||Ce>5)&&console.log(`[Engine] generic-site clamp session=${se} host=${Js(k).host} iterations=${Ie.maxIterationsPerTurn} (was ${Ce??300})`)}let ye={id:se,projectId:ae,title:E||"Cloud Session",createdAt:Date.now(),updatedAt:Date.now(),isArchived:!1,status:"idle",kind:S||"assistant_v2",config:Ie,routingContext:T},Ee={projectId:ae,sessionId:se,userId:x??void 0,userToken:b??void 0,memoryItems:O??[],testPlans:P??[],issues:L??[],credentials:V??[],platform:D??void 0,appVersion:Y??void 0,retryOfSessionId:typeof te=="string"&&te?te:void 0,engineSessionKind:X??void 0};console.log(`[Engine] Session ${se}: ${Ee.memoryItems?.length??0} memoryItems, ${Ee.issues?.length??0} issues, ${Ee.credentials?.length??0} credentials`),Ee.credentials?.length&&t.seedCredentials(se,Ee.credentials);let Pe={id:se,type:"agent",engineSessionKind:X??void 0,chatSession:ye,seed:Ee,ws:new Set,events:[],startedAt:Date.now(),lastActivityAt:Date.now()};if(c.set(se,Pe),await tr.upsertSession(ye),Array.isArray(M)&&M.length>0)for(let he of M)await tr.addMessage({...he,sessionId:se});AP(ye,Ee),g.json({sessionId:se,config:Ie})}),i.get("/api/engine/session/:id",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}g.json({id:m.id,type:m.type,status:m.chatSession.status,running:m.agent?.isRunning??m.runner?.isRunning??!1,eventCount:m.events.length,startedAt:m.startedAt,userId:m.seed?.userId??null})}),i.patch("/api/engine/session/:id/config",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{autoApprove:S}=p.body??{};S!=null&&(m.chatSession.config.autoApprove=S),g.json({ok:!0,config:m.chatSession.config})}),i.post("/api/engine/session/:id/bootstrap",async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(ac(m,"agent",g)){if(!m.agent){if(m._agentInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._agentInitializing=!0;try{m.agent=GP(m,t,e,n,r,s),await tr.upsertSession(m.chatSession)}finally{m._agentInitializing=!1}}try{m.agent.startWelcomeBootstrap(m.chatSession).catch(S=>{console.error(`[Engine] bootstrap error for session ${m.id}:`,S.message),lt(m,{type:"session:error",error:S.message})}),g.json({ok:!0})}catch(S){g.status(500).json({error:S.message})}}}),i.post("/api/engine/session/:id/message",Gs(FP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"agent",g))return;m.awaitingUserSince=void 0;let{text:S,attachments:E,entryId:v}=p.body;if(!m.agent){if(m._agentInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._agentInitializing=!0;try{m.agent=GP(m,t,e,n,r,s),await tr.upsertSession(m.chatSession)}finally{m._agentInitializing=!1}}try{let x=Array.isArray(E)&&E.length?await Promise.all(E.map(mZ)):void 0;m.agent.sendMessage(m.chatSession,S,x,typeof v=="string"&&v?v:void 0).catch(b=>{console.error(`[Engine] sendMessage error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/run",Gs(UP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{testPlan:S,initialMemory:E}=p.body,v=new Set(["setup","action","verify"]);for(let x of S.steps??[])if(!x.type||!v.has(x.type)){let b=(x.type??"").toLowerCase();x.type=b.includes("verify")?"verify":b.includes("setup")?"setup":"action"}if(!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let x=oc(m,n,r,s),b=new Vs(t),_=sc(x,t,m.seed,e,b);m.runner=new Xn(m.id,_),m.sink=_.sink,ic(_.sink,m.id,m.chatSession.projectId,{memoryRepo:_.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run",testPlanId:S.id},await _.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}try{m.lastRunOutcome=void 0;let x=m.runner.startRun(m.chatSession,S,{initialMemory:E,onMemoryUpdate:b=>{lt(m,{type:"memory:updated",memory:b})}});x&&typeof x.catch=="function"&&x.catch(b=>{console.error(`[Engine] startRun error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/batch-run",Gs($P),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{plans:S,mode:E,concurrency:v,initialMemory:x,batchRunId:b,planSessions:_}=p.body,w=new Set(["setup","action","verify"]);for(let T of S)for(let R of T.steps??[])if(!R.type||!w.has(R.type)){let O=(R.type??"").toLowerCase();R.type=O.includes("verify")?"verify":O.includes("setup")?"setup":"action"}if(E==="sequential"&&!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let T=oc(m,n,r,s),R=new Vs(t),O=sc(T,t,m.seed,e,R);m.runner=new Xn(m.id,O),m.sink=O.sink,ic(O.sink,m.id,m.chatSession.projectId,{memoryRepo:O.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run"},await O.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}let A=T=>{lt(m,T)},k;E==="sequential"&&(k=S.map((T,R)=>{let O=_?.[R];return{...m.chatSession,id:O?.id??`${m.chatSession.id}__plan${R}`,kind:"test_run",testPlanId:O?.testPlanId??T.id,createdAt:Date.now(),updatedAt:Date.now()}}),await Promise.all(k.map(T=>tr.upsertSession(T))));try{let T=E==="sequential"?{runner:m.runner}:(()=>{let O=oc(m,n,r,s),P=new Vs(t);return{deps:sc(O,t,m.seed,e,P),sessionId:m.id}})();vg(T,m.chatSession,S,{mode:E,concurrency:v,initialMemory:x,batchRunId:b,planSessions:k},A).then(async O=>{b&&m.seed?.userId&&process.env.API_URL&&await fetch(`${process.env.API_URL}/api/sync/entities/batch-runs/${b}`,{method:"PUT",headers:Xa(m.seed?.userId??"",m.seed?.userToken),body:JSON.stringify({status:O.status,updatedAt:Date.now(),endedAt:Date.now()})}).catch(()=>{})}).catch(async O=>{lt(m,{type:"session:error",error:O.message}),b&&m.seed?.userId&&process.env.API_URL&&await fetch(`${process.env.API_URL}/api/sync/entities/batch-runs/${b}`,{method:"PUT",headers:Xa(m.seed?.userId??"",m.seed?.userToken),body:JSON.stringify({status:"partial",updatedAt:Date.now(),endedAt:Date.now()})}).catch(()=>{})}),g.json({ok:!0})}catch(T){g.status(500).json({error:T.message})}}),i.post("/api/engine/session/:id/runner-message",Gs(jP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{text:S,testPlan:E,attachments:v}=p.body;if(!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let x=oc(m,n,r,s),b=new Vs(t),_=sc(x,t,m.seed,e,b);m.runner=new Xn(m.id,_),m.sink=_.sink,ic(_.sink,m.id,m.chatSession.projectId,{memoryRepo:_.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run",testPlanId:E.id},await _.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}try{let x=m.runner.sendMessage(m.chatSession,E,S,v);x&&typeof x.catch=="function"&&x.catch(b=>{console.error(`[Engine] runner sendMessage error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/evaluate",Gs(BP),async(p,g)=>{if(!c.get(p.params.id)){g.status(404).json({error:"Session not found"});return}let{expression:S}=p.body;try{let E=await t.evaluate(p.params.id,S);g.json({result:E})}catch(E){g.status(500).json({error:E.message})}}),i.post("/api/engine/session/:id/stop",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}m.agent?.stop("user_stopped"),m.runner?.stop("user_stopped"),g.json({ok:!0})}),i.post("/api/engine/session/:id/reset",async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"session_not_found"});return}if(m.type!=="runner"||!m.runner){g.status(400).json({error:"not_a_runner_session"});return}let S=p.body?.keepMemory??!0;try{await m.runner.resetForNextPlan({keepMemory:S}),m.events.length=0,g.status(200).json({ok:!0})}catch(E){if(E?.message?.includes("cannot reset while a run is in progress")){g.status(409).json({error:"run_in_progress"});return}g.status(500).json({error:"reset_failed",message:E?.message})}}),i.post("/api/engine/session/:id/credentials",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{credentials:S}=p.body;if(!Array.isArray(S)||S.length===0){g.status(400).json({error:"credentials array required"});return}m.secretsService?.addCredentials(S);let v=[...m.seed?.credentials??[],...S];t.seedCredentials(p.params.id,v),m.seed&&(m.seed.credentials=v),m.sink?.emit({kind:"log",ts:Date.now(),sessionId:p.params.id,level:"info",source:"Engine",msg:"modeA.engine.credentials_added",data:{count:S.length,names:S.map(x=>x.name),totalAfter:v.length}}),g.json({ok:!0,count:S.length})}),i.post("/api/engine/session/:id/user-provided-test-email",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{email:S}=p.body,E=typeof S=="string"?S.trim().toLowerCase():null;if(!(E&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E))||!E){g.status(400).json({error:"valid email required"});return}m.chatSession.config.userProvidedTestEmail=E,m.chatSession.config.testingEmailPolicy=void 0,m.sink?.emit({kind:"log",ts:Date.now(),sessionId:p.params.id,level:"info",source:"Engine",msg:"modeA.activated",data:{email:E,trigger:"user_filled_needs"}}),g.json({ok:!0})}),i.delete("/api/engine/session/:id",async(p,g)=>{let m=c.get(p.params.id);if(m){m.agent?.stop(),m.runner?.stop(),m._cleanupListeners?.(),m.sink?.destroy?.();for(let S of m.ws)S.close();t.clearCredentials(p.params.id),await t.cleanupSession(p.params.id),await t.cleanupSession(`${p.params.id}:child-browser`).catch(()=>{}),tr.deleteSession(p.params.id),c.delete(p.params.id)}g.json({ok:!0})}),i.post("/api/engine/chat-title",Gs(VP),async(p,g)=>{let{text:m}=p.body;try{let S=`Generate a concise 3-5 word title summarizing WHAT is being tested or asked. Never include process words like "testing", "test", "verification", "check", "session", "QA", "validate". Focus only on the subject matter.
|
|
1886
|
+
`),v=mP(e.secretAccessKey,u,d,f),x=Za(v,E).toString("hex"),b=`${m} Credential=${e.accessKeyId}/${S}, SignedHeaders=${p}, Signature=${x}`;try{let _=await fetch(s,{method:"GET",headers:{Host:a,"x-amz-date":c,"x-amz-content-sha256":n,Authorization:b}});if(_.ok)return Buffer.from(await _.arrayBuffer());if(_.status===404)return null;if(yP.has(_.status)&&r<Vr){console.warn(`[R2Upload] GET ${_.status} on attempt ${r+1}, retrying in ${eo}ms...`),await new Promise(w=>setTimeout(w,eo));continue}return console.error(`[R2Upload] Download failed: ${_.status} ${_.statusText} (attempt ${r+1}/${Vr+1})`),null}catch(_){if(r<Vr){console.warn(`[R2Upload] Network error on attempt ${r+1}, retrying: ${_.message}`),await new Promise(w=>setTimeout(w,eo));continue}return console.error(`[R2Upload] Download failed after ${Vr+1} attempts: ${_.message}`),null}}return null}async function qQ(t,e,n){let r=await fP(t);return Cy(r,e,n)}async function to(t,e,n){return Cy(t,e,n)}function GQ(){let t=process.env.SIGNED_VIDEO_URLS?.trim().toLowerCase();return t==="1"||t==="true"}function HQ(){let t=process.env.VIDEO_PROXY_BASE?.trim();if(t)return t.replace(/\/+$/,"");let e=process.env.API_URL?.trim();if(e)return e.replace(/\/+$/,"")}function WQ(t,e){return`${t}/api/videos/stream?key=${encodeURIComponent(e)}`}async function Ny(t,e,n="video/mp4"){if(!GQ())return qQ(t,e,n);let r=process.env.R2_PRIVATE_BUCKET?.trim();if(!r)return console.error("[R2Upload] SIGNED_VIDEO_URLS is enabled but R2_PRIVATE_BUCKET is unset \u2014 refusing to upload the recording to the public bucket (fail-closed, no video URL)"),null;let s=HQ();if(!s)return console.error("[R2Upload] SIGNED_VIDEO_URLS is enabled but neither VIDEO_PROXY_BASE nor API_URL is set \u2014 cannot build a durable video-proxy URL (fail-closed, no video URL)"),null;let i=process.env.R2_PRIVATE_PREFIX?.trim().replace(/^\/+|\/+$/g,""),a=i?`${i}/${e}`:e,o=await fP(t);return await Cy(o,a,n,{bucket:r})?WQ(s,a):null}async function vP(t,e){let n=await Zt(`${t.apiUrl}/api/chat-videos/${encodeURIComponent(e.chatSessionId)}`,{method:"PUT",body:JSON.stringify({childId:e.childId,projectId:e.projectId,videoUrl:e.videoUrl,markers:e.markers??null})},{userId:t.userId,userToken:t.userToken});if(!n.ok){let r=await n.text().catch(()=>`HTTP ${n.status}`);console.error(`[chatVideoPersist] Failed to persist chat video for ${e.chatSessionId}/${e.childId} (status ${n.status}):`,r)}}var rc=class{constructor(e){this.userId=e}async save(e){let n=this.decodeBase64(e.base64);if(!n)return{};let r=this.buildKey(e.projectId,e.type,e.issueId??e.messageId);try{let s=await to(n,r,"image/png");return s?{url:s}:{}}catch(s){return console.warn(`[R2ImageStorage] upload failed: ${s.message}`),{}}}async get(e){let n=e.type==="issue"?e.issueId:e.messageId;if(!n)return null;let r=this.buildKey(e.projectId,e.type,n);try{let s=await wp(r);return s?s.toString("base64"):null}catch(s){return console.warn(`[R2ImageStorage] download failed: ${s.message}`),null}}buildKey(e,n,r){return`${["analytics",this.userId,e,n,r??"unknown"].map(i=>i.replace(/:/g,"--")).join("/")}.png`}async delete(){}async deleteSession(){}async clearProject(){}decodeBase64(e){let n=e.includes(",")?e.split(",")[1]:e;if(!n)return null;try{return Buffer.from(n.replace(/\s/g,""),"base64")}catch{return null}}};function bP(t,e){return fetch(t,{method:"GET",headers:{Authorization:`Bearer ${e}`}})}var Sp=class{constructor(e,n,r){this.apiUrl=e;this.userId=n;this.userToken=r}async fetchRecentEmails(e){let n=!!process.env.ADMIN_SERVICE_KEY;if(!n&&!this.userToken)throw new Error("email fetch: no ADMIN_SERVICE_KEY and no user token");let r=n?await Zt((()=>{let i=new URL("/api/admin/email/fetch",this.apiUrl);return i.searchParams.set("targetEmail",e),i.toString()})(),{method:"GET"},{userId:this.userId,userToken:this.userToken}):await bP((()=>{let i=new URL("/api/email/fetch",this.apiUrl);return i.searchParams.set("targetEmail",e),i.toString()})(),this.userToken);if(!r.ok){let i=await r.text().catch(()=>`HTTP ${r.status}`);throw new Error(`email fetch failed: ${i}`)}let s=await r.json();return Array.isArray(s.emails)?s.emails:[]}};async function _P(t,e,n){let r=!!process.env.ADMIN_SERVICE_KEY;if(!t||!r&&!n)return console.error("[ApiEmailService] readiness auth unavailable",{apiUrl:t??null,userId:e,reason:t?"no ADMIN_SERVICE_KEY and no user token":"API_URL not set"}),{available:!1,reason:"email service auth unavailable"};try{let s=r?await Zt(new URL("/api/admin/email/readiness",t).toString(),{method:"GET"},{userId:e,userToken:n}):await bP(new URL("/api/email/readiness",t).toString(),n);if(!s.ok){let a=`readiness returned ${s.status}`;return console.error("[ApiEmailService] readiness non-2xx",{apiUrl:t,userId:e,status:s.status,usedAuth:r?"admin":"user-bearer",reason:a}),{available:!1,reason:a}}let i=await s.json();return i?.available&&i.email?{available:!0,email:i.email}:{available:!1,reason:i?.reason??"email inbox unavailable"}}catch(s){let i=s?.message??"readiness failed";return console.error("[ApiEmailService] readiness threw",{apiUrl:t,userId:e,reason:i}),{available:!1,reason:i}}}var Ep=()=>process.env.API_URL,tr=new cp,SP=new up,EP=new hp,KQ=new fp,TP=new mp,IP=new gp,YQ=new rp,JQ=new yp,xP={async store(){throw new Error("Not supported on cloud")},async read(t){let e=wP(t,"utf-8");return{content:e,sizeBytes:Buffer.byteLength(e)}},async readBinary(t){let e=wP(t);return{data:new Uint8Array(e),sizeBytes:e.length}},async getAbsolutePath(t){if(zQ(t))return t;throw new Error(`Cannot resolve attachment path: ${t}`)},async addRef(){},async removeRef(){},async deleteUnreferenced(){return 0}};function Uy(t){return{platform:t?.platform??"web",userId:t?.userId,...t?.appVersion?{appVersion:t.appVersion}:{},...t?.retryOfSessionId?{retryOfSessionId:t.retryOfSessionId}:{}}}function $y(t){if(process.env.DIAG_FILE_SINK)return new sp(process.env.DIAG_FILE_SINK);if(process.env.DIAG_LOCAL==="true")return new Gi;let e=Ep(),n=process.env.ADMIN_SERVICE_KEY;if(e&&n)return new Hi(e,{kind:"service",serviceKey:n,fallbackUserId:t?.userId,bearerFallback:t?.userToken});let r=t?.userToken;return e&&r?new Hi(e,{kind:"bearer",token:r}):process.env.NODE_ENV!=="production"?new Gi:new bo}function XQ(t){return t?.platform==="cli"&&!!t.userId}function QQ(t,e){let n=e.engineSessionKind==="runner"?"test_run":void 0;return{kind:"session_start",ts:Date.now(),sessionId:t.id,sessionMeta:Kr(t,{...Uy(e),...n?{sessionKind:n}:{},eagerSeed:!0})}}function AP(t,e,n=$y,r=1e4){if(!XQ(e))return;let s=n(e);s.emit(QQ(t,e));let i=!1,a=()=>{i||(i=!0,s.destroy?.())},o,l=new Promise(u=>{o=setTimeout(u,r)}),c=s.flush().catch(()=>{});Promise.race([c,l]).then(()=>{o&&clearTimeout(o),a()})}function kP(t){let e=Ep();return!e||!process.env.ADMIN_SERVICE_KEY&&!t?.userToken?null:new Sp(e,t?.userId??"local-cli",t?.userToken)}var Oy;function RP(){if(Oy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Oy=e?jr(Hn,{google:e}):null}let t=Oy;return t?(e,n)=>cy(t,e,n):null}var Py;function ZQ(){if(Py===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Py=e?jr(Hn,{google:e}):null}let t=Py;return t?(e,n)=>Am(t,e,n):null}var My;function eZ(){if(My===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;My=e?jr(Hn,{google:e}):null}let t=My;return t?(e,n)=>Rm(t,e,n):null}var Dy;function tZ(){if(Dy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Dy=e?jr(Hn,{google:e}):null}let t=Dy;return t?(e,n)=>cm(t,e,n):null}var Ly;function nZ(){if(Ly===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Ly=e?jr(Hn,{google:e}):null}let t=Ly;return t?(e,n)=>hm(t,e,n):null}var Fy;function rZ(){if(Fy===void 0){let e=process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY;Fy=e?jr(Hn,{google:e}):null}let t=Fy;return t?(e,n)=>uP({model:t,assertion:e,meter:n}).then(r=>r.result):null}function sc(t,e,n,r,s){let i=$y(n),a=tr,o=n?.userToken,l=Ep(),c=l&&(n?.userId||o)?new Qa(l,n?.userId??"",o,n?.memoryItems?.length?{projectId:n.projectId,items:n.memoryItems}:void 0,void 0,n?.sessionId):(()=>{let g=new Ql;return n?.memoryItems?.length&&g.seed(n.projectId,n.memoryItems),g})(),u=l&&(n?.userId||o)?new ec(l,n?.userId??"",o):(()=>{let g=new Xl;return n?.issues?.length&&g.seed(n.issues),g})(),d=l&&(n?.userId||o)?new Zl(l,n?.userId??"",o):SP,f=new tc(n?.credentials??[]),h=n?.userId?new rc(n.userId):null,p=kP(n);return{chatRepo:a,issuesRepo:u,memoryRepo:c,testPlanV2RunRepo:d,secretsService:f,model:t,computerUseService:e,mobileMcpService:r,authService:EP,sink:i,sessionMetaExtras:Uy(n),sampleFilesService:YQ,attachmentStorageService:xP,imageStorageService:h,notificationService:KQ,emailService:p,llmAccessService:TP,errorReporter:IP,supervisorService:new wa(t),screencastService:s??void 0,createVideoRecorder:()=>new nc,uploadVideo:(g,m)=>Ny(g,m,"video/mp4"),driftJudge:RP(),blindReader:ZQ(),criterionRegrader:eZ(),stateExtractor:tZ(),conceptClassifier:nZ(),predicateBasisCompiler:rZ()}}function sZ(t,e,n=process.env){return{...n.AGENTIQA_DISABLE_MODEL_FALLBACK==="1"?{fallbackModelIds:[]}:{},onFallback:r=>{t.emit({kind:"log",ts:Date.now(),sessionId:e??"unknown",level:"warn",source:"ManagedModelRouting",msg:"provider_location_fallback",data:{reason:r.reason,primaryModelId:r.primaryModelId,fallbackModelId:r.fallbackModelId,role:"coordinator"}})}}}function CP(t,e,n,r,s,i){let a=$y(n),o=tr,l=n?.userToken,c=Ep(),u=c&&(n?.userId||l)?new Qa(c,n?.userId??"",l,n?.memoryItems?.length?{projectId:n.projectId,items:n.memoryItems}:void 0,void 0,n?.sessionId):(()=>{let _=new Ql;return n?.memoryItems?.length&&_.seed(n.projectId,n.memoryItems),_})(),d=c&&(n?.userId||l)?new ec(c,n?.userId??"",l):(()=>{let _=new Xl;return n?.issues?.length&&_.seed(n.issues),_})(),f=new tc(n?.credentials??[]),h=c&&(n?.userId||l)?new Zl(c,n?.userId??"",l):SP,p=n?.testPlans?.length?(()=>{let _=new dp;return _.seed(n.testPlans),_})():void 0,g=process.env.COORDINATOR_MODEL?.trim()||zv,m=i?Ka(g,i,sZ(a,n?.sessionId)):void 0,S=c&&l?new op(c,l,n?.userId??"",n?.sessionId):(()=>{let _=new ip;return n?.appMap&&_.seed(n.projectId,n.appMap),_})(),E=c&&l?new lp(c,l,n?.userId??""):(()=>{let _=new ap;return n?.journalEntries?.length&&_.seed(n.projectId,n.journalEntries),_})(),v=c&&l?new pp(c,l):JQ,x=n?.userId?new rc(n.userId):null,b=kP(n);return{chatRepo:o,model:t,coordinatorModel:m,computerUseService:e,authService:EP,sink:a,sessionMetaExtras:Uy(n),memoryRepo:u,secretsService:f,issuesRepo:d,mobileMcpService:r,screencastService:s??void 0,errorReporter:IP,llmAccessService:TP,supervisorService:new wa(t),testPlanV2RunRepo:h,testPlanV2Repo:p,appMapRepo:S,journalRepo:E,projectsRepo:v,imageStorageService:x,emailService:b,attachmentStorageService:xP,createVideoRecorder:()=>new nc,uploadVideo:(_,w)=>Ny(_,w,"video/mp4"),persistChildVideo:c&&(n?.userId||l)?async _=>vP({apiUrl:c,userId:n?.userId??"",userToken:l},_):void 0,driftJudge:RP()}}async function ic(t,e,n,r){try{let[s,i,a]=await Promise.all([r.memoryRepo instanceof Qa?r.memoryRepo.listDetailed(n).catch(()=>({items:[],source:"empty"})):r.memoryRepo.list(n).then(l=>({items:l,source:"inmemory"})).catch(()=>({items:[],source:"inmemory"})),r.appMapRepo?r.appMapRepo.get(n).catch(()=>null):Promise.resolve(null),r.journalRepo?r.journalRepo.list(n).catch(()=>[]):Promise.resolve([])]),o={projectId:n,memoryItems:s.items.length,memorySource:s.source,appMapPresent:!!i&&((i.surfaces?.length??0)>0||(i.entities?.length??0)>0),appMapSurfaces:i?.surfaces?.length??0,journalEntries:a.length};t.emit({kind:"log",ts:Date.now(),sessionId:e,level:"info",source:"MemorySeed",msg:"seed_context",data:{...o}})}catch{}}import NP from"express-rate-limit";var OP=NP({windowMs:6e4,max:60,standardHeaders:!0,legacyHeaders:!1,skip:t=>t.path==="/health",message:{error:"Too many requests, please try again later"}}),PP=NP({windowMs:6e4,max:5,standardHeaders:!0,legacyHeaders:!1,message:{error:"Too many session creation requests, please try again later"}}),MP=20;import{z as re}from"zod";function Gs(t){return(e,n,r)=>{let s=t.safeParse(e.body);if(!s.success){let i=s.error.issues.map(a=>({path:a.path.join("."),message:a.message}));console.error("[Validation] Failed:",e.method,e.path,JSON.stringify(i)),n.status(400).json({error:"Validation failed",details:i});return}e.body=s.data,r()}}var DP=re.union([re.number(),re.string()]).transform(t=>typeof t=="string"?new Date(t).getTime():t),LP=re.object({sessionId:re.string().max(100).optional(),sessionKind:re.string().max(50).optional(),sessionTitle:re.string().max(200).optional(),projectId:re.string().max(100).optional(),userId:re.string().max(100).optional(),userToken:re.string().max(4e3).optional(),model:re.string().max(100).optional(),screenWidth:re.number().int().min(320).max(3840).optional(),screenHeight:re.number().int().min(320).max(3840).optional(),initialUrl:re.string().max(2048).optional(),routingContext:re.object({bootstrapSource:re.enum(["welcome_url_form","chat_message"]).optional(),routingMode:re.enum(["mapper_then_coordinator","specific_task_via_coordinator"]).optional(),bootstrapStartedAt:re.number().optional(),bootstrapCompletedAt:re.number().optional()}).optional(),snapshotOnly:re.boolean().optional(),memoryItems:re.union([re.array(re.object({id:re.string().max(100).optional(),text:re.string().max(5e3),category:re.string().max(100).nullable().optional()}).passthrough()).max(100),re.array(re.string().max(5e3)).max(100)]).optional(),testPlans:re.array(re.object({id:re.string().max(100),projectId:re.string().max(100),title:re.string().max(500),steps:re.array(re.record(re.string(),re.unknown())).max(200)}).passthrough()).max(20).optional(),issues:re.array(re.record(re.string(),re.unknown())).max(200).optional(),credentials:re.array(re.object({name:re.string().max(500),secret:re.string().max(500)}).passthrough()).max(20).optional(),messages:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),role:re.enum(["user","model","system"]),text:re.string().max(5e4).optional(),timestamp:re.number(),actionName:re.string().max(200).optional(),actionArgs:re.unknown().optional(),url:re.string().max(2048).optional(),hasScreenshot:re.boolean().optional(),runId:re.string().max(200).optional()}).passthrough()).max(200).optional(),engineSessionKind:re.enum(["agent","runner"]).optional(),platform:re.string().max(50).optional(),autoApprove:re.boolean().optional(),resultFirstDiscovery:re.boolean().optional(),memoryWriteback:re.boolean().optional(),persistBrowserProfile:re.boolean().optional(),availableCapabilities:re.object({capabilities:re.array(re.enum(["email_verification","oauth_redirect","sms_verification"])).max(10)}).optional(),goal:re.string().max(2e3).optional(),verbose:re.boolean().optional(),knownIssueTitles:re.array(re.string()).optional(),mobileConfig:re.object({platform:re.enum(["android","ios"]),deviceId:re.string().max(200).optional(),appIdentifier:re.string().max(500).optional()}).optional(),seedCookies:re.array(re.object({name:re.string().max(200),value:re.string().max(4096),domain:re.string().max(200),path:re.string().max(200).optional(),expires:re.number().optional(),httpOnly:re.boolean().optional(),secure:re.boolean().optional(),sameSite:re.enum(["Strict","Lax","None"]).optional()}).passthrough()).max(50).optional(),seedLocalStorage:re.array(re.object({url:re.string().max(2048),items:re.record(re.string().max(200),re.string().max(4096))})).max(20).optional()}).passthrough(),FP=re.object({text:re.string().min(1,"text is required").max(5e4),entryId:re.string().max(200).optional(),attachments:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),originalName:re.string().max(500),mimeType:re.string().max(200),sizeBytes:re.number(),category:re.enum(["text","image","binary"]),r2Key:re.string().max(1e3),r2Url:re.string().max(2048)}).passthrough()).max(20).optional()});function iZ(t){if(t==null)return;if(t==="setup"||t==="action"||t==="verify")return t;let e=String(t).toLowerCase();return e.includes("verify")?"verify":e.includes("setup")?"setup":"action"}var aZ=re.object({text:re.string().max(5e3),type:re.preprocess(iZ,re.enum(["setup","action","verify"]).optional()),criteria:re.array(re.object({check:re.string().max(2e3),strict:re.boolean().default(!0),expectedValue:re.string().max(2e3).optional(),grounding:re.object({value:re.string().max(2e3),evidence:re.string().max(2e3),envKey:re.string().max(500),status:re.enum(["candidate","confirmed"]),observedAt:re.string().max(100),runId:re.string().max(200),greens:re.number()}).passthrough().optional()})).max(50).optional(),fileAssets:re.array(re.object({storedPath:re.string().max(1e3),originalName:re.string().max(500),r2Url:re.string().max(2e3).optional()})).max(10).optional()}).passthrough(),jy=re.object({id:re.string().max(100),projectId:re.string().max(100),title:re.string().max(500),steps:re.array(aZ).min(1).max(100),createdAt:DP,updatedAt:DP,sourceSessionId:re.string().max(100).nullish(),chatSessionId:re.string().max(100).nullish(),config:re.record(re.string(),re.unknown()).nullish(),labels:re.array(re.string().max(100)).max(50).nullish()}).passthrough(),UP=re.object({testPlan:jy,initialMemory:re.record(re.string().max(200),re.string().max(2e3)).optional()}),$P=re.object({plans:re.array(jy).min(1).max(20),mode:re.enum(["sequential","parallel"]),concurrency:re.number().int().min(1).max(5).optional(),initialMemory:re.record(re.string().max(200),re.string().max(2e3)).optional(),batchRunId:re.string().optional(),planSessions:re.array(re.object({id:re.string().max(200),testPlanId:re.string().max(200).optional()})).max(20).optional()}),jP=re.object({text:re.string().min(1,"text is required").max(5e4),testPlan:jy,attachments:re.array(re.object({id:re.string().max(200),sessionId:re.string().max(200),originalName:re.string().max(500),mimeType:re.string().max(200),sizeBytes:re.number(),category:re.enum(["text","image","binary"]),r2Key:re.string().max(1e3),r2Url:re.string().max(2048)}).passthrough()).max(20).optional()}),BP=re.object({expression:re.string().min(1,"expression is required").max(1e4)}),VP=re.object({text:re.string().min(1,"text is required").max(2e3)});process.on("uncaughtException",t=>{console.error("[Engine] Uncaught exception:",t)});process.on("unhandledRejection",t=>{console.error("[Engine] Unhandled rejection:",t)});var dZ=120*1e3;function pZ(){let t=Number(process.env.RUNNER_STALL_TIMEOUT_MS);return Number.isFinite(t)&&t>0?t:dZ}function hZ(t){let e=typeof t.type=="string"?t.type:"event";if(e==="action:progress"){let n=t.action,r=typeof n?.actionName=="string"?n.actionName:"unknown action",s=typeof n?.status=="string"?n.status:"unknown status",i=typeof n?.stepIndex=="number"?` step ${n.stepIndex}`:"";return`${e}${i}: ${r} ${s}`}if(e==="supervisor_verdict"){let n=typeof t.verdict=="string"?t.verdict:"unknown",r=typeof t.message=="string"&&t.message?` (${t.message})`:"";return`${e}: ${n}${r}`}if(e==="message:added"){let n=t.message,r=typeof n?.actionName=="string"?n.actionName:typeof n?.role=="string"?n.role:"message";return`${e}: ${r}`}if(e==="session:error"){let n=typeof t.error=="string"?`: ${t.error}`:"";return`${e}${n}`}return e}function fZ(t,e=Date.now(),n=pZ()){let r=0;for(let[s,i]of t){if(!i.runner?.isRunning||i.lastRunOutcome)continue;let a=e-i.lastActivityAt;if(a<=n)continue;let o=i.lastBroadcastSummary??"no engine events after run start",l=`Run stalled after ${Math.round(a/1e3)}s without engine events or run_complete. Last event: ${o}.`;console.error(`[Engine] Failing stalled runner session ${s}: ${l}`),i.sink?.emit({kind:"log",ts:e,sessionId:s,level:"error",source:"ExecutionEngine",msg:"runner_stall_timeout",data:{idleMs:a,timeoutMs:n,lastEvent:o}}),i.runner.failStalledRun(l),r++}return r}function GP(t,e,n,r,s,i){let a=oc(t,r,s,i),o=new Vs(e),l=CP(a,e,t.seed,n,o,r);t.secretsService=l.secretsService,t.sink=l.sink,t.type="agent",t.seed?.credentials?.length&&l.sink.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"Engine",msg:"modeA.activated",data:{credCount:t.seed.credentials.length,credNames:t.seed.credentials.map(u=>u.name),trigger:"project_creds_existed"}});let c=new Ll(t.id,l);if(ic(l.sink,t.id,t.chatSession.projectId,{memoryRepo:l.memoryRepo,appMapRepo:l.appMapRepo,journalRepo:l.journalRepo}),t.seed?.credentials?.length&&!t.chatSession.config?.userProvidedTestEmail){let u=t.seed.credentials.find(d=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.name));if(u){let d=u.name.trim().toLowerCase();t.chatSession.config.userProvidedTestEmail=d,t.chatSession.config.testingEmailPolicy=void 0,l.sink.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"Engine",msg:"modeA.activated",data:{email:d,trigger:"project_creds_derived_email",policyNulled:!0}})}}return t._cleanupListeners=gZ(t,c),c}function Vy(){return process.env.DEFAULT_MODEL?.trim()||Hn}function oc(t,e,n,r){let s=t.chatSession.config?.model??Vy(),i=process.env.AGENTIQA_DISABLE_MODEL_FALLBACK==="1",a=Ka(s,e,{...i?{fallbackModelIds:[]}:{},onFallback:o=>{t.sink?.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"warn",source:"ManagedModelRouting",msg:"provider_location_fallback",data:{reason:o.reason,primaryModelId:o.primaryModelId,fallbackModelId:o.fallbackModelId}})}});return n&&(a=Ty(a,r,!0,(o,l,c)=>{t.sink?.emit({kind:"log",ts:Date.now(),sessionId:t.id,level:"info",source:"LLMCache",message:`${o?"HIT":"MISS"} ${l.slice(0,8)} (msgs=${c})`})})),a}function ac(t,e,n){return t.engineSessionKind&&t.engineSessionKind!==e?(n.status(409).json({error:`Session "${t.engineSessionKind}" cannot use "${e}" endpoint`}),!1):!0}function lt(t,e){t.lastActivityAt=Date.now(),t.lastBroadcastSummary=hZ(e);let{screenshotBase64:n,...r}=e;if(t.events.push(r),n&&e.message&&e.message.id){let i=e.message.id,o=`screenshots/${t.chatSession.projectId||"unknown"}/${t.id}/${i}.png`,l=Buffer.from(n,"base64");t.screenshotUrls||(t.screenshotUrls=new Map),t.pendingScreenshotUploads||(t.pendingScreenshotUploads=[]);let c=to(l,o,"image/png").then(u=>{u?t.screenshotUrls.set(i,u):console.warn(`[Engine] Screenshot upload returned null for ${i}`)}).catch(u=>{console.warn(`[Engine] Screenshot upload error for ${i}: ${u.message}`)});t.pendingScreenshotUploads.push(c)}let s=JSON.stringify(e);for(let i of t.ws)i.readyState===ki.OPEN&&i.send(s)}async function mZ(t){if(!t.r2Url)return t;let e=await import("node:os"),n=await import("node:fs"),r=await import("node:path"),s=r.join(e.tmpdir(),"agentiqa-attachments");n.existsSync(s)||n.mkdirSync(s,{recursive:!0});let i=r.join(s,`${Date.now()}-${t.originalName}`),a=await fetch(t.r2Url);if(!a.ok)throw new Error(`Failed to download attachment: ${a.status}`);let o=new Uint8Array(await a.arrayBuffer());return n.writeFileSync(i,o),{...t,localPath:i}}function gZ(t,e){return e.on("action:progress",n=>{lt(t,{type:"action:progress",...n})}),e.on("message:added",n=>{n?.message?.actionName==="ask_user"&&(t.awaitingUserSince=Date.now()),lt(t,{type:"message:added",...n})}),e.on("session:stopped",n=>{t.awaitingUserSince=void 0,lt(t,{type:"session:stopped",...n})}),e.on("session:blocked",n=>{t.awaitingUserSince=Date.now(),lt(t,{type:"session:blocked",...n})}),e.on("session:error",n=>{lt(t,{type:"session:error",...n})}),e.on("session:status-changed",n=>{lt(t,{type:"session:status-changed",...n})}),e.on("context:updated",n=>{lt(t,{type:"context:updated",...n})}),e.on("test_plan:saved",n=>{lt(t,{type:"test_plan:saved",...n})}),e.on("benchmark:milestone",n=>{lt(t,{type:"benchmark:milestone",...n})}),e.on("session:coverage-requested",n=>{lt(t,{type:"session:coverage-requested",...n})}),e.on("session:interrupt-requested",n=>{lt(t,{type:"session:interrupt-requested",...n})}),e.on("screencast:frame",n=>{HP(t,{type:"screencast:frame",...n})}),e.on("screencast:started",n=>{lt(t,{type:"screencast:started",...n})}),e.on("screencast:stopped",n=>{lt(t,{type:"screencast:stopped",...n})}),()=>e.removeAllListeners()}function By(t,e){return e.on("action:progress",n=>{lt(t,{type:"action:progress",...n})}),e.on("message:added",n=>{lt(t,{type:"message:added",...n})}),e.on("session:stopped",n=>{lt(t,{type:"session:stopped",...n})}),e.on("session:error",n=>{lt(t,{type:"session:error",...n})}),e.on("run:completed",async n=>{lt(t,{type:"run:completed",...n}),t.lastRunOutcome={type:"run:completed",run:n.run,runMemory:n.runMemory};try{t.pendingScreenshotUploads?.length&&await Promise.allSettled(t.pendingScreenshotUploads);let r=n.run;if(r?.id&&t.seed?.userId&&process.env.API_URL){let s=r.sessionId??t.chatSession.id,i=await tr.listMessages(s),{messages:a,usedFallback:o}=fl(i,r.id);o&&console.warn(`[Engine] run ${r.id}: strict runId filter empty on session ${s}, falling back to permissive (${a.length} of ${i.length})`);let l=new Set(["upload_file"]),c=a.filter(h=>h.role==="user"||h.role==="model"&&(h.actionName||h.text&&!/^(<ctrl\d+>\s*)+$/.test(h.text))||h.role==="system"&&(h.hasScreenshot||t.screenshotUrls?.has(h.id)||l.has(h.actionName??"")));console.log(`[Engine] Persisting messages for run ${r.id}: ${c.length} visible of ${a.length} run / ${i.length} total`);let u=(h,p)=>{if(!h)return;let g={};if(h.stepText&&(g.stepText=h.stepText),typeof h.planStepIndex=="number"&&(g.planStepIndex=h.planStepIndex),h.status&&(g.status=h.status),p==="report_issue")for(let m of["title","description","severity","confidence","issueId","issueConfirmed","issueDismissed"])h[m]!==void 0&&(g[m]=h[m]);return p==="propose_update"&&h.updates&&(g.updates=h.updates),p==="spawn_agent"&&h.childAgent&&(g.childAgent=h.childAgent),p==="child_completed"&&h.childAgent&&(g.childAgent=h.childAgent,h.status&&(g.status=h.status),h.summary&&(g.summary=h.summary)),p==="run_complete"&&Array.isArray(h.screenshots)&&(g.screenshots=h.screenshots.map(({base64:m,...S})=>S)),Object.keys(g).length>0?g:void 0},d=c.map(h=>({id:h.id,role:h.role,text:h.text,timestamp:h.timestamp,actionName:h.actionName,actionArgs:u(h.actionArgs,h.actionName),url:h.url,hasScreenshot:h.hasScreenshot||t.screenshotUrls?.has(h.id)||!1,screenshotUrl:t.screenshotUrls?.get(h.id)??void 0,runId:h.runId})),f=await fetch(`${process.env.API_URL}/api/sync/entities/test-plan-runs/${r.id}`,{method:"PUT",headers:Xa(t.seed?.userId??"",t.seed?.userToken),body:JSON.stringify({testPlanId:r.testPlanId,projectId:r.projectId,status:r.status,terminationReason:r.terminationReason,messages:d,updatedAt:Date.now()})});f.ok||console.error(`[Engine] Message persist API error for run ${r.id}: ${f.status} ${f.statusText}`)}}catch(r){console.error("[Engine] Error persisting run messages:",r.message)}finally{t.pendingScreenshotUploads=[]}}),e.on("session:status-changed",n=>{lt(t,{type:"session:status-changed",...n})}),e.on("run:started",n=>{lt(t,{type:"run:started",...n})}),e.on("benchmark:milestone",n=>{lt(t,{type:"benchmark:milestone",...n})}),e.on("session:coverage-requested",n=>{lt(t,{type:"session:coverage-requested",...n})}),e.on("session:interrupt-requested",n=>{lt(t,{type:"session:interrupt-requested",...n})}),e.on("screencast:frame",n=>{HP(t,{type:"screencast:frame",...n})}),e.on("screencast:started",n=>{lt(t,{type:"screencast:started",...n})}),e.on("screencast:stopped",n=>{lt(t,{type:"screencast:stopped",...n})}),()=>e.removeAllListeners()}function HP(t,e){t.lastActivityAt=Date.now();let n=JSON.stringify(e);for(let r of t.ws)r.readyState===ki.OPEN&&r.send(n)}function WP(t,e){let n={google:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,anthropic:process.env.ANTHROPIC_API_KEY,openai:process.env.OPENAI_API_KEY,openaiBaseURL:process.env.OPENAI_BASE_URL},r=process.env.NODE_ENV!=="production"&&process.env.LLM_CACHE!=="0",s=lZ.join(oZ.tmpdir(),"agentiqa-llm-cache"),i=qP(),a=process.env.ENGINE_API_TOKEN;i.use((p,g,m)=>{if(g.header("Access-Control-Allow-Origin","*"),g.header("Access-Control-Allow-Methods","GET, POST, DELETE, OPTIONS"),g.header("Access-Control-Allow-Headers","Content-Type, Authorization, X-Session-Token"),p.method==="OPTIONS"){g.sendStatus(204);return}m()}),i.use(qP.json({limit:"1mb"})),i.use(OP),i.use((p,g,m)=>{if(p.path==="/health"){m();return}if(!a){m();return}if(p.headers.authorization===`Bearer ${a}`){m();return}g.status(401).json({error:"Unauthorized"})});let o=cZ.createServer(i),l=new uZ({server:o,path:"/ws",perMessageDeflate:!1}),c=new Map;t.setDiagnosticSinkResolver(p=>c.get(p)?.sink);let u=600*1e3,d=(()=>{let p=Number(process.env.ENGINE_PAUSE_HOLD_MS);return Number.isFinite(p)&&p>0?p:1200*1e3})(),f=setInterval(()=>{let p=Date.now();fZ(c,p);for(let[g,m]of c){let S=!m.agent?.isRunning&&!m.runner?.isRunning,E=m.ws.size===0,v=p-m.lastActivityAt>u,x=m.awaitingUserSince!==void 0&&p-m.awaitingUserSince<d;if(S&&E&&v&&!x){let b=p-m.lastActivityAt,_=m.lastRunOutcome!==void 0;console.log(JSON.stringify({event:"session_idle_reap",sessionId:g,idleMs:b,hadAgentActivity:_})),console.log(`[Engine] Reaping idle session ${g} (age: ${Math.round((p-m.startedAt)/1e3)}s)`),m.agent?.stop(),m.runner?.stop(),m._cleanupListeners?.(),m.sink?.destroy?.(),lt(m,{type:"session:error",error:"Session expired due to inactivity"});for(let w of m.ws)w.readyState===ki.OPEN&&w.close(1e3,"Session expired");t.clearCredentials(g),t.cleanupSession(g).catch(()=>{}),t.cleanupSession(`${g}:child-browser`).catch(()=>{}),tr.deleteSession(g),c.delete(g)}}},6e4);o.on("close",()=>clearInterval(f)),t.onBrowserDisconnected=()=>{if(!t.isBrowserShutdownExpected()){console.error("[Engine] Browser crashed \u2014 stopping all active sessions");for(let[p,g]of c){g.agent?.stop(),g.runner?.stop(),g._cleanupListeners?.(),g.sink?.destroy?.(),lt(g,{type:"session:error",error:"Browser process crashed"});for(let m of g.ws)m.close();t.clearCredentials(p),tr.deleteSession(p),c.delete(p)}}},i.post("/api/engine/session",PP,Gs(LP),async(p,g)=>{if(c.size>=MP){g.status(503).json({error:"Server at capacity, try again later"});return}let{sessionId:m,sessionKind:S,sessionTitle:E,projectId:v,userId:x,userToken:b,model:_,screenWidth:w,screenHeight:A,initialUrl:k,routingContext:T,snapshotOnly:R,memoryItems:O,testPlans:P,issues:L,credentials:V,engineSessionKind:X,mobileConfig:z,goal:U,verbose:j,knownIssueTitles:K,autoApprove:q,parallelChildren:Z,resultFirstDiscovery:ne,memoryWriteback:G,platform:D,appVersion:Y,persistBrowserProfile:B,seedCookies:H,seedLocalStorage:$,availableCapabilities:N,messages:M,browserNavigationScope:F,retryOfSessionId:te}=p.body,se=m||ve("session"),pe;if(typeof k=="string"&&k.length>0&&k!=="about:blank")try{let he=/^https?:\/\//i.test(k)?k:`https://${k}`;pe=new URL(he).origin}catch{pe=void 0}let ke=c.get(se);if(ke){if(X&&ke.engineSessionKind&&X!==ke.engineSessionKind){g.status(409).json({error:`Session ${se} exists with kind '${ke.engineSessionKind}', cannot reuse as '${X}'`});return}console.log(`[Engine] Session ${se} already exists (running: ${ke.agent?.isRunning??ke.runner?.isRunning??!1}), returning existing`),g.json({sessionId:se,config:ke.chatSession.config,existing:!0});return}let ae=v??ve("project"),ee=await _P(process.env.API_URL,x??"local-cli",b),le=ee.available&&ee.email?uh(ee.email,se,{canCheckInbox:!0}):null,fe=Array.isArray(V)&&V.length>0,oe=iP({requestedCapabilities:N,canCheckInbox:le?.canCheckInbox,hasCredentials:fe}),Ie={screenWidth:w??1280,screenHeight:A??720,model:_??Vy(),initialUrl:k,...pe?{appUnderTestOrigin:pe}:{},...Array.isArray(F)&&F.length>0?{browserNavigationScope:F.map(String)}:{},snapshotOnly:R??!1,...oe.length>0?{availableCapabilities:{capabilities:oe}}:{},...le?{testingEmailPolicy:le}:{},...z?{platform:"mobile",mobileConfig:z}:{},...q!=null&&{autoApprove:q},...Z!=null&&{parallelChildren:Z},...ne!=null&&{resultFirstDiscovery:ne},...G!=null&&{memoryWriteback:G},...B!=null&&{persistBrowserProfile:B},...Array.isArray(H)&&H.length>0?{seedCookies:H}:{},...Array.isArray($)&&$.length>0?{seedLocalStorage:$}:{}};if(k&&Js(k).matched){let Ce=Ie.maxIterationsPerTurn;Ie.maxIterationsPerTurn=Math.min(Ce??300,5),(Ce===void 0||Ce>5)&&console.log(`[Engine] generic-site clamp session=${se} host=${Js(k).host} iterations=${Ie.maxIterationsPerTurn} (was ${Ce??300})`)}let ye={id:se,projectId:ae,title:E||"Cloud Session",createdAt:Date.now(),updatedAt:Date.now(),isArchived:!1,status:"idle",kind:S||"assistant_v2",config:Ie,routingContext:T},Ee={projectId:ae,sessionId:se,userId:x??void 0,userToken:b??void 0,memoryItems:O??[],testPlans:P??[],issues:L??[],credentials:V??[],platform:D??void 0,appVersion:Y??void 0,retryOfSessionId:typeof te=="string"&&te?te:void 0,engineSessionKind:X??void 0};console.log(`[Engine] Session ${se}: ${Ee.memoryItems?.length??0} memoryItems, ${Ee.issues?.length??0} issues, ${Ee.credentials?.length??0} credentials`),Ee.credentials?.length&&t.seedCredentials(se,Ee.credentials);let Pe={id:se,type:"agent",engineSessionKind:X??void 0,chatSession:ye,seed:Ee,ws:new Set,events:[],startedAt:Date.now(),lastActivityAt:Date.now()};if(c.set(se,Pe),await tr.upsertSession(ye),Array.isArray(M)&&M.length>0)for(let he of M)await tr.addMessage({...he,sessionId:se});AP(ye,Ee),g.json({sessionId:se,config:Ie})}),i.get("/api/engine/session/:id",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}g.json({id:m.id,type:m.type,status:m.chatSession.status,running:m.agent?.isRunning??m.runner?.isRunning??!1,eventCount:m.events.length,startedAt:m.startedAt,userId:m.seed?.userId??null})}),i.patch("/api/engine/session/:id/config",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{autoApprove:S}=p.body??{};S!=null&&(m.chatSession.config.autoApprove=S),g.json({ok:!0,config:m.chatSession.config})}),i.post("/api/engine/session/:id/bootstrap",async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(ac(m,"agent",g)){if(!m.agent){if(m._agentInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._agentInitializing=!0;try{m.agent=GP(m,t,e,n,r,s),await tr.upsertSession(m.chatSession)}finally{m._agentInitializing=!1}}try{m.agent.startWelcomeBootstrap(m.chatSession).catch(S=>{console.error(`[Engine] bootstrap error for session ${m.id}:`,S.message),lt(m,{type:"session:error",error:S.message})}),g.json({ok:!0})}catch(S){g.status(500).json({error:S.message})}}}),i.post("/api/engine/session/:id/message",Gs(FP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"agent",g))return;m.awaitingUserSince=void 0;let{text:S,attachments:E,entryId:v}=p.body;if(!m.agent){if(m._agentInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._agentInitializing=!0;try{m.agent=GP(m,t,e,n,r,s),await tr.upsertSession(m.chatSession)}finally{m._agentInitializing=!1}}try{let x=Array.isArray(E)&&E.length?await Promise.all(E.map(mZ)):void 0;m.agent.sendMessage(m.chatSession,S,x,typeof v=="string"&&v?v:void 0).catch(b=>{console.error(`[Engine] sendMessage error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/run",Gs(UP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{testPlan:S,initialMemory:E}=p.body,v=new Set(["setup","action","verify"]);for(let x of S.steps??[])if(!x.type||!v.has(x.type)){let b=(x.type??"").toLowerCase();x.type=b.includes("verify")?"verify":b.includes("setup")?"setup":"action"}if(!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let x=oc(m,n,r,s),b=new Vs(t),_=sc(x,t,m.seed,e,b);m.runner=new Xn(m.id,_),m.sink=_.sink,ic(_.sink,m.id,m.chatSession.projectId,{memoryRepo:_.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run",testPlanId:S.id},await _.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}try{m.lastRunOutcome=void 0;let x=m.runner.startRun(m.chatSession,S,{initialMemory:E,onMemoryUpdate:b=>{lt(m,{type:"memory:updated",memory:b})}});x&&typeof x.catch=="function"&&x.catch(b=>{console.error(`[Engine] startRun error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/batch-run",Gs($P),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{plans:S,mode:E,concurrency:v,initialMemory:x,batchRunId:b,planSessions:_}=p.body,w=new Set(["setup","action","verify"]);for(let T of S)for(let R of T.steps??[])if(!R.type||!w.has(R.type)){let O=(R.type??"").toLowerCase();R.type=O.includes("verify")?"verify":O.includes("setup")?"setup":"action"}if(E==="sequential"&&!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let T=oc(m,n,r,s),R=new Vs(t),O=sc(T,t,m.seed,e,R);m.runner=new Xn(m.id,O),m.sink=O.sink,ic(O.sink,m.id,m.chatSession.projectId,{memoryRepo:O.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run"},await O.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}let A=T=>{lt(m,T)},k;E==="sequential"&&(k=S.map((T,R)=>{let O=_?.[R];return{...m.chatSession,id:O?.id??`${m.chatSession.id}__plan${R}`,kind:"test_run",testPlanId:O?.testPlanId??T.id,createdAt:Date.now(),updatedAt:Date.now()}}),await Promise.all(k.map(T=>tr.upsertSession(T))));try{let T=E==="sequential"?{runner:m.runner}:(()=>{let O=oc(m,n,r,s),P=new Vs(t);return{deps:sc(O,t,m.seed,e,P),sessionId:m.id}})();vg(T,m.chatSession,S,{mode:E,concurrency:v,initialMemory:x,batchRunId:b,planSessions:k},A).then(async O=>{b&&m.seed?.userId&&process.env.API_URL&&await fetch(`${process.env.API_URL}/api/sync/entities/batch-runs/${b}`,{method:"PUT",headers:Xa(m.seed?.userId??"",m.seed?.userToken),body:JSON.stringify({status:O.status,updatedAt:Date.now(),endedAt:Date.now()})}).catch(()=>{})}).catch(async O=>{lt(m,{type:"session:error",error:O.message}),b&&m.seed?.userId&&process.env.API_URL&&await fetch(`${process.env.API_URL}/api/sync/entities/batch-runs/${b}`,{method:"PUT",headers:Xa(m.seed?.userId??"",m.seed?.userToken),body:JSON.stringify({status:"partial",updatedAt:Date.now(),endedAt:Date.now()})}).catch(()=>{})}),g.json({ok:!0})}catch(T){g.status(500).json({error:T.message})}}),i.post("/api/engine/session/:id/runner-message",Gs(jP),async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}if(!ac(m,"runner",g))return;let{text:S,testPlan:E,attachments:v}=p.body;if(!m.runner){if(m._runnerInitializing){g.status(409).json({error:"Session is initializing, retry shortly"});return}m._runnerInitializing=!0;try{let x=oc(m,n,r,s),b=new Vs(t),_=sc(x,t,m.seed,e,b);m.runner=new Xn(m.id,_),m.sink=_.sink,ic(_.sink,m.id,m.chatSession.projectId,{memoryRepo:_.memoryRepo}),m.type="runner",m._cleanupListeners=By(m,m.runner),m.chatSession={...m.chatSession,kind:"test_run",testPlanId:E.id},await _.chatRepo.upsertSession(m.chatSession)}finally{m._runnerInitializing=!1}}try{let x=m.runner.sendMessage(m.chatSession,E,S,v);x&&typeof x.catch=="function"&&x.catch(b=>{console.error(`[Engine] runner sendMessage error for session ${m.id}:`,b.message),lt(m,{type:"session:error",error:b.message})}),g.json({ok:!0})}catch(x){g.status(500).json({error:x.message})}}),i.post("/api/engine/session/:id/evaluate",Gs(BP),async(p,g)=>{if(!c.get(p.params.id)){g.status(404).json({error:"Session not found"});return}let{expression:S}=p.body;try{let E=await t.evaluate(p.params.id,S);g.json({result:E})}catch(E){g.status(500).json({error:E.message})}}),i.post("/api/engine/session/:id/stop",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}m.agent?.stop("user_stopped"),m.runner?.stop("user_stopped"),g.json({ok:!0})}),i.post("/api/engine/session/:id/reset",async(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"session_not_found"});return}if(m.type!=="runner"||!m.runner){g.status(400).json({error:"not_a_runner_session"});return}let S=p.body?.keepMemory??!0;try{await m.runner.resetForNextPlan({keepMemory:S}),m.events.length=0,g.status(200).json({ok:!0})}catch(E){if(E?.message?.includes("cannot reset while a run is in progress")){g.status(409).json({error:"run_in_progress"});return}g.status(500).json({error:"reset_failed",message:E?.message})}}),i.post("/api/engine/session/:id/credentials",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{credentials:S}=p.body;if(!Array.isArray(S)||S.length===0){g.status(400).json({error:"credentials array required"});return}m.secretsService?.addCredentials(S);let v=[...m.seed?.credentials??[],...S];t.seedCredentials(p.params.id,v),m.seed&&(m.seed.credentials=v),m.sink?.emit({kind:"log",ts:Date.now(),sessionId:p.params.id,level:"info",source:"Engine",msg:"modeA.engine.credentials_added",data:{count:S.length,names:S.map(x=>x.name),totalAfter:v.length}}),g.json({ok:!0,count:S.length})}),i.post("/api/engine/session/:id/user-provided-test-email",(p,g)=>{let m=c.get(p.params.id);if(!m){g.status(404).json({error:"Session not found"});return}let{email:S}=p.body,E=typeof S=="string"?S.trim().toLowerCase():null;if(!(E&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E))||!E){g.status(400).json({error:"valid email required"});return}m.chatSession.config.userProvidedTestEmail=E,m.chatSession.config.testingEmailPolicy=void 0,m.sink?.emit({kind:"log",ts:Date.now(),sessionId:p.params.id,level:"info",source:"Engine",msg:"modeA.activated",data:{email:E,trigger:"user_filled_needs"}}),g.json({ok:!0})}),i.delete("/api/engine/session/:id",async(p,g)=>{let m=c.get(p.params.id);if(m){m.agent?.stop(),m.runner?.stop(),m._cleanupListeners?.(),m.sink?.destroy?.();for(let S of m.ws)S.close();t.clearCredentials(p.params.id),await t.cleanupSession(p.params.id),await t.cleanupSession(`${p.params.id}:child-browser`).catch(()=>{}),tr.deleteSession(p.params.id),c.delete(p.params.id)}g.json({ok:!0})}),i.post("/api/engine/chat-title",Gs(VP),async(p,g)=>{let{text:m}=p.body;try{let S=`Generate a concise 3-5 word title summarizing WHAT is being tested or asked. Never include process words like "testing", "test", "verification", "check", "session", "QA", "validate". Focus only on the subject matter.
|
|
1887
1887
|
|
|
1888
1888
|
User message: "${String(m).slice(0,500)}"
|
|
1889
1889
|
|
|
@@ -1994,14 +1994,14 @@ Reply with ONLY the title, no quotes, no punctuation at the end.`,E=Ka(Vy(),n);r
|
|
|
1994
1994
|
z-index: 999999;
|
|
1995
1995
|
transform: translate(-50%, -50%);
|
|
1996
1996
|
transition: left 0.1s, top 0.1s;
|
|
1997
|
-
`,document.body.appendChild(a)),a.style.left=`${s}px`,a.style.top=`${i}px`},{x:n,y:r})}catch{}}getSuggestedSampleFiles(e,n){return[]}async ensureBrowser(){if(!this.browser){console.log("[BasePlaywright] Launching browser");let e=performance.now();this.browser=await this.launchBrowser();let n=Math.round(performance.now()-e);console.log(`[BasePlaywright] Browser launched in ${n}ms`),this.browser.on("disconnected",()=>{console.log("[BasePlaywright] Browser disconnected"),this.browser=null,this.sessions.clear(),this.onBrowserDisconnected?.()})}return this.browser}async ensureSession(e,n){if(this.sessions.has(e))return this.sessions.get(e);e.includes(":child-")||await this.cleanupOtherSessions(e);let r=await this.createSession(e,n);return this.sessions.set(e,r),r}async invoke(e){let n=await this.ensureSession(e.sessionId,e.config);n.lastInvokeAt=Date.now(),n.browserNavigationScope=Array.isArray(e.config?.browserNavigationScope)?e.config.browserNavigationScope.map(String):void 0,n.allowExternalNavigation=!!e.config?.allowExternalNavigation,n.testingEmailPolicy=jt(e.config)??void 0,n.isTestPlanReplay=!!e.config?.isTestPlanReplay;let r=e.config?.loginCredentialEmails;n.loginCredentialEmails=Array.isArray(r)?r.map(String):void 0;let s=cM(e.config);s&&(n.appUnderTestOrigin=s);let i=e.args??{};n.currentStepText=typeof i.stepText=="string"?i.stepText:void 0;let a=performance.now(),o,l,c=this.safeCurrentUrl(n);try{let d=await this.dispatch(n,e.action,i);d=this.withSessionMetadata(n,d);let f=Math.round(performance.now()-a);if(console.log(`[BasePlaywright] ${e.action} completed in ${f}ms`),n.tab2||n.isExtensionSession){let h=n.tab1&&!n.tab1.isClosed(),p=n.tab2&&!n.tab2.isClosed(),g=[];h&&g.push(n.tab1.url()),p&&g.push(n.tab2.url()),d={...d,metadata:{activeTab:n.activeTab,tabCount:(h?1:0)+(p?1:0),tabUrls:g,...n.pendingExtensionPopup?{pendingExtensionPopup:!0}:{},...d.metadata}},n.pendingExtensionPopup=!1}o={screenshot:d.screenshot.toString("base64"),url:d.url,aiSnapshot:d.aiSnapshot,domChanges:d.domChanges,metadata:d.metadata,canvasDominant:d.canvasDominant,snapshotKind:d.snapshotKind,captureMode:d.captureMode},l=n.page}catch(d){let f=String(d?.message||"");if(d instanceof ir)throw d;if(d instanceof cc){let h=this.withSessionMetadata(n,await this.captureState(n));o={screenshot:h.screenshot.toString("base64"),url:h.url,aiSnapshot:h.aiSnapshot,metadata:{...h.metadata,error:`${d.message}. Re-emit ${d.action} with valid normalized integer coordinates (x and y each between 0 and 1000), or target the element by its "label" or "ref" instead.`},canvasDominant:h.canvasDominant,snapshotKind:h.snapshotKind},l=n.page}else if(f.includes("Execution context was destroyed")||f.includes("most likely because of a navigation")||f.includes("navigation")){console.log(`[BasePlaywright] Navigation detected during ${e.action}, recovering`),n.needsFullSnapshot=!0;try{await n.page.waitForLoadState("load",{timeout:5e3})}catch{}let h=await this.captureState(n),p=this.withSessionMetadata(n,h);o={screenshot:p.screenshot.toString("base64"),url:p.url,aiSnapshot:p.aiSnapshot,metadata:p.metadata,canvasDominant:p.canvasDominant,snapshotKind:p.snapshotKind},l=n.page}else if(f.includes("Browser session closed")||f.includes("Target closed")||f.includes("has been closed")||f.includes("Page crashed")){console.log(`[BasePlaywright] Session closed for ${e.sessionId}, recreating`),this.sessions.delete(e.sessionId);try{let h=await this.ensureSession(e.sessionId,e.config),p=this.withSessionMetadata(h,await this.dispatch(h,e.action,i));o={screenshot:p.screenshot.toString("base64"),url:p.url,aiSnapshot:p.aiSnapshot,metadata:p.metadata,canvasDominant:p.canvasDominant,snapshotKind:p.snapshotKind},l=h.page}catch(h){console.error("[BasePlaywright] Retry after session recreation failed:",h);let p=h instanceof Error?h.message:String(h);throw new Error(`Browser session recovery failed: ${p}`)}}else throw d}let u=await this.containPendingPopupEscapes(n);if(u)o=u;else if(e.action!=="navigate"&&l){this.maybeAnchorAppUnderTestOrigin(n,o.url);let d=await this.containCrossEnvironmentAfterAction(n,l,o);d?o=d:(await this.assertNoCloudflareBlockAfterCrossOriginNav(l,c,o.url),await this.assertNoCaptchaGate(n,l,e.action,i,c,o.url),await this.assertNoCredentialRejection(n,l,e.action,i,o.url),await this.assertNoThirdPartyIdpLogin(n,e.action,i,o.url))}return o.metadata={...o.metadata??{},events:this.buildAndResetDigest(l)},o}buildAndResetDigest(e){let n=e?lc.get(e):void 0;if(!n)return{consoleErrors:[],pageErrors:[],failedRequests:[],pendingRequests:[],recentWrites:[]};let r=Date.now(),s={consoleErrors:n.rollingConsoleErrors.slice(),pageErrors:n.rollingPageErrors.slice(),failedRequests:n.rollingFailedRequests.slice(),pendingRequests:Array.from(n.pendingWrites).map(i=>({url:i.url,method:i.method,ageMs:r-i.startTs})),recentWrites:n.rollingRecentWrites.slice()};return n.rollingConsoleErrors=[],n.rollingPageErrors=[],n.rollingFailedRequests=[],n.rollingRecentWrites=[],s}async readFocusedFieldValue(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)return n.value;if(n instanceof HTMLElement&&n.isContentEditable)return n.textContent??""})}catch{return}}async getFocusedElementFingerprint(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(!n||n===document.body)return;let r=d=>(d??"").replace(/\s+/g," ").trim(),s=n.tagName.toLowerCase(),i=n instanceof HTMLInputElement?n.type:"",a=n.id||"",o=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n.name:"",l=r(n.getAttribute("aria-label")),c=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?r(n.placeholder):"",u="";return(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&(u=r(n.labels?.[0]?.textContent)),!u&&a&&(u=r(document.querySelector(`label[for="${CSS.escape(a)}"]`)?.textContent)),[s,i,a,o,l,c,u].join("|")})}catch{return}}async getFocusedFieldName(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(!n||n===document.body)return;let r=u=>{let d=[];for(let f of Array.from(u.childNodes))if(f.nodeType===Node.TEXT_NODE){let h=f.textContent?.trim();h&&d.push(h)}else if(f instanceof HTMLElement&&!s(f)){let h=f.innerText?.trim();h&&d.push(h)}return d.join(" ").replace(/\s+/g," ").trim()},s=u=>u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement||u.isContentEditable,i=n.getAttribute("aria-label");if(i)return i;let a=n.getAttribute("aria-labelledby");if(a){let u=a.split(/\s+/).map(d=>document.getElementById(d)?.textContent?.trim()).filter(Boolean).join(" ");if(u)return u}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){let u=n.labels?.[0]?.textContent?.trim();if(u)return u}let o=n.id;if(o){let u=document.querySelector(`label[for="${o}"]`);if(u)return u.textContent?.trim()}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){if(n.placeholder)return n.placeholder;if(n.name)return n.name}let l=n.previousElementSibling;for(;l;){let u=l instanceof HTMLElement?l.innerText?.trim():void 0;if(u)return u;l=l.previousElementSibling}let c=n.parentElement;for(let u=0;c&&u<3;u+=1,c=c.parentElement){let d=r(c);if(d)return d}})}catch{return}}async awaitPageReady(e){return e.waitForLoadState("domcontentloaded",{timeout:5e3}).then(()=>!0).catch(()=>!1)}dialogsAcceptedOn(e){return pM(e)}async probeClickEffect(e,n,r,s){if(Ic()==="off")return null;if(e.lastCaptureCanvasDominant)return this.diagLog?.(e.sessionId,"click_effect:probe_skipped",{reason:"canvas-memo",url:this.safeCurrentUrl(e)??""}),null;let i=null;try{let a=await qn.waitForMutation(n,{timeoutMs:Tc});a&&(i={count:a.count,attrCount:a.attrCount})}catch{i=null}return{mutationCount:i?.count??null,attrCount:i?.attrCount??null,urlBefore:r??"",urlAfter:this.safeCurrentUrl(e)??"",dialogsBefore:s,dialogsAfter:pM(n)}}resolveClickEffect(e,n,r){if(!n)return{};let s=Xv(n,r),i=Ic()==="enforce";return s.effectObserved===!1&&this.diagLog?.(e.sessionId,i?"click_effect:signaled":"click_effect:would_signal",{url:n.urlAfter,clickPath:r.clickPath,settleMs:Tc,mutationCount:n.mutationCount,attrCount:n.attrCount,targetTag:r.target?.tag??null,targetRole:r.target?.role??null,canvasDominant:r.canvasDominant===!0,suppressedBy:s.suppressedBy??null,advisoryEmitted:i&&!!s.note}),i?s:{}}async screenshotWithSlowSiteRetry(e,n={}){let{page:r}=e,s=(e.screenshotCount??0)===0,i=15e3,a=25e3,l={type:"png",timeout:s?i:5e3};n.fullPage&&(l.fullPage=!0);try{let c=await r.screenshot(l);return e.screenshotCount=(e.screenshotCount??0)+1,c}catch(c){if(!s||!pi(c))throw c;let u=r.url();this.diagLog?.(e.sessionId,"screenshot_first_timeout_retry",{url:u,firstTimeoutMs:i,retryTimeoutMs:a}),this.reportStartupNavigate(e,"slow_site_retry",{url:u,firstTimeoutMs:i,retryTimeoutMs:a});let d={type:"png",timeout:a};n.fullPage&&(d.fullPage=!0);try{let f=await r.screenshot(d);return e.screenshotCount=(e.screenshotCount??0)+1,this.diagLog?.(e.sessionId,"screenshot_first_retry_success",{url:u}),f}catch(f){throw pi(f)?(this.reportStartupNavigate(e,"slow_site_error",{url:u,totalTimeoutMs:i+a,attemptCount:2}),new Cr({url:u,totalTimeoutMs:i+a,attemptCount:2})):f}}}async captureState(e,n={}){let{page:r}=e;e.expectDomQuiescence&&!process.env.AQ_NO_DOM_OBSERVER&&!process.env.AQ_NO_DOM_DELAY&&await qn.waitForQuiescence(r,{minQuietMs:100,maxMs:800});let s,i=!1;try{s=await this.screenshotWithSlowSiteRetry(e)}catch(d){if(n.onScreenshotTimeout!=="degrade"||!pi(d))throw d;let f=await this.captureOracleScreenshotResilient(e);f?s=f:(s=PZ,i=!0)}let a=r.url(),o,l;try{let d=await r._snapshotForAI({track:e.sessionId+":"+e.activeTab}),f=typeof d=="string"?d:d?.full,h=typeof d=="object"?d?.incremental:void 0;!e.needsFullSnapshot&&h?(o=h,l="incremental"):(o=f,e.needsFullSnapshot=!1,l=f!=null?"full":void 0)}catch{o=void 0,e.needsFullSnapshot=!0}let c=process.env.AQ_NO_DOM_OBSERVER?void 0:await qn.flush(r)??void 0,u=await this.computeCanvasDominant(e);return e.lastCaptureCanvasDominant=u,{screenshot:s,url:a,aiSnapshot:o,domChanges:c,canvasDominant:u,snapshotKind:l,...i&&{metadata:{note:OZ}}}}async captureOracleScreenshotResilient(e){let{page:n}=e;for(let r=1;r<=oM;r++)try{let s=await n.screenshot({type:"png",timeout:Jy});return e.screenshotCount=(e.screenshotCount??0)+1,this.diagLog?.(e.sessionId,"wait_oracle_screenshot_retry_success",{attempt:r,timeoutMs:Jy}),s}catch(s){if(!pi(s))throw s;this.diagLog?.(e.sessionId,"wait_oracle_screenshot_timeout",{attempt:r,attempts:oM,timeoutMs:Jy})}return null}async computeCanvasDominant(e){try{return await e.page.evaluate(()=>{let n=window.innerWidth,r=window.innerHeight,s=n*r;if(s<=0)return!1;let i=0;for(let a of Array.from(document.querySelectorAll("canvas"))){let o=window.getComputedStyle(a);if(o.display==="none"||o.visibility==="hidden"||o.opacity==="0"||o.pointerEvents==="none"||a.closest('[aria-hidden="true"]'))continue;let l=a.getBoundingClientRect(),c=Math.max(0,l.left),u=Math.max(0,l.top),d=Math.min(n,l.right),f=Math.min(r,l.bottom),h=d-c,p=f-u;h>0&&p>0&&(i+=h*p)}return Math.min(i/s,1)>=.4})}catch{return!1}}withSessionMetadata(e,n){return e.httpsCertFallback?{...n,metadata:{...n.metadata??{},httpsCertFallback:e.httpsCertFallback}}:n}shouldResetDomObserverBeforeAction(e){return!new Set(["open_web_browser","screenshot","snapshot","wait","wait_5_seconds","wait_for_element","full_page_screenshot","run_js"]).has(e)}shouldWaitForDomQuiescenceAfterAction(e){return this.shouldResetDomObserverBeforeAction(e)}async dispatch(e,n,r){let s=await this.dispatchPlatformAction(e,n,r);if(s)return s;let i=r?.fullSnapshot===!0,a=e.needsFullSnapshot;i&&(e.needsFullSnapshot=!0);let{viewportWidth:o,viewportHeight:l}=e,c=h=>Math.floor(h/1e3*o),u=h=>Math.floor(h/1e3*l),d=!process.env.AQ_NO_DOM_OBSERVER&&this.shouldResetDomObserverBeforeAction(n),f=e.expectDomQuiescence;d&&await qn.reset(e.page),e.expectDomQuiescence=this.shouldWaitForDomQuiescenceAfterAction(n);try{switch(n){case"open_web_browser":case"screenshot":return await this.captureState(e);case"snapshot":return e.needsFullSnapshot=!0,await this.captureState(e);case"click_at":{let h=Array.isArray(r.modifiers)?r.modifiers.map(String):[];if(r.label)return await this.clickByLabel(e,String(r.label),h);if(r.ref)return await this.clickByRef(e,String(r.ref),h);let p=this.requireNormalizedPoint(n,r);return await this.clickAt(e,c(p.x),u(p.y),h)}case"double_click_at":{let h=Array.isArray(r.modifiers)?r.modifiers.map(String):[];if(r.label)return await this.clickByLabel(e,String(r.label),h,2);if(r.ref)return await this.clickByRef(e,String(r.ref),h,2);let p=this.requireNormalizedPoint(n,r);return await this.clickAt(e,c(p.x),u(p.y),h,2)}case"right_click_at":{if(r.ref)return await this.rightClickByRef(e,String(r.ref));let h=this.requireNormalizedPoint(n,r);return await this.rightClickAt(e,c(h.x),u(h.y))}case"hover_at":{if(r.ref)return await this.hoverByRef(e,String(r.ref));let h=this.requireNormalizedPoint(n,r);return await this.hoverAt(e,c(h.x),u(h.y))}case"type_text_at":{let h=r.clearBeforeTyping??r.clear_before_typing??!0;if(r.label)return await this.typeByLabel(e,String(r.label),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h);if(r.ref)return await this.typeByRef(e,String(r.ref),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h);let p=this.requireNormalizedPoint(n,r);return await this.typeTextAt(e,c(p.x),u(p.y),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h)}case"scroll_document":return await this.scrollDocument(e,String(r.direction));case"scroll_to_bottom":return await this.scrollToBottom(e);case"scroll_at":{let h=String(r.direction),p=r.magnitude!=null?Number(r.magnitude):800;if(h==="up"||h==="down"?p=u(p):(h==="left"||h==="right")&&(p=c(p)),r.ref){let m=await this.resolveRefCenter(e,String(r.ref));return m?await this.scrollAt(e,m.x,m.y,h,p):await this.refNotFoundError(e,String(r.ref))}let g=this.requireNormalizedPoint(n,r);return await this.scrollAt(e,c(g.x),u(g.y),h,p)}case"wait":return await this.waitSeconds(e,Number(r.seconds||2));case"wait_for_element":return await this.waitForElement(e,String(r.textContent??""),Number(r.timeoutSeconds||5));case"wait_5_seconds":return await this.waitSeconds(e,5);case"full_page_screenshot":return await this.fullPageScreenshot(e);case"switch_layout":{let h=Number(r.width),p=Number(r.height);return e.viewportWidth=h,e.viewportHeight=p,await this.switchLayout(e,h,p)}case"go_back":return await this.goBack(e);case"go_forward":return await this.goForward(e);case"navigate":{let h=String(r.url??r.href??"");if(e.isExtensionSession){if(h.startsWith("chrome-extension://")){if(e.tab1&&!e.tab1.isClosed())await e.tab1.goto(h),await this.awaitPageReady(e.tab1);else{let p=await e.context.newPage();Tp(p),await p.goto(h),await this.awaitPageReady(p)}return e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0,await e.page.bringToFront()),await this.captureState(e)}e.tab2&&!e.tab2.isClosed()&&(e.page=e.tab2,e.activeTab="tab2")}else e.activeTab==="tab2"&&e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0);return await this.navigate(e,h)}case"key_combination":return await this.keyCombination(e,Array.isArray(r.keys)?r.keys.map(String):[]);case"set_focused_input_value":return await this.setFocusedInputValue(e,String(r.value??""),typeof r.expectedElementFingerprint=="string"?r.expectedElementFingerprint:void 0);case"drag_and_drop":{let h,p;if(r.ref){let S=await this.resolveRefCenter(e,String(r.ref));if(!S)return await this.refNotFoundError(e,String(r.ref));h=S.x,p=S.y}else{let S=this.requireNormalizedPoint(n,r);h=c(S.x),p=u(S.y)}let g,m;if(r.destinationRef){let S=await this.resolveRefCenter(e,String(r.destinationRef));if(!S)return await this.refNotFoundError(e,String(r.destinationRef));g=S.x,m=S.y}else{let S=this.requireNormalizedPoint(n,r,r.destinationX!==void 0?"destinationX":"destination_x",r.destinationY!==void 0?"destinationY":"destination_y");g=c(S.x),m=u(S.y)}return await this.dragAndDrop(e,h,p,g,m)}case"upload_file":{let h=Array.isArray(r.filePaths)?r.filePaths.map(String):[String(r.filePaths??"")];return await this.uploadFile(e,h,{clearStaleMarker:r.clearStaleMarker===!0})}case"http_request":return await this.httpRequest(e,String(r.url??""),String(r.method??"GET"),r.headers,r.body!=null?String(r.body):void 0);case"run_js":return await this.runJs(e,String(r.code??""));case"switch_tab":{let h=String(r.tab??"tab1"),p=h==="main"?"tab1":h==="extension"?"tab2":h;return await this.switchTab(e,p)}case"close_tab":return await this.closeTab(e);default:return console.warn(`[BasePlaywright] Unsupported action: ${n}`),await this.captureState(e)}}finally{e.expectDomQuiescence=f,i&&e.needsFullSnapshot&&(e.needsFullSnapshot=a)}}async clickAt(e,n,r,s=[],i=1){let{page:a}=e,o=this.safeCurrentUrl(e);try{await a.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}await this.onBeforeAction(e,n,r);let l={isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:null,clickTarget:null},c=uM();try{let T=await a.evaluateHandle(P=>document.elementFromPoint(P.x,P.y),{x:n,y:r}),R=T.asElement(),O=R?await R.evaluate(hM,{captureAffordance:c}).catch(()=>null):null;await T.dispose().catch(()=>{}),l=await a.evaluate(P=>{let L=document.elementFromPoint(P.x,P.y);if(!L)return{isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:null,clickTarget:null};let V={tag:L.tagName.toLowerCase(),text:(L.textContent||"").trim().slice(0,80),role:L.getAttribute("role")||""},X=L.closest("a[href], area[href]"),z=null,U=L.closest("select");if(U)z=U;else if(L instanceof HTMLLabelElement&&L.htmlFor){let j=document.getElementById(L.htmlFor);j instanceof HTMLSelectElement&&(z=j)}else{let j=L instanceof HTMLLabelElement?L:L.closest("label");if(j){let K=j.querySelector("select");K&&(z=K)}}if(z){z.focus();let j=z.options[z.selectedIndex]?.textContent?.trim()||"",K=Array.from(z.options).map(Z=>Z.textContent?.trim()||Z.value);return{isSelect:!0,isMultiple:z.multiple,selectedText:j,options:K,clickedElement:null,clickTarget:null}}return{isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:V,clickTarget:null,linkHref:X?.href||""}},{x:n,y:r}),l.clickTarget=O}catch(T){let R=String(T?.message||"");if(!(R.includes("Execution context was destroyed")||R.includes("navigation")))throw T}if(l.isSelect&&!l.isMultiple)return await this.awaitPageReady(a),{...await this.captureState(e),metadata:{elementType:"select",valueBefore:l.selectedText,valueAfter:l.selectedText,availableOptions:l.options,...l.clickTarget?{clickTarget:l.clickTarget}:{}}};if(l.linkHref){let T=await this.containCrossEnvironmentIfNeeded(e,l.linkHref);if(T)return T;let R=await this.blockScopedNavigationIfNeeded(e,l.linkHref);if(R)return R}let u=null,d=!1;if(QP()&&!l.linkHref){let T=await this.resolveInteractiveDescendantAtPoint(a,n,r,Gy);if(T.status==="retarget"){if(T.final.linkHref){let R=await this.containCrossEnvironmentIfNeeded(e,T.final.linkHref);if(R)return R;let O=await this.blockScopedNavigationIfNeeded(e,T.final.linkHref);if(O)return O}u=T}else T.status==="none"&&(d=!0)}let f=c&&u===null&&l.clickTarget&&!il(l.clickTarget)?l.clickTarget.affordance:void 0;f&&(f.directListener=await this.probeDirectClickListener(e,n,r));let h=a.waitForEvent("filechooser",{timeout:150}).catch(()=>null),p=a.waitForEvent("download",{timeout:500}).catch(()=>null);await qn.reset(a);let g=this.dialogsAcceptedOn(a);if(u){let T=a.locator(`[data-agentiqa-click-target="${u.marker}"]`).first(),R=s.map(P=>P).filter(Boolean),O={force:!0,timeout:3e3,modifiers:R.length?R:void 0};i>1?await T.dblclick(O):await T.click(O)}else{for(let T of s)await a.keyboard.down(T);await a.mouse.click(n,r,{clickCount:i});for(let T of s)await a.keyboard.up(T)}let m=await h;if(m){let R=await m.element().evaluate(L=>{let V=L;return document.querySelectorAll("[data-agentiqa-file-target]").forEach(X=>X.removeAttribute("data-agentiqa-file-target")),V.setAttribute("data-agentiqa-file-target","true"),V instanceof HTMLInputElement?{accept:V.accept||"*",multiple:V.multiple}:{accept:"*",multiple:!1}}),O=this.getSuggestedSampleFiles(R.accept,R.multiple);return console.log(`[BasePlaywright] FILE CHOOSER INTERCEPTED: accept="${R.accept}", multiple=${R.multiple}`),{...await this.captureState(e),metadata:{elementType:"file",accept:R.accept,multiple:R.multiple,suggestedFiles:O}}}let S=await p;if(S){let T=S.suggestedFilename(),R=S.url();console.log(`[BasePlaywright] DOWNLOAD INTERCEPTED: "${T}" from ${R}`),await S.cancel();try{await a.goBack({waitUntil:"domcontentloaded",timeout:5e3})}catch{}return{...await this.captureState(e),metadata:{elementType:"download",downloadFilename:T,downloadUrl:R,clickedElement:l.clickedElement??void 0,clickTarget:l.clickTarget??void 0}}}await this.awaitPageReady(a);let E=null;if(d){let T=await qn.peek(a);E={count:T.count,attrCount:T.attrCount}}let v=await this.probeClickEffect(e,a,o,g),x=await this.captureState(e),b;if(u){let T=l.clickTarget?{...l.clickTarget}:{tag:u.original.tag,text:u.original.text,role:"",accessibleName:"",disabled:!1,nativeDisabled:!1,ariaDisabled:!1,inert:!1};delete T.affordance,b={...T,retargeted:!0,retargetedFrom:u.original,retargetedTo:u.final}}else b=l.clickTarget??void 0;let _=E!=null&&E.count===0&&E.attrCount===0&&x.url===o,w;_&&!x.canvasDominant&&(w='This click did not produce a visible change within the brief capture window: the DOM, text, and URL are all unchanged. It may have landed on empty space or a non-interactive area, or an effect may still be pending. If the interface did not change as you intended, target the control by its "label" or "ref" from the latest snapshot, or try different coordinates.');let A=this.resolveClickEffect(e,v,{canvasDominant:x.canvasDominant,suppressAdvisory:!!w,target:b?.retargetedTo??b,clickPath:u?"retarget":"coordinate"});!w&&A.note&&(w=A.note);let k={...l.clickedElement?{clickedElement:l.clickedElement}:{},...b?{clickTarget:b}:{},...w?{note:w}:{},..._?{noObservedEffect:!0}:{},...A.effectObserved!==void 0?{effectObserved:A.effectObserved}:{}};return Object.keys(k).length>0?{...x,metadata:k}:x}async resolveInteractiveDescendantAtPoint(e,n,r,s){let i;try{i=await e.evaluate(({x:u,y:d,descendSelector:f,pointSelector:h})=>{let p=document.elementFromPoint(u,d);if(!p)return{status:"none"};if(p.closest(h))return{status:"interactive"};let g=E=>{let v=window.getComputedStyle(E);if(v.display==="none"||v.visibility==="hidden")return!1;let x=E.getBoundingClientRect();return x.width>0&&x.height>0},S=Array.from(p.querySelectorAll(f)).filter(g).map((E,v)=>{E.setAttribute("data-agentiqa-descend-idx",String(v));let x=E.getBoundingClientRect(),b=E.closest("a[href], area[href]");return{index:v,rect:{left:x.left,top:x.top,right:x.right,bottom:x.bottom,width:x.width,height:x.height},tag:E.tagName.toLowerCase(),text:(E.textContent||"").trim().slice(0,80),role:E.getAttribute("role")||"",linkHref:b?.href||void 0}});return{status:"candidates",original:{tag:p.tagName.toLowerCase(),text:(p.textContent||"").trim().slice(0,80)},candidates:S}},{x:n,y:r,descendSelector:Hy,pointSelector:JP})}catch{return{status:"none"}}if(i.status!=="candidates")return i;let a=XP(i.candidates,{x:n,y:r},s);if(!a)return await e.evaluate(()=>{document.querySelectorAll("[data-agentiqa-descend-idx]").forEach(u=>u.removeAttribute("data-agentiqa-descend-idx"))}).catch(()=>{}),{status:"none"};let o=i.candidates[a.index],l=`agentiqa_click_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return await e.evaluate(({index:u,marker:d})=>{let f=document.querySelector(`[data-agentiqa-descend-idx="${u}"]`);return document.querySelectorAll("[data-agentiqa-descend-idx]").forEach(h=>h.removeAttribute("data-agentiqa-descend-idx")),f?(document.querySelectorAll("[data-agentiqa-click-target]").forEach(h=>h.removeAttribute("data-agentiqa-click-target")),f.setAttribute("data-agentiqa-click-target",d),!0):!1},{index:a.index,marker:l}).catch(()=>!1)?{status:"retarget",marker:l,original:i.original,final:{tag:o.tag,text:o.text,role:o.role,linkHref:o.linkHref}}:{status:"none"}}async getAffordanceCdpSession(e){let n=e.page;if(e.affordanceCdpSession&&e.affordanceCdpSessionPage===n)return e.affordanceCdpSession;this.invalidateAffordanceCdpSession(e);let r=await n.context().newCDPSession(n);return e.affordanceCdpSession=r,e.affordanceCdpSessionPage=n,r}invalidateAffordanceCdpSession(e){let n=e.affordanceCdpSession;e.affordanceCdpSession=void 0,e.affordanceCdpSessionPage=void 0,n&&n.detach?.().catch(()=>{})}async probeDirectClickListener(e,n,r){let{page:s}=e,i="data-agentiqa-affordance-probe",a=!1;try{if(a=await s.evaluate(({px:u,py:d,attr:f})=>{let h=document.elementFromPoint(u,d);return h?(h.setAttribute(f,"1"),!0):!1},{px:n,py:r,attr:i}),!a)return null;let o=await this.getAffordanceCdpSession(e),l;try{l=await o.send("Runtime.evaluate",{expression:`document.querySelector('[${i}]')`,returnByValue:!1})}catch{return this.invalidateAffordanceCdpSession(e),null}let c=l?.result?.objectId;if(!c)return null;try{let u=await o.send("DOMDebugger.getEventListeners",{objectId:c,depth:0});return(Array.isArray(u?.listeners)?u.listeners:[]).some(f=>f?.type==="click")}catch{return this.invalidateAffordanceCdpSession(e),null}finally{await o.send("Runtime.releaseObject",{objectId:c}).catch(()=>{})}}catch{return null}finally{a&&await s.evaluate(o=>{document.querySelector(`[${o}]`)?.removeAttribute(o)},i).catch(()=>{})}}async clickByRef(e,n,r=[],s=1){let{page:i}=e,a=3e3,o=this.safeCurrentUrl(e);try{await i.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let l=i.locator(`aria-ref=${n}`),c=await l.boundingBox({timeout:a});c&&await this.onBeforeAction(e,c.x+c.width/2,c.y+c.height/2);let u=await l.evaluate(k=>({tag:k.tagName.toLowerCase(),text:(k.textContent||"").trim().slice(0,80),role:k.getAttribute("role")||"",linkHref:k.closest("a[href], area[href]")?.href})).catch(()=>null),d=await l.evaluate(hM,{captureAffordance:uM()}).catch(()=>null),f=await l.evaluate(k=>{let T=k instanceof HTMLSelectElement?k:k.closest("select");if(!T)return null;T.focus();let R=T.options[T.selectedIndex]?.textContent?.trim()||"",O=Array.from(T.options).map(P=>P.textContent?.trim()||P.value);return{selectedText:R,options:O,isMultiple:T.multiple}}).catch(()=>null);if(f&&!f.isMultiple)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:f.selectedText,valueAfter:f.selectedText,availableOptions:f.options,...d?{clickTarget:d}:{}}};if(u?.linkHref){let k=await this.containCrossEnvironmentIfNeeded(e,u.linkHref);if(k)return k;let T=await this.blockScopedNavigationIfNeeded(e,u.linkHref);if(T)return T}let h=i.waitForEvent("filechooser",{timeout:500}).catch(()=>null),p=i.waitForEvent("download",{timeout:500}).catch(()=>null),g=r.map(k=>k).filter(Boolean);await qn.reset(i);let m=this.dialogsAcceptedOn(i),S={force:!0,timeout:a,modifiers:g.length?g:void 0};s>1?await l.dblclick(S):await l.click(S);let E=await h;if(E){let T=await E.element().evaluate(P=>{let L=P;return document.querySelectorAll("[data-agentiqa-file-target]").forEach(V=>V.removeAttribute("data-agentiqa-file-target")),L.setAttribute("data-agentiqa-file-target","true"),L instanceof HTMLInputElement?{accept:L.accept||"*",multiple:L.multiple}:{accept:"*",multiple:!1}}),R=this.getSuggestedSampleFiles(T.accept,T.multiple);return console.log(`[BasePlaywright] FILE CHOOSER INTERCEPTED via ref=${n}: accept="${T.accept}"`),{...await this.captureState(e),metadata:{elementType:"file",accept:T.accept,multiple:T.multiple,suggestedFiles:R}}}let v=await p;if(v){let k=v.suggestedFilename(),T=v.url();console.log(`[BasePlaywright] DOWNLOAD INTERCEPTED via ref=${n}: "${k}" from ${T}`),await v.cancel();try{await i.goBack({waitUntil:"domcontentloaded",timeout:5e3})}catch{}return{...await this.captureState(e),metadata:{elementType:"download",downloadFilename:k,downloadUrl:T,clickedElement:u??void 0,clickTarget:d??void 0}}}await this.awaitPageReady(i);let x=await this.probeClickEffect(e,i,o,m),b=await this.captureState(e),_=this.resolveClickEffect(e,x,{canvasDominant:b.canvasDominant,target:u??d,clickPath:"ref"}),w=_.effectObserved!==void 0||_.note!==void 0,A=_.note?b.metadata?.note?`${b.metadata.note} ${_.note}`:_.note:b.metadata?.note;return u||d||w?{...b,metadata:{...b.metadata,...u?{clickedElement:u}:{},...d?{clickTarget:d}:{},...A?{note:A}:{},..._.effectObserved!==void 0?{effectObserved:_.effectObserved}:{}}}:b}catch(l){console.warn(`[BasePlaywright] clickByRef ref=${n} failed: ${l.message}`);let c=await this.captureState(e),d=(l.message??"").includes("intercepts pointer events")?`Ref "${n}" is covered by another element (overlay/popup). Dismiss the overlay first, or try a different ref.`:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`;return{...c,metadata:{error:d}}}}async resolveClickableByLabel(e,n){return await e.evaluate(({requestedLabel:r,selector:s})=>{let i=v=>v.replace(/\s+/g," ").trim().replace(/[?:.!]+$/,"").toLowerCase(),a=v=>i(v).replace(/[\s:_-]+/g,""),o=i(r),l=a(r),c=(v,x)=>!!x&&v.startsWith(x)&&(v.length===x.length||/[\s:>/-]/.test(v.charAt(x.length))),u=v=>{let x=i(v);return x?x===o?0:a(v)===l?1:c(x,o)||c(o,x)?2:null:null},d=v=>{let x=window.getComputedStyle(v);if(x.display==="none"||x.visibility==="hidden")return!1;let b=v.getBoundingClientRect();return b.width>0&&b.height>0},f=v=>{let x=v.getAttribute("aria-label");if(x&&x.trim())return x.trim();let b=v.getAttribute("aria-labelledby");if(b){let A=b.split(/\s+/).map(k=>document.getElementById(k)?.textContent?.trim()).filter(Boolean).join(" ");if(A)return A}if(v instanceof HTMLInputElement&&(v.type==="submit"||v.type==="button"||v.type==="reset")&&v.value&&v.value.trim())return v.value.trim();let _=(v.innerText||v.textContent||"").trim();if(_)return _;let w=v.getAttribute("title");return w&&w.trim()?w.trim():""},h=Array.from(document.querySelectorAll(s)).filter(v=>d(v)),p=[];for(let v of h){let x=f(v),b=u(x);b!=null&&p.push({element:v,name:x,rank:b})}if(p.length===0)return{status:"none"};p.sort((v,x)=>v.rank-x.rank);let g=p[0].rank,m=p.filter(v=>v.rank===g);if(Array.from(new Set(m.map(v=>v.element))).length>1)return{status:"ambiguous",matches:m.slice(0,5).map(v=>v.name)};let E=`agentiqa_click_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return document.querySelectorAll("[data-agentiqa-click-target]").forEach(v=>v.removeAttribute("data-agentiqa-click-target")),m[0].element.setAttribute("data-agentiqa-click-target",E),{status:"ok",marker:E,matchedName:m[0].name}},{requestedLabel:n,selector:Hy})}async clickByLabel(e,n,r=[],s=1){let{page:i}=e,a=3e3,o=s>1?"Double-click":"Click",l=this.safeCurrentUrl(e);try{await i.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}let c=await this.resolveClickableByLabel(i,n);if(c.status!=="ok"){let u=await this.captureState(e),d=c.status==="ambiguous"?`More than one control is named "${n}" (${(c.matches||[]).join(", ")}). ${o} by ref from the latest snapshot, or use a more specific name.`:`No clickable control named "${n}" was found on the page. Check the latest snapshot and ${o.toLowerCase()} by ref, or use coordinates.`;return{...u,metadata:{...u.metadata,note:d}}}try{let u=i.locator(`[data-agentiqa-click-target="${c.marker}"]`).first(),d=await u.boundingBox({timeout:a});d&&await this.onBeforeAction(e,d.x+d.width/2,d.y+d.height/2);let f=await u.evaluate(b=>({tag:b.tagName.toLowerCase(),text:(b.textContent||"").trim().slice(0,80),role:b.getAttribute("role")||"",linkHref:b.closest("a[href], area[href]")?.href})).catch(()=>null);if(f?.linkHref){let b=await this.containCrossEnvironmentIfNeeded(e,f.linkHref);if(b)return b;let _=await this.blockScopedNavigationIfNeeded(e,f.linkHref);if(_)return _}let h=r.map(b=>b).filter(Boolean);await qn.reset(i);let p=this.dialogsAcceptedOn(i),g={force:!0,timeout:a,modifiers:h.length?h:void 0};s>1?await u.dblclick(g):await u.click(g),await this.awaitPageReady(i);let m=await this.probeClickEffect(e,i,l,p),S=await this.captureState(e),E=this.resolveClickEffect(e,m,{canvasDominant:S.canvasDominant,target:f,clickPath:"label"}),v=E.effectObserved!==void 0||E.note!==void 0,x=E.note?S.metadata?.note?`${S.metadata.note} ${E.note}`:E.note:S.metadata?.note;return f||v?{...S,metadata:{...S.metadata,...f?{clickedElement:f}:{},...x?{note:x}:{},...E.effectObserved!==void 0?{effectObserved:E.effectObserved}:{}}}:S}catch(u){let d=await this.captureState(e);return{...d,metadata:{...d.metadata,note:`Could not ${o.toLowerCase()} "${n}": ${u?.message??"unknown error"}. Try ${o.toLowerCase()}ing by ref from the latest snapshot.`}}}}async rightClickAt(e,n,r){let{page:s}=e;try{await s.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}return await this.onBeforeAction(e,n,r),await s.mouse.click(n,r,{button:"right"}),await this.awaitPageReady(s),await this.captureState(e)}async rightClickByRef(e,n){let{page:r}=e,s=3e3;try{await r.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let i=r.locator(`aria-ref=${n}`),a=await i.boundingBox({timeout:s});return a&&await this.onBeforeAction(e,a.x+a.width/2,a.y+a.height/2),await i.click({button:"right",force:!0,timeout:s}),await this.awaitPageReady(r),await this.captureState(e)}catch(i){console.warn(`[BasePlaywright] rightClickByRef ref=${n} failed: ${i.message}`);let a=await this.captureState(e),l=(i.message??"").includes("intercepts pointer events")?`Ref "${n}" is covered by another element (overlay/popup). Dismiss the overlay first, or try a different ref.`:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`;return{...a,metadata:{error:l}}}}async hoverAt(e,n,r){let{page:s}=e;return await this.onBeforeAction(e,n,r),await s.mouse.move(n,r),await new Promise(i=>setTimeout(i,300)),await this.captureState(e)}async hoverByRef(e,n){let{page:r}=e,s=3e3;try{await r.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let i=r.locator(`aria-ref=${n}`),a=await i.boundingBox({timeout:s});return a&&await this.onBeforeAction(e,a.x+a.width/2,a.y+a.height/2),await i.hover({force:!0,timeout:s}),await new Promise(o=>setTimeout(o,300)),await this.captureState(e)}catch(i){return console.warn(`[BasePlaywright] hoverByRef ref=${n} failed: ${i.message}`),{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}}async typeTextAt(e,n,r,s,i,a,o=!1){let{page:l}=e;await this.onBeforeAction(e,n,r),await l.mouse.click(n,r);let c;try{c=await l.evaluate(()=>{let T=document.activeElement;return T instanceof HTMLInputElement?{type:"input",inputType:T.type}:T instanceof HTMLTextAreaElement?{type:"textarea",inputType:"textarea"}:T instanceof HTMLSelectElement?{type:"select",inputType:"select"}:T.isContentEditable?{type:"contenteditable",inputType:"contenteditable"}:{type:"other",inputType:"none"}})}catch{console.warn("[BasePlaywright] page.evaluate blocked in typeTextAt, falling back to keyboard typing"),c={type:"input",inputType:"text"}}let u=["date","time","datetime-local","month","week"],d=c.type==="input"&&u.includes(c.inputType),h=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(c.inputType),p=nM()&&!h&&!d&&!i&&(s??"").trim()!=="",g=!1,m,S;if(p&&await this.computeCanvasDominant(e)){g=!0,await this.settleForInputHandlers(l);let T=await this.captureVerificationFrame(e);await this.settleForInputHandlers(l),S=await this.captureVerificationFrame(e),m=T&&S?zy(T,S):void 0}let E=h&&!d?await this.readFocusedFieldValue(l):void 0,v=a===!0||a==="true";if(s=this.normalizeTestingEmailForFocusedField(e,s,{inputType:c.inputType}),d){let T=!1;try{T=await l.evaluate(R=>{let O=document.activeElement;if(O instanceof HTMLInputElement){let P=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;return P?P.call(O,R):O.value=R,O.dispatchEvent(new Event("input",{bubbles:!0})),O.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1},s)}catch{}T||(v&&h&&(await l.keyboard.press("ControlOrMeta+a"),await l.keyboard.press("Backspace")),await l.keyboard.type(s,{delay:10}))}else v&&h&&(await l.keyboard.press("ControlOrMeta+a"),await l.keyboard.press("Backspace")),await Ri(l,s,10);i&&(await l.keyboard.press("Enter"),await this.awaitPageReady(l)),await this.settleForInputHandlers(l);let x=await this.getFocusedFieldName(l),b=await this.getFocusedElementFingerprint(l),_=h&&!d?await this.readFocusedFieldValue(l):void 0,w=Xy({requested:s,valueBefore:E,valueAfter:_,pressEnter:i,sensitive:o}),A=await this.captureState(e),k={...A.metadata};if(x&&(k.typedIntoField=x),b&&(k.elementFingerprint=b),k.inputType=c.inputType,!o&&E!==void 0&&(k.valueBefore=E),!o&&_!==void 0&&(k.valueAfter=_),w.valueMismatch&&(k.valueMismatch=!0,k.error=w.error),g){let T=rM(A.aiSnapshot,s),R;if(!T&&m===!0){let L=await this.captureVerificationFrame(e);S&&L&&(R=!zy(S,L))}let O=sM({requested:s,a11yConfirmed:T,boardStatic:m,frameChanged:R,pressEnter:i,sensitive:o});O.outcome==="not_found"&&(k.canvasTypeVerification=O.verification,k.error||(k.error=O.error));let P=O.outcome==="landed"?T?"landed_a11y":"landed_pixel":O.outcome==="not_found"?"text_not_found":O.outcome;this.diagLog?.(e.sessionId,"canvas_type_verify",{outcome:P,a11yConfirmed:T,boardStatic:m,frameChanged:R,textLength:(s??"").length,x:n,y:r})}return{...A,metadata:k}}async settleForInputHandlers(e){try{await e.evaluate(()=>new Promise(n=>requestAnimationFrame(()=>setTimeout(n,50))))}catch{}}async captureVerificationFrame(e){let{page:n}=e;try{return await n.screenshot({type:"png",timeout:5e3})}catch{return}}async typeByRef(e,n,r,s,i,a=!1){let{page:o}=e,l=3e3;try{await o.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let c=o.locator(`aria-ref=${n}`),u=await c.boundingBox({timeout:l});u&&await this.onBeforeAction(e,u.x+u.width/2,u.y+u.height/2),await c.click({force:!0,timeout:l});let d;try{d=await o.evaluate(()=>{let A=document.activeElement;return A instanceof HTMLInputElement?{inputType:A.type}:A instanceof HTMLTextAreaElement?{inputType:"textarea"}:A.isContentEditable?{inputType:"contenteditable"}:{inputType:"none"}})}catch{console.warn(`[BasePlaywright] page.evaluate blocked for typeByRef ref=${n}, falling back to keyboard typing`),d={inputType:"text"}}let h=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(d.inputType),g=["date","time","datetime-local","month","week"].includes(d.inputType);if(!h&&!g)return{...await this.captureState(e),metadata:{error:`Ref "${n}" resolved to a non-text element (${d.inputType||"unknown"}). Use a different ref that targets the text input directly.`}};let m=i===!0||i==="true";r=this.normalizeTestingEmailForFocusedField(e,r,{inputType:d.inputType});let S=g?void 0:await this.readFocusedFieldValue(o);if(g)try{await o.evaluate(A=>{let k=document.activeElement;if(k instanceof HTMLInputElement){let T=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;T?T.call(k,A):k.value=A,k.dispatchEvent(new Event("input",{bubbles:!0})),k.dispatchEvent(new Event("change",{bubbles:!0}))}},r)}catch{await o.keyboard.type(r,{delay:15})}else m&&h?(await o.keyboard.press("ControlOrMeta+a"),r?await Ri(o,r,15):await o.keyboard.press("Backspace")):r&&await Ri(o,r,15);s&&await o.keyboard.press("Enter"),await this.awaitPageReady(o);try{await o.evaluate(()=>new Promise(A=>requestAnimationFrame(()=>setTimeout(A,50))))}catch{}let E=await this.getFocusedFieldName(o),v=await this.getFocusedElementFingerprint(o),x=g?void 0:await this.readFocusedFieldValue(o),b=g?{valueMismatch:!1}:Xy({requested:r,valueBefore:S,valueAfter:x,pressEnter:s,sensitive:a}),_=await this.captureState(e),w={..._.metadata};return E&&(w.typedIntoField=E),v&&(w.elementFingerprint=v),w.inputType=d.inputType,!a&&S!==void 0&&(w.valueBefore=S),!a&&x!==void 0&&(w.valueAfter=x),b.valueMismatch&&(w.valueMismatch=!0,w.error=b.error),{..._,metadata:w}}catch(c){return console.warn(`[BasePlaywright] typeByRef ref=${n} failed: ${c.message}`),{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}}async typeByLabel(e,n,r,s,i){let{page:a}=e,o=3e3,l=await a.evaluate(_=>{let w=D=>D.replace(/\s+/g," ").trim().replace(/:$/,"").toLowerCase(),A=D=>w(D).replace(/[\s:_-]+/g,""),k=w(_),T=A(_),R=D=>{let Y=w(D);return Y?Y===k?0:A(D)===T?1:Y.includes(k)||k.includes(Y)?2:null:null},O=D=>{let Y=window.getComputedStyle(D);if(Y.display==="none"||Y.visibility==="hidden")return!1;let B=D.getBoundingClientRect();return B.width>0&&B.height>0},P=D=>D instanceof HTMLTextAreaElement?!D.disabled:D instanceof HTMLInputElement?D.disabled||D.type==="hidden"?!1:["text","password","email","search","url","tel","number","date","time","datetime-local","month","week"].includes(D.type):D.isContentEditable,L=D=>D instanceof HTMLInputElement?`input[type=${D.type}]`:D instanceof HTMLTextAreaElement?"textarea":D.isContentEditable?"contenteditable":D.tagName.toLowerCase(),V=D=>D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D.value:D.isContentEditable?D.textContent??"":"",X=D=>{let Y=[];for(let B of Array.from(D.childNodes))if(B.nodeType===Node.TEXT_NODE){let H=B.textContent?.trim();H&&Y.push(H)}else if(B instanceof HTMLElement&&!P(B)){let H=B.innerText?.trim();H&&Y.push(H)}return Y.join(" ").replace(/\s+/g," ").trim()},z=D=>{let Y=[],B=(F,te,se)=>{let pe=F?.replace(/\s+/g," ").trim();pe&&Y.push({label:pe,source:te,priority:se})};B(D.getAttribute("aria-label"),"aria-label",0);let H=D.getAttribute("aria-labelledby");if(H&&B(H.split(/\s+/).map(F=>document.getElementById(F)?.textContent?.trim()).filter(Boolean).join(" "),"aria-labelledby",0),D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement)for(let F of Array.from(D.labels??[]))B(F.textContent,"label",0);let $=D.id;$&&B(document.querySelector(`label[for="${$}"]`)?.textContent,"label[for]",0),(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement)&&(B(D.placeholder,"placeholder",1),B(D.name,"name",2),B(D.id,"id",2));let N=D.previousElementSibling;for(;N;)B(N instanceof HTMLElement?N.innerText:N.textContent,"previous-sibling",3),N=N.previousElementSibling;let M=D.parentElement;for(let F=0;M&&F<3;F+=1,M=M.parentElement)B(X(M),"container-text",4+F);return Y},U=[],j=Array.from(document.querySelectorAll('input:not([type="hidden"]), textarea, [contenteditable="true"]')).filter(D=>P(D)&&O(D));for(let D of j)for(let Y of z(D)){let B=R(Y.label);B!=null&&U.push({element:D,label:Y.label,source:Y.source,priority:Y.priority,matchRank:Y.priority*10+B,elementType:L(D),valueBefore:V(D)})}if(U.length===0)return{status:"none",error:`No text input found for label "${_}". Check the latest page snapshot for the field label or use ref/x/y.`};U.sort((D,Y)=>D.matchRank-Y.matchRank);let K=U[0].matchRank,q=U.filter(D=>D.matchRank===K);if(Array.from(new Set(q.map(D=>D.element))).length>1)return{status:"ambiguous",error:`Multiple text inputs matched label "${_}". Use a more specific label or a direct ref.`,matches:q.map(D=>({label:D.label,source:D.source,elementType:D.elementType}))};let ne=`agentiqa_label_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return q[0].element.setAttribute("data-agentiqa-label-target",ne),{status:"ok",marker:ne,matchedLabel:q[0].label,labelSource:q[0].source,elementType:q[0].elementType,valueBefore:q[0].valueBefore}},n);if(l.status!=="ok"){let _=await this.captureState(e);return{..._,metadata:{..._.metadata,error:l.error,...l.status==="ambiguous"&&{matches:l.matches}}}}let c=a.locator(`[data-agentiqa-label-target="${l.marker}"]`).first(),u=await c.boundingBox({timeout:o});u&&await this.onBeforeAction(e,u.x+u.width/2,u.y+u.height/2),await c.click({force:!0,timeout:o});let d=await a.evaluate(()=>{let _=document.activeElement;return _ instanceof HTMLInputElement?{inputType:_.type}:_ instanceof HTMLTextAreaElement?{inputType:"textarea"}:_.isContentEditable?{inputType:"contenteditable"}:{inputType:"none"}}),h=["date","time","datetime-local","month","week"].includes(d.inputType),g=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(d.inputType);if(!g&&!h){let _=await this.captureState(e);return{..._,metadata:{..._.metadata,error:`Label "${n}" resolved to a non-text element (${d.inputType||"unknown"}). Use a different label or direct ref.`}}}let m=i===!0||i==="true";if(r=this.normalizeTestingEmailForFocusedField(e,r,{inputType:d.inputType,label:n,matchedLabel:l.matchedLabel}),h)try{await a.evaluate(_=>{let w=document.activeElement;if(w instanceof HTMLInputElement){let A=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;A?A.call(w,_):w.value=_,w.dispatchEvent(new Event("input",{bubbles:!0})),w.dispatchEvent(new Event("change",{bubbles:!0}))}},r)}catch{await a.keyboard.type(r,{delay:15})}else m&&g?(await a.keyboard.press("ControlOrMeta+a"),r?await Ri(a,r,15):await a.keyboard.press("Backspace")):r&&await Ri(a,r,15);s&&await a.keyboard.press("Enter"),await this.awaitPageReady(a);try{await a.evaluate(()=>new Promise(_=>requestAnimationFrame(()=>setTimeout(_,50))))}catch{}let S=await this.getFocusedFieldName(a),E=await this.getFocusedElementFingerprint(a),v=await a.evaluate(()=>{let _=document.activeElement;return _ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_.value:_ instanceof HTMLElement&&_.isContentEditable?_.textContent??"":""}),x=h?{valueMismatch:!1}:Xy({requested:r,valueBefore:l.valueBefore,valueAfter:v,pressEnter:s}),b=await this.captureState(e);return{...b,metadata:{...b.metadata,typedIntoField:S??l.matchedLabel,matchedLabel:l.matchedLabel,labelSource:l.labelSource,elementType:l.elementType,inputType:d.inputType,valueBefore:l.valueBefore,valueAfter:v,...E&&{elementFingerprint:E},...x.valueMismatch?{valueMismatch:!0,error:x.error}:{}}}}async scrollDocument(e,n){let{page:r,viewportHeight:s}=e,i=Math.floor(s*.8),a=n==="up"||n==="down",o=n==="up"||n==="left"?-i:i;return await r.evaluate(({vertical:l,signed:c})=>{let u=document.scrollingElement||document.documentElement,d=null,f=0;for(let m of Array.from(document.querySelectorAll("*"))){let S=l?m.scrollHeight-m.clientHeight:m.scrollWidth-m.clientWidth;if(S<=f)continue;let E=l?getComputedStyle(m).overflowY:getComputedStyle(m).overflowX;E!=="auto"&&E!=="scroll"||(f=S,d=m)}let h=l?u.scrollHeight-u.clientHeight:u.scrollWidth-u.clientWidth,p=l?0:c,g=l?c:0;!d||h>=f?window.scrollBy(p,g):d.scrollBy(p,g)},{vertical:a,signed:o}),await new Promise(l=>setTimeout(l,200)),await this.captureState(e)}async scrollToBottom(e){let{page:n}=e;return await n.evaluate(()=>{let r=document.scrollingElement||document.documentElement,s=null,i=0;for(let o of Array.from(document.querySelectorAll("*"))){let l=o.scrollHeight-o.clientHeight;if(l<=i)continue;let c=getComputedStyle(o).overflowY;c!=="auto"&&c!=="scroll"||(i=l,s=o)}let a=r.scrollHeight-r.clientHeight;!s||a>=i?window.scrollTo(0,r.scrollHeight):s.scrollTo(0,s.scrollHeight)}),await new Promise(r=>setTimeout(r,200)),await this.captureState(e)}async scrollAt(e,n,r,s,i){let{page:a}=e;await a.mouse.move(n,r);let o=0,l=0;switch(s){case"up":l=-i;break;case"down":l=i;break;case"left":o=-i;break;case"right":o=i;break}return await a.mouse.wheel(o,l),await new Promise(c=>setTimeout(c,200)),await this.captureState(e)}async waitSeconds(e,n){let r=Math.min(Math.max(n,1),30);return await new Promise(s=>setTimeout(s,r*1e3)),await this.captureState(e)}async waitForVisibleTextOrIdentifierLabel(e,n,r){let s=e.getByText(n,{exact:!1}).first().waitFor({state:"visible",timeout:r}),i=FZ(n);if(!i){await s;return}let a=e.waitForFunction(({spec:o})=>{let l=document.body?.innerText??"",c=f=>(f.match(/[A-Za-z0-9][A-Za-z0-9_-]*/g)??[]).some(p=>{let g=(p.match(/[A-Za-z]/g)??[]).length,m=(p.match(/\d/g)??[]).length;return g>=1&&m>=2?!0:/^[A-Za-z]{2,}[-_]\d+$/.test(p)}),u=f=>f.toLowerCase().match(/[a-z0-9]+/g)??[];return l.split(/\n+/).map(f=>f.trim()).filter(Boolean).some(f=>{if(!c(f))return!1;let h=new Set(u(f));return o.anchors.every(p=>h.has(p))})},{spec:i},{timeout:r});await Promise.any([s,a])}async waitForElement(e,n,r){let{page:s}=e;if(await this.computeCanvasDominant(e)){let l=Math.min(Math.max(r,1),10);try{return await this.waitForVisibleTextOrIdentifierLabel(s,n,l*1e3),await new Promise(c=>setTimeout(c,300)),await this.captureState(e,{onScreenshotTimeout:"degrade"})}catch{return{...await this.captureState(e,{onScreenshotTimeout:"degrade"}),metadata:{error:Uk(n)}}}}let i=(()=>{let l=typeof process<"u"&&process?.env?Number(process.env.REPLAY_WAIT_POLL_MS):NaN;return Number.isFinite(l)&&l>0?Math.round(l/1e3):180})(),a=e.isTestPlanReplay===!0?i:30,o=Math.min(Math.max(r,1),a);try{return await this.waitForVisibleTextOrIdentifierLabel(s,n,o*1e3),await new Promise(l=>setTimeout(l,300)),await this.captureState(e,{onScreenshotTimeout:"degrade"})}catch{return{...await this.captureState(e,{onScreenshotTimeout:"degrade"}),metadata:{error:Lk(n,o)}}}}async fullPageScreenshot(e){let{page:n}=e,r=n.url(),s=await this.measureFullPageGeometry(e);if(rm(s)!=="inner_scroll"){let c=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});if(oA(this.pngHeightPx(c),s)){if(!Ge("EVIDENCE_FIDELITY"))return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"shadow_fullpage_viewport_only"),{screenshot:c,url:r,captureMode:"viewport_degraded"};let u=await this.captureInnerExtentFull(e,s);if(u)return{screenshot:u,url:r,captureMode:"cdp_full"};let d=await this.captureScrollStitch(e,s);return d?{screenshot:d,url:r,captureMode:"scroll_stitch"}:(this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"no_full_render"),{screenshot:c,url:r,captureMode:"viewport_degraded"})}return{screenshot:c,url:r,captureMode:"document_full"}}if(!Ge("EVIDENCE_FIDELITY")){let c=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"shadow_inner_scroll"),{screenshot:c,url:r,captureMode:"viewport_degraded"}}let a=await this.captureInnerExtentFull(e,s);if(a)return{screenshot:a,url:r,captureMode:"cdp_full"};let o=await this.captureScrollStitch(e,s);if(o)return{screenshot:o,url:r,captureMode:"scroll_stitch"};let l=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"no_full_render"),{screenshot:l,url:r,captureMode:"viewport_degraded"}}async measureFullPageGeometry(e){let{page:n}=e;try{return await n.evaluate(()=>{let s=document.scrollingElement||document.documentElement,i=window.innerHeight,a=Math.max(s?s.scrollHeight:0,document.body?document.body.scrollHeight:0),o=0,l=document.querySelectorAll("*");for(let c=0;c<l.length;c++){let u=l[c],f=window.getComputedStyle(u).overflowY;if(f!=="auto"&&f!=="scroll"||u.scrollHeight<=u.clientHeight+1)continue;let h=u.getBoundingClientRect();h.height<1||h.bottom<=0||h.top>=i||u.scrollHeight>o&&(o=u.scrollHeight)}return{viewportH:i,documentH:a,innerContainerH:o,dpr:window.devicePixelRatio||1}})}catch{let r=n.viewportSize()?.height??0;return{viewportH:r,documentH:r+4+1,innerContainerH:0,dpr:1}}}async captureInnerExtentFull(e,n){let{page:r}=e,s=null;try{s=await r.evaluate(i=>{let a=document.scrollingElement||document.documentElement,o=null,l=0,c=document.querySelectorAll("*");for(let d=0;d<c.length;d++){let f=c[d],p=window.getComputedStyle(f).overflowY;p!=="auto"&&p!=="scroll"||f.scrollHeight<=f.clientHeight+1||f.scrollHeight>l&&(l=f.scrollHeight,o=f)}if(!o||l<i-4)return null;let u=o;return u.__aqPrevCss=u.style.cssText,u.setAttribute("data-aq-fullpage-expanded","1"),u.style.setProperty("max-height","none","important"),u.style.setProperty("height","auto","important"),u.style.setProperty("overflow","visible","important"),a&&a.scrollHeight,{documentH:a?a.scrollHeight:0}},n.innerContainerH)}catch{s=null}if(!s)return null;try{return s.documentH<=n.viewportH+4?null:(await new Promise(i=>setTimeout(i,120)),await this.screenshotWithSlowSiteRetry(e,{fullPage:!0}))}catch{return null}finally{await this.restoreExpandedContainer(e)}}async restoreExpandedContainer(e){try{await e.page.evaluate(()=>{let n=document.querySelector("[data-aq-fullpage-expanded]");n&&(typeof n.__aqPrevCss=="string"?n.style.cssText=n.__aqPrevCss:n.removeAttribute("style"),delete n.__aqPrevCss,n.removeAttribute("data-aq-fullpage-expanded"))})}catch{}}async captureScrollStitch(e,n){let{page:r}=e,s=12,i=null;try{i=await r.evaluate(()=>{let l=null,c=0,u=document.querySelectorAll("*");for(let h=0;h<u.length;h++){let p=u[h],m=window.getComputedStyle(p).overflowY;m!=="auto"&&m!=="scroll"||p.scrollHeight<=p.clientHeight+1||p.scrollHeight>c&&(c=p.scrollHeight,l=p)}if(!l)return null;let d=l;d.__aqPrevScrollTop=d.scrollTop,d.setAttribute("data-aq-stitch","1");let f=d.getBoundingClientRect();return{x:Math.max(0,Math.floor(f.left)),y:Math.max(0,Math.floor(f.top)),width:Math.max(1,Math.floor(f.width)),clientH:Math.max(1,Math.floor(d.clientHeight)),scrollH:Math.floor(d.scrollHeight)}})}catch{i=null}if(!i)return null;let a=Math.min(s,Math.ceil(i.scrollH/i.clientH));if(a<2)return await this.clearStitchMarker(e),null;let o=[];try{for(let l=0;l<a;l++){let c=l*i.clientH;await r.evaluate(h=>{let p=document.querySelector("[data-aq-stitch]");p&&(p.scrollTop=h)},c),await new Promise(h=>setTimeout(h,80));let u=i.scrollH-c,d=Math.max(1,Math.min(i.clientH,u)),f=await r.screenshot({type:"png",clip:{x:i.x,y:i.y,width:i.width,height:d}});o.push({buf:f,height:d})}return await this.stitchTilesVertically(o,i.width)}catch{return null}finally{await this.clearStitchMarker(e)}}async clearStitchMarker(e){try{await e.page.evaluate(()=>{let n=document.querySelector("[data-aq-stitch]");n&&(typeof n.__aqPrevScrollTop=="number"&&(n.scrollTop=n.__aqPrevScrollTop),delete n.__aqPrevScrollTop,n.removeAttribute("data-aq-stitch"))})}catch{}}async stitchTilesVertically(e,n){if(e.length===0)return null;try{let{PNG:r}=await import("pngjs"),s=e.map(c=>r.sync.read(c.buf)),i=s[0].width;if(s.some(c=>c.width!==i))return null;let a=s.reduce((c,u)=>c+u.height,0);if(a<=0)return null;let o=new r({width:i,height:a}),l=0;for(let c of s)r.bitblt(c,o,0,0,c.width,c.height,0,l),l+=c.height;return r.sync.write(o)}catch{return null}}pngHeightPx(e){return e.length<24||e.readUInt32BE(0)!==2303741511?0:e.readUInt32BE(20)}emitCaptureDegradedMarker(e,n,r,s,i){this.diagLog?.(e.sessionId,"full_page_capture:degraded",{captureMode:"viewport_degraded",url:n,viewportH:r.viewportH,documentH:r.documentH,innerContainerH:r.innerContainerH,capturedH:s,reason:i})}async switchLayout(e,n,r){let{page:s}=e;return await s.setViewportSize({width:n,height:r}),await this.captureState(e)}async goBack(e){let{page:n}=e;return e.needsFullSnapshot=!0,await n.goBack(),await this.awaitPageReady(n),await this.captureState(e)}async goForward(e){let{page:n}=e;return e.needsFullSnapshot=!0,await n.goForward(),await this.awaitPageReady(n),await this.captureState(e)}async navigate(e,n){let{page:r}=e,s=Mr(n),i=await this.containCrossEnvironmentIfNeeded(e,s);if(i)return i;let a=await this.blockScopedNavigationIfNeeded(e,s);if(a)return a;let o=await Wy(s,{allowPrivateNetwork:this.preflightAllowsPrivateNetwork(),allowLocalFileUrls:this.preflightAllowsLocalFileUrls()});if(!o.ok)throw new kn(o);e.needsFullSnapshot=!0;let l=Date.now();this.reportStartupNavigate(e,"goto_start",{url:s});let c=await r.goto(s,{waitUntil:"domcontentloaded"}),u=await this.awaitPageReady(r);this.reportStartupNavigate(e,"goto_done",{elapsedMs:Date.now()-l,pageSettled:u,landedUrl:r.url()}),await this.assertNoCloudflareBlock(r,c,s);let d=[],f=c?.request().redirectedFrom()??null;for(;f;)d.unshift(f.url()),f=f.redirectedFrom();let h=r.url();this.maybeAnchorAppUnderTestOrigin(e,h),await this.assertNoThirdPartyIdpLogin(e,"navigate",{},h);let p=await this.resolveContainmentAction(e,h);if(p!=="allow")return await this.containCrossEnvironmentLanding(e,h,p==="escalate");this.recordCanonicalRedirectOrigin(e,s,h);let g=_f(s,h,d,(E,v,x,b)=>console.warn(`[BasePlaywright] [${v}] ${x}`,b??"")),m=Date.now();this.reportStartupNavigate(e,"first_screenshot_start");let S=await this.captureState(e);return this.reportStartupNavigate(e,"first_screenshot_done",{elapsedMs:Date.now()-m,bytes:S.screenshot.length}),{...S,metadata:{...S.metadata??{},navigateMeta:g,pageSettled:u}}}async blockScopedNavigationIfNeeded(e,n){if(e.canonicalRedirectOrigins?.size)try{let a=new URL(n,e.page.url()),o=l=>l.slice(0,4)==="www."?l.slice(4):l;for(let l of e.canonicalRedirectOrigins){let c=new URL(l);if(c.protocol===a.protocol&&c.port===a.port&&o(c.hostname)===o(a.hostname))return null}}catch{}let r=k0({targetUrl:n,currentUrl:e.page.url(),scope:e.browserNavigationScope,allowExternalNavigation:e.allowExternalNavigation,httpsCertFallbackHost:e.httpsCertFallback?.host});if(r.allowed)return null;let s=await this.captureState(e),i=e.browserNavigationScope?.join(", ")||"(none)";return{...s,metadata:{...s.metadata??{},error:`Navigation blocked: ${n} is outside the allowed scope (${i}). Record/report the external link without opening it unless the user explicitly asked to validate external links.`,scopedNavigation:{status:"blocked",targetUrl:n,reason:r.reason}}}}maybeAnchorAppUnderTestOrigin(e,n){if(!(e.appUnderTestOrigin||!n))try{let r=new URL(n);/^https?:$/i.test(r.protocol)&&(e.appUnderTestOrigin=r.origin)}catch{}}async returnToSafeOrigin(e,n){if(e.appUnderTestOrigin)try{await n.goto(e.appUnderTestOrigin,{waitUntil:"domcontentloaded"}),await this.awaitPageReady(n)}catch{}if(e.needsFullSnapshot=!0,!e.appUnderTestOrigin||Tl(e.appUnderTestOrigin,n.url(),{scope:e.browserNavigationScope}))try{await n.goto("about:blank",{waitUntil:"domcontentloaded"})}catch{}}async containCrossEnvironmentIfNeeded(e,n){let r=await this.resolveContainmentAction(e,n);if(r==="allow")return null;let s=await this.captureState(e);return{...s,metadata:{...s.metadata??{},error:La(n,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"blocked",targetUrl:n,...r==="escalate"?{needsUserDecision:!0}:{}}}}}async containCrossEnvironmentLanding(e,n,r=!1){await this.returnToSafeOrigin(e,e.page);let s=await this.captureState(e);return{...s,metadata:{...s.metadata??{},error:La(n,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"contained",escapedUrl:n,returnedTo:s.url,...r?{needsUserDecision:!0}:{}}}}}async containCrossEnvironmentAfterAction(e,n,r){let s=await this.resolveContainmentAction(e,r.url);if(s==="allow")return null;let i=r.url;await this.returnToSafeOrigin(e,n);let a=this.withSessionMetadata(e,await this.captureState(e));return{screenshot:a.screenshot.toString("base64"),url:a.url,aiSnapshot:a.aiSnapshot,domChanges:a.domChanges,metadata:{...a.metadata??{},error:La(i,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"contained",escapedUrl:i,returnedTo:a.url,...s==="escalate"?{needsUserDecision:!0}:{}}}}}async containPendingPopupEscapes(e){let n=e.pendingPopupEscapes;if(!n||n.length===0)return null;e.pendingPopupEscapes=void 0;let r=[];for(let o of n)await this.resolveContainmentAction(e,o.escapedUrl)!=="allow"&&r.push(o);if(r.length===0)return null;let s=r[0].escapedUrl;if(r.some(o=>e.page===o.popup||e.tab2===o.popup)){e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1");for(let o of r)e.tab2===o.popup&&(e.tab2=void 0);e.needsFullSnapshot=!0}for(let o of r)try{await o.popup.close()}catch{}let i={status:"contained",escapedUrl:s};if(!e.page||e.page.isClosed())return{screenshot:"",url:s,aiSnapshot:void 0,domChanges:void 0,metadata:{error:La(s,e.appUnderTestOrigin),crossEnvironmentContainment:i}};let a=this.withSessionMetadata(e,await this.captureState(e));return{screenshot:a.screenshot.toString("base64"),url:a.url,aiSnapshot:a.aiSnapshot,domChanges:a.domChanges,metadata:{...a.metadata??{},error:La(s,e.appUnderTestOrigin),crossEnvironmentContainment:i}}}async keyCombination(e,n){let{page:r}=e,s=n.map(a=>jZ[a.toLowerCase()]??a),i=s.some(a=>Qy.has(a));if(s.length===1)await r.keyboard.press(s[0]);else if(i){let a=s.filter(l=>Qy.has(l)),o=s.filter(l=>!Qy.has(l));for(let l of a)await r.keyboard.down(l);for(let l of o)await r.keyboard.press(l);for(let l of a.reverse())await r.keyboard.up(l)}else for(let a of s)await r.keyboard.press(a);return await this.awaitPageReady(r),await this.captureState(e)}async setFocusedInputValue(e,n,r){let{page:s}=e;if(r){let c=await this.getFocusedElementFingerprint(s);if(c!==r){let u=await this.captureState(e);return{...u,metadata:{...u.metadata,verbatimGuardMismatch:!0,...c&&{elementFingerprint:c}}}}}let i={isSelect:!1,inputType:"none"};try{i=await s.evaluate(()=>{let c=document.activeElement;return c instanceof HTMLSelectElement?{isSelect:!0,inputType:"select"}:c instanceof HTMLInputElement?{isSelect:!1,inputType:c.type}:c instanceof HTMLTextAreaElement?{isSelect:!1,inputType:"textarea"}:c?.isContentEditable?{isSelect:!1,inputType:"contenteditable"}:{isSelect:!1,inputType:"none"}})}catch{return console.warn("[BasePlaywright] page.evaluate blocked in setFocusedInputValue, falling back to keyboard typing"),n=this.normalizeTestingEmailForFocusedField(e,n,{}),await s.keyboard.press("ControlOrMeta+a"),await Ri(s,n,10),{...await this.captureState(e),metadata:{elementType:"unknown (evaluate blocked)",valueBefore:"",valueAfter:n}}}if(i.isSelect)return await this.setSelectValue(e,n);n=this.normalizeTestingEmailForFocusedField(e,n,{inputType:i.inputType});let a=await s.evaluate(c=>{let u=document.activeElement,d=g=>g instanceof HTMLInputElement?`input[type=${g.type}]`:g instanceof HTMLTextAreaElement?"textarea":g.isContentEditable?"contenteditable":g.tagName.toLowerCase(),f=g=>g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement?g.value:g.isContentEditable&&g.textContent||"";if(!u||u===document.body)return{success:!1,error:"No element is focused",elementType:"none",valueBefore:"",valueAfter:""};let h=d(u),p=f(u);try{if(u instanceof HTMLInputElement){let g=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;g?g.call(u,c):u.value=c,u.dispatchEvent(new Event("input",{bubbles:!0})),u.dispatchEvent(new Event("change",{bubbles:!0}))}else if(u instanceof HTMLTextAreaElement){let g=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set;g?g.call(u,c):u.value=c,u.dispatchEvent(new Event("input",{bubbles:!0})),u.dispatchEvent(new Event("change",{bubbles:!0}))}else if(u.isContentEditable)u.textContent=c,u.dispatchEvent(new Event("input",{bubbles:!0}));else return{success:!1,error:`Element is not editable: ${h}`,elementType:h,valueBefore:p,valueAfter:p}}catch(g){return{success:!1,error:String(g.message||g),elementType:h,valueBefore:p,valueAfter:f(u)}}return{success:!0,elementType:h,valueBefore:p,valueAfter:f(u)}},n),o=await this.getFocusedElementFingerprint(s);return{...await this.captureState(e),metadata:{elementType:a.elementType,inputType:i.inputType,valueBefore:a.valueBefore,valueAfter:a.valueAfter,...o&&{elementFingerprint:o},...a.error&&{error:a.error}}}}async setSelectValue(e,n){let{page:r}=e,s=await r.evaluate(()=>{let u=document.activeElement;if(!(u instanceof HTMLSelectElement))return null;let d=u.options[u.selectedIndex]?.textContent?.trim()||"",f=Array.from(u.options).map(h=>h.textContent?.trim()||h.value);return{valueBefore:d,options:f}});if(!s)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:"",valueAfter:"",error:"No select element is focused. Use click_at on the select first."}};let a=(await r.evaluateHandle(()=>document.activeElement)).asElement();if(!a)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:s.valueBefore,valueAfter:s.valueBefore,error:"Could not get select element handle",availableOptions:s.options}};let o=!1;try{await a.selectOption({label:n}),o=!0}catch{try{await a.selectOption({value:n}),o=!0}catch{}}let l=await r.evaluate(()=>{let u=document.activeElement;return u instanceof HTMLSelectElement?u.options[u.selectedIndex]?.textContent?.trim()||u.value:""});return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:s.valueBefore,valueAfter:l,...!o&&{error:`No option matching "${n}"`},availableOptions:s.options}}}async uploadFile(e,n,r){let{page:s}=e,i=r?.clearStaleMarker===!0;console.log(`[BasePlaywright] upload_file called with filePaths=${JSON.stringify(n)}`+(i?" (clearStaleMarker)":""));let o=(await s.evaluateHandle(f=>{f&&document.querySelectorAll("[data-agentiqa-file-target]").forEach(E=>E.removeAttribute("data-agentiqa-file-target"));let h=document.querySelector('input[type="file"][data-agentiqa-file-target]');if(h)return h;let p=document.activeElement;if(p instanceof HTMLInputElement&&p.type==="file")return p;let g=Array.from(document.querySelectorAll('input[type="file"]'));if(g.length===0)return p;let m=g.filter(E=>E.closest('[role="dialog"], dialog, [aria-modal="true"]')),S=m.length>0?m:g;return S[S.length-1]},i)).asElement();if(!o)return{...await this.captureState(e),metadata:{elementType:"file",error:"No file input found. Use click_at on the file input first."}};let l=await s.evaluate(f=>f instanceof HTMLInputElement&&f.type==="file"?{isFileInput:!0,accept:f.accept||"*",multiple:f.multiple}:{isFileInput:!1,accept:"",multiple:!1},o);if(!l.isFileInput)return{...await this.captureState(e),metadata:{elementType:"not-file-input",error:"No file input found. Use click_at on the file input/upload area first."}};await o.evaluate(f=>{document.querySelectorAll("[data-agentiqa-file-target]").forEach(h=>h.removeAttribute("data-agentiqa-file-target")),f.setAttribute("data-agentiqa-file-target","true")});try{await o.setInputFiles(n),console.log(`[BasePlaywright] upload_file setInputFiles succeeded, count=${n.length}`)}catch(f){return console.log(`[BasePlaywright] upload_file setInputFiles failed: ${f.message}`),{...await this.captureState(e),metadata:{elementType:"file",accept:l.accept,multiple:l.multiple,error:`File upload failed: ${f.message}`}}}let c=await this.onFilesUploaded(n),u=await o.evaluate(f=>f.files?.length??0).catch(()=>0);return console.log(`[BasePlaywright] upload_file result: fileCount=${u}`),await this.awaitPageReady(s),{...await this.captureState(e),metadata:{elementType:"file",accept:l.accept,multiple:l.multiple,fileCount:u,...c.length>0&&{storedAssets:c}}}}async dragAndDrop(e,n,r,s,i){let{page:a}=e;return await a.mouse.move(n,r),await a.mouse.down(),await a.mouse.move(s,i,{steps:10}),await a.mouse.up(),await this.captureState(e)}async resolveRefCenter(e,n){try{let i=await e.page.locator(`aria-ref=${n}`).boundingBox({timeout:3e3});return i?{x:Math.floor(i.x+i.width/2),y:Math.floor(i.y+i.height/2)}:null}catch{return null}}async refNotFoundError(e,n){return{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}async switchTab(e,n){if(n==="tab1"){let r=!e.tab1||e.tab1.isClosed();if(this.diagLog?.(e.sessionId,"switchTab tab1 requested",{tab1Closed:r,hasExtId:!!e.extensionId}),r&&e.extensionId){this.diagLog?.(e.sessionId,"switchTab auto-recreating tab1 at popup.html");let s=await e.context.newPage();Tp(s),await s.goto(`chrome-extension://${e.extensionId}/popup.html`,{timeout:5e3}),e.tab1=s}if(!e.tab1||e.tab1.isClosed())return{...await this.captureState(e),metadata:{error:"Tab 1 is not available"}};if(e.page=e.tab1,e.activeTab="tab1",e.extensionId){let s=e.tab1.url();if(!s.startsWith(`chrome-extension://${e.extensionId}`)){this.diagLog?.(e.sessionId,"switchTab navigating to popup.html",{beforeUrl:s});try{await e.tab1.goto(`chrome-extension://${e.extensionId}/popup.html`,{timeout:5e3});let i=e.tab1.url();this.diagLog?.(e.sessionId,"switchTab popup.html loaded",{afterUrl:i})}catch(i){this.diagLog?.(e.sessionId,"switchTab popup.html failed",{error:i?.message})}}}}else{if(!e.tab2||e.tab2.isClosed())return{...await this.captureState(e),metadata:{error:"Tab 2 is not available. No second tab is open."}};e.page=e.tab2,e.activeTab="tab2"}return e.needsFullSnapshot=!0,await e.page.bringToFront(),await this.captureState(e)}async closeTab(e){if(e.activeTab==="tab1")return{...await this.captureState(e),metadata:{error:"Cannot close tab 1"}};if(e.tab2&&!e.tab2.isClosed())try{await e.tab2.close()}catch{}return e.tab2=void 0,e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0,await e.page.bringToFront(),await this.captureState(e)}static HTTP_BODY_MAX_LENGTH=5e4;async httpRequest(e,n,r,s,i){let{page:a}=e;try{let o={method:r,timeout:3e4,ignoreHTTPSErrors:!0};s&&(o.headers=s),i&&r!=="GET"&&(o.data=i);let l=await a.request.fetch(n,o),c=await l.text(),u=!1;if(c.length>t.HTTP_BODY_MAX_LENGTH&&(c=c.slice(0,t.HTTP_BODY_MAX_LENGTH),u=!0),(l.headers()["content-type"]||"").includes("application/json")&&!u)try{c=JSON.stringify(JSON.parse(c),null,2),c.length>t.HTTP_BODY_MAX_LENGTH&&(c=c.slice(0,t.HTTP_BODY_MAX_LENGTH),u=!0)}catch{}return{...await this.captureState(e),metadata:{httpResponse:{status:l.status(),statusText:l.statusText(),headers:l.headers(),body:c,...u&&{truncated:!0}}}}}catch(o){return{...await this.captureState(e),metadata:{error:`HTTP request failed: ${o.message}`}}}}static RUN_JS_INPUT_MAX_LENGTH=4e3;static RUN_JS_RESULT_MAX_LENGTH=5e3;static RUN_JS_TIMEOUT_MS=1e4;async runJs(e,n){if(n.length>t.RUN_JS_INPUT_MAX_LENGTH)return{...await this.captureState(e),metadata:{error:`run_js code exceeded ${t.RUN_JS_INPUT_MAX_LENGTH}-char cap (${n.length} chars).`}};let r=`(async () => {
|
|
1997
|
+
`,document.body.appendChild(a)),a.style.left=`${s}px`,a.style.top=`${i}px`},{x:n,y:r})}catch{}}getSuggestedSampleFiles(e,n){return[]}async ensureBrowser(){if(!this.browser){console.log("[BasePlaywright] Launching browser");let e=performance.now();this.browser=await this.launchBrowser();let n=Math.round(performance.now()-e);console.log(`[BasePlaywright] Browser launched in ${n}ms`),this.browser.on("disconnected",()=>{console.log("[BasePlaywright] Browser disconnected"),this.browser=null,this.sessions.clear(),this.onBrowserDisconnected?.()})}return this.browser}async ensureSession(e,n){if(this.sessions.has(e))return this.sessions.get(e);e.includes(":child-")||await this.cleanupOtherSessions(e);let r=await this.createSession(e,n);return this.sessions.set(e,r),r}async invoke(e){let n=await this.ensureSession(e.sessionId,e.config);n.lastInvokeAt=Date.now(),n.browserNavigationScope=Array.isArray(e.config?.browserNavigationScope)?e.config.browserNavigationScope.map(String):void 0,n.allowExternalNavigation=!!e.config?.allowExternalNavigation,n.testingEmailPolicy=jt(e.config)??void 0,n.isTestPlanReplay=!!e.config?.isTestPlanReplay;let r=e.config?.loginCredentialEmails;n.loginCredentialEmails=Array.isArray(r)?r.map(String):void 0;let s=cM(e.config);s&&(n.appUnderTestOrigin=s);let i=e.args??{};n.currentStepText=typeof i.stepText=="string"?i.stepText:void 0;let a=performance.now(),o,l,c=this.safeCurrentUrl(n);try{let d=await this.dispatch(n,e.action,i);d=this.withSessionMetadata(n,d);let f=Math.round(performance.now()-a);if(console.log(`[BasePlaywright] ${e.action} completed in ${f}ms`),n.tab2||n.isExtensionSession){let h=n.tab1&&!n.tab1.isClosed(),p=n.tab2&&!n.tab2.isClosed(),g=[];h&&g.push(n.tab1.url()),p&&g.push(n.tab2.url()),d={...d,metadata:{activeTab:n.activeTab,tabCount:(h?1:0)+(p?1:0),tabUrls:g,...n.pendingExtensionPopup?{pendingExtensionPopup:!0}:{},...d.metadata}},n.pendingExtensionPopup=!1}o={screenshot:d.screenshot.toString("base64"),url:d.url,aiSnapshot:d.aiSnapshot,domChanges:d.domChanges,metadata:d.metadata,canvasDominant:d.canvasDominant,snapshotKind:d.snapshotKind,captureMode:d.captureMode},l=n.page}catch(d){let f=String(d?.message||"");if(d instanceof ir)throw d;if(d instanceof cc){let h=this.withSessionMetadata(n,await this.captureState(n));o={screenshot:h.screenshot.toString("base64"),url:h.url,aiSnapshot:h.aiSnapshot,metadata:{...h.metadata,error:`${d.message}. Re-emit ${d.action} with valid normalized integer coordinates (x and y each between 0 and 1000), or target the element by its "label" or "ref" instead.`},canvasDominant:h.canvasDominant,snapshotKind:h.snapshotKind},l=n.page}else if(f.includes("Execution context was destroyed")||f.includes("most likely because of a navigation")||f.includes("navigation")){console.log(`[BasePlaywright] Navigation detected during ${e.action}, recovering`),n.needsFullSnapshot=!0;try{await n.page.waitForLoadState("load",{timeout:5e3})}catch{}let h=await this.captureState(n),p=this.withSessionMetadata(n,h);o={screenshot:p.screenshot.toString("base64"),url:p.url,aiSnapshot:p.aiSnapshot,metadata:p.metadata,canvasDominant:p.canvasDominant,snapshotKind:p.snapshotKind},l=n.page}else if(f.includes("Browser session closed")||f.includes("Target closed")||f.includes("has been closed")||f.includes("Page crashed")){console.log(`[BasePlaywright] Session closed for ${e.sessionId}, recreating`),this.sessions.delete(e.sessionId);try{let h=await this.ensureSession(e.sessionId,e.config),p=this.withSessionMetadata(h,await this.dispatch(h,e.action,i));o={screenshot:p.screenshot.toString("base64"),url:p.url,aiSnapshot:p.aiSnapshot,metadata:p.metadata,canvasDominant:p.canvasDominant,snapshotKind:p.snapshotKind},l=h.page}catch(h){console.error("[BasePlaywright] Retry after session recreation failed:",h);let p=h instanceof Error?h.message:String(h);throw new Error(`Browser session recovery failed: ${p}`)}}else throw d}let u=await this.containPendingPopupEscapes(n);if(u)o=u;else if(e.action!=="navigate"&&l){this.maybeAnchorAppUnderTestOrigin(n,o.url);let d=await this.containCrossEnvironmentAfterAction(n,l,o);d?o=d:(await this.assertNoCloudflareBlockAfterCrossOriginNav(l,c,o.url),await this.assertNoCaptchaGate(n,l,e.action,i,c,o.url),await this.assertNoCredentialRejection(n,l,e.action,i,o.url),await this.assertNoThirdPartyIdpLogin(n,e.action,i,o.url))}return o.metadata={...o.metadata??{},events:this.buildAndResetDigest(l)},o}buildAndResetDigest(e){let n=e?lc.get(e):void 0;if(!n)return{consoleErrors:[],pageErrors:[],failedRequests:[],pendingRequests:[],recentWrites:[]};let r=Date.now(),s={consoleErrors:n.rollingConsoleErrors.slice(),pageErrors:n.rollingPageErrors.slice(),failedRequests:n.rollingFailedRequests.slice(),pendingRequests:Array.from(n.pendingWrites).map(i=>({url:i.url,method:i.method,ageMs:r-i.startTs})),recentWrites:n.rollingRecentWrites.slice()};return n.rollingConsoleErrors=[],n.rollingPageErrors=[],n.rollingFailedRequests=[],n.rollingRecentWrites=[],s}async readFocusedFieldValue(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)return n.value;if(n instanceof HTMLElement&&n.isContentEditable)return n.textContent??""})}catch{return}}async getFocusedElementFingerprint(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(!n||n===document.body)return;let r=d=>(d??"").replace(/\s+/g," ").trim(),s=n.tagName.toLowerCase(),i=n instanceof HTMLInputElement?n.type:"",a=n.id||"",o=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?n.name:"",l=r(n.getAttribute("aria-label")),c=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?r(n.placeholder):"",u="";return(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&(u=r(n.labels?.[0]?.textContent)),!u&&a&&(u=r(document.querySelector(`label[for="${CSS.escape(a)}"]`)?.textContent)),[s,i,a,o,l,c,u].join("|")})}catch{return}}async getFocusedFieldName(e){try{return await e.evaluate(()=>{let n=document.activeElement;if(!n||n===document.body)return;let r=u=>{let d=[];for(let f of Array.from(u.childNodes))if(f.nodeType===Node.TEXT_NODE){let h=f.textContent?.trim();h&&d.push(h)}else if(f instanceof HTMLElement&&!s(f)){let h=f.innerText?.trim();h&&d.push(h)}return d.join(" ").replace(/\s+/g," ").trim()},s=u=>u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement||u.isContentEditable,i=n.getAttribute("aria-label");if(i)return i;let a=n.getAttribute("aria-labelledby");if(a){let u=a.split(/\s+/).map(d=>document.getElementById(d)?.textContent?.trim()).filter(Boolean).join(" ");if(u)return u}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){let u=n.labels?.[0]?.textContent?.trim();if(u)return u}let o=n.id;if(o){let u=document.querySelector(`label[for="${o}"]`);if(u)return u.textContent?.trim()}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement){if(n.placeholder)return n.placeholder;if(n.name)return n.name}let l=n.previousElementSibling;for(;l;){let u=l instanceof HTMLElement?l.innerText?.trim():void 0;if(u)return u;l=l.previousElementSibling}let c=n.parentElement;for(let u=0;c&&u<3;u+=1,c=c.parentElement){let d=r(c);if(d)return d}})}catch{return}}async awaitPageReady(e){return e.waitForLoadState("domcontentloaded",{timeout:5e3}).then(()=>!0).catch(()=>!1)}dialogsAcceptedOn(e){return pM(e)}async probeClickEffect(e,n,r,s){let i=Ic();if(i==="off"||i==="shadow"&&!this.diagLog)return null;if(e.lastCaptureCanvasDominant)return this.diagLog?.(e.sessionId,"click_effect:probe_skipped",{reason:"canvas-memo",url:this.safeCurrentUrl(e)??""}),null;let a=null;try{let o=await qn.waitForMutation(n,{timeoutMs:Tc});o&&(a={count:o.count,attrCount:o.attrCount})}catch{a=null}return{mutationCount:a?.count??null,attrCount:a?.attrCount??null,urlBefore:r??"",urlAfter:this.safeCurrentUrl(e)??"",dialogsBefore:s,dialogsAfter:pM(n)}}resolveClickEffect(e,n,r){if(!n)return{};let s=Xv(n,r),i=Ic()==="enforce";return s.effectObserved===!1&&this.diagLog?.(e.sessionId,i?"click_effect:signaled":"click_effect:would_signal",{url:n.urlAfter,clickPath:r.clickPath,settleMs:Tc,mutationCount:n.mutationCount,attrCount:n.attrCount,targetTag:r.target?.tag??null,targetRole:r.target?.role??null,canvasDominant:r.canvasDominant===!0,suppressedBy:s.suppressedBy??null,advisoryEmitted:i&&!!s.note}),i?s:{}}async screenshotWithSlowSiteRetry(e,n={}){let{page:r}=e,s=(e.screenshotCount??0)===0,i=15e3,a=25e3,l={type:"png",timeout:s?i:5e3};n.fullPage&&(l.fullPage=!0);try{let c=await r.screenshot(l);return e.screenshotCount=(e.screenshotCount??0)+1,c}catch(c){if(!s||!pi(c))throw c;let u=r.url();this.diagLog?.(e.sessionId,"screenshot_first_timeout_retry",{url:u,firstTimeoutMs:i,retryTimeoutMs:a}),this.reportStartupNavigate(e,"slow_site_retry",{url:u,firstTimeoutMs:i,retryTimeoutMs:a});let d={type:"png",timeout:a};n.fullPage&&(d.fullPage=!0);try{let f=await r.screenshot(d);return e.screenshotCount=(e.screenshotCount??0)+1,this.diagLog?.(e.sessionId,"screenshot_first_retry_success",{url:u}),f}catch(f){throw pi(f)?(this.reportStartupNavigate(e,"slow_site_error",{url:u,totalTimeoutMs:i+a,attemptCount:2}),new Cr({url:u,totalTimeoutMs:i+a,attemptCount:2})):f}}}async captureState(e,n={}){let{page:r}=e;e.expectDomQuiescence&&!process.env.AQ_NO_DOM_OBSERVER&&!process.env.AQ_NO_DOM_DELAY&&await qn.waitForQuiescence(r,{minQuietMs:100,maxMs:800});let s,i=!1;try{s=await this.screenshotWithSlowSiteRetry(e)}catch(d){if(n.onScreenshotTimeout!=="degrade"||!pi(d))throw d;let f=await this.captureOracleScreenshotResilient(e);f?s=f:(s=PZ,i=!0)}let a=r.url(),o,l;try{let d=await r._snapshotForAI({track:e.sessionId+":"+e.activeTab}),f=typeof d=="string"?d:d?.full,h=typeof d=="object"?d?.incremental:void 0;!e.needsFullSnapshot&&h?(o=h,l="incremental"):(o=f,e.needsFullSnapshot=!1,l=f!=null?"full":void 0)}catch{o=void 0,e.needsFullSnapshot=!0}let c=process.env.AQ_NO_DOM_OBSERVER?void 0:await qn.flush(r)??void 0,u=await this.computeCanvasDominant(e);return e.lastCaptureCanvasDominant=u,{screenshot:s,url:a,aiSnapshot:o,domChanges:c,canvasDominant:u,snapshotKind:l,...i&&{metadata:{note:OZ}}}}async captureOracleScreenshotResilient(e){let{page:n}=e;for(let r=1;r<=oM;r++)try{let s=await n.screenshot({type:"png",timeout:Jy});return e.screenshotCount=(e.screenshotCount??0)+1,this.diagLog?.(e.sessionId,"wait_oracle_screenshot_retry_success",{attempt:r,timeoutMs:Jy}),s}catch(s){if(!pi(s))throw s;this.diagLog?.(e.sessionId,"wait_oracle_screenshot_timeout",{attempt:r,attempts:oM,timeoutMs:Jy})}return null}async computeCanvasDominant(e){try{return await e.page.evaluate(()=>{let n=window.innerWidth,r=window.innerHeight,s=n*r;if(s<=0)return!1;let i=0;for(let a of Array.from(document.querySelectorAll("canvas"))){let o=window.getComputedStyle(a);if(o.display==="none"||o.visibility==="hidden"||o.opacity==="0"||o.pointerEvents==="none"||a.closest('[aria-hidden="true"]'))continue;let l=a.getBoundingClientRect(),c=Math.max(0,l.left),u=Math.max(0,l.top),d=Math.min(n,l.right),f=Math.min(r,l.bottom),h=d-c,p=f-u;h>0&&p>0&&(i+=h*p)}return Math.min(i/s,1)>=.4})}catch{return!1}}withSessionMetadata(e,n){return e.httpsCertFallback?{...n,metadata:{...n.metadata??{},httpsCertFallback:e.httpsCertFallback}}:n}shouldResetDomObserverBeforeAction(e){return!new Set(["open_web_browser","screenshot","snapshot","wait","wait_5_seconds","wait_for_element","full_page_screenshot","run_js"]).has(e)}shouldWaitForDomQuiescenceAfterAction(e){return this.shouldResetDomObserverBeforeAction(e)}async dispatch(e,n,r){let s=await this.dispatchPlatformAction(e,n,r);if(s)return s;let i=r?.fullSnapshot===!0,a=e.needsFullSnapshot;i&&(e.needsFullSnapshot=!0);let{viewportWidth:o,viewportHeight:l}=e,c=h=>Math.floor(h/1e3*o),u=h=>Math.floor(h/1e3*l),d=!process.env.AQ_NO_DOM_OBSERVER&&this.shouldResetDomObserverBeforeAction(n),f=e.expectDomQuiescence;d&&await qn.reset(e.page),e.expectDomQuiescence=this.shouldWaitForDomQuiescenceAfterAction(n);try{switch(n){case"open_web_browser":case"screenshot":return await this.captureState(e);case"snapshot":return e.needsFullSnapshot=!0,await this.captureState(e);case"click_at":{let h=Array.isArray(r.modifiers)?r.modifiers.map(String):[];if(r.label)return await this.clickByLabel(e,String(r.label),h);if(r.ref)return await this.clickByRef(e,String(r.ref),h);let p=this.requireNormalizedPoint(n,r);return await this.clickAt(e,c(p.x),u(p.y),h)}case"double_click_at":{let h=Array.isArray(r.modifiers)?r.modifiers.map(String):[];if(r.label)return await this.clickByLabel(e,String(r.label),h,2);if(r.ref)return await this.clickByRef(e,String(r.ref),h,2);let p=this.requireNormalizedPoint(n,r);return await this.clickAt(e,c(p.x),u(p.y),h,2)}case"right_click_at":{if(r.ref)return await this.rightClickByRef(e,String(r.ref));let h=this.requireNormalizedPoint(n,r);return await this.rightClickAt(e,c(h.x),u(h.y))}case"hover_at":{if(r.ref)return await this.hoverByRef(e,String(r.ref));let h=this.requireNormalizedPoint(n,r);return await this.hoverAt(e,c(h.x),u(h.y))}case"type_text_at":{let h=r.clearBeforeTyping??r.clear_before_typing??!0;if(r.label)return await this.typeByLabel(e,String(r.label),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h);if(r.ref)return await this.typeByRef(e,String(r.ref),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h);let p=this.requireNormalizedPoint(n,r);return await this.typeTextAt(e,c(p.x),u(p.y),String(r.text??""),!!(r.pressEnter??r.press_enter??!1),h)}case"scroll_document":return await this.scrollDocument(e,String(r.direction));case"scroll_to_bottom":return await this.scrollToBottom(e);case"scroll_at":{let h=String(r.direction),p=r.magnitude!=null?Number(r.magnitude):800;if(h==="up"||h==="down"?p=u(p):(h==="left"||h==="right")&&(p=c(p)),r.ref){let m=await this.resolveRefCenter(e,String(r.ref));return m?await this.scrollAt(e,m.x,m.y,h,p):await this.refNotFoundError(e,String(r.ref))}let g=this.requireNormalizedPoint(n,r);return await this.scrollAt(e,c(g.x),u(g.y),h,p)}case"wait":return await this.waitSeconds(e,Number(r.seconds||2));case"wait_for_element":return await this.waitForElement(e,String(r.textContent??""),Number(r.timeoutSeconds||5));case"wait_5_seconds":return await this.waitSeconds(e,5);case"full_page_screenshot":return await this.fullPageScreenshot(e);case"switch_layout":{let h=Number(r.width),p=Number(r.height);return e.viewportWidth=h,e.viewportHeight=p,await this.switchLayout(e,h,p)}case"go_back":return await this.goBack(e);case"go_forward":return await this.goForward(e);case"navigate":{let h=String(r.url??r.href??"");if(e.isExtensionSession){if(h.startsWith("chrome-extension://")){if(e.tab1&&!e.tab1.isClosed())await e.tab1.goto(h),await this.awaitPageReady(e.tab1);else{let p=await e.context.newPage();Tp(p),await p.goto(h),await this.awaitPageReady(p)}return e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0,await e.page.bringToFront()),await this.captureState(e)}e.tab2&&!e.tab2.isClosed()&&(e.page=e.tab2,e.activeTab="tab2")}else e.activeTab==="tab2"&&e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0);return await this.navigate(e,h)}case"key_combination":return await this.keyCombination(e,Array.isArray(r.keys)?r.keys.map(String):[]);case"set_focused_input_value":return await this.setFocusedInputValue(e,String(r.value??""),typeof r.expectedElementFingerprint=="string"?r.expectedElementFingerprint:void 0);case"drag_and_drop":{let h,p;if(r.ref){let S=await this.resolveRefCenter(e,String(r.ref));if(!S)return await this.refNotFoundError(e,String(r.ref));h=S.x,p=S.y}else{let S=this.requireNormalizedPoint(n,r);h=c(S.x),p=u(S.y)}let g,m;if(r.destinationRef){let S=await this.resolveRefCenter(e,String(r.destinationRef));if(!S)return await this.refNotFoundError(e,String(r.destinationRef));g=S.x,m=S.y}else{let S=this.requireNormalizedPoint(n,r,r.destinationX!==void 0?"destinationX":"destination_x",r.destinationY!==void 0?"destinationY":"destination_y");g=c(S.x),m=u(S.y)}return await this.dragAndDrop(e,h,p,g,m)}case"upload_file":{let h=Array.isArray(r.filePaths)?r.filePaths.map(String):[String(r.filePaths??"")];return await this.uploadFile(e,h,{clearStaleMarker:r.clearStaleMarker===!0})}case"http_request":return await this.httpRequest(e,String(r.url??""),String(r.method??"GET"),r.headers,r.body!=null?String(r.body):void 0);case"run_js":return await this.runJs(e,String(r.code??""));case"switch_tab":{let h=String(r.tab??"tab1"),p=h==="main"?"tab1":h==="extension"?"tab2":h;return await this.switchTab(e,p)}case"close_tab":return await this.closeTab(e);default:return console.warn(`[BasePlaywright] Unsupported action: ${n}`),await this.captureState(e)}}finally{e.expectDomQuiescence=f,i&&e.needsFullSnapshot&&(e.needsFullSnapshot=a)}}async clickAt(e,n,r,s=[],i=1){let{page:a}=e,o=this.safeCurrentUrl(e);try{await a.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}await this.onBeforeAction(e,n,r);let l={isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:null,clickTarget:null},c=uM();try{let T=await a.evaluateHandle(P=>document.elementFromPoint(P.x,P.y),{x:n,y:r}),R=T.asElement(),O=R?await R.evaluate(hM,{captureAffordance:c}).catch(()=>null):null;await T.dispose().catch(()=>{}),l=await a.evaluate(P=>{let L=document.elementFromPoint(P.x,P.y);if(!L)return{isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:null,clickTarget:null};let V={tag:L.tagName.toLowerCase(),text:(L.textContent||"").trim().slice(0,80),role:L.getAttribute("role")||""},X=L.closest("a[href], area[href]"),z=null,U=L.closest("select");if(U)z=U;else if(L instanceof HTMLLabelElement&&L.htmlFor){let j=document.getElementById(L.htmlFor);j instanceof HTMLSelectElement&&(z=j)}else{let j=L instanceof HTMLLabelElement?L:L.closest("label");if(j){let K=j.querySelector("select");K&&(z=K)}}if(z){z.focus();let j=z.options[z.selectedIndex]?.textContent?.trim()||"",K=Array.from(z.options).map(Z=>Z.textContent?.trim()||Z.value);return{isSelect:!0,isMultiple:z.multiple,selectedText:j,options:K,clickedElement:null,clickTarget:null}}return{isSelect:!1,isMultiple:!1,selectedText:"",options:[],clickedElement:V,clickTarget:null,linkHref:X?.href||""}},{x:n,y:r}),l.clickTarget=O}catch(T){let R=String(T?.message||"");if(!(R.includes("Execution context was destroyed")||R.includes("navigation")))throw T}if(l.isSelect&&!l.isMultiple)return await this.awaitPageReady(a),{...await this.captureState(e),metadata:{elementType:"select",valueBefore:l.selectedText,valueAfter:l.selectedText,availableOptions:l.options,...l.clickTarget?{clickTarget:l.clickTarget}:{}}};if(l.linkHref){let T=await this.containCrossEnvironmentIfNeeded(e,l.linkHref);if(T)return T;let R=await this.blockScopedNavigationIfNeeded(e,l.linkHref);if(R)return R}let u=null,d=!1;if(QP()&&!l.linkHref){let T=await this.resolveInteractiveDescendantAtPoint(a,n,r,Gy);if(T.status==="retarget"){if(T.final.linkHref){let R=await this.containCrossEnvironmentIfNeeded(e,T.final.linkHref);if(R)return R;let O=await this.blockScopedNavigationIfNeeded(e,T.final.linkHref);if(O)return O}u=T}else T.status==="none"&&(d=!0)}let f=c&&u===null&&l.clickTarget&&!il(l.clickTarget)?l.clickTarget.affordance:void 0;f&&(f.directListener=await this.probeDirectClickListener(e,n,r));let h=a.waitForEvent("filechooser",{timeout:150}).catch(()=>null),p=a.waitForEvent("download",{timeout:500}).catch(()=>null);await qn.reset(a);let g=this.dialogsAcceptedOn(a);if(u){let T=a.locator(`[data-agentiqa-click-target="${u.marker}"]`).first(),R=s.map(P=>P).filter(Boolean),O={force:!0,timeout:3e3,modifiers:R.length?R:void 0};i>1?await T.dblclick(O):await T.click(O)}else{for(let T of s)await a.keyboard.down(T);await a.mouse.click(n,r,{clickCount:i});for(let T of s)await a.keyboard.up(T)}let m=await h;if(m){let R=await m.element().evaluate(L=>{let V=L;return document.querySelectorAll("[data-agentiqa-file-target]").forEach(X=>X.removeAttribute("data-agentiqa-file-target")),V.setAttribute("data-agentiqa-file-target","true"),V instanceof HTMLInputElement?{accept:V.accept||"*",multiple:V.multiple}:{accept:"*",multiple:!1}}),O=this.getSuggestedSampleFiles(R.accept,R.multiple);return console.log(`[BasePlaywright] FILE CHOOSER INTERCEPTED: accept="${R.accept}", multiple=${R.multiple}`),{...await this.captureState(e),metadata:{elementType:"file",accept:R.accept,multiple:R.multiple,suggestedFiles:O}}}let S=await p;if(S){let T=S.suggestedFilename(),R=S.url();console.log(`[BasePlaywright] DOWNLOAD INTERCEPTED: "${T}" from ${R}`),await S.cancel();try{await a.goBack({waitUntil:"domcontentloaded",timeout:5e3})}catch{}return{...await this.captureState(e),metadata:{elementType:"download",downloadFilename:T,downloadUrl:R,clickedElement:l.clickedElement??void 0,clickTarget:l.clickTarget??void 0}}}await this.awaitPageReady(a);let E=null;if(d){let T=await qn.peek(a);E={count:T.count,attrCount:T.attrCount}}let v=await this.probeClickEffect(e,a,o,g),x=await this.captureState(e),b;if(u){let T=l.clickTarget?{...l.clickTarget}:{tag:u.original.tag,text:u.original.text,role:"",accessibleName:"",disabled:!1,nativeDisabled:!1,ariaDisabled:!1,inert:!1};delete T.affordance,b={...T,retargeted:!0,retargetedFrom:u.original,retargetedTo:u.final}}else b=l.clickTarget??void 0;let _=E!=null&&E.count===0&&E.attrCount===0&&x.url===o,w;_&&!x.canvasDominant&&(w='This click did not produce a visible change within the brief capture window: the DOM, text, and URL are all unchanged. It may have landed on empty space or a non-interactive area, or an effect may still be pending. If the interface did not change as you intended, target the control by its "label" or "ref" from the latest snapshot, or try different coordinates.');let A=this.resolveClickEffect(e,v,{canvasDominant:x.canvasDominant,suppressAdvisory:!!w,target:b?.retargetedTo??b,clickPath:u?"retarget":"coordinate"});!w&&A.note&&(w=A.note);let k={...l.clickedElement?{clickedElement:l.clickedElement}:{},...b?{clickTarget:b}:{},...w?{note:w}:{},..._?{noObservedEffect:!0}:{},...A.effectObserved!==void 0?{effectObserved:A.effectObserved}:{}};return Object.keys(k).length>0?{...x,metadata:k}:x}async resolveInteractiveDescendantAtPoint(e,n,r,s){let i;try{i=await e.evaluate(({x:u,y:d,descendSelector:f,pointSelector:h})=>{let p=document.elementFromPoint(u,d);if(!p)return{status:"none"};if(p.closest(h))return{status:"interactive"};let g=E=>{let v=window.getComputedStyle(E);if(v.display==="none"||v.visibility==="hidden")return!1;let x=E.getBoundingClientRect();return x.width>0&&x.height>0},S=Array.from(p.querySelectorAll(f)).filter(g).map((E,v)=>{E.setAttribute("data-agentiqa-descend-idx",String(v));let x=E.getBoundingClientRect(),b=E.closest("a[href], area[href]");return{index:v,rect:{left:x.left,top:x.top,right:x.right,bottom:x.bottom,width:x.width,height:x.height},tag:E.tagName.toLowerCase(),text:(E.textContent||"").trim().slice(0,80),role:E.getAttribute("role")||"",linkHref:b?.href||void 0}});return{status:"candidates",original:{tag:p.tagName.toLowerCase(),text:(p.textContent||"").trim().slice(0,80)},candidates:S}},{x:n,y:r,descendSelector:Hy,pointSelector:JP})}catch{return{status:"none"}}if(i.status!=="candidates")return i;let a=XP(i.candidates,{x:n,y:r},s);if(!a)return await e.evaluate(()=>{document.querySelectorAll("[data-agentiqa-descend-idx]").forEach(u=>u.removeAttribute("data-agentiqa-descend-idx"))}).catch(()=>{}),{status:"none"};let o=i.candidates[a.index],l=`agentiqa_click_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return await e.evaluate(({index:u,marker:d})=>{let f=document.querySelector(`[data-agentiqa-descend-idx="${u}"]`);return document.querySelectorAll("[data-agentiqa-descend-idx]").forEach(h=>h.removeAttribute("data-agentiqa-descend-idx")),f?(document.querySelectorAll("[data-agentiqa-click-target]").forEach(h=>h.removeAttribute("data-agentiqa-click-target")),f.setAttribute("data-agentiqa-click-target",d),!0):!1},{index:a.index,marker:l}).catch(()=>!1)?{status:"retarget",marker:l,original:i.original,final:{tag:o.tag,text:o.text,role:o.role,linkHref:o.linkHref}}:{status:"none"}}async getAffordanceCdpSession(e){let n=e.page;if(e.affordanceCdpSession&&e.affordanceCdpSessionPage===n)return e.affordanceCdpSession;this.invalidateAffordanceCdpSession(e);let r=await n.context().newCDPSession(n);return e.affordanceCdpSession=r,e.affordanceCdpSessionPage=n,r}invalidateAffordanceCdpSession(e){let n=e.affordanceCdpSession;e.affordanceCdpSession=void 0,e.affordanceCdpSessionPage=void 0,n&&n.detach?.().catch(()=>{})}async probeDirectClickListener(e,n,r){let{page:s}=e,i="data-agentiqa-affordance-probe",a=!1;try{if(a=await s.evaluate(({px:u,py:d,attr:f})=>{let h=document.elementFromPoint(u,d);return h?(h.setAttribute(f,"1"),!0):!1},{px:n,py:r,attr:i}),!a)return null;let o=await this.getAffordanceCdpSession(e),l;try{l=await o.send("Runtime.evaluate",{expression:`document.querySelector('[${i}]')`,returnByValue:!1})}catch{return this.invalidateAffordanceCdpSession(e),null}let c=l?.result?.objectId;if(!c)return null;try{let u=await o.send("DOMDebugger.getEventListeners",{objectId:c,depth:0});return(Array.isArray(u?.listeners)?u.listeners:[]).some(f=>f?.type==="click")}catch{return this.invalidateAffordanceCdpSession(e),null}finally{await o.send("Runtime.releaseObject",{objectId:c}).catch(()=>{})}}catch{return null}finally{a&&await s.evaluate(o=>{document.querySelector(`[${o}]`)?.removeAttribute(o)},i).catch(()=>{})}}async clickByRef(e,n,r=[],s=1){let{page:i}=e,a=3e3,o=this.safeCurrentUrl(e);try{await i.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let l=i.locator(`aria-ref=${n}`),c=await l.boundingBox({timeout:a});c&&await this.onBeforeAction(e,c.x+c.width/2,c.y+c.height/2);let u=await l.evaluate(k=>({tag:k.tagName.toLowerCase(),text:(k.textContent||"").trim().slice(0,80),role:k.getAttribute("role")||"",linkHref:k.closest("a[href], area[href]")?.href})).catch(()=>null),d=await l.evaluate(hM,{captureAffordance:uM()}).catch(()=>null),f=await l.evaluate(k=>{let T=k instanceof HTMLSelectElement?k:k.closest("select");if(!T)return null;T.focus();let R=T.options[T.selectedIndex]?.textContent?.trim()||"",O=Array.from(T.options).map(P=>P.textContent?.trim()||P.value);return{selectedText:R,options:O,isMultiple:T.multiple}}).catch(()=>null);if(f&&!f.isMultiple)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:f.selectedText,valueAfter:f.selectedText,availableOptions:f.options,...d?{clickTarget:d}:{}}};if(u?.linkHref){let k=await this.containCrossEnvironmentIfNeeded(e,u.linkHref);if(k)return k;let T=await this.blockScopedNavigationIfNeeded(e,u.linkHref);if(T)return T}let h=i.waitForEvent("filechooser",{timeout:500}).catch(()=>null),p=i.waitForEvent("download",{timeout:500}).catch(()=>null),g=r.map(k=>k).filter(Boolean);await qn.reset(i);let m=this.dialogsAcceptedOn(i),S={force:!0,timeout:a,modifiers:g.length?g:void 0};s>1?await l.dblclick(S):await l.click(S);let E=await h;if(E){let T=await E.element().evaluate(P=>{let L=P;return document.querySelectorAll("[data-agentiqa-file-target]").forEach(V=>V.removeAttribute("data-agentiqa-file-target")),L.setAttribute("data-agentiqa-file-target","true"),L instanceof HTMLInputElement?{accept:L.accept||"*",multiple:L.multiple}:{accept:"*",multiple:!1}}),R=this.getSuggestedSampleFiles(T.accept,T.multiple);return console.log(`[BasePlaywright] FILE CHOOSER INTERCEPTED via ref=${n}: accept="${T.accept}"`),{...await this.captureState(e),metadata:{elementType:"file",accept:T.accept,multiple:T.multiple,suggestedFiles:R}}}let v=await p;if(v){let k=v.suggestedFilename(),T=v.url();console.log(`[BasePlaywright] DOWNLOAD INTERCEPTED via ref=${n}: "${k}" from ${T}`),await v.cancel();try{await i.goBack({waitUntil:"domcontentloaded",timeout:5e3})}catch{}return{...await this.captureState(e),metadata:{elementType:"download",downloadFilename:k,downloadUrl:T,clickedElement:u??void 0,clickTarget:d??void 0}}}await this.awaitPageReady(i);let x=await this.probeClickEffect(e,i,o,m),b=await this.captureState(e),_=this.resolveClickEffect(e,x,{canvasDominant:b.canvasDominant,target:u??d,clickPath:"ref"}),w=_.effectObserved!==void 0||_.note!==void 0,A=_.note?b.metadata?.note?`${b.metadata.note} ${_.note}`:_.note:b.metadata?.note;return u||d||w?{...b,metadata:{...b.metadata,...u?{clickedElement:u}:{},...d?{clickTarget:d}:{},...A?{note:A}:{},..._.effectObserved!==void 0?{effectObserved:_.effectObserved}:{}}}:b}catch(l){console.warn(`[BasePlaywright] clickByRef ref=${n} failed: ${l.message}`);let c=await this.captureState(e),d=(l.message??"").includes("intercepts pointer events")?`Ref "${n}" is covered by another element (overlay/popup). Dismiss the overlay first, or try a different ref.`:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`;return{...c,metadata:{error:d}}}}async resolveClickableByLabel(e,n){return await e.evaluate(({requestedLabel:r,selector:s})=>{let i=v=>v.replace(/\s+/g," ").trim().replace(/[?:.!]+$/,"").toLowerCase(),a=v=>i(v).replace(/[\s:_-]+/g,""),o=i(r),l=a(r),c=(v,x)=>!!x&&v.startsWith(x)&&(v.length===x.length||/[\s:>/-]/.test(v.charAt(x.length))),u=v=>{let x=i(v);return x?x===o?0:a(v)===l?1:c(x,o)||c(o,x)?2:null:null},d=v=>{let x=window.getComputedStyle(v);if(x.display==="none"||x.visibility==="hidden")return!1;let b=v.getBoundingClientRect();return b.width>0&&b.height>0},f=v=>{let x=v.getAttribute("aria-label");if(x&&x.trim())return x.trim();let b=v.getAttribute("aria-labelledby");if(b){let A=b.split(/\s+/).map(k=>document.getElementById(k)?.textContent?.trim()).filter(Boolean).join(" ");if(A)return A}if(v instanceof HTMLInputElement&&(v.type==="submit"||v.type==="button"||v.type==="reset")&&v.value&&v.value.trim())return v.value.trim();let _=(v.innerText||v.textContent||"").trim();if(_)return _;let w=v.getAttribute("title");return w&&w.trim()?w.trim():""},h=Array.from(document.querySelectorAll(s)).filter(v=>d(v)),p=[];for(let v of h){let x=f(v),b=u(x);b!=null&&p.push({element:v,name:x,rank:b})}if(p.length===0)return{status:"none"};p.sort((v,x)=>v.rank-x.rank);let g=p[0].rank,m=p.filter(v=>v.rank===g);if(Array.from(new Set(m.map(v=>v.element))).length>1)return{status:"ambiguous",matches:m.slice(0,5).map(v=>v.name)};let E=`agentiqa_click_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return document.querySelectorAll("[data-agentiqa-click-target]").forEach(v=>v.removeAttribute("data-agentiqa-click-target")),m[0].element.setAttribute("data-agentiqa-click-target",E),{status:"ok",marker:E,matchedName:m[0].name}},{requestedLabel:n,selector:Hy})}async clickByLabel(e,n,r=[],s=1){let{page:i}=e,a=3e3,o=s>1?"Double-click":"Click",l=this.safeCurrentUrl(e);try{await i.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}let c=await this.resolveClickableByLabel(i,n);if(c.status!=="ok"){let u=await this.captureState(e),d=c.status==="ambiguous"?`More than one control is named "${n}" (${(c.matches||[]).join(", ")}). ${o} by ref from the latest snapshot, or use a more specific name.`:`No clickable control named "${n}" was found on the page. Check the latest snapshot and ${o.toLowerCase()} by ref, or use coordinates.`;return{...u,metadata:{...u.metadata,note:d}}}try{let u=i.locator(`[data-agentiqa-click-target="${c.marker}"]`).first(),d=await u.boundingBox({timeout:a});d&&await this.onBeforeAction(e,d.x+d.width/2,d.y+d.height/2);let f=await u.evaluate(b=>({tag:b.tagName.toLowerCase(),text:(b.textContent||"").trim().slice(0,80),role:b.getAttribute("role")||"",linkHref:b.closest("a[href], area[href]")?.href})).catch(()=>null);if(f?.linkHref){let b=await this.containCrossEnvironmentIfNeeded(e,f.linkHref);if(b)return b;let _=await this.blockScopedNavigationIfNeeded(e,f.linkHref);if(_)return _}let h=r.map(b=>b).filter(Boolean);await qn.reset(i);let p=this.dialogsAcceptedOn(i),g={force:!0,timeout:a,modifiers:h.length?h:void 0};s>1?await u.dblclick(g):await u.click(g),await this.awaitPageReady(i);let m=await this.probeClickEffect(e,i,l,p),S=await this.captureState(e),E=this.resolveClickEffect(e,m,{canvasDominant:S.canvasDominant,target:f,clickPath:"label"}),v=E.effectObserved!==void 0||E.note!==void 0,x=E.note?S.metadata?.note?`${S.metadata.note} ${E.note}`:E.note:S.metadata?.note;return f||v?{...S,metadata:{...S.metadata,...f?{clickedElement:f}:{},...x?{note:x}:{},...E.effectObserved!==void 0?{effectObserved:E.effectObserved}:{}}}:S}catch(u){let d=await this.captureState(e);return{...d,metadata:{...d.metadata,note:`Could not ${o.toLowerCase()} "${n}": ${u?.message??"unknown error"}. Try ${o.toLowerCase()}ing by ref from the latest snapshot.`}}}}async rightClickAt(e,n,r){let{page:s}=e;try{await s.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}return await this.onBeforeAction(e,n,r),await s.mouse.click(n,r,{button:"right"}),await this.awaitPageReady(s),await this.captureState(e)}async rightClickByRef(e,n){let{page:r}=e,s=3e3;try{await r.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let i=r.locator(`aria-ref=${n}`),a=await i.boundingBox({timeout:s});return a&&await this.onBeforeAction(e,a.x+a.width/2,a.y+a.height/2),await i.click({button:"right",force:!0,timeout:s}),await this.awaitPageReady(r),await this.captureState(e)}catch(i){console.warn(`[BasePlaywright] rightClickByRef ref=${n} failed: ${i.message}`);let a=await this.captureState(e),l=(i.message??"").includes("intercepts pointer events")?`Ref "${n}" is covered by another element (overlay/popup). Dismiss the overlay first, or try a different ref.`:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`;return{...a,metadata:{error:l}}}}async hoverAt(e,n,r){let{page:s}=e;return await this.onBeforeAction(e,n,r),await s.mouse.move(n,r),await new Promise(i=>setTimeout(i,300)),await this.captureState(e)}async hoverByRef(e,n){let{page:r}=e,s=3e3;try{await r.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let i=r.locator(`aria-ref=${n}`),a=await i.boundingBox({timeout:s});return a&&await this.onBeforeAction(e,a.x+a.width/2,a.y+a.height/2),await i.hover({force:!0,timeout:s}),await new Promise(o=>setTimeout(o,300)),await this.captureState(e)}catch(i){return console.warn(`[BasePlaywright] hoverByRef ref=${n} failed: ${i.message}`),{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}}async typeTextAt(e,n,r,s,i,a,o=!1){let{page:l}=e;await this.onBeforeAction(e,n,r),await l.mouse.click(n,r);let c;try{c=await l.evaluate(()=>{let T=document.activeElement;return T instanceof HTMLInputElement?{type:"input",inputType:T.type}:T instanceof HTMLTextAreaElement?{type:"textarea",inputType:"textarea"}:T instanceof HTMLSelectElement?{type:"select",inputType:"select"}:T.isContentEditable?{type:"contenteditable",inputType:"contenteditable"}:{type:"other",inputType:"none"}})}catch{console.warn("[BasePlaywright] page.evaluate blocked in typeTextAt, falling back to keyboard typing"),c={type:"input",inputType:"text"}}let u=["date","time","datetime-local","month","week"],d=c.type==="input"&&u.includes(c.inputType),h=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(c.inputType),p=nM()&&!h&&!d&&!i&&(s??"").trim()!=="",g=!1,m,S;if(p&&await this.computeCanvasDominant(e)){g=!0,await this.settleForInputHandlers(l);let T=await this.captureVerificationFrame(e);await this.settleForInputHandlers(l),S=await this.captureVerificationFrame(e),m=T&&S?zy(T,S):void 0}let E=h&&!d?await this.readFocusedFieldValue(l):void 0,v=a===!0||a==="true";if(s=this.normalizeTestingEmailForFocusedField(e,s,{inputType:c.inputType}),d){let T=!1;try{T=await l.evaluate(R=>{let O=document.activeElement;if(O instanceof HTMLInputElement){let P=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;return P?P.call(O,R):O.value=R,O.dispatchEvent(new Event("input",{bubbles:!0})),O.dispatchEvent(new Event("change",{bubbles:!0})),!0}return!1},s)}catch{}T||(v&&h&&(await l.keyboard.press("ControlOrMeta+a"),await l.keyboard.press("Backspace")),await l.keyboard.type(s,{delay:10}))}else v&&h&&(await l.keyboard.press("ControlOrMeta+a"),await l.keyboard.press("Backspace")),await Ri(l,s,10);i&&(await l.keyboard.press("Enter"),await this.awaitPageReady(l)),await this.settleForInputHandlers(l);let x=await this.getFocusedFieldName(l),b=await this.getFocusedElementFingerprint(l),_=h&&!d?await this.readFocusedFieldValue(l):void 0,w=Xy({requested:s,valueBefore:E,valueAfter:_,pressEnter:i,sensitive:o}),A=await this.captureState(e),k={...A.metadata};if(x&&(k.typedIntoField=x),b&&(k.elementFingerprint=b),k.inputType=c.inputType,!o&&E!==void 0&&(k.valueBefore=E),!o&&_!==void 0&&(k.valueAfter=_),w.valueMismatch&&(k.valueMismatch=!0,k.error=w.error),g){let T=rM(A.aiSnapshot,s),R;if(!T&&m===!0){let L=await this.captureVerificationFrame(e);S&&L&&(R=!zy(S,L))}let O=sM({requested:s,a11yConfirmed:T,boardStatic:m,frameChanged:R,pressEnter:i,sensitive:o});O.outcome==="not_found"&&(k.canvasTypeVerification=O.verification,k.error||(k.error=O.error));let P=O.outcome==="landed"?T?"landed_a11y":"landed_pixel":O.outcome==="not_found"?"text_not_found":O.outcome;this.diagLog?.(e.sessionId,"canvas_type_verify",{outcome:P,a11yConfirmed:T,boardStatic:m,frameChanged:R,textLength:(s??"").length,x:n,y:r})}return{...A,metadata:k}}async settleForInputHandlers(e){try{await e.evaluate(()=>new Promise(n=>requestAnimationFrame(()=>setTimeout(n,50))))}catch{}}async captureVerificationFrame(e){let{page:n}=e;try{return await n.screenshot({type:"png",timeout:5e3})}catch{return}}async typeByRef(e,n,r,s,i,a=!1){let{page:o}=e,l=3e3;try{await o.evaluate(()=>window.getSelection()?.removeAllRanges())}catch{}try{let c=o.locator(`aria-ref=${n}`),u=await c.boundingBox({timeout:l});u&&await this.onBeforeAction(e,u.x+u.width/2,u.y+u.height/2),await c.click({force:!0,timeout:l});let d;try{d=await o.evaluate(()=>{let A=document.activeElement;return A instanceof HTMLInputElement?{inputType:A.type}:A instanceof HTMLTextAreaElement?{inputType:"textarea"}:A.isContentEditable?{inputType:"contenteditable"}:{inputType:"none"}})}catch{console.warn(`[BasePlaywright] page.evaluate blocked for typeByRef ref=${n}, falling back to keyboard typing`),d={inputType:"text"}}let h=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(d.inputType),g=["date","time","datetime-local","month","week"].includes(d.inputType);if(!h&&!g)return{...await this.captureState(e),metadata:{error:`Ref "${n}" resolved to a non-text element (${d.inputType||"unknown"}). Use a different ref that targets the text input directly.`}};let m=i===!0||i==="true";r=this.normalizeTestingEmailForFocusedField(e,r,{inputType:d.inputType});let S=g?void 0:await this.readFocusedFieldValue(o);if(g)try{await o.evaluate(A=>{let k=document.activeElement;if(k instanceof HTMLInputElement){let T=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;T?T.call(k,A):k.value=A,k.dispatchEvent(new Event("input",{bubbles:!0})),k.dispatchEvent(new Event("change",{bubbles:!0}))}},r)}catch{await o.keyboard.type(r,{delay:15})}else m&&h?(await o.keyboard.press("ControlOrMeta+a"),r?await Ri(o,r,15):await o.keyboard.press("Backspace")):r&&await Ri(o,r,15);s&&await o.keyboard.press("Enter"),await this.awaitPageReady(o);try{await o.evaluate(()=>new Promise(A=>requestAnimationFrame(()=>setTimeout(A,50))))}catch{}let E=await this.getFocusedFieldName(o),v=await this.getFocusedElementFingerprint(o),x=g?void 0:await this.readFocusedFieldValue(o),b=g?{valueMismatch:!1}:Xy({requested:r,valueBefore:S,valueAfter:x,pressEnter:s,sensitive:a}),_=await this.captureState(e),w={..._.metadata};return E&&(w.typedIntoField=E),v&&(w.elementFingerprint=v),w.inputType=d.inputType,!a&&S!==void 0&&(w.valueBefore=S),!a&&x!==void 0&&(w.valueAfter=x),b.valueMismatch&&(w.valueMismatch=!0,w.error=b.error),{..._,metadata:w}}catch(c){return console.warn(`[BasePlaywright] typeByRef ref=${n} failed: ${c.message}`),{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}}async typeByLabel(e,n,r,s,i){let{page:a}=e,o=3e3,l=await a.evaluate(_=>{let w=D=>D.replace(/\s+/g," ").trim().replace(/:$/,"").toLowerCase(),A=D=>w(D).replace(/[\s:_-]+/g,""),k=w(_),T=A(_),R=D=>{let Y=w(D);return Y?Y===k?0:A(D)===T?1:Y.includes(k)||k.includes(Y)?2:null:null},O=D=>{let Y=window.getComputedStyle(D);if(Y.display==="none"||Y.visibility==="hidden")return!1;let B=D.getBoundingClientRect();return B.width>0&&B.height>0},P=D=>D instanceof HTMLTextAreaElement?!D.disabled:D instanceof HTMLInputElement?D.disabled||D.type==="hidden"?!1:["text","password","email","search","url","tel","number","date","time","datetime-local","month","week"].includes(D.type):D.isContentEditable,L=D=>D instanceof HTMLInputElement?`input[type=${D.type}]`:D instanceof HTMLTextAreaElement?"textarea":D.isContentEditable?"contenteditable":D.tagName.toLowerCase(),V=D=>D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement?D.value:D.isContentEditable?D.textContent??"":"",X=D=>{let Y=[];for(let B of Array.from(D.childNodes))if(B.nodeType===Node.TEXT_NODE){let H=B.textContent?.trim();H&&Y.push(H)}else if(B instanceof HTMLElement&&!P(B)){let H=B.innerText?.trim();H&&Y.push(H)}return Y.join(" ").replace(/\s+/g," ").trim()},z=D=>{let Y=[],B=(F,te,se)=>{let pe=F?.replace(/\s+/g," ").trim();pe&&Y.push({label:pe,source:te,priority:se})};B(D.getAttribute("aria-label"),"aria-label",0);let H=D.getAttribute("aria-labelledby");if(H&&B(H.split(/\s+/).map(F=>document.getElementById(F)?.textContent?.trim()).filter(Boolean).join(" "),"aria-labelledby",0),D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement)for(let F of Array.from(D.labels??[]))B(F.textContent,"label",0);let $=D.id;$&&B(document.querySelector(`label[for="${$}"]`)?.textContent,"label[for]",0),(D instanceof HTMLInputElement||D instanceof HTMLTextAreaElement)&&(B(D.placeholder,"placeholder",1),B(D.name,"name",2),B(D.id,"id",2));let N=D.previousElementSibling;for(;N;)B(N instanceof HTMLElement?N.innerText:N.textContent,"previous-sibling",3),N=N.previousElementSibling;let M=D.parentElement;for(let F=0;M&&F<3;F+=1,M=M.parentElement)B(X(M),"container-text",4+F);return Y},U=[],j=Array.from(document.querySelectorAll('input:not([type="hidden"]), textarea, [contenteditable="true"]')).filter(D=>P(D)&&O(D));for(let D of j)for(let Y of z(D)){let B=R(Y.label);B!=null&&U.push({element:D,label:Y.label,source:Y.source,priority:Y.priority,matchRank:Y.priority*10+B,elementType:L(D),valueBefore:V(D)})}if(U.length===0)return{status:"none",error:`No text input found for label "${_}". Check the latest page snapshot for the field label or use ref/x/y.`};U.sort((D,Y)=>D.matchRank-Y.matchRank);let K=U[0].matchRank,q=U.filter(D=>D.matchRank===K);if(Array.from(new Set(q.map(D=>D.element))).length>1)return{status:"ambiguous",error:`Multiple text inputs matched label "${_}". Use a more specific label or a direct ref.`,matches:q.map(D=>({label:D.label,source:D.source,elementType:D.elementType}))};let ne=`agentiqa_label_target_${Date.now()}_${Math.random().toString(36).slice(2)}`;return q[0].element.setAttribute("data-agentiqa-label-target",ne),{status:"ok",marker:ne,matchedLabel:q[0].label,labelSource:q[0].source,elementType:q[0].elementType,valueBefore:q[0].valueBefore}},n);if(l.status!=="ok"){let _=await this.captureState(e);return{..._,metadata:{..._.metadata,error:l.error,...l.status==="ambiguous"&&{matches:l.matches}}}}let c=a.locator(`[data-agentiqa-label-target="${l.marker}"]`).first(),u=await c.boundingBox({timeout:o});u&&await this.onBeforeAction(e,u.x+u.width/2,u.y+u.height/2),await c.click({force:!0,timeout:o});let d=await a.evaluate(()=>{let _=document.activeElement;return _ instanceof HTMLInputElement?{inputType:_.type}:_ instanceof HTMLTextAreaElement?{inputType:"textarea"}:_.isContentEditable?{inputType:"contenteditable"}:{inputType:"none"}}),h=["date","time","datetime-local","month","week"].includes(d.inputType),g=["text","password","email","search","url","tel","number","textarea","contenteditable"].includes(d.inputType);if(!g&&!h){let _=await this.captureState(e);return{..._,metadata:{..._.metadata,error:`Label "${n}" resolved to a non-text element (${d.inputType||"unknown"}). Use a different label or direct ref.`}}}let m=i===!0||i==="true";if(r=this.normalizeTestingEmailForFocusedField(e,r,{inputType:d.inputType,label:n,matchedLabel:l.matchedLabel}),h)try{await a.evaluate(_=>{let w=document.activeElement;if(w instanceof HTMLInputElement){let A=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;A?A.call(w,_):w.value=_,w.dispatchEvent(new Event("input",{bubbles:!0})),w.dispatchEvent(new Event("change",{bubbles:!0}))}},r)}catch{await a.keyboard.type(r,{delay:15})}else m&&g?(await a.keyboard.press("ControlOrMeta+a"),r?await Ri(a,r,15):await a.keyboard.press("Backspace")):r&&await Ri(a,r,15);s&&await a.keyboard.press("Enter"),await this.awaitPageReady(a);try{await a.evaluate(()=>new Promise(_=>requestAnimationFrame(()=>setTimeout(_,50))))}catch{}let S=await this.getFocusedFieldName(a),E=await this.getFocusedElementFingerprint(a),v=await a.evaluate(()=>{let _=document.activeElement;return _ instanceof HTMLInputElement||_ instanceof HTMLTextAreaElement?_.value:_ instanceof HTMLElement&&_.isContentEditable?_.textContent??"":""}),x=h?{valueMismatch:!1}:Xy({requested:r,valueBefore:l.valueBefore,valueAfter:v,pressEnter:s}),b=await this.captureState(e);return{...b,metadata:{...b.metadata,typedIntoField:S??l.matchedLabel,matchedLabel:l.matchedLabel,labelSource:l.labelSource,elementType:l.elementType,inputType:d.inputType,valueBefore:l.valueBefore,valueAfter:v,...E&&{elementFingerprint:E},...x.valueMismatch?{valueMismatch:!0,error:x.error}:{}}}}async scrollDocument(e,n){let{page:r,viewportHeight:s}=e,i=Math.floor(s*.8),a=n==="up"||n==="down",o=n==="up"||n==="left"?-i:i;return await r.evaluate(({vertical:l,signed:c})=>{let u=document.scrollingElement||document.documentElement,d=null,f=0;for(let m of Array.from(document.querySelectorAll("*"))){let S=l?m.scrollHeight-m.clientHeight:m.scrollWidth-m.clientWidth;if(S<=f)continue;let E=l?getComputedStyle(m).overflowY:getComputedStyle(m).overflowX;E!=="auto"&&E!=="scroll"||(f=S,d=m)}let h=l?u.scrollHeight-u.clientHeight:u.scrollWidth-u.clientWidth,p=l?0:c,g=l?c:0;!d||h>=f?window.scrollBy(p,g):d.scrollBy(p,g)},{vertical:a,signed:o}),await new Promise(l=>setTimeout(l,200)),await this.captureState(e)}async scrollToBottom(e){let{page:n}=e;return await n.evaluate(()=>{let r=document.scrollingElement||document.documentElement,s=null,i=0;for(let o of Array.from(document.querySelectorAll("*"))){let l=o.scrollHeight-o.clientHeight;if(l<=i)continue;let c=getComputedStyle(o).overflowY;c!=="auto"&&c!=="scroll"||(i=l,s=o)}let a=r.scrollHeight-r.clientHeight;!s||a>=i?window.scrollTo(0,r.scrollHeight):s.scrollTo(0,s.scrollHeight)}),await new Promise(r=>setTimeout(r,200)),await this.captureState(e)}async scrollAt(e,n,r,s,i){let{page:a}=e;await a.mouse.move(n,r);let o=0,l=0;switch(s){case"up":l=-i;break;case"down":l=i;break;case"left":o=-i;break;case"right":o=i;break}return await a.mouse.wheel(o,l),await new Promise(c=>setTimeout(c,200)),await this.captureState(e)}async waitSeconds(e,n){let r=Math.min(Math.max(n,1),30);return await new Promise(s=>setTimeout(s,r*1e3)),await this.captureState(e)}async waitForVisibleTextOrIdentifierLabel(e,n,r){let s=e.getByText(n,{exact:!1}).first().waitFor({state:"visible",timeout:r}),i=FZ(n);if(!i){await s;return}let a=e.waitForFunction(({spec:o})=>{let l=document.body?.innerText??"",c=f=>(f.match(/[A-Za-z0-9][A-Za-z0-9_-]*/g)??[]).some(p=>{let g=(p.match(/[A-Za-z]/g)??[]).length,m=(p.match(/\d/g)??[]).length;return g>=1&&m>=2?!0:/^[A-Za-z]{2,}[-_]\d+$/.test(p)}),u=f=>f.toLowerCase().match(/[a-z0-9]+/g)??[];return l.split(/\n+/).map(f=>f.trim()).filter(Boolean).some(f=>{if(!c(f))return!1;let h=new Set(u(f));return o.anchors.every(p=>h.has(p))})},{spec:i},{timeout:r});await Promise.any([s,a])}async waitForElement(e,n,r){let{page:s}=e;if(await this.computeCanvasDominant(e)){let l=Math.min(Math.max(r,1),10);try{return await this.waitForVisibleTextOrIdentifierLabel(s,n,l*1e3),await new Promise(c=>setTimeout(c,300)),await this.captureState(e,{onScreenshotTimeout:"degrade"})}catch{return{...await this.captureState(e,{onScreenshotTimeout:"degrade"}),metadata:{error:Uk(n)}}}}let i=(()=>{let l=typeof process<"u"&&process?.env?Number(process.env.REPLAY_WAIT_POLL_MS):NaN;return Number.isFinite(l)&&l>0?Math.round(l/1e3):180})(),a=e.isTestPlanReplay===!0?i:30,o=Math.min(Math.max(r,1),a);try{return await this.waitForVisibleTextOrIdentifierLabel(s,n,o*1e3),await new Promise(l=>setTimeout(l,300)),await this.captureState(e,{onScreenshotTimeout:"degrade"})}catch{return{...await this.captureState(e,{onScreenshotTimeout:"degrade"}),metadata:{error:Lk(n,o)}}}}async fullPageScreenshot(e){let{page:n}=e,r=n.url(),s=await this.measureFullPageGeometry(e);if(rm(s)!=="inner_scroll"){let c=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});if(oA(this.pngHeightPx(c),s)){if(!Ge("EVIDENCE_FIDELITY"))return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"shadow_fullpage_viewport_only"),{screenshot:c,url:r,captureMode:"viewport_degraded"};let u=await this.captureInnerExtentFull(e,s);if(u)return{screenshot:u,url:r,captureMode:"cdp_full"};let d=await this.captureScrollStitch(e,s);return d?{screenshot:d,url:r,captureMode:"scroll_stitch"}:(this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"no_full_render"),{screenshot:c,url:r,captureMode:"viewport_degraded"})}return{screenshot:c,url:r,captureMode:"document_full"}}if(!Ge("EVIDENCE_FIDELITY")){let c=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"shadow_inner_scroll"),{screenshot:c,url:r,captureMode:"viewport_degraded"}}let a=await this.captureInnerExtentFull(e,s);if(a)return{screenshot:a,url:r,captureMode:"cdp_full"};let o=await this.captureScrollStitch(e,s);if(o)return{screenshot:o,url:r,captureMode:"scroll_stitch"};let l=await this.screenshotWithSlowSiteRetry(e,{fullPage:!0});return this.emitCaptureDegradedMarker(e,r,s,s.viewportH,"no_full_render"),{screenshot:l,url:r,captureMode:"viewport_degraded"}}async measureFullPageGeometry(e){let{page:n}=e;try{return await n.evaluate(()=>{let s=document.scrollingElement||document.documentElement,i=window.innerHeight,a=Math.max(s?s.scrollHeight:0,document.body?document.body.scrollHeight:0),o=0,l=document.querySelectorAll("*");for(let c=0;c<l.length;c++){let u=l[c],f=window.getComputedStyle(u).overflowY;if(f!=="auto"&&f!=="scroll"||u.scrollHeight<=u.clientHeight+1)continue;let h=u.getBoundingClientRect();h.height<1||h.bottom<=0||h.top>=i||u.scrollHeight>o&&(o=u.scrollHeight)}return{viewportH:i,documentH:a,innerContainerH:o,dpr:window.devicePixelRatio||1}})}catch{let r=n.viewportSize()?.height??0;return{viewportH:r,documentH:r+4+1,innerContainerH:0,dpr:1}}}async captureInnerExtentFull(e,n){let{page:r}=e,s=null;try{s=await r.evaluate(i=>{let a=document.scrollingElement||document.documentElement,o=null,l=0,c=document.querySelectorAll("*");for(let d=0;d<c.length;d++){let f=c[d],p=window.getComputedStyle(f).overflowY;p!=="auto"&&p!=="scroll"||f.scrollHeight<=f.clientHeight+1||f.scrollHeight>l&&(l=f.scrollHeight,o=f)}if(!o||l<i-4)return null;let u=o;return u.__aqPrevCss=u.style.cssText,u.setAttribute("data-aq-fullpage-expanded","1"),u.style.setProperty("max-height","none","important"),u.style.setProperty("height","auto","important"),u.style.setProperty("overflow","visible","important"),a&&a.scrollHeight,{documentH:a?a.scrollHeight:0}},n.innerContainerH)}catch{s=null}if(!s)return null;try{return s.documentH<=n.viewportH+4?null:(await new Promise(i=>setTimeout(i,120)),await this.screenshotWithSlowSiteRetry(e,{fullPage:!0}))}catch{return null}finally{await this.restoreExpandedContainer(e)}}async restoreExpandedContainer(e){try{await e.page.evaluate(()=>{let n=document.querySelector("[data-aq-fullpage-expanded]");n&&(typeof n.__aqPrevCss=="string"?n.style.cssText=n.__aqPrevCss:n.removeAttribute("style"),delete n.__aqPrevCss,n.removeAttribute("data-aq-fullpage-expanded"))})}catch{}}async captureScrollStitch(e,n){let{page:r}=e,s=12,i=null;try{i=await r.evaluate(()=>{let l=null,c=0,u=document.querySelectorAll("*");for(let h=0;h<u.length;h++){let p=u[h],m=window.getComputedStyle(p).overflowY;m!=="auto"&&m!=="scroll"||p.scrollHeight<=p.clientHeight+1||p.scrollHeight>c&&(c=p.scrollHeight,l=p)}if(!l)return null;let d=l;d.__aqPrevScrollTop=d.scrollTop,d.setAttribute("data-aq-stitch","1");let f=d.getBoundingClientRect();return{x:Math.max(0,Math.floor(f.left)),y:Math.max(0,Math.floor(f.top)),width:Math.max(1,Math.floor(f.width)),clientH:Math.max(1,Math.floor(d.clientHeight)),scrollH:Math.floor(d.scrollHeight)}})}catch{i=null}if(!i)return null;let a=Math.min(s,Math.ceil(i.scrollH/i.clientH));if(a<2)return await this.clearStitchMarker(e),null;let o=[];try{for(let l=0;l<a;l++){let c=l*i.clientH;await r.evaluate(h=>{let p=document.querySelector("[data-aq-stitch]");p&&(p.scrollTop=h)},c),await new Promise(h=>setTimeout(h,80));let u=i.scrollH-c,d=Math.max(1,Math.min(i.clientH,u)),f=await r.screenshot({type:"png",clip:{x:i.x,y:i.y,width:i.width,height:d}});o.push({buf:f,height:d})}return await this.stitchTilesVertically(o,i.width)}catch{return null}finally{await this.clearStitchMarker(e)}}async clearStitchMarker(e){try{await e.page.evaluate(()=>{let n=document.querySelector("[data-aq-stitch]");n&&(typeof n.__aqPrevScrollTop=="number"&&(n.scrollTop=n.__aqPrevScrollTop),delete n.__aqPrevScrollTop,n.removeAttribute("data-aq-stitch"))})}catch{}}async stitchTilesVertically(e,n){if(e.length===0)return null;try{let{PNG:r}=await import("pngjs"),s=e.map(c=>r.sync.read(c.buf)),i=s[0].width;if(s.some(c=>c.width!==i))return null;let a=s.reduce((c,u)=>c+u.height,0);if(a<=0)return null;let o=new r({width:i,height:a}),l=0;for(let c of s)r.bitblt(c,o,0,0,c.width,c.height,0,l),l+=c.height;return r.sync.write(o)}catch{return null}}pngHeightPx(e){return e.length<24||e.readUInt32BE(0)!==2303741511?0:e.readUInt32BE(20)}emitCaptureDegradedMarker(e,n,r,s,i){this.diagLog?.(e.sessionId,"full_page_capture:degraded",{captureMode:"viewport_degraded",url:n,viewportH:r.viewportH,documentH:r.documentH,innerContainerH:r.innerContainerH,capturedH:s,reason:i})}async switchLayout(e,n,r){let{page:s}=e;return await s.setViewportSize({width:n,height:r}),await this.captureState(e)}async goBack(e){let{page:n}=e;return e.needsFullSnapshot=!0,await n.goBack(),await this.awaitPageReady(n),await this.captureState(e)}async goForward(e){let{page:n}=e;return e.needsFullSnapshot=!0,await n.goForward(),await this.awaitPageReady(n),await this.captureState(e)}async navigate(e,n){let{page:r}=e,s=Mr(n),i=await this.containCrossEnvironmentIfNeeded(e,s);if(i)return i;let a=await this.blockScopedNavigationIfNeeded(e,s);if(a)return a;let o=await Wy(s,{allowPrivateNetwork:this.preflightAllowsPrivateNetwork(),allowLocalFileUrls:this.preflightAllowsLocalFileUrls()});if(!o.ok)throw new kn(o);e.needsFullSnapshot=!0;let l=Date.now();this.reportStartupNavigate(e,"goto_start",{url:s});let c=await r.goto(s,{waitUntil:"domcontentloaded"}),u=await this.awaitPageReady(r);this.reportStartupNavigate(e,"goto_done",{elapsedMs:Date.now()-l,pageSettled:u,landedUrl:r.url()}),await this.assertNoCloudflareBlock(r,c,s);let d=[],f=c?.request().redirectedFrom()??null;for(;f;)d.unshift(f.url()),f=f.redirectedFrom();let h=r.url();this.maybeAnchorAppUnderTestOrigin(e,h),await this.assertNoThirdPartyIdpLogin(e,"navigate",{},h);let p=await this.resolveContainmentAction(e,h);if(p!=="allow")return await this.containCrossEnvironmentLanding(e,h,p==="escalate");this.recordCanonicalRedirectOrigin(e,s,h);let g=_f(s,h,d,(E,v,x,b)=>console.warn(`[BasePlaywright] [${v}] ${x}`,b??"")),m=Date.now();this.reportStartupNavigate(e,"first_screenshot_start");let S=await this.captureState(e);return this.reportStartupNavigate(e,"first_screenshot_done",{elapsedMs:Date.now()-m,bytes:S.screenshot.length}),{...S,metadata:{...S.metadata??{},navigateMeta:g,pageSettled:u}}}async blockScopedNavigationIfNeeded(e,n){if(e.canonicalRedirectOrigins?.size)try{let a=new URL(n,e.page.url()),o=l=>l.slice(0,4)==="www."?l.slice(4):l;for(let l of e.canonicalRedirectOrigins){let c=new URL(l);if(c.protocol===a.protocol&&c.port===a.port&&o(c.hostname)===o(a.hostname))return null}}catch{}let r=k0({targetUrl:n,currentUrl:e.page.url(),scope:e.browserNavigationScope,allowExternalNavigation:e.allowExternalNavigation,httpsCertFallbackHost:e.httpsCertFallback?.host});if(r.allowed)return null;let s=await this.captureState(e),i=e.browserNavigationScope?.join(", ")||"(none)";return{...s,metadata:{...s.metadata??{},error:`Navigation blocked: ${n} is outside the allowed scope (${i}). Record/report the external link without opening it unless the user explicitly asked to validate external links.`,scopedNavigation:{status:"blocked",targetUrl:n,reason:r.reason}}}}maybeAnchorAppUnderTestOrigin(e,n){if(!(e.appUnderTestOrigin||!n))try{let r=new URL(n);/^https?:$/i.test(r.protocol)&&(e.appUnderTestOrigin=r.origin)}catch{}}async returnToSafeOrigin(e,n){if(e.appUnderTestOrigin)try{await n.goto(e.appUnderTestOrigin,{waitUntil:"domcontentloaded"}),await this.awaitPageReady(n)}catch{}if(e.needsFullSnapshot=!0,!e.appUnderTestOrigin||Tl(e.appUnderTestOrigin,n.url(),{scope:e.browserNavigationScope}))try{await n.goto("about:blank",{waitUntil:"domcontentloaded"})}catch{}}async containCrossEnvironmentIfNeeded(e,n){let r=await this.resolveContainmentAction(e,n);if(r==="allow")return null;let s=await this.captureState(e);return{...s,metadata:{...s.metadata??{},error:La(n,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"blocked",targetUrl:n,...r==="escalate"?{needsUserDecision:!0}:{}}}}}async containCrossEnvironmentLanding(e,n,r=!1){await this.returnToSafeOrigin(e,e.page);let s=await this.captureState(e);return{...s,metadata:{...s.metadata??{},error:La(n,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"contained",escapedUrl:n,returnedTo:s.url,...r?{needsUserDecision:!0}:{}}}}}async containCrossEnvironmentAfterAction(e,n,r){let s=await this.resolveContainmentAction(e,r.url);if(s==="allow")return null;let i=r.url;await this.returnToSafeOrigin(e,n);let a=this.withSessionMetadata(e,await this.captureState(e));return{screenshot:a.screenshot.toString("base64"),url:a.url,aiSnapshot:a.aiSnapshot,domChanges:a.domChanges,metadata:{...a.metadata??{},error:La(i,e.appUnderTestOrigin),crossEnvironmentContainment:{status:"contained",escapedUrl:i,returnedTo:a.url,...s==="escalate"?{needsUserDecision:!0}:{}}}}}async containPendingPopupEscapes(e){let n=e.pendingPopupEscapes;if(!n||n.length===0)return null;e.pendingPopupEscapes=void 0;let r=[];for(let o of n)await this.resolveContainmentAction(e,o.escapedUrl)!=="allow"&&r.push(o);if(r.length===0)return null;let s=r[0].escapedUrl;if(r.some(o=>e.page===o.popup||e.tab2===o.popup)){e.tab1&&!e.tab1.isClosed()&&(e.page=e.tab1,e.activeTab="tab1");for(let o of r)e.tab2===o.popup&&(e.tab2=void 0);e.needsFullSnapshot=!0}for(let o of r)try{await o.popup.close()}catch{}let i={status:"contained",escapedUrl:s};if(!e.page||e.page.isClosed())return{screenshot:"",url:s,aiSnapshot:void 0,domChanges:void 0,metadata:{error:La(s,e.appUnderTestOrigin),crossEnvironmentContainment:i}};let a=this.withSessionMetadata(e,await this.captureState(e));return{screenshot:a.screenshot.toString("base64"),url:a.url,aiSnapshot:a.aiSnapshot,domChanges:a.domChanges,metadata:{...a.metadata??{},error:La(s,e.appUnderTestOrigin),crossEnvironmentContainment:i}}}async keyCombination(e,n){let{page:r}=e,s=n.map(a=>jZ[a.toLowerCase()]??a),i=s.some(a=>Qy.has(a));if(s.length===1)await r.keyboard.press(s[0]);else if(i){let a=s.filter(l=>Qy.has(l)),o=s.filter(l=>!Qy.has(l));for(let l of a)await r.keyboard.down(l);for(let l of o)await r.keyboard.press(l);for(let l of a.reverse())await r.keyboard.up(l)}else for(let a of s)await r.keyboard.press(a);return await this.awaitPageReady(r),await this.captureState(e)}async setFocusedInputValue(e,n,r){let{page:s}=e;if(r){let c=await this.getFocusedElementFingerprint(s);if(c!==r){let u=await this.captureState(e);return{...u,metadata:{...u.metadata,verbatimGuardMismatch:!0,...c&&{elementFingerprint:c}}}}}let i={isSelect:!1,inputType:"none"};try{i=await s.evaluate(()=>{let c=document.activeElement;return c instanceof HTMLSelectElement?{isSelect:!0,inputType:"select"}:c instanceof HTMLInputElement?{isSelect:!1,inputType:c.type}:c instanceof HTMLTextAreaElement?{isSelect:!1,inputType:"textarea"}:c?.isContentEditable?{isSelect:!1,inputType:"contenteditable"}:{isSelect:!1,inputType:"none"}})}catch{return console.warn("[BasePlaywright] page.evaluate blocked in setFocusedInputValue, falling back to keyboard typing"),n=this.normalizeTestingEmailForFocusedField(e,n,{}),await s.keyboard.press("ControlOrMeta+a"),await Ri(s,n,10),{...await this.captureState(e),metadata:{elementType:"unknown (evaluate blocked)",valueBefore:"",valueAfter:n}}}if(i.isSelect)return await this.setSelectValue(e,n);n=this.normalizeTestingEmailForFocusedField(e,n,{inputType:i.inputType});let a=await s.evaluate(c=>{let u=document.activeElement,d=g=>g instanceof HTMLInputElement?`input[type=${g.type}]`:g instanceof HTMLTextAreaElement?"textarea":g.isContentEditable?"contenteditable":g.tagName.toLowerCase(),f=g=>g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement?g.value:g.isContentEditable&&g.textContent||"";if(!u||u===document.body)return{success:!1,error:"No element is focused",elementType:"none",valueBefore:"",valueAfter:""};let h=d(u),p=f(u);try{if(u instanceof HTMLInputElement){let g=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set;g?g.call(u,c):u.value=c,u.dispatchEvent(new Event("input",{bubbles:!0})),u.dispatchEvent(new Event("change",{bubbles:!0}))}else if(u instanceof HTMLTextAreaElement){let g=Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set;g?g.call(u,c):u.value=c,u.dispatchEvent(new Event("input",{bubbles:!0})),u.dispatchEvent(new Event("change",{bubbles:!0}))}else if(u.isContentEditable)u.textContent=c,u.dispatchEvent(new Event("input",{bubbles:!0}));else return{success:!1,error:`Element is not editable: ${h}`,elementType:h,valueBefore:p,valueAfter:p}}catch(g){return{success:!1,error:String(g.message||g),elementType:h,valueBefore:p,valueAfter:f(u)}}return{success:!0,elementType:h,valueBefore:p,valueAfter:f(u)}},n),o=await this.getFocusedElementFingerprint(s);return{...await this.captureState(e),metadata:{elementType:a.elementType,inputType:i.inputType,valueBefore:a.valueBefore,valueAfter:a.valueAfter,...o&&{elementFingerprint:o},...a.error&&{error:a.error}}}}async setSelectValue(e,n){let{page:r}=e,s=await r.evaluate(()=>{let u=document.activeElement;if(!(u instanceof HTMLSelectElement))return null;let d=u.options[u.selectedIndex]?.textContent?.trim()||"",f=Array.from(u.options).map(h=>h.textContent?.trim()||h.value);return{valueBefore:d,options:f}});if(!s)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:"",valueAfter:"",error:"No select element is focused. Use click_at on the select first."}};let a=(await r.evaluateHandle(()=>document.activeElement)).asElement();if(!a)return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:s.valueBefore,valueAfter:s.valueBefore,error:"Could not get select element handle",availableOptions:s.options}};let o=!1;try{await a.selectOption({label:n}),o=!0}catch{try{await a.selectOption({value:n}),o=!0}catch{}}let l=await r.evaluate(()=>{let u=document.activeElement;return u instanceof HTMLSelectElement?u.options[u.selectedIndex]?.textContent?.trim()||u.value:""});return{...await this.captureState(e),metadata:{elementType:"select",valueBefore:s.valueBefore,valueAfter:l,...!o&&{error:`No option matching "${n}"`},availableOptions:s.options}}}async uploadFile(e,n,r){let{page:s}=e,i=r?.clearStaleMarker===!0;console.log(`[BasePlaywright] upload_file called with filePaths=${JSON.stringify(n)}`+(i?" (clearStaleMarker)":""));let o=(await s.evaluateHandle(f=>{f&&document.querySelectorAll("[data-agentiqa-file-target]").forEach(E=>E.removeAttribute("data-agentiqa-file-target"));let h=document.querySelector('input[type="file"][data-agentiqa-file-target]');if(h)return h;let p=document.activeElement;if(p instanceof HTMLInputElement&&p.type==="file")return p;let g=Array.from(document.querySelectorAll('input[type="file"]'));if(g.length===0)return p;let m=g.filter(E=>E.closest('[role="dialog"], dialog, [aria-modal="true"]')),S=m.length>0?m:g;return S[S.length-1]},i)).asElement();if(!o)return{...await this.captureState(e),metadata:{elementType:"file",error:"No file input found. Use click_at on the file input first."}};let l=await s.evaluate(f=>f instanceof HTMLInputElement&&f.type==="file"?{isFileInput:!0,accept:f.accept||"*",multiple:f.multiple}:{isFileInput:!1,accept:"",multiple:!1},o);if(!l.isFileInput)return{...await this.captureState(e),metadata:{elementType:"not-file-input",error:"No file input found. Use click_at on the file input/upload area first."}};await o.evaluate(f=>{document.querySelectorAll("[data-agentiqa-file-target]").forEach(h=>h.removeAttribute("data-agentiqa-file-target")),f.setAttribute("data-agentiqa-file-target","true")});try{await o.setInputFiles(n),console.log(`[BasePlaywright] upload_file setInputFiles succeeded, count=${n.length}`)}catch(f){return console.log(`[BasePlaywright] upload_file setInputFiles failed: ${f.message}`),{...await this.captureState(e),metadata:{elementType:"file",accept:l.accept,multiple:l.multiple,error:`File upload failed: ${f.message}`}}}let c=await this.onFilesUploaded(n),u=await o.evaluate(f=>f.files?.length??0).catch(()=>0);return console.log(`[BasePlaywright] upload_file result: fileCount=${u}`),await this.awaitPageReady(s),{...await this.captureState(e),metadata:{elementType:"file",accept:l.accept,multiple:l.multiple,fileCount:u,...c.length>0&&{storedAssets:c}}}}async dragAndDrop(e,n,r,s,i){let{page:a}=e;return await a.mouse.move(n,r),await a.mouse.down(),await a.mouse.move(s,i,{steps:10}),await a.mouse.up(),await this.captureState(e)}async resolveRefCenter(e,n){try{let i=await e.page.locator(`aria-ref=${n}`).boundingBox({timeout:3e3});return i?{x:Math.floor(i.x+i.width/2),y:Math.floor(i.y+i.height/2)}:null}catch{return null}}async refNotFoundError(e,n){return{...await this.captureState(e),metadata:{error:`Ref "${n}" not found \u2014 the page may have changed. Check the latest page snapshot for updated refs.`}}}async switchTab(e,n){if(n==="tab1"){let r=!e.tab1||e.tab1.isClosed();if(this.diagLog?.(e.sessionId,"switchTab tab1 requested",{tab1Closed:r,hasExtId:!!e.extensionId}),r&&e.extensionId){this.diagLog?.(e.sessionId,"switchTab auto-recreating tab1 at popup.html");let s=await e.context.newPage();Tp(s),await s.goto(`chrome-extension://${e.extensionId}/popup.html`,{timeout:5e3}),e.tab1=s}if(!e.tab1||e.tab1.isClosed())return{...await this.captureState(e),metadata:{error:"Tab 1 is not available"}};if(e.page=e.tab1,e.activeTab="tab1",e.extensionId){let s=e.tab1.url();if(!s.startsWith(`chrome-extension://${e.extensionId}`)){this.diagLog?.(e.sessionId,"switchTab navigating to popup.html",{beforeUrl:s});try{await e.tab1.goto(`chrome-extension://${e.extensionId}/popup.html`,{timeout:5e3});let i=e.tab1.url();this.diagLog?.(e.sessionId,"switchTab popup.html loaded",{afterUrl:i})}catch(i){this.diagLog?.(e.sessionId,"switchTab popup.html failed",{error:i?.message})}}}}else{if(!e.tab2||e.tab2.isClosed())return{...await this.captureState(e),metadata:{error:"Tab 2 is not available. No second tab is open."}};e.page=e.tab2,e.activeTab="tab2"}return e.needsFullSnapshot=!0,await e.page.bringToFront(),await this.captureState(e)}async closeTab(e){if(e.activeTab==="tab1")return{...await this.captureState(e),metadata:{error:"Cannot close tab 1"}};if(e.tab2&&!e.tab2.isClosed())try{await e.tab2.close()}catch{}return e.tab2=void 0,e.page=e.tab1,e.activeTab="tab1",e.needsFullSnapshot=!0,await e.page.bringToFront(),await this.captureState(e)}static HTTP_BODY_MAX_LENGTH=5e4;async httpRequest(e,n,r,s,i){let{page:a}=e;try{let o={method:r,timeout:3e4,ignoreHTTPSErrors:!0};s&&(o.headers=s),i&&r!=="GET"&&(o.data=i);let l=await a.request.fetch(n,o),c=await l.text(),u=!1;if(c.length>t.HTTP_BODY_MAX_LENGTH&&(c=c.slice(0,t.HTTP_BODY_MAX_LENGTH),u=!0),(l.headers()["content-type"]||"").includes("application/json")&&!u)try{c=JSON.stringify(JSON.parse(c),null,2),c.length>t.HTTP_BODY_MAX_LENGTH&&(c=c.slice(0,t.HTTP_BODY_MAX_LENGTH),u=!0)}catch{}return{...await this.captureState(e),metadata:{httpResponse:{status:l.status(),statusText:l.statusText(),headers:l.headers(),body:c,...u&&{truncated:!0}}}}}catch(o){return{...await this.captureState(e),metadata:{error:`HTTP request failed: ${o.message}`}}}}static RUN_JS_INPUT_MAX_LENGTH=4e3;static RUN_JS_RESULT_MAX_LENGTH=5e3;static RUN_JS_TIMEOUT_MS=1e4;async runJs(e,n){if(n.length>t.RUN_JS_INPUT_MAX_LENGTH)return{...await this.captureState(e),metadata:{error:`run_js code exceeded ${t.RUN_JS_INPUT_MAX_LENGTH}-char cap (${n.length} chars).`}};let r=`(async () => {
|
|
1998
1998
|
try {
|
|
1999
1999
|
const __res = await (async () => { ${n} })();
|
|
2000
2000
|
return { ok: true, value: __res };
|
|
2001
2001
|
} catch (e) {
|
|
2002
2002
|
return { ok: false, error: e && e.message ? e.message : String(e) };
|
|
2003
2003
|
}
|
|
2004
|
-
})()`;try{let s=await Promise.race([e.page.evaluate(r),new Promise((l,c)=>setTimeout(()=>c(new Error(`page.evaluate exceeded ${t.RUN_JS_TIMEOUT_MS}ms`)),t.RUN_JS_TIMEOUT_MS))]),i=await this.captureState(e);if(!s.ok)return{...i,metadata:{error:`run_js threw: ${s.error??"unknown error"}`}};let a;try{a=s.value===void 0?"undefined":JSON.stringify(s.value,null,2),a===void 0&&(a=String(s.value))}catch{a=String(s.value)}let o=!1;return a.length>t.RUN_JS_RESULT_MAX_LENGTH&&(a=a.slice(0,t.RUN_JS_RESULT_MAX_LENGTH),o=!0),{...i,metadata:{jsResult:{value:a,...o&&{truncated:!0}}}}}catch(s){return{...await this.captureState(e),metadata:{error:`run_js failed: ${s?.message??String(s)}`}}}}async evaluate(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`No session found: ${e}`);return await r.page.evaluate(n)}async waitForWritesDrained(e,n,r){let s=this.sessions.get(e);if(!s)return{drained:!0,waitedMs:0,pendingAtStart:0,pendingAtEnd:0,oldestAgeMs:null,timedOut:!1,aborted:!1};let i=[s.page,s.tab1,s.tab2].filter(o=>!!o),a=Array.from(new Set(i));return KP({timeoutMs:n,signal:r?.signal,pollSet:()=>{let o=0;for(let l of a){let c=lc.get(l);c&&(o+=c.pendingWrites.size)}return o},oldestAgeMs:()=>{let o=1/0,l=Date.now();for(let c of a){let u=lc.get(c);if(u)for(let d of u.pendingWrites){let f=l-d.startTs;f<o&&(o=f)}}return o===1/0?0:o}})}async cleanupSession(e){let n=this.sessions.get(e);if(n){console.log(`[BasePlaywright] Cleaning up session ${e}`),await this.stopScreencast(e),n.affordanceCdpSession&&(await n.affordanceCdpSession.detach().catch(()=>{}),n.affordanceCdpSession=void 0,n.affordanceCdpSessionPage=void 0);try{await n.context.close()}catch{}this.sessions.delete(e)}}getSessionNotices(e){let r=this.sessions.get(e)?.httpsCertFallback;if(r)return[{kind:"https_cert_fallback",message:`The HTTPS version of ${r.host} had a certificate issue (${r.errorCode}) \u2014 tested against ${r.fallbackUrl} instead.`,details:{originalUrl:r.originalUrl,fallbackUrl:r.fallbackUrl,host:r.host,errorCode:r.errorCode}}]}async cleanupOtherSessions(e){let r=Date.now();for(let[s,i]of this.sessions)s!==e&&(r-i.lastInvokeAt<3e4||await this.cleanupSession(s))}async getStorageState(e){let n=this.sessions.get(e);if(!n)throw new Error(`Session ${e} not found`);return n.context.storageState()}async checkAuthState(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`No session ${e}`);let s=r.page;switch(n.kind){case"urlMatches":return new RegExp(n.pattern).test(s.url());case"textVisible":return await s.getByText(n.text).first().isVisible().catch(()=>!1);case"textAbsent":return!await s.getByText(n.text).first().isVisible().catch(()=>!1)}}async cleanup(){for(let[e]of this.sessions)await this.cleanupSession(e);if(this.browser){try{this.browserShutdownExpected=!0,await this.browser.close()}catch{}finally{this.browserShutdownExpected=!1}this.browser=null}}isBrowserShutdownExpected(){return this.browserShutdownExpected}async startScreencast(e){let n=this.sessions.get(e);if(!(!n||n.screencastActive))try{let r=n.tab1??n.page,s=await r.context().newCDPSession(r);n.cdpSession=s,n.screencastActive=!0,n.screencastStartTime=n.screencastStartTime??Date.now(),n.screencastFrameCallbacks=n.screencastFrameCallbacks??[],n.lastScreencastFrameAt=Date.now(),s.on("Page.screencastFrame",a=>{let o=Date.now()-(n.screencastStartTime??Date.now());n.lastScreencastFrameAt=Date.now(),s.send("Page.screencastFrameAck",{sessionId:a.sessionId}).catch(l=>{this.diagLog?.(e,"screencast_frame_ack_failed",{error:String(l?.message??l)}),this.restartScreencast(e,"frame_ack_failed")});for(let l of n.screencastFrameCallbacks??[])try{l({data:a.data,timestamp:o})}catch{}}),await s.send("Page.startScreencast",{format:"jpeg",quality:40,maxWidth:n.viewportWidth,maxHeight:n.viewportHeight,everyNthFrame:5});let i=await s.send("Page.captureScreenshot",{format:"jpeg",quality:40}).catch(a=>(this.diagLog?.(e,"screencast_bootstrap_frame_failed",{error:String(a?.message??a)}),null));if(i?.data){let a=Date.now()-(n.screencastStartTime??Date.now());n.lastScreencastFrameAt=Date.now();for(let o of n.screencastFrameCallbacks??[])try{o({data:i.data,timestamp:a})}catch{}}n.screencastWatchdog&&clearInterval(n.screencastWatchdog),n.screencastWatchdog=setInterval(()=>{if(!n.screencastActive||n.screencastRestarting)return;let a=n.lastScreencastFrameAt??0;Date.now()-a>1e4&&this.restartScreencast(e,"frame_starvation")},5e3)}catch(r){console.warn("[BasePlaywright] Failed to start screencast:",r),n.screencastActive=!1}}async restartScreencast(e,n){let r=this.sessions.get(e);if(!(!r||!r.screencastActive||r.screencastRestarting)){r.screencastRestarting=!0,this.diagLog?.(e,"screencast_restart",{reason:n});try{let s=r.cdpSession;r.cdpSession=void 0,r.screencastActive=!1,s&&(await s.send("Page.stopScreencast").catch(()=>{}),await s.detach().catch(()=>{})),await this.startScreencast(e)}catch(s){console.warn("[BasePlaywright] Failed to restart screencast:",s)}finally{r.screencastRestarting=!1}}}async stopScreencast(e){let n=this.sessions.get(e);if(!(!n||!n.screencastActive))try{n.cdpSession&&(await n.cdpSession.send("Page.stopScreencast").catch(()=>{}),await n.cdpSession.detach().catch(()=>{}))}catch{}finally{n.screencastWatchdog&&(clearInterval(n.screencastWatchdog),n.screencastWatchdog=void 0),n.cdpSession=void 0,n.screencastActive=!1,n.screencastStartTime=void 0,n.lastScreencastFrameAt=void 0,n.screencastFrameCallbacks=[]}}onScreencastFrame(e,n){let r=this.sessions.get(e);return r?(r.screencastFrameCallbacks||(r.screencastFrameCallbacks=[]),r.screencastFrameCallbacks.push(n),()=>{let s=r.screencastFrameCallbacks?.indexOf(n)??-1;s>=0&&r.screencastFrameCallbacks?.splice(s,1)}):()=>{}}};import{existsSync as mM}from"node:fs";import{mkdirSync as VZ,writeFileSync as qZ}from"node:fs";import nv from"node:path";import GZ from"node:os";var tv=nv.join(GZ.tmpdir(),`agentiqa-samples-${Kl}`),fM=!1;function HZ(){if(!fM){VZ(tv,{recursive:!0});for(let{filename:t,base64:e}of Ja){let n=nv.join(tv,t);mM(n)||qZ(n,Buffer.from(e,"base64"))}fM=!0}}function gM(t,e){HZ();let n=t==="*"?["*"]:t.split(",").map(s=>s.trim().toLowerCase()),r=[];for(let s of Ja){let i=nv.join(tv,s.filename);mM(i)&&(n.includes("*")||n.some(a=>s.mimeTypes.includes(a)))&&r.push(i)}return e?r.slice(0,3):r.slice(0,1)}import{createCipheriv as WZ,createDecipheriv as zZ,hkdfSync as yM,randomBytes as KZ}from"node:crypto";var bM="aes-256-gcm",sv=32,no=12,rv=16,vM="agentiqa-browser-profile";function YZ(t){if(/^[0-9a-fA-F]{64}$/.test(t))return Buffer.from(t,"hex");try{let e=Buffer.from(t,"base64");return e.length===sv?e:null}catch{return null}}function _M(){return SM().key}function wM(){return SM().source}function SM(){let t=process.env.PROFILE_ENCRYPTION_KEY?.trim();if(t){let r=YZ(t);if(r)return{key:r,source:"PROFILE_ENCRYPTION_KEY"}}let e=process.env.ADMIN_SERVICE_KEY?.trim();if(e)return{key:Buffer.from(yM("sha256",e,"",vM,sv)),source:"ADMIN_SERVICE_KEY"};let n=process.env.E2E_ADMIN_SERVICE_KEY?.trim();return n?{key:Buffer.from(yM("sha256",n,"",vM,sv)),source:"E2E_ADMIN_SERVICE_KEY"}:{key:null,source:"none"}}function EM(t){let e=_M();if(!e)return null;let n=KZ(no),r=WZ(bM,e,n),s=Buffer.concat([r.update(t,"utf8"),r.final()]),i=r.getAuthTag();return Buffer.concat([n,i,s])}function TM(t){let e=_M();if(!e||!Buffer.isBuffer(t)||t.length<=no+rv)return null;try{let n=t.subarray(0,no),r=t.subarray(no,no+rv),s=t.subarray(no+rv),i=zZ(bM,e,n);return i.setAuthTag(r),Buffer.concat([i.update(s),i.final()]).toString("utf8")}catch{return null}}function xM(t){return`browser-profiles/${t}.json.enc`}var IM=!1;function JZ(){IM||(IM=!0,console.warn("[CloudProfileStore] profile encryption unavailable (no PROFILE_ENCRYPTION_KEY / ADMIN_SERVICE_KEY / E2E_ADMIN_SERVICE_KEY) \u2014 durable browser-profile persistence disabled"))}async function AM(t,e){try{let n=EM(JSON.stringify(e));if(!n){JZ();return}await to(n,xM(t),"application/octet-stream")}catch(n){console.error(`[CloudProfileStore] save failed for ${t}: ${n.message}`)}}async function kM(t){try{let e=await wp(xM(t));if(!e)return null;let n=TM(e);return n?JSON.parse(n):(console.warn("[CloudProfileStore] decrypt failed for existing browser profile",{projectId:t,keySource:wM(),bytes:e.length}),null)}catch{return null}}var xp=class extends Ip{sessionCredentials=new Map;projectProfiles=new Map;allowPrivateNetwork;constructor(e={}){super(),this.allowPrivateNetwork=e.allowPrivateNetwork??!1}preflightAllowsPrivateNetwork(){return this.allowPrivateNetwork||super.preflightAllowsPrivateNetwork()}preflightAllowsLocalFileUrls(){return!1}seedCredentials(e,n){this.sessionCredentials.set(e,new Map(n.map(r=>[r.name,{secret:r.secret}])))}clearCredentials(e){this.sessionCredentials.delete(e)}allowsLocalFileUrls(){return!1}async saveProjectProfile(e,n){this.projectProfiles.set(e,n),await AM(e,n)}async getProjectProfile(e){let n=this.projectProfiles.get(e);if(n!==void 0)return n;let r=await kM(e);return r!=null&&this.projectProfiles.set(e,r),r??null}getSuggestedSampleFiles(e,n){return gM(e,n)}async dispatchPlatformAction(e,n,r){if(n==="type_project_credential_at"){let s=String(r.credentialName??r.credential_name??"").trim();if(!s)throw new Error("credentialName is required");let a=this.sessionCredentials.get(e.sessionId)?.get(s);if(!a)throw new Error(`Credential "${s}" not found`);let o=a.secret,l=!!(r.pressEnter??r.press_enter??!1),c=r.clearBeforeTyping??r.clear_before_typing??!0;if(r.ref)return await this.typeByRef(e,String(r.ref),o,l,c,!0);if(!Ky(r)){let g=await this.locateSoleVisiblePasswordCenter(e);if(g)return await this.typeTextAt(e,g.x,g.y,o,l,c,!0);throw Yy()}let{viewportWidth:u,viewportHeight:d}=e,f=g=>Math.floor(g/1e3*u),h=g=>Math.floor(g/1e3*d),p=this.requireNormalizedPoint(n,r);return await this.typeTextAt(e,f(p.x),h(p.y),o,l,c,!0)}}};import{spawn as XZ}from"node:child_process";import{existsSync as QZ}from"node:fs";import{createRequire as ZZ}from"node:module";function eee(t=ZZ(import.meta.url),e=QZ){try{let n=t("ffmpeg-static");return typeof n=="string"&&n.length>0&&e(n)?n:null}catch{return null}}function tee(t="ffmpeg",e=XZ){return new Promise(n=>{try{let r=e(t,["-version"],{stdio:["ignore","ignore","ignore"]});r.on("error",()=>n(!1)),r.on("close",s=>n(s===0))}catch{n(!1)}})}async function Ap(t={}){let e=(t.bundled??eee)();return e?{command:e,source:"bundled"}:await(t.pathRunnable??tee)()?{command:"ffmpeg",source:"path"}:{command:null,source:"none"}}function Ci(t){Zd()&&process.stderr.write(`[agentiqa] ${t}
|
|
2004
|
+
})()`;try{let s=await Promise.race([e.page.evaluate(r),new Promise((l,c)=>setTimeout(()=>c(new Error(`page.evaluate exceeded ${t.RUN_JS_TIMEOUT_MS}ms`)),t.RUN_JS_TIMEOUT_MS))]),i=await this.captureState(e);if(!s.ok)return{...i,metadata:{error:`run_js threw: ${s.error??"unknown error"}`}};let a;try{a=s.value===void 0?"undefined":JSON.stringify(s.value,null,2),a===void 0&&(a=String(s.value))}catch{a=String(s.value)}let o=!1;return a.length>t.RUN_JS_RESULT_MAX_LENGTH&&(a=a.slice(0,t.RUN_JS_RESULT_MAX_LENGTH),o=!0),{...i,metadata:{jsResult:{value:a,...o&&{truncated:!0}}}}}catch(s){return{...await this.captureState(e),metadata:{error:`run_js failed: ${s?.message??String(s)}`}}}}async evaluate(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`No session found: ${e}`);return await r.page.evaluate(n)}async waitForWritesDrained(e,n,r){let s=this.sessions.get(e);if(!s)return{drained:!0,waitedMs:0,pendingAtStart:0,pendingAtEnd:0,oldestAgeMs:null,timedOut:!1,aborted:!1};let i=[s.page,s.tab1,s.tab2].filter(o=>!!o),a=Array.from(new Set(i));return KP({timeoutMs:n,signal:r?.signal,pollSet:()=>{let o=0;for(let l of a){let c=lc.get(l);c&&(o+=c.pendingWrites.size)}return o},oldestAgeMs:()=>{let o=1/0,l=Date.now();for(let c of a){let u=lc.get(c);if(u)for(let d of u.pendingWrites){let f=l-d.startTs;f<o&&(o=f)}}return o===1/0?0:o}})}async cleanupSession(e){let n=this.sessions.get(e);if(n){console.log(`[BasePlaywright] Cleaning up session ${e}`),await this.stopScreencast(e),n.affordanceCdpSession&&(await n.affordanceCdpSession.detach().catch(()=>{}),n.affordanceCdpSession=void 0,n.affordanceCdpSessionPage=void 0);try{await n.context.close()}catch{}this.sessions.delete(e)}}getSessionNotices(e){let r=this.sessions.get(e)?.httpsCertFallback;if(r)return[{kind:"https_cert_fallback",message:`The HTTPS version of ${r.host} had a certificate issue (${r.errorCode}) \u2014 tested against ${r.fallbackUrl} instead.`,details:{originalUrl:r.originalUrl,fallbackUrl:r.fallbackUrl,host:r.host,errorCode:r.errorCode}}]}async cleanupOtherSessions(e){let r=Date.now();for(let[s,i]of this.sessions)s!==e&&(r-i.lastInvokeAt<3e4||await this.cleanupSession(s))}async getStorageState(e){let n=this.sessions.get(e);if(!n)throw new Error(`Session ${e} not found`);return n.context.storageState()}async checkAuthState(e,n){let r=this.sessions.get(e);if(!r)throw new Error(`No session ${e}`);let s=r.page;switch(n.kind){case"urlMatches":return new RegExp(n.pattern).test(s.url());case"textVisible":return await s.getByText(n.text).first().isVisible().catch(()=>!1);case"textAbsent":return!await s.getByText(n.text).first().isVisible().catch(()=>!1)}}async cleanup(){for(let[e]of this.sessions)await this.cleanupSession(e);if(this.browser){try{this.browserShutdownExpected=!0,await this.browser.close()}catch{}finally{this.browserShutdownExpected=!1}this.browser=null}}isBrowserShutdownExpected(){return this.browserShutdownExpected}async startScreencast(e){let n=this.sessions.get(e);if(!(!n||n.screencastActive))try{let r=n.tab1??n.page,s=await r.context().newCDPSession(r);n.cdpSession=s,n.screencastActive=!0,n.screencastStartTime=n.screencastStartTime??Date.now(),n.screencastFrameCallbacks=n.screencastFrameCallbacks??[],n.lastScreencastFrameAt=Date.now(),s.on("Page.screencastFrame",a=>{let o=Date.now()-(n.screencastStartTime??Date.now());n.lastScreencastFrameAt=Date.now(),s.send("Page.screencastFrameAck",{sessionId:a.sessionId}).catch(l=>{this.diagLog?.(e,"screencast_frame_ack_failed",{error:String(l?.message??l)}),this.restartScreencast(e,"frame_ack_failed")});for(let l of n.screencastFrameCallbacks??[])try{l({data:a.data,timestamp:o})}catch{}}),await s.send("Page.startScreencast",{format:"jpeg",quality:40,maxWidth:n.viewportWidth,maxHeight:n.viewportHeight,everyNthFrame:5});let i=await s.send("Page.captureScreenshot",{format:"jpeg",quality:40}).catch(a=>(this.diagLog?.(e,"screencast_bootstrap_frame_failed",{error:String(a?.message??a)}),null));if(i?.data){let a=Date.now()-(n.screencastStartTime??Date.now());n.lastScreencastFrameAt=Date.now();for(let o of n.screencastFrameCallbacks??[])try{o({data:i.data,timestamp:a})}catch{}}n.screencastWatchdog&&clearInterval(n.screencastWatchdog),n.screencastWatchdog=setInterval(()=>{if(!n.screencastActive||n.screencastRestarting)return;let a=n.lastScreencastFrameAt??0;Date.now()-a>1e4&&this.restartScreencast(e,"frame_starvation")},5e3)}catch(r){console.warn("[BasePlaywright] Failed to start screencast:",r),n.screencastActive=!1}}async restartScreencast(e,n){let r=this.sessions.get(e);if(!(!r||!r.screencastActive||r.screencastRestarting)){r.screencastRestarting=!0,this.diagLog?.(e,"screencast_restart",{reason:n});try{let s=r.cdpSession;r.cdpSession=void 0,r.screencastActive=!1,s&&(await s.send("Page.stopScreencast").catch(()=>{}),await s.detach().catch(()=>{})),await this.startScreencast(e)}catch(s){console.warn("[BasePlaywright] Failed to restart screencast:",s)}finally{r.screencastRestarting=!1}}}async stopScreencast(e){let n=this.sessions.get(e);if(!(!n||!n.screencastActive))try{n.cdpSession&&(await n.cdpSession.send("Page.stopScreencast").catch(()=>{}),await n.cdpSession.detach().catch(()=>{}))}catch{}finally{n.screencastWatchdog&&(clearInterval(n.screencastWatchdog),n.screencastWatchdog=void 0),n.cdpSession=void 0,n.screencastActive=!1,n.screencastStartTime=void 0,n.lastScreencastFrameAt=void 0,n.screencastFrameCallbacks=[]}}onScreencastFrame(e,n){let r=this.sessions.get(e);return r?(r.screencastFrameCallbacks||(r.screencastFrameCallbacks=[]),r.screencastFrameCallbacks.push(n),()=>{let s=r.screencastFrameCallbacks?.indexOf(n)??-1;s>=0&&r.screencastFrameCallbacks?.splice(s,1)}):()=>{}}};import{existsSync as mM}from"node:fs";import{mkdirSync as VZ,writeFileSync as qZ}from"node:fs";import nv from"node:path";import GZ from"node:os";var tv=nv.join(GZ.tmpdir(),`agentiqa-samples-${Kl}`),fM=!1;function HZ(){if(!fM){VZ(tv,{recursive:!0});for(let{filename:t,base64:e}of Ja){let n=nv.join(tv,t);mM(n)||qZ(n,Buffer.from(e,"base64"))}fM=!0}}function gM(t,e){HZ();let n=t==="*"?["*"]:t.split(",").map(s=>s.trim().toLowerCase()),r=[];for(let s of Ja){let i=nv.join(tv,s.filename);mM(i)&&(n.includes("*")||n.some(a=>s.mimeTypes.includes(a)))&&r.push(i)}return e?r.slice(0,3):r.slice(0,1)}import{createCipheriv as WZ,createDecipheriv as zZ,hkdfSync as yM,randomBytes as KZ}from"node:crypto";var bM="aes-256-gcm",sv=32,no=12,rv=16,vM="agentiqa-browser-profile";function YZ(t){if(/^[0-9a-fA-F]{64}$/.test(t))return Buffer.from(t,"hex");try{let e=Buffer.from(t,"base64");return e.length===sv?e:null}catch{return null}}function _M(){return SM().key}function wM(){return SM().source}function SM(){let t=process.env.PROFILE_ENCRYPTION_KEY?.trim();if(t){let r=YZ(t);if(r)return{key:r,source:"PROFILE_ENCRYPTION_KEY"}}let e=process.env.ADMIN_SERVICE_KEY?.trim();if(e)return{key:Buffer.from(yM("sha256",e,"",vM,sv)),source:"ADMIN_SERVICE_KEY"};let n=process.env.E2E_ADMIN_SERVICE_KEY?.trim();return n?{key:Buffer.from(yM("sha256",n,"",vM,sv)),source:"E2E_ADMIN_SERVICE_KEY"}:{key:null,source:"none"}}function EM(t){let e=_M();if(!e)return null;let n=KZ(no),r=WZ(bM,e,n),s=Buffer.concat([r.update(t,"utf8"),r.final()]),i=r.getAuthTag();return Buffer.concat([n,i,s])}function TM(t){let e=_M();if(!e||!Buffer.isBuffer(t)||t.length<=no+rv)return null;try{let n=t.subarray(0,no),r=t.subarray(no,no+rv),s=t.subarray(no+rv),i=zZ(bM,e,n);return i.setAuthTag(r),Buffer.concat([i.update(s),i.final()]).toString("utf8")}catch{return null}}function xM(t){return`browser-profiles/${t}.json.enc`}var IM=!1;function JZ(){IM||(IM=!0,console.warn("[CloudProfileStore] profile encryption unavailable (no PROFILE_ENCRYPTION_KEY / ADMIN_SERVICE_KEY / E2E_ADMIN_SERVICE_KEY) \u2014 durable browser-profile persistence disabled"))}async function AM(t,e){try{let n=EM(JSON.stringify(e));if(!n){JZ();return}await to(n,xM(t),"application/octet-stream")}catch(n){console.error(`[CloudProfileStore] save failed for ${t}: ${n.message}`)}}async function kM(t){try{let e=await wp(xM(t));if(!e)return null;let n=TM(e);return n?JSON.parse(n):(console.warn("[CloudProfileStore] decrypt failed for existing browser profile",{projectId:t,keySource:wM(),bytes:e.length}),null)}catch{return null}}var xp=class extends Ip{sessionCredentials=new Map;projectProfiles=new Map;allowPrivateNetwork;resolveSink;constructor(e={}){super(),this.allowPrivateNetwork=e.allowPrivateNetwork??!1}setDiagnosticSinkResolver(e){this.resolveSink=e,this.diagLog=(n,r,s)=>{let i=this.lookupSink(n);i&&i.emit({kind:"log",ts:Date.now(),sessionId:n,level:"info",source:"PlaywrightService",msg:r,data:s})}}lookupSink(e){let n=this.resolveSink?.(e);if(n)return n;let r=e.indexOf(":");if(!(r<=0))return this.resolveSink?.(e.slice(0,r))}preflightAllowsPrivateNetwork(){return this.allowPrivateNetwork||super.preflightAllowsPrivateNetwork()}preflightAllowsLocalFileUrls(){return!1}seedCredentials(e,n){this.sessionCredentials.set(e,new Map(n.map(r=>[r.name,{secret:r.secret}])))}clearCredentials(e){this.sessionCredentials.delete(e)}allowsLocalFileUrls(){return!1}async saveProjectProfile(e,n){this.projectProfiles.set(e,n),await AM(e,n)}async getProjectProfile(e){let n=this.projectProfiles.get(e);if(n!==void 0)return n;let r=await kM(e);return r!=null&&this.projectProfiles.set(e,r),r??null}getSuggestedSampleFiles(e,n){return gM(e,n)}async dispatchPlatformAction(e,n,r){if(n==="type_project_credential_at"){let s=String(r.credentialName??r.credential_name??"").trim();if(!s)throw new Error("credentialName is required");let a=this.sessionCredentials.get(e.sessionId)?.get(s);if(!a)throw new Error(`Credential "${s}" not found`);let o=a.secret,l=!!(r.pressEnter??r.press_enter??!1),c=r.clearBeforeTyping??r.clear_before_typing??!0;if(r.ref)return await this.typeByRef(e,String(r.ref),o,l,c,!0);if(!Ky(r)){let g=await this.locateSoleVisiblePasswordCenter(e);if(g)return await this.typeTextAt(e,g.x,g.y,o,l,c,!0);throw Yy()}let{viewportWidth:u,viewportHeight:d}=e,f=g=>Math.floor(g/1e3*u),h=g=>Math.floor(g/1e3*d),p=this.requireNormalizedPoint(n,r);return await this.typeTextAt(e,f(p.x),h(p.y),o,l,c,!0)}}};import{spawn as XZ}from"node:child_process";import{existsSync as QZ}from"node:fs";import{createRequire as ZZ}from"node:module";function eee(t=ZZ(import.meta.url),e=QZ){try{let n=t("ffmpeg-static");return typeof n=="string"&&n.length>0&&e(n)?n:null}catch{return null}}function tee(t="ffmpeg",e=XZ){return new Promise(n=>{try{let r=e(t,["-version"],{stdio:["ignore","ignore","ignore"]});r.on("error",()=>n(!1)),r.on("close",s=>n(s===0))}catch{n(!1)}})}async function Ap(t={}){let e=(t.bundled??eee)();return e?{command:e,source:"bundled"}:await(t.pathRunnable??tee)()?{command:"ffmpeg",source:"path"}:{command:null,source:"none"}}function Ci(t){Zd()&&process.stderr.write(`[agentiqa] ${t}
|
|
2005
2005
|
`)}async function aee(){return new Promise((t,e)=>{let n=nee();n.listen(0,()=>{let r=n.address();if(typeof r=="object"&&r){let s=r.port;n.close(()=>t(s))}else e(new Error("Could not determine port"))}),n.on("error",e)})}function oee(){try{let e=ree(import.meta.url).resolve("@mobilenext/mobile-mcp/lib/index.js"),n=new np({resolveServerPath:()=>e,quiet:!0});return Ci("Mobile MCP support enabled"),n}catch{return Ci("Mobile MCP support disabled (@mobilenext/mobile-mcp not found)"),null}}function lee(t){if(t){let n=s=>s.map(i=>typeof i=="string"?i:iee(i,{depth:4})).join(" "),r=(s,i)=>{try{see(t,`${new Date().toISOString()} [${s}] ${n(i)}
|
|
2006
2006
|
`)}catch{}};console.log=(...s)=>r("log",s),console.warn=(...s)=>r("warn",s),console.error=(...s)=>r("error",s);return}let e=()=>{};console.log=e,console.warn=e}async function ro(t){let e=t.port??await aee();Ci(`Starting engine on port ${e}...`),lee(t.logFile),t.geminiKey&&(process.env.GOOGLE_API_KEY=t.geminiKey),t.anthropicKey&&(process.env.ANTHROPIC_API_KEY=t.anthropicKey),t.openaiKey&&(process.env.OPENAI_API_KEY=t.openaiKey);let n=process.env.AGENTIQA_API_URL||"https://agentiqa.com";if(process.env.API_URL||(process.env.API_URL=n),!process.env[vp]&&!process.env[bp]){let o=await Ap();o.source==="bundled"&&o.command?(process.env[vp]=o.command,Ci(`ffmpeg: using bundled binary at ${o.command}`)):o.source==="path"?Ci("ffmpeg: using system binary on PATH"):(process.env[bp]="1",Ci("ffmpeg: not found (bundled or PATH) \u2014 video recording will be skipped"))}let r=new xp({allowPrivateNetwork:!0}),s=oee(),i=WP(r,s);await new Promise(o=>{i.listen(e,o)});let a=`http://localhost:${e}`;return Ci("Engine ready"),{url:a,shutdown:async()=>{if(s&&"isConnected"in s){let o=s;o.isConnected()&&await o.disconnect()}await r.cleanup(),i.close()}}}import{readFileSync as wee}from"node:fs";import qM from"node:path";import{readFileSync as cee,writeFileSync as uee,mkdirSync as dee,unlinkSync as pee,chmodSync as hee}from"node:fs";import{homedir as fee}from"node:os";import RM from"node:path";var CM=RM.join(fee(),".agentiqa"),kp=RM.join(CM,"credentials.json");function _r(){try{let t=cee(kp,"utf-8"),e=JSON.parse(t);return!e.token||!e.email||!e.expiresAt||new Date(e.expiresAt)<new Date?null:e}catch{return null}}function NM(t){dee(CM,{recursive:!0}),uee(kp,JSON.stringify(t,null,2)+`
|
|
2007
2007
|
`,"utf-8");try{hee(kp,384)}catch{}}function OM(){try{return pee(kp),!0}catch{return!1}}var mee="https://agentiqa.com",PM=600*1e3;async function MM(t,e){let n=e||process.env.AGENTIQA_API_URL||mee,r=await fetch(`${n}/api/service-keys/exchange`,{method:"POST",headers:xt({"Content-Type":"application/json","X-Service-Key":t})});if(!r.ok){let s=await r.json().catch(()=>({error:r.statusText}));throw new Error(`Service key exchange failed (${r.status}): ${s.error??r.statusText}`)}return await r.json()}function gee(t,e=Date.now(),n=PM){let r=Date.parse(t.expiresAt);return Number.isNaN(r)?!1:r-e<n}var iv=new Map;async function DM(t,e={}){let n=e.nowMs??Date.now(),r=e.thresholdMs??PM;if(!gee(t,n,r))return{auth:t,refreshed:!1};let s=e.serviceKey??process.env.AGENTIQA_SERVICE_KEY;if(!s)return{auth:t,refreshed:!1};let i=e.exchange??MM,a=iv.get(s);return a||(a=(async()=>i(s,e.apiUrl))(),iv.set(s,a),a.catch(()=>{}).finally(()=>{iv.delete(s)})),{auth:await a,refreshed:!0}}async function Ni(t){let e=process.env.AGENTIQA_SERVICE_KEY;if(e)return{type:"service-key",auth:await MM(e,t)};let n=_r();return n?{type:"credentials",creds:n}:null}function av(t){return t?t.type==="service-key"?{userId:t.auth.userId,projectId:t.auth.projectId,userToken:t.auth.token}:{userToken:t.creds.token}:{}}var yee={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY"};function vee(t,e){return t==="openai"?`OpenAI API key not found for --model ${e}
|