Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Guard policy: only the hard list refuses; other checks leave a note
Barack Sokullud952aa1c347e
diff --git a/AGENT.md b/AGENT.mdindex c2af504d2..f2d010ade 100644--- a/AGENT.md+++ b/AGENT.md@@ -51,6 +51,13 @@ vanilla JS/CSS unless there is a very strong reason to add a framework.messages, download files, record media, or mutate remote state.- Do not weaken permission-gate behavior or host checks to make a task pass.Fix the routing, user prompt, or adapter instead.+- Guards (WebBrain checks that refuse, defer or stop a model action) follow+ `docs/guards.md`. Only the hard list refuses outright: the wrong recipient,+ deleting data, money, credentials, and publishing something the user did+ not ask for. Every other check leaves a note for the model or asks the+ user. A new guard is registered in `src/*/src/agent/guard-policy.js` with+ what it does when it cannot decide and `mustNotBlock`, a test of a+ legitimate task it must let through. `test/guard-policy.mjs` enforces this.- Avoid committing secrets, trace files with private page content, downloadeduser files, or generated artifacts unless the task explicitly requires them.@@ -70,6 +77,8 @@ vanilla JS/CSS unless there is a very strong reason to add a framework.permissions, and user-risk model.- `docs/prompt-injection-defense.md`: mandatory reading for any change thatpasses page-derived content into prompts or tool results.+- `docs/guards.md`: mandatory reading before adding or changing a check that+ refuses, defers or stops a tool call, write, submit or completion.## Layoutdiff --git a/docs/guards.md b/docs/guards.mdnew file mode 100644index 000000000..53dee0bcb--- /dev/null+++ b/docs/guards.md@@ -0,0 +1,85 @@+# Guards++A guard is WebBrain code, not the user, that refuses, defers or stops a tool+call, a write, a submit or a completion. Every guard is registered in+`src/*/src/agent/guard-policy.js` with a class and what it does when it knows+the action is wrong (`onDecided`) and when it cannot tell (`onCannotDecide`):+`block`, `ask` or `advise`. The file is shared verbatim by both builds.++## The policy++- **Only the hard list refuses.** Five classes may refuse an action outright:+ the wrong recipient (`recipient`), deleting data (`deletion`), spending+ money (`money`), credentials (`credentials`), and publishing or sending+ something the user did not ask for (`unrequested_publication`). When a hard+ guard cannot decide, it asks the user on WebBrain's own card where one+ exists (`ask`), and refuses otherwise.+- **Everything else advises.** Verification, exact readback, evidence and+ completion checks are `quality` guards. They tell the model about the+ problem instead of stopping it:+ - A tool call goes through, and its result starts with+ `guardAdvisories: [{ guard, note }]`, so a truncated result keeps them. A+ note is dropped when another check then refuses the call, because nothing+ went through.+ - A completion guard refuses a `done` or a plain final once per run, and+ that refusal is its note. Each guard gets its own: when two apply, the+ second is checked once the first has advised. The next completion a guard+ would refuse is accepted, and the final answer ends with one line,+ "WebBrain could not verify everything: …" (at most four items).+ - A completion accepted over a guard that knows the claim is wrong (the+ completion judge's "not done", an unauthorized mutation, missing or+ failed progress rows, text that went into a formatting toolbar) ends the+ run as `partial`, not `success`. Missing evidence alone keeps the+ model's outcome.+ - A write that went out but could not be read back exactly (GitHub's+ CodeMirror editor is the usual case) is an unverified success: it locks+ nothing, arms no text-write debt and is not a loop failure.+ - A quality guard whose `onCannotDecide` is `ask` asks the user when it+ cannot verify a consequential step, such as a commit or a post. Where+ that guard has no card, it refuses.+- **Not guards.** These keep their behavior: the user's own permissions,+ modes and budgets (`permission_gate`); same-site, frame and task-authority+ boundaries, CAPTCHA and access walls, and a person acting in the same tab+ (`host_check`); loop and observation limits (`budget`); calls that cannot+ run as given (`infra`); and Stop, corrections and cancelled cards+ (`user_control`).+- **Strict checks.** Settings → General → "Strict checks" (`strictGuards`)+ makes every quality guard block again, with the old forced verification+ turns and the failure-only `done`.+- **Unregistered ids** keep blocking, so a refusal that was never registered+ is not silently relaxed.++## What still refuses, and why++| Class | Guards | Why |+|---|---|---|+| `recipient` | `chat-send-recipient-guards`, `native-chat-receipt-not-durable`, `preparation-timeout-recipient-preflight`, `recipient-active-conversation-pin`, `recipient-dispatch-binding-revalidate`, `recipient-guard-refusal`, `recipient-mismatch-confirm-card`, `schedule-resume-chat-state-not-durable`, `social-preflight-context-mismatch` | A message to the wrong person cannot be taken back. A resumed run without a durable receipt would send a delivered message again. |+| `deletion` | `deletion-confirm-card`, `deletion-guard-refusal`, `preparation-timeout-submit-preflight`, `truncated-preview-replacement`, `unsaved-changes-data-loss` | Deleted data, including a field value replaced by its own shortened preview, is gone. |+| `money` | `captcha-paid-solve-protection` | A paid solve spends the user's balance. |+| `credentials` | `chat-user-input-required`, `otp-mailbox-scope`, `strict-secret-credential-handling` | One-time codes, passwords and payment details are the user's to enter. |+| `unrequested_publication` | `bot-memory-reservation`, `click-duplicate-submit`, `clickax-task-click-lock`, `consequential-durability-checkpoint`, `github-conditional-commit-unbound`, `recipient-guard-unrequested-send`, `sched-reconciliation-required`, `social-api-publication-route`, `social-publication-audit`, `social-publication-authorization-guard`, `steer-post-correction-commit-guard`, `steer-prior-submission-unreconciled` | A post, commit, submit or send the user did not ask for, or a second copy of one that may already have gone out, is public or hard to undo. |++The `permission_gate`, `host_check`, `budget`, `infra` and `user_control`+entries in the registry document checks that are not guards; they are listed+there so the registry covers every refusal.++## Adding a guard++1. Prefer not to. Fix the routing, the prompt or the adapter first, and+ check that the problem is not a reader that cannot see what the page+ shows (the CodeMirror readback was one).+2. Register the id in `guard-policy.js` with its `class`, `family`,+ `decides`, `onDecided`, `onCannotDecide` and a one-line `summary`. A check+ that only lacks evidence is `quality`, whatever it protects.+3. Declare `mustNotBlock: 'test/<file>.mjs#<test name>'`: a test of a+ legitimate task the guard must let through. Write it first; it is the+ guard's false-positive budget.+4. Route the decision through the agent's helpers: `_guardAdvisesFor` for a+ note on a tool call, `_guardRefusesOnce` for a completion,+ `_guardOutcome` for anything else. Test the default and Strict checks.++`test/guard-policy.mjs` enforces this: the registry's shape, that only the+hard list refuses, that every id the code names is registered, `mustNotBlock`+for every guard added after the registry (the 158 that existed then are+grandfathered, and that list only shrinks), and a ceiling on completion+refusals (`blockedDone: true`) per build.diff --git a/docs/literal-editor-verification.md b/docs/literal-editor-verification.mdindex e910c2a61..0cbffd65e 100644--- a/docs/literal-editor-verification.md+++ b/docs/literal-editor-verification.md@@ -14,4 +14,4 @@ The nested three-origin case additionally exposed unfenced focus during legacy iThe installed three-origin flow now also completes successfully after its one exact native application POST. Independent completion proof binds the actual submitted frame, task, run, action sequence, fresh document and success receipt. The frame is refreshed after the completion evaluator waits; a changed or missing frame cannot preserve success. `test/completion-iframe-submit.mjs` covers those receipt boundaries in both builds.-These controlled applications do not establish support for every third-party editor, sandbox, closed shadow tree, or canvas. `contenteditable="plaintext-only"` can sanitize native insertion differently; an altered settled value remains an uncertain failure instead of being accepted as exact. The saved-state assertions cover the production routes they exercise without claiming live authenticated service verification.+These controlled applications do not establish support for every third-party editor, sandbox, closed shadow tree, or canvas. `contenteditable="plaintext-only"` can sanitize native insertion differently; an altered settled value is never accepted as exact. It is reported as an unverified write with a note (a failure with text-write debt under Settings → Strict checks; see `docs/rich-text-input.md`). The saved-state assertions cover the production routes they exercise without claiming live authenticated service verification.diff --git a/docs/rich-text-input.md b/docs/rich-text-input.mdindex e0e6cafd9..36cfe9043 100644--- a/docs/rich-text-input.md+++ b/docs/rich-text-input.md@@ -80,6 +80,21 @@ text reader, so headings, lists and blockquotes can also be replaced. Full nativselection must cover empty blocks and inline atoms as well as text; an interceptedpartial selection leaves the original application document intact.+A write whose text went out but whose settled value cannot be confirmed is+reported, not locked. Editors without a document reader are read back through+`innerText`, the rendered layout: GitHub's CodeMirror shows every blank line+twice and omits off-screen lines, so a correct file never reads back exactly.+By default such a write returns `success: true`, `unverifiedWrite: true`+(`verified: false` when the readback differs) and a note in `guardAdvisories`;+`readbackExact: false` marks the rendered-text fallback. Later writes to that editor are not refused,+the loop detector does not count the write as a failure, and a browser batch+continues. Editor proofs are still dropped, so a commit or publication gate never+treats the write as verified; the agent keeps a non-blocking record for those+gates (`_unverifiedTextWriteRecord`). `set_field({submit: true})` still withholds+its Enter for an unverified value and says so (`submitSkipped: 'value_unverified'`).+Settings → General → Strict checks restores the failure result, the text-write+debt and its readback-only recovery lock (see `test/guard-advisory-writes.mjs`).+When context verification or repeated page changes prevent the next action,the task shows a specific explanation and Give up / Retry choices. Retry keepscompleted progress and verifies the current page again using the normal checks.diff --git a/docs/security-model.md b/docs/security-model.mdindex b7e37c419..883e4bcf1 100644--- a/docs/security-model.md+++ b/docs/security-model.md@@ -260,6 +260,19 @@ are separate prompts: they never time out.The logic lives in `src/*/src/agent/clarify-timeout.js`.+## Guards++WebBrain's own checks on model actions are registered in+`src/*/src/agent/guard-policy.js`. Only five classes may refuse an action+outright: the wrong recipient, deleting data, money, credentials, and+publishing or sending something the user did not ask for. Verification,+readback, evidence and completion checks leave a note for the model instead,+and a completion accepted over them tells the user what was not verified.+Permission gates, host and frame boundaries, CAPTCHA and access walls, and+loop budgets are not guards and keep their behavior. Settings → General →+**Strict checks** makes every verification check block again.+`docs/guards.md` lists what still refuses and the rule for adding a guard.+## `/allow-api` FlagSet per-conversation via the `/allow-api` slash command in the side panel, ordiff --git a/package.json b/package.jsonindex 28603c69d..5f26bb228 100644--- a/package.json+++ b/package.json@@ -63,8 +63,8 @@"benchmark:relevance": "node scripts/benchmark-offline-relevance.mjs --verbose","test:social-contract": "node --test test/social-publish-contract.mjs test/publication-quote-markup.mjs","test:social-contract:dom": "node test/social-publish-contract-dom.mjs",- "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/lifecycle-steering-restart.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/clarify-timeout-policy.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",- "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/delivery-click-ax-response-loss.mjs test/delivery-stop-compound.mjs test/delivery-cdp-input.mjs test/delivery-click-locks.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs",+ "test:runtime-lifecycle": "node test/bot-memory-dom.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/lifecycle-steering-restart.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/clarify-timeout-policy.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/guard-policy.mjs test/lifecycle-planner-digest.mjs test/lifecycle-vision-fallback.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/guards-steering-receipts.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/history-recovery.mjs test/history-recovery-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs && node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/literal-frame-mv3.mjs && node test/quality/mastodon-publication-mv3.mjs && node test/quality/mastodon-reply-route-mv3.mjs && node test/quality/mastodon-deletion-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs && node test/quality/mastodon-delete-confirmation-mv3.mjs --menu-read && node test/quality/mastodon-delete-confirmation-mv3.mjs --vague && node test/quality/unbound-deletion-mv3.mjs && node test/quality/recipient-clarify-mv3.mjs && node test/quality/open-chat-recipients-mv3.mjs && node test/quality/correction-cross-site-mv3.mjs && node test/quality/anchored-action-mv3.mjs && node test/quality/inline-social-composer-mv3.mjs && node test/quality/x-compose-dialog-mv3.mjs && node test/quality/bluesky-composer-mv3.mjs && node test/quality/dropdown-menu-matrix.mjs && node test/quality/mastodon-deletion-navigation-mv3.mjs && node test/quality/semantic-navigation-matrix.mjs && node test/quality/workflow-replay-mv3.mjs && node test/quality/generative-media-mv3.mjs && node test/quality/cdp-worker-restart-mv3.mjs && node test/quality/steering-worker-restart-mv3.mjs",+ "test:page-feedback": "node --test test/trusted-field-preparation.mjs test/guard-advisory-writes.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/delivery-click-ax-response-loss.mjs test/delivery-stop-compound.mjs test/delivery-cdp-input.mjs test/delivery-click-locks.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs && node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs","test:history-recovery": "node --test test/history-recovery.mjs test/history-recovery-ui.mjs test/history-recovery-state.mjs test/history-recovery-scheduler.mjs test/history-recovery-atomic.mjs test/conversation-persistence.mjs","test:chat-steering": "node --test test/chat-steering.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs","test:rich-text-dom": "node test/ui-content-lifecycle.mjs --dom",@@ -96,8 +96,8 @@"test:quality:whatsapp": "node test/quality/whatsapp-contact-matrix.mjs","test:chat-draft-recovery": "node --test test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs && node test/quality/native-chat-presubmit-mv3.mjs","test:upload-owner": "node --test test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs",- "test:shard:quick": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:provider-instances:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:browser-batch && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs",- "test:shard:runtime-unit": "node --test test/skill-download-wait.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/clarify-timeout-policy.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/auto-mode.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/video-upload-attachment.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/lifecycle-planner-digest.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-vision-fallback.mjs test/delivery-click-locks.mjs test/guards-steering-receipts.mjs test/terminal-user-messages.mjs test/improver-providers.mjs test/improver-providers-agent.mjs test/improver-guards-ledger.mjs test/improver-guards-tools.mjs test/improver-clarify.mjs test/improver-clarify-scheduler.mjs test/improver-misc.mjs test/improver-forms.mjs test/improver-forms-strict-secrets.mjs test/improver-content-press-keys-hint.mjs && npm run test:plan-notifications",+ "test:shard:quick": "npm run test:cms && npm run test:markdown && npm run test:generative-media && npm run test:systemone && npm run test:systemone:fast && node --test test/guard-policy.mjs test/browser-dialogs.mjs test/capsolver-cloud-broker.mjs test/captcha-providers.mjs test/captcha-weighted-fallback.mjs test/captcha-hcaptcha-providers.mjs test/captcha-native-providers.mjs test/captcha-runtime-policy.mjs test/captcha-callback-bridge.mjs test/captcha-bridge-registration.mjs test/captcha-aws-recovery.mjs test/captcha-documented-contracts.mjs test/huggingface-signup-recovery.mjs test/trace-full-export.mjs test/feedback-traces.mjs && npm run test:firefox-bidi && npm run test:billing-notice && npm run test:compass-quota && npm run test:provider-limits && npm run test:provider-catalog && npm run test:provider-instances:ui && npm run test:openrouter-capabilities && npm run test:anthropic && npm run test:browser-batch && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:cloud-bridge-approval && npm run test:discord && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && npm run test:workflow-editor && node --test test/profile-sync-stats.mjs && node --test test/memcode-recall.mjs",+ "test:shard:runtime-unit": "node --test test/skill-download-wait.mjs && node --test test/agent-lifecycle.mjs test/runtime-startup.mjs test/run-ui-scheduled-lifecycle.mjs test/transport-deadlines.mjs test/cdp-worker-restart.mjs test/bot-memory.mjs test/bot-memory-click-guard.mjs test/bot-memory-registries.mjs test/bot-memory-cloud-controller.mjs test/cdp-clear-receipt.mjs test/cdp-field-submit-recovery.mjs test/conversation-persistence.mjs test/context-live-tool-group.mjs test/integration-races.mjs test/watch-completion-checkpoint.mjs test/runtime-model-identity.mjs test/provider-message-privacy.mjs test/runtime-task-authority.mjs test/planner-repair-authority.mjs test/runtime-progress-continuation.mjs test/chat-resume-chain.mjs test/chat-resume-completion.mjs test/native-chat-execution-ledger.mjs test/chat-send-dispatch-result.mjs test/chat-reply-dedup-race.mjs test/memcode-lifecycle.mjs test/runtime-peer-review.mjs test/read-continuation-schema.mjs test/completion-submit-acknowledgement.mjs test/completion-live-status.mjs test/completion-iframe-submit.mjs test/form-validation-alert-readings.mjs test/control-effect-readings.mjs test/trusted-retry-readings.mjs test/completion-semantic-commit.mjs test/completion-diagnostics.mjs test/mastodon-publication.mjs test/calculator.mjs test/chat-recovery-protocol.mjs test/chat-pending-reconciliation.mjs test/semantic-page-retry.mjs test/pdf-detection.mjs test/runtime-lifecycle.mjs test/collection-read-progress.mjs test/network-lifecycle.mjs test/text-write-cancellation.mjs test/guard-advisory-writes.mjs test/trusted-field-preparation.mjs test/draftjs-text.mjs test/codemirror-text.mjs test/rich-text-frameworks.mjs test/cdp-managed-text-selection.mjs test/firefox-rich-text-readback.mjs test/contenteditable-beforeinput.mjs test/trusted-field-preparation-ownership.mjs test/typing-preparation-geometry.mjs test/chat-steering.mjs test/resource-mutation-guards.mjs test/completion-steering-receipt-authority.mjs test/steering-revision-recovery.mjs test/pending-clarification-hydration.mjs test/clarify-timeout-policy.mjs test/permission-steering-wakeup.mjs test/pure-calculation-reply.mjs test/pure-calculation-tools.mjs test/page-feedback.mjs test/page-feedback-progress.mjs test/page-feedback-unbindable-target.mjs test/guard-advisory-actions.mjs test/rich-text-preflight-page-change.mjs test/keyboard-receiver-frame.mjs test/ask-response-scope.mjs test/auto-mode.mjs test/ask-completion-churn.mjs test/page-feedback-policy.mjs test/research-escalation-page-feedback.mjs test/page-feedback-transport-races.mjs test/page-feedback-recovery.mjs test/telegram-read-preparation-agent.mjs test/media-download-agent-handler.mjs test/code-scanning-url-recipient.mjs test/apocalypse-comm-parsing.mjs test/apocalypse-scalar-decoding.mjs test/bitgpu-chat-security.mjs test/social-media-url-upgrades.mjs test/downloaded-file-saved-bytes.mjs test/downloaded-file-local-probe.mjs test/formless-verification-recovery.mjs test/file-upload-accept.mjs test/file-upload-accept-agent.mjs test/workflow-route-generic-completion.mjs test/release-publication-completion.mjs test/workflow-implicit-metadata.mjs test/workflow-field-readings.mjs test/workflow-field-anchors.mjs test/user-turn-kind.mjs test/follow-up-task-context.mjs test/completion-current-execution-evidence.mjs test/video-upload-attachment.mjs test/feedback-automatic-churn.mjs test/feedback-navigation-idle.mjs test/feedback-run-boundaries.mjs test/feedback-ask-viewing.mjs test/lifecycle-terminal-done.mjs test/incomplete-completion-recovery.mjs test/guard-advisory-completion.mjs test/lifecycle-planner-digest.mjs test/lifecycle-steering-latency.mjs test/lifecycle-steering-restart.mjs test/lifecycle-vision-fallback.mjs test/delivery-click-locks.mjs test/guards-steering-receipts.mjs test/terminal-user-messages.mjs test/improver-providers.mjs test/improver-providers-agent.mjs test/improver-guards-ledger.mjs test/improver-guards-tools.mjs test/improver-clarify.mjs test/improver-clarify-scheduler.mjs test/improver-misc.mjs test/improver-forms.mjs test/improver-forms-strict-secrets.mjs test/improver-content-press-keys-hint.mjs && npm run test:plan-notifications","test:shard:browser-a": "node --test test/captcha-draft-content.mjs test/captcha-challenge-surfaces.mjs && node test/bot-memory-dom.mjs && node test/bot-memory-click-dom.mjs && node test/ui-content-lifecycle.mjs && node --test test/native-telegram-chat.mjs test/native-telegram-recipient.mjs test/telegram-native-baseline.mjs test/telegram-native-latest.mjs test/native-chat-pre-enter-draft.mjs test/chat-draft-dispatch-ownership.mjs test/native-telegram-alias-preparation.mjs test/telegram-read-preparation-content.mjs test/queued-composer-ownership.mjs test/onboarding-provider-ready.mjs test/workflow-native-targets.mjs test/native-whatsapp-chat.mjs test/native-chat-context-identity.mjs test/native-whatsapp-contact.mjs test/whatsapp-native-bootstrap.mjs test/whatsapp-drawer-identity.mjs test/whatsapp-read-latest.mjs test/whatsapp-read-preparation.mjs test/whatsapp-chat-completion.mjs test/whatsapp-chat-restart.mjs test/chat-goal-lifecycle.mjs test/chat-completion.mjs test/chat-generic-dispatch.mjs test/completion-live-status-browser.mjs test/native-confirmation-visibility.mjs test/native-button-preparation.mjs test/read-continuation-browser.mjs test/iframe-preparation-focus.mjs test/contenteditable-literal.mjs test/native-chat-empty-editor.mjs test/native-chat-trusted-clear.mjs test/chat-steering-ui.mjs test/recipient-confirmation-ui.mjs test/assistant-message-visibility-ui.mjs test/page-monitor-ui.mjs test/x-compose-trusted-typing.mjs test/page-monitor-dialog.mjs test/page-monitor-dialog-native.mjs test/page-monitor-inline-post.mjs test/bluesky-composer-context.mjs test/page-monitor-anchored.mjs test/page-monitor-upload-owner.mjs test/page-monitor-upload-release.mjs test/page-monitor-native-controls.mjs test/page-monitor-native-preparation.mjs test/native-preparation-cold.mjs test/page-monitor-navigation.mjs test/page-monitor-main-owner.mjs test/page-monitor-collateral-controls.mjs test/accessibility-tree-scoped-budget.mjs test/ax-reference-origin.mjs test/page-monitor-decorative-hit.mjs test/social-ui-navigation.mjs test/native-resource-deletion-binding.mjs test/native-mastodon-confirmation.mjs test/dropdown-menu-inventory.mjs test/page-monitor-passive-progress.mjs test/page-monitor-feed-items.mjs test/media-download-binding.mjs test/media-download-capture-integration.mjs test/social-media-downloader-reinjection.mjs test/upload-file-local-state-guidance.mjs test/monitor-intervention-contract.mjs test/monitor-owned-geometry.mjs test/monitor-viewport-remainder.mjs test/monitor-scroll-churn.mjs test/monitor-local-attribution.mjs test/monitor-lifecycle-leaks.mjs test/lifecycle-run-ui.mjs test/lifecycle-menu-prompts-held.mjs test/delivery-cdp-input.mjs test/delivery-click-ax-response-loss.mjs test/delivery-native-button-geometry.mjs test/delivery-hover-transition.mjs test/delivery-native-button-route.mjs test/delivery-dispatch-boundary.mjs test/delivery-stop-compound.mjs test/guards-control-classification.mjs test/guards-unbound-deletion.mjs test/submit-probe-readings.mjs test/improver-content-account-chrome.mjs test/improver-content-recipient.mjs test/improver-content-truncated-replacement.mjs test/improver-forms-probe.mjs test/improver-misc-trace-browser.mjs","test:shard:browser-b1": "node test/message-recipient-upload.mjs && node test/message-recipient-clarify-binding.mjs && node --test test/message-recipient-whatsapp.mjs test/message-control-readings.mjs && node test/quality/integration-mv3.mjs --full-form && node test/quality/integration-mv3.mjs --batch && node test/quality/literal-calculate-midrun-mv3.mjs && node test/quality/ask-completion-churn-mv3.mjs && node test/quality/ask-person-activity-mv3.mjs && node test/quality/telegram-cold-preparation-mv3.mjs && node test/quality/native-chat-mv3.mjs && node test/quality/native-chat-presubmit-mv3.mjs && node test/quality/cloud-bot-memory-mv3.mjs","test:shard:browser-b2": "node test/quality/whatsapp-contact-matrix.mjs && node test/quality/pdf-detection-mv3.mjs && node test/quality/download-upload-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs && node test/quality/upload-release-binding-mv3.mjs --selector-recovery && node test/quality/upload-release-binding-mv3.mjs --sequential-assets && node test/quality/release-review-world-mv3.mjs && node test/quality/downloaded-file-saved-bytes-mv3.mjs && node test/quality/file-upload-accept-mv3.mjs && node test/quality/bulk-resume-mv3.mjs && node test/quality/shared-action-guards-mv3.mjs && node test/quality/video-upload-attachment-mv3.mjs",diff --git a/src/chrome/src/agent/agent.js b/src/chrome/src/agent/agent.jsindex 9ebcaef17..0b1dd5962 100644--- a/src/chrome/src/agent/agent.js+++ b/src/chrome/src/agent/agent.js@@ -75,7 +75,7 @@ import {workflowRequiredRowsAreProcessed,} from './adapter-workflow-evidence.js';import { messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';-import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession } from './chat-workflow.js';+import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession, WAIVABLE_CHAT_SEND_REASONS } from './chat-workflow.js';import {fetchUrl,executeHttpSkillTool,@@ -164,6 +164,7 @@ import { GENERATIVE_MEDIA_SETUP_NOTE, isImageGenConfigured, mediaPermissionUrl,import { extractFirstJsonObject } from './json-extract.js';import { repairAssistantDisplayText, repairClarifyText, sanitizeText as sanitizePlannerText } from './text-sanitize.js';import { clarifyQuestionIsHard, clarifyTimedAnswer, clarifyTimeoutChoice, normalizeClarifyConsequence, normalizeClarifyTimeoutPolicy } from './clarify-timeout.js';+import { guardAdvisory, guardEntry, guardOutcome, withGuardAdvisories } from './guard-policy.js';import { emptyOutputFailureMessage, modelOutputDiagnostics } from './model-output-diagnostics.js';import { stepLimitUserMessage, terminalGuardUserMessage } from './terminal-messages.js';import { buildCustomSkillsPrompt, buildSkillLoaderDefinition, buildSkillToolDefinitions, buildSkillToolRegistry, getEligibleCustomSkills, getEligibleSkillCatalog, normalizeCustomSkills } from './skills.js';@@ -301,6 +302,9 @@ const PAGE_BLOCKER_RETRY_MS = 30_000;// at most this long, before the single press.const NATIVE_BUTTON_HOVER_SETTLE_MS = 600;const NATIVE_BUTTON_HOVER_POLL_MS = 50;+// jev-target-changed advice: the fast path planned this call against an+// observation the page no longer matches.+const JEV_TARGET_CHANGED_NOTE = 'The page changed after WebBrain\'s fast path planned this action, so its target could not be confirmed as the one it observed. It was sent to the element its ref or selector resolves to now; read the page before relying on the result.';const ASK_MODE_HANDOFF_TIMEOUT_MS = 5_000;const CONTENT_ACTION_SIGNAL_DEADLINES = new WeakMap();// A completed focus click is a browser dispatch, but need not be a text write.@@ -491,6 +495,17 @@ function selectionScopedResponseLanguagePolicy(locale) {};}+// What the user is told when a run ends with plain text after the "end with+// done" note was given once (Strict checks off).+// Completion guards whose decided case means the task is not done (a+// judge's sure verdict, a forbidden submission, failed or missing items,+// text typed into a toolbar). Accepted over their advice, a success claim+// ends the run as partial.+const OUTCOME_DOWNGRADING_GUARDS = new Set(['completion-verifier-not-done', 'plan-unauthorized-mutation-recorded',+ 'progress-success-claim-checks', 'done-rich-text-toolbar-obligation']);++const PLAIN_FINAL_PROTOCOL_CAVEAT = 'The task ended with a plain answer instead of a checked completion.';+function defaultPlanExecutionBlockNudge({viaDone = false,missingEvidence = false,@@ -959,6 +974,10 @@ export class Agent extends LoopDetector {// Settings → General → "When a question times out": 'finish' (default)// keeps the task moving, 'safe' takes the safe default. See clarify-timeout.js.this.clarifyTimeoutPolicy = 'finish';+ // Settings → General → "Strict checks" (off by default): quality+ // guards advise instead of refusing. See guard-policy.js.+ this.strictGuards = false;+ this._guardRunStates = new Map();this.maxContextMessages = 50; // minimum soft cap; larger provider windows scale this upthis._debugLog = []; // ring buffer for deep verbose (LLM requests/responses)this._debugLogMax = 200; // max entries before oldest are dropped@@ -1113,6 +1132,10 @@ export class Agent extends LoopDetector {this._lastAxScopes = new Map(); // tabId -> { documentToken, pageUrl }, captured by the latest AX readthis._uncertainTextMutations = new Map(); // tabId -> Map(target -> unresolved, potentially applied text write; no raw text)this._verifiedTextReplacements = new Map(); // tabId -> exact replacement digest bound to the live document+ // tabId -> Map(target -> latest write that went out but could not be+ // verified; no raw text). Default mode keeps this instead of debt and+ // never blocks on it; see _unverifiedTextWriteRecord.+ this._unverifiedTextWrites = new Map();// tabId -> recent document tokens (bounded) whose mutation records are// retained so a back-forward cache return restores their guards.this._recentTextMutationDocuments = new Map();@@ -1358,24 +1381,41 @@ export class Agent extends LoopDetector {}async _resolveExactTableDone(tabId, args, onUpdate = null) {+ // exact-table-done: by default each refusal below is given once per+ // run; the next done is accepted with what can be delivered and a+ // caveat for the user.if (typeof args?.data_ref !== 'string' || !args.data_ref) {const error = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), args?.summary);- return error ? { success: false, blockedDone: true, exactTableUnverified: true, error } : null;+ return error && this._exactTableAnswerRefuses(tabId, error)+ ? { success: false, blockedDone: true, exactTableUnverified: true, error } : null;}const state = this.readCompletenessStates.get(tabId);const record = state?.exactTableExports?.get(args.data_ref);const owner = this._exactTableOwner(tabId);if (!record || !record.owner.current() || !owner?.current() || record.runToken !== owner.runToken) {- return { success: false, blockedDone: true, exactTableUnverified: true,- error: 'Unknown, expired, or superseded table data_ref. Extract the table in this current task first.' };+ // Accepted, it delivers only the model's own summary, never rows+ // another task or run extracted.+ return this._guardRefusesOnce(tabId, 'exact-table-done', { decided: false,+ caveat: 'The table reference had expired, so the exact table could not be delivered.' })+ ? { success: false, blockedDone: true, exactTableUnverified: true,+ error: 'Unknown, expired, or superseded table data_ref. Extract the table in this current task first.' }+ : null;}onUpdate?.('tool_call', { name: 'extract_data', args: record.args, verification: true });const verified = await this.executeTool(tabId, 'extract_data', record.args, onUpdate,{ _exactTableVerificationRecord: record });onUpdate?.('tool_result', { name: 'extract_data', result: verified, verification: true });if (!owner.current() || verified?.verifiedExactTable !== true) {- return { success: false, blockedDone: true, exactTableUnverified: true,- error: verified?.error || 'Table freshness could not be verified in the owning task. Extract again.' };+ if (this._guardRefusesOnce(tabId, 'exact-table-done', { decided: false,+ caveat: 'The table on the page may have changed after it was extracted.' })) {+ return { success: false, blockedDone: true, exactTableUnverified: true,+ error: verified?.error || 'Table freshness could not be verified in the owning task. Extract again.' };+ }+ // Accepted: the stored snapshot is delivered while its task still owns+ // it, unless Strict secret mode now applies (the snapshot predates it,+ // and its re-projection may be what failed).+ if (owner.current() && this.strictSecretMode !== true) args.summary = record.summary;+ return null;}args.summary = record.summary;return null;@@ -2552,12 +2592,12 @@ export class Agent extends LoopDetector {pageUrl, currentUrl: submit.currentUrl }, text => this._sha256TextSync(text));}- _completionDoneBlock(tabId, name, args, batchStartState = null) {+ _completionDoneBlock(tabId, name, args, batchStartState = null, { skip = null } = {}) {const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;const outcome = name === 'done_json' ? 'success' : String(args?.outcome || '').trim().toLowerCase();const toolbarObligation = this._richTextToolbarGuard.completionAction(tabId);- if (outcome === 'success' && toolbarObligation) {+ if (outcome === 'success' && toolbarObligation && skip?.has?.('rich_text_toolbar_target_unresolved') !== true) {return {reason: 'rich_text_toolbar_target_unresolved',error: 'Success is blocked because the last text-entry attempt targeted a rich-text formatting toolbar. Enter the requested content in the editor body, verify that non-toolbar edit on a fresh turn, then complete; otherwise report a partial or failed outcome.',@@ -2565,12 +2605,15 @@ export class Agent extends LoopDetector {};}const state = this.completionInvariants.get(tabId);- const block = completionDoneBlock(state, name, args);+ const block = completionDoneBlock(state, name, args, { skip });if (block) return block;- if (outcome !== 'success' || !batchStartState) return null;+ if (outcome !== 'success' || !batchStartState || skip?.has?.('prior_turn_verification_required') === true) return null;const batchStartSequence = Number(batchStartState.sequence || 0);const lastActionSequence = Number(state?.lastAction?.sequence || 0);- if (batchStartState.verificationDebt || lastActionSequence > batchStartSequence) {+ // Debt carried into this batch that was just accepted over its note+ // (verification_required) is the same concern, not a second one.+ const carriedDebtAccepted = skip?.has?.('verification_required') === true && state?.verificationDebt === true;+ if ((batchStartState.verificationDebt && !carriedDebtAccepted) || lastActionSequence > batchStartSequence) {return {reason: 'prior_turn_verification_required',error: 'A success completion cannot rely on action or observation results from the same assistant tool batch. Let this batch finish, inspect the returned evidence on the next model turn, then call done again; otherwise use outcome="partial" or outcome="failed".',@@ -3010,7 +3053,7 @@ export class Agent extends LoopDetector {};}- async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null) {+ async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null, advisories = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled || !guard.scheduledResume || guard.siteWorkflow|| guard.requiresStateChange !== false || guard.requiresSubmission !== false) return null;@@ -3061,6 +3104,14 @@ export class Agent extends LoopDetector {await this._ensureWorkflowMetadataRequirements(tabId, {provider: this._activeProvider(tabId), costState: this.currentCostState.get(tabId) || null,}, guard.taskText, pageUrl);+ // github-conditional-commit-rearm (quality): the contract is armed above,+ // before this first write, so its proof and every later commit already+ // bind to it. Without Strict checks the action is sent now under that+ // contract, and the note tells the model what the rebuilt prompt requires.+ if (this._guardAdvisesFor(advisories, 'github-conditional-commit-rearm',+ 'WebBrain switched this resumed task to its conditional file-edit-and-commit contract before this action. Success now needs a verified file edit, a commit, and a readback of the exact committed file; verify the editor change before committing.')) {+ return null;+ }return {success: false, noDispatch: true, dispatched: false, retryable: true,workflowRearmed: true, workflowJob: 'edit-file-and-commit',@@ -3068,7 +3119,7 @@ export class Agent extends LoopDetector {};}- async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId)) {+ async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId), advisories = null) {const socialBlock = await this._socialPublicationPreSubmitBlock(tabId, name, args, detectedSubmit, provider);if (socialBlock) return socialBlock;await this._captureMastodonPublicationAttempt(tabId, name, args, detectedSubmit, provider);@@ -3120,7 +3171,25 @@ export class Agent extends LoopDetector {// authorize bytes that were never hashed, so only a non-mutating final// activation may use an existing binding. Anything else must split into// a plain write (verified on its own) followed by a separate click.+ // github-commit-split-write-required (quality): when the action does look+ // like the commit and the verified file and message binding a commit click+ // would need is in place, Strict checks off lets it run with a note; the+ // committed raw file is then checked against that binding after the commit.+ // An inconclusive detection is the cannot-decide case and keeps refusing,+ // and so does a missing binding (github-commit-evidence-binding).if (name !== 'click' && name !== 'click_ax' && name !== 'iframe_click') {+ if (looksLikeSubmit && this._guardAdvises('github-commit-split-write-required')) {+ const pageUrl = await this._currentUrl(tabId);+ await this._refreshGithubTextReplacementProofs(tabId, pageUrl);+ const binding = this._workflowSubmitBindingForAttempt(tabId, pageUrl, {}, detectedSubmit);+ if (binding?.metadataRequirementsIncomplete !== true && binding?.githubFileCommit+ && this._guardAdvisesFor(advisories, 'github-commit-split-write-required',+ name === 'execute_js'+ ? 'This script may change the editor or commit message while it commits, so the earlier verified file and message proofs do not cover it. It ran anyway; read the committed file and commit message back before reporting success.'+ : 'This action can change field values while it submits the commit, so the earlier verified file and message proofs do not cover it. It ran anyway; read the committed file and commit message back before reporting success.')) {+ return null;+ }+ }return {success: false,dispatched: false,@@ -5199,6 +5268,277 @@ export class Agent extends LoopDetector {};}+ // Completion guards under the default policy (Settings → General →+ // "Strict checks" off; see guard-policy.js). A completion guard refuses a+ // done or a plain final at most once per run, and that refusal is the+ // model's note. The next completion the same guard would refuse is+ // accepted, and its final answer tells the user what was not verified.+ // Strict checks keep every refusal, its budget and its forced turns.++ // Only an accepted completion ends a run, so a caveat a completion guard+ // recorded while an earlier attempt was still refused by another guard is+ // stale. A guard that fires again records it again during this attempt.+ // Caveats of other guard families are kept.+ _beginCompletionGuardAttempt(tabId) {+ const state = this._guardRunState(tabId);+ for (const id of [...state.caveats.keys()]) {+ if (guardEntry(id)?.family === 'completion') state.caveats.delete(id);+ }+ state.outcomeDowngrades?.clear();+ }++ // True once guard `id` advises and has used its one refusal in this run.+ _guardHasAdvised(tabId, id, { decided = true } = {}) {+ return this._guardAdvises(id, { decided }) && this._guardRunState(tabId).advised.has(id);+ }++ // Adds the "WebBrain could not verify everything" line, if any, to the+ // answer of an accepted completion. _guardRunState first drops a previous+ // run's caveats.+ _withCompletionCaveat(tabId, text) {+ const line = this._guardRunState(tabId) && this._guardCaveatLine(tabId);+ if (!line) return text;+ const base = String(text ?? '').trimEnd();+ return base ? `${base}\n\n${line}` : line;+ }++ // The guard behind a completion-invariant refusal, with the sentence the+ // user sees when a completion is accepted over it.+ _completionInvariantGuard(tabId, reason) {+ if (reason === 'rich_text_toolbar_target_unresolved') {+ return { id: 'done-rich-text-toolbar-obligation', decided: true,+ caveat: 'The last text may have gone into a formatting toolbar instead of the editor.' };+ }+ if (reason === 'iframe_form_verification_required') {+ return { id: 'done-iframe-form-unverified', decided: false,+ caveat: 'The form fields edited inside an embedded frame were not read back.' };+ }+ if (reason === 'verification_required') {+ return { id: 'done-verification-debt', decided: false,+ caveat: this.completionInvariants.get(tabId)?.lastAction?.downloadAction === true+ ? 'The download was not checked after it started.'+ : 'The page was not checked again after the last action.' };+ }+ if (reason === 'prior_turn_verification_required') {+ return { id: 'done-invariant-shape-checks', decided: false,+ caveat: 'Success was reported in the same step as the last action, before its result was seen.' };+ }+ if (reason === 'missing_outcome') {+ return { id: 'done-invariant-shape-checks', decided: true,+ caveat: 'The final report did not say whether the task succeeded, so it counts as partial.' };+ }+ return null;+ }++ _completionInvariantRefuses(tabId, block) {+ const guard = this._completionInvariantGuard(tabId, block?.reason);+ return !guard || this._guardRefusesOnce(tabId, guard.id, { decided: guard.decided, caveat: guard.caveat });+ }++ // A plain final in an Act/Dev run that acted. The "end with done, not+ // plain text" note is given once per run, shared with the plan guard's+ // plain-final protocol.+ _completionPlainFinalRefuses(tabId) {+ const state = this.completionInvariants.get(tabId);+ // Every applicable invariant gets its note in priority order: one+ // that already advised is accepted and the next one is checked.+ const guards = [];+ if (this._richTextToolbarGuard.hasPending(tabId)) guards.push(this._completionInvariantGuard(tabId, 'rich_text_toolbar_target_unresolved'));+ if (state?.iframeFormVerificationDebt) guards.push(this._completionInvariantGuard(tabId, 'iframe_form_verification_required'));+ if (state?.verificationDebt) guards.push(this._completionInvariantGuard(tabId, 'verification_required'));+ if (guards.length) {+ return guards.some(guard => this._guardRefusesOnce(tabId, guard.id, { decided: guard.decided, caveat: guard.caveat }));+ }+ const refuses = this._guardRefusesOnce(tabId, 'plain-final-done-protocol', { decided: true, caveat: PLAIN_FINAL_PROTOCOL_CAVEAT });+ const planProtocolRefuses = this._guardRefusesOnce(tabId, 'plan-plain-final-protocol', {+ caveat: PLAIN_FINAL_PROTOCOL_CAVEAT,+ });+ return refuses && planProtocolRefuses;+ }++ // progress-ledger-unresolved: rows still pending or acted (any outcome).+ // progress-success-claim-checks: success over missing, incomplete,+ // duplicate, skipped or failed rows.+ _progressGuardRefuses(tabId) {+ const rows = this._currentTaskLedgerRows(tabId);+ if (ledgerDoneBlock(rows, { limit: 1 })) {+ const counts = progressCounts(rows);+ return this._guardRefusesOnce(tabId, 'progress-ledger-unresolved', {+ caveat: `${counts.unresolved} of ${counts.total} items in the task's progress list were not finished.`,+ });+ }+ return this._guardRefusesOnce(tabId, 'progress-success-claim-checks', {+ caveat: 'Some items in the task\'s progress list are missing, incomplete, skipped or failed.',+ });+ }++ // read-coverage-incomplete: pages of a requested whole-thread read are+ // missing (it knows), or Gmail's expansion was not confirmed (it cannot+ // tell). Ask mode cannot expand Gmail messages, so by default that+ // limitation reaches the user through this caveat.+ _readCoverageGuardRefuses(tabId) {+ const state = this.readCompletenessStates.get(tabId);+ const expansionUnverified = state?.requiresExpansionEvidence === true+ && state.treeCoverageComplete === true && state.expansionConfirmed !== true;+ return this._guardRefusesOnce(tabId, 'read-coverage-incomplete', {+ decided: !expansionUnverified,+ caveat: !expansionUnverified ? 'Not every part of the conversation was confirmed as read.'+ : this._isActionMode(this._effectiveRunMode(tabId))+ ? 'Some Gmail messages may have stayed collapsed, so the whole conversation was not confirmed as read.'+ : 'Ask mode cannot expand collapsed Gmail messages, so some messages in the conversation may be missing.',+ });+ }++ // exact-table-done for table JSON given without the app's data_ref.+ _exactTableAnswerRefuses(tabId, error) {+ const rowCountMismatch = /^The JSON rowCount /.test(String(error || ''));+ return this._guardRefusesOnce(tabId, 'exact-table-done', {+ decided: rowCountMismatch,+ caveat: rowCountMismatch ? 'The table\'s row count does not match its rows.'+ : 'The table was not checked against the exact rows on the page.',+ });+ }++ // The checks a plain final passes before the plan guard. By default each+ // one drops out once its guard has refused in this run.+ _plainFinalGuardBlocks(tabId, content) {+ const progressFinalBlock = this._plainFinalProgressBlock(tabId);+ const completionFinalBlock = this._completionPlainFinalBlock(tabId);+ const readFinalBlock = this._readCompletenessBlock(tabId);+ const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), content);+ return {+ progressFinalBlock: progressFinalBlock && this._progressGuardRefuses(tabId) ? progressFinalBlock : null,+ completionFinalBlock: completionFinalBlock && this._completionPlainFinalRefuses(tabId) ? completionFinalBlock : null,+ readFinalBlock: readFinalBlock && this._readCoverageGuardRefuses(tabId) ? readFinalBlock : null,+ exactTableFinalBlock: exactTableFinalBlock && this._exactTableAnswerRefuses(tabId, exactTableFinalBlock)+ ? exactTableFinalBlock : null,+ };+ }++ // Strict checks: the third plain final under a completion block ends the+ // run as partial. By default each block refuses once and the next plain+ // final is accepted, so the run never needs this stop.+ _plainFinalTwoStrikeEnds() {+ return !this._guardAdvises('plain-final-two-strike-partial');+ }++ // completion-verifier-not-done: the completion judge's sure pending or+ // failed verdict. completion-evidence-freshness: the judged evidence+ // changed while it was being judged (engine 'freshness').+ _completionVerdictRefuses(tabId, decision) {+ const freshness = decision?.engine === 'freshness';+ return this._guardRefusesOnce(tabId, freshness ? 'completion-evidence-freshness' : 'completion-verifier-not-done', {+ decided: !freshness,+ caveat: freshness ? 'The page changed while the result was being checked.'+ : decision?.outcome === 'failed' ? 'An independent check of the page suggested that the task did not succeed.'+ : 'An independent check of the page could not confirm that the task had finished.',+ });+ }++ _iframeResultStaleRefuses(tabId) {+ return this._guardRefusesOnce(tabId, 'completion-evidence-freshness', { decided: false,+ caveat: 'The submitted form inside an embedded frame could not be read again at the end.' });+ }++ _calculationRefreshRefuses(tabId) {+ return this._guardRefusesOnce(tabId, 'completion-evidence-freshness', { decided: false,+ caveat: 'The calculation could not be checked again against the current page.' });+ }++ // completion-page-warning: an open dialog or a failed validation the page+ // shows (it knows), or a visible form or edit route without a verified+ // submit (it cannot tell).+ _completionPageWarningRefuses(tabId, key) {+ const text = String(key || '');+ const known = /\|dialog\|\d+$/.test(text) || text.endsWith('|submit-validation-failed');+ const caveat = /\|dialog\|\d+$/.test(text) ? 'A dialog was still open on the page at the end.'+ : text.endsWith('|submit-validation-failed') ? 'The form showed a validation error after it was submitted.'+ : text.includes('|pending-form|') ? 'The form still looked unsubmitted at the end.'+ : 'The page was still on an edit screen with no sign that the change was saved.';+ return this._guardRefusesOnce(tabId, 'completion-page-warning', { decided: known, caveat });+ }++ _completionPageWarningSuffix(blocks) {+ return this._guardAdvises('completion-page-warning')+ ? ' (If the task is complete and this form or dialog is unrelated to it, say so in the done summary.)'+ : ` (block attempt ${blocks}/2 — if you genuinely believe the task is complete and the visible form/dialog is unrelated, re-call done with summary explicitly acknowledging this, e.g. "already-existing product, no submit needed".)`;+ }++ // incomplete-task-redirect: the judge's continue_now or wait_then_check+ // reading of an honest partial or failed ending. A block without+ // `recovery` is incomplete-task-check-stale (the task or page changed+ // while it was read): a host check that always stands.+ _incompleteRedirectRefuses(tabId, block) {+ if (!block?.recovery) return true;+ return this._guardRefusesOnce(tabId, 'incomplete-task-redirect', {+ caveat: 'WebBrain judged that more of the task could still be done.',+ });+ }++ // The guards behind a plan-execution refusal, each with the sentence the+ // user sees when a completion is accepted over it.+ _planGuardFindings(state, flags) {+ const findings = [];+ const add = (id, decided, caveat) => {+ const prior = findings.find(finding => finding.id === id);+ if (prior) prior.caveat = `${prior.caveat} ${caveat}`;+ else findings.push({ id, decided, caveat });+ };+ if (!flags.viaDone) add('plan-plain-final-protocol', true, PLAIN_FINAL_PROTOCOL_CAVEAT);+ else if (flags.looksPlanOnly) {+ add('plan-done-summary-shape', true, flags.runtimeModeContradiction+ ? 'The final answer blamed a read-only mode that was not in use.'+ : 'The final answer looked like a plan rather than a result.');+ }+ if (flags.forbiddenSubmission) {+ add('plan-unauthorized-mutation-recorded', true, 'The form was submitted even though the task was to leave it unsubmitted.');+ } else if (state.conditionalMutationBlocked) {+ add('plan-unauthorized-mutation-recorded', true, 'The planned repair was not made because no matching workflow allowed it.');+ }+ if (flags.missingRequiredSchedulingTool) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the scheduled task was created.');+ if (flags.missingRequiredDownload) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the file was downloaded.');+ if (flags.missingJobEvidence) add('plan-required-evidence-missing', false, 'The result was not checked the way this kind of task requires.');+ if (flags.missingDraftEvidence) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the draft was saved with every requested field.');+ if (flags.missingRequiredLedger) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that every item was handled.');+ if (flags.missingSocialPublishTargets.length) {+ add('plan-publication-evidence-missing', false, `I couldn't confirm the post on ${flags.missingSocialPublishTargets+ .map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}.`);+ }+ if (flags.missingRequiredSubmission && this._workflowVerificationKind(state.siteWorkflow) === 'published_resource') {+ // The byte-exact raw-blob check stays the evidence for a GitHub file+ // commit; only its refusal is advised.+ const githubFile = state.siteWorkflow?.adapterName === 'github' && state.siteWorkflow?.job?.id === 'edit-file-and-commit';+ const caveat = githubFile ? 'I couldn\'t confirm that the committed file matches the requested text.'+ : 'I couldn\'t confirm that the published result matches the request.';+ add('plan-publication-evidence-missing', false, caveat);+ if (githubFile) add('github-committed-file-verification', false, caveat);+ } else if (flags.missingRequiredSubmission && !flags.missingSocialPublishTargets.length) {+ add('plan-submission-evidence-missing', false, 'I couldn\'t confirm that the submission went through.');+ }+ if (flags.missingEvidence && findings.every(finding => ['plan-plain-final-protocol', 'plan-done-summary-shape'].includes(finding.id))) {+ add('plan-execution-evidence-missing', false, state.requiresStateChange === false+ ? 'No successful page read or tool result backs this answer.'+ : 'I couldn\'t confirm that the requested change was made.');+ }+ return findings;+ }++ // Default mode for the plan-execution guard: each finding gives its note+ // once per run and is then accepted with its caveat, so this guard never+ // ends the run itself. null keeps the strict path: Strict checks, a+ // drifted task (a host check), and the two endings that hold no answer to+ // accept, a planner or policy object and a stale cancellation echo.+ _planGuardAdvisory(tabId, state, flags) {+ if (state.taskDrifted || flags.staleCancellation || flags.structuredPlan) return null;+ const findings = this._planGuardFindings(state, flags);+ if (!findings.length || findings.some(finding => !this._guardAdvises(finding.id, finding))) return null;+ let refuses = false;+ for (const finding of findings) {+ if (this._guardRefusesOnce(tabId, finding.id, finding)) refuses = true;+ }+ return refuses ? 'refuse' : 'accept';+ }+_completionPlainFinalBlock(tabId) {const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;@@ -5210,6 +5550,11 @@ export class Agent extends LoopDetector {_completionRecoveryPolicy(tabId, tools, { verification = false, done = false, failure = false } = {}) {if (!this._isActionMode(this._effectiveRunMode(tabId))) return null;+ // By default a refused completion only leaves its note: the model keeps+ // every tool and may still report success. Strict checks restore the+ // forced read-only turn, the done-only turn and the failure-only done.+ if (this._guardAdvises('completion-recovery-forced-turns', { decided: false })+ && this._guardAdvises('completion-failure-only-done', { decided: false })) return null;const state = this.completionInvariants.get(tabId);const available = Array.isArray(tools) ? tools : [];const failureOnlyTerminalTool = () => {@@ -9183,6 +9528,7 @@ export class Agent extends LoopDetector {for (const [owner, map] of [[this._uncertainTextMutations, this._uncertainTextMutations.get(tabId)],[this._verifiedTextReplacements, this._verifiedTextReplacements.get(tabId)],+ [this._unverifiedTextWrites, this._unverifiedTextWrites?.get(tabId)],]) {if (!(map instanceof Map)) continue;for (const [key, entry] of map) {@@ -9239,6 +9585,18 @@ export class Agent extends LoopDetector {async _richTextToolbarToolBlock(tabId, toolName, args = {}, executionContext = null) {if (!this._richTextToolbarGuard.hasPending(tabId)) return null;if (!RICH_TEXT_TOOLBAR_GUARDED_TOOLS.has(toolName)) return null;+ // The preflight already advised this exact call and recorded its+ // obligation; checking it again would only repeat that note.+ if (executionContext?.richTextToolbarWrongTargetAdvised === true) return null;+ // rich-text-toolbar-recovery-obligation (quality): while an earlier text+ // entry into a formatting toolbar is unresolved, a call on that toolbar,+ // or one whose target cannot be checked, is refused only in Strict+ // checks. Otherwise it runs unbound with a note; the obligation stays+ // until a verified editor-body edit releases it.+ const advises = (note, decided) => this._guardAdvisesFor(executionContext?.guardAdvisories,+ 'rich-text-toolbar-recovery-obligation', note, { decided });+ const toolbarNote = 'This target belongs to the rich-text formatting toolbar that received the earlier text entry, not the editor body. It was used anyway; the requested content still has to be entered in the editor body and verified there.';+ const uncheckedNote = 'An earlier text entry went into a rich-text formatting toolbar, and WebBrain could not check that this target is not that toolbar. It was sent anyway; enter the requested content in the editor body and verify it there.';const probe = await this._probeRichTextToolbarRetryTarget(tabId, toolName, args);if (!probe?.resolved) {const knownRefBlock = this._richTextToolbarGuard.blockRef(@@ -9247,7 +9605,9 @@ export class Agent extends LoopDetector {args,this._lastAxScopes.get(tabId)?.documentToken || '',);- if (knownRefBlock) return knownRefBlock;+ if (knownRefBlock) return advises(toolbarNote, true) ? null : knownRefBlock;+ // A selector matching several frames has no single target to send to.+ if (DISPATCH_BINDING_TOOLS.has(toolName) && probe?.ambiguous !== true && advises(uncheckedNote, false)) return null;return DISPATCH_BINDING_TOOLS.has(toolName)? {success: false,@@ -9281,7 +9641,7 @@ export class Agent extends LoopDetector {}if (evaluation.block) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);- return evaluation.block;+ return advises(toolbarNote, true) ? null : evaluation.block;}if (evaluation.guarded !== true) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);@@ -9292,6 +9652,7 @@ export class Agent extends LoopDetector {&& !richTextToolbarDispatchBindingReady(toolName, args, probe.dispatchBinding)) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);+ if (advises(uncheckedNote, false)) return null;return {success: false,dispatched: false,@@ -9347,7 +9708,10 @@ export class Agent extends LoopDetector {return true;}- _applyRichTextToolbarWrongTarget(tabId, toolName, args, result, candidate, decision, audit, identity = {}) {+ // The recovery obligation is evidence that the requested content may not be+ // in the editor body, so it is recorded whether the entry is refused or+ // (Strict checks off) sent with a note.+ _recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, identity = {}, { advised = false } = {}) {const recorded = this._richTextToolbarGuard.recordWrongTarget(tabId, {toolName,args,@@ -9355,6 +9719,25 @@ export class Agent extends LoopDetector {decision,identity,});+ const runId = this.currentRunId.get(tabId);+ if (runId) {+ trace.recordNote(runId, null, 'rich_text_toolbar_wrong_target', {+ toolName,+ refId: typeof args?.ref_id === 'string' ? args.ref_id : '',+ targetKind: recorded.obligation.targetKind,+ source: decision.source,+ confidence: audit?.confidence ?? null,+ blockedRefCount: recorded.blockedRefCount,+ persistentRecoveryObligation: true,+ recoveryTargetUnknown: !recorded.hasExactRecoveryTarget,+ ...(advised ? { advised: true } : {}),+ });+ }+ return recorded;+ }++ _applyRichTextToolbarWrongTarget(tabId, toolName, args, result, candidate, decision, audit, identity = {}) {+ const recorded = this._recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, identity);const obligation = recorded.obligation;const associatedEditorRef = typeof candidate?.associatedEditorRef === 'string'&& /^ref_\d+$/.test(candidate.associatedEditorRef)@@ -9382,19 +9765,6 @@ export class Agent extends LoopDetector {? `This edit was blocked before dispatch because the target is a rich-text formatting toolbar control, not the editor body. Do not retry this ref or another font-family, font-size, style, color, or link control in the same toolbar. Use the associated editor body ${associatedEditorRef}, enter the requested content there, and verify that exact editor edit.`: 'This edit was blocked before dispatch because the target is a rich-text formatting toolbar control, not the editor body. Do not retry this ref or another font-family, font-size, style, color, or link control in the same toolbar. Re-read the tree, focus the associated editor body, enter the requested content there, and verify that exact editor edit.',});- const runId = this.currentRunId.get(tabId);- if (runId) {- trace.recordNote(runId, null, 'rich_text_toolbar_wrong_target', {- toolName,- refId: typeof args?.ref_id === 'string' ? args.ref_id : '',- targetKind: obligation.targetKind,- source: decision.source,- confidence: audit?.confidence ?? null,- blockedRefCount: recorded.blockedRefCount,- persistentRecoveryObligation: true,- recoveryTargetUnknown: !recorded.hasExactRecoveryTarget,- });- }}async _classifyRichTextToolbarTarget(tabId, provider, dataUrl) {@@ -9456,13 +9826,21 @@ export class Agent extends LoopDetector {if (!['set_field', 'type_ax', 'type_text', 'iframe_type'].includes(toolName)) {return { block: null, shot: null };}+ const advisories = captureOptions?.guardAdvisories || null;+ // rich-text-toolbar-target-unresolved (quality, cannot decide): when this+ // safety preflight cannot resolve or keep the typing target, Strict checks+ // off skips the toolbar check and lets the tool resolve its target itself+ // (an iframe goes to the handler's own single-target census).+ const unresolvedAdvises = note => this._guardAdvisesFor(advisories, 'rich-text-toolbar-target-unresolved',+ note, { decided: false });+ const unresolvedNote = 'WebBrain could not resolve this typing target for its rich-text toolbar check, so it could not confirm the text goes into the editor body rather than a formatting control. It was sent anyway; read the field back to verify.';// The trusted selector resolver scrolls its target into view, and the// page-feedback fence refuses that scroll while the page is changing.const pageChangedSelectorMessage = 'The page changed while WebBrain was locating this selector\'s target, so nothing was typed. '+ 'On a page that keeps updating, typing by selector is refused the same way each time: type into the field with type_ax and its ref_id from get_accessibility_tree instead.';// A target the observed certificate cannot bind (such as a selector that// names several elements) gets that answer before any probe of it.- const unbindable = await this._pageFeedbackUnbindableResult?.(tabId, toolName, args);+ const unbindable = await this._pageFeedbackUnbindableResult?.(tabId, toolName, args, advisories);if (unbindable) return { block: unbindable, shot: null };const selectorBackedType = toolName === 'type_text'&& typeof args?.selector === 'string'@@ -9478,7 +9856,16 @@ export class Agent extends LoopDetector {if (!probe?.resolved) {const ambiguousIframeTarget = toolName === 'iframe_type' && probe?.ambiguous === true;const pageChanged = selectorBackedType && probe?.pageChangedDuringResolve === true;- return ambiguousIframeTarget || (toolName === 'iframe_type' && recoveryPending) || selectorBackedType || focusedType+ const refusable = ambiguousIframeTarget || (toolName === 'iframe_type' && recoveryPending) || selectorBackedType || focusedType;+ // A selector the page-feedback fence kept from resolving (the page is+ // changing) is that host check's refusal, not this guard's: the tool's+ // own resolver would meet the same fence, so it keeps its answer. An+ // iframe selector naming several elements has no single target to send+ // to and keeps its answer too.+ if (refusable && !pageChanged && !ambiguousIframeTarget && unresolvedAdvises(unresolvedNote)) {+ return { block: null, shot: null, iframeTargetUnresolved: toolName === 'iframe_type' };+ }+ return refusable? {block: {success: false,@@ -9520,6 +9907,11 @@ export class Agent extends LoopDetector {// time, so do not invite a retry that cannot succeed.const resolverUnavailable = selectorBackedType && probe.trustedResolverUnavailable === true;const pageChanged = selectorBackedType && !resolverUnavailable && probe.pageChangedDuringResolve === true;+ // Advised: the released probe is not passed on, so the tool resolves+ // its own target without a preserved identity. A resolver that cannot+ // attach, or that the page-feedback fence stopped, would fail the same+ // way in the tool, so those keep their precise answer.+ if (!resolverUnavailable && !pageChanged && unresolvedAdvises(unresolvedNote)) return { block: null, shot: null };return {block: {success: false,@@ -9552,9 +9944,15 @@ export class Agent extends LoopDetector {|| (!Number.isInteger(probe.frameId) || probe.frameId === 0 ? probe.rect : null);const visionAvailable = !!(await this._resolveVisionRoute(tabId, provider)).provider;const visualAuditAllowanceAvailable = this._canTakeToolbarAuditScreenshot(tabId);- const visualAuditEligible = this._shouldAutoScreenshot(toolName)+ let visualAuditEligible = this._shouldAutoScreenshot(toolName)&& visualAuditAllowanceAvailable&& visionAvailable;+ // Advised: the visual check is skipped and the page-structure score below+ // decides alone, as it does when no vision model is configured.+ if (visualAuditEligible && toolName === 'iframe_type' && !annotationRect+ && unresolvedAdvises('The matching iframe target could not be brought into view for WebBrain\'s visual toolbar check, so it was classified by page structure only. Read the field back to verify the text went into the editor body.')) {+ visualAuditEligible = false;+ }if (visualAuditEligible && toolName === 'iframe_type' && !annotationRect) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);return {@@ -9654,6 +10052,15 @@ export class Agent extends LoopDetector {audit,);if (decision.wrongTarget) {+ // rich-text-toolbar-wrong-target (quality): Strict checks off types into+ // the probed target with a note instead of refusing. The obligation is+ // still recorded, so later toolbar calls and completion know the+ // requested content may not be in the editor body.+ if (this._guardAdvisesFor(advisories, 'rich-text-toolbar-wrong-target',+ 'WebBrain\'s check reads this target as a rich-text formatting toolbar control (font, size, style, color or link), not the editor body. The text was typed there anyway; enter the requested content in the editor body and verify it there.')) {+ this._recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, probe, { advised: true });+ return { block: null, shot, audit, decision, traceCapture, probe, wrongTargetAdvised: true };+ }const block = {};this._applyRichTextToolbarWrongTarget(tabId, toolName, args, block, candidate, decision, audit, probe);await this._releaseRichTextToolbarProbeTarget(tabId, probe);@@ -11476,6 +11883,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn `**${label}** ${gap.reason} ${caution}\n\n${text}`;}+ // An on-device standalone answer that ends mid-sentence is retried once;+ // by default the next one is shown with a caveat instead of an error.+ _standaloneTruncationRefuses(tabId) {+ return this._guardRefusesOnce(tabId, 'plain-final-unusable-output', {+ caveat: 'The on-device answer may be cut off.',+ });+ }+_isClearlyIncompleteStandaloneAnswer(content, runOptions = {}) {if (!this._isStandaloneWebgpuRun(runOptions)) return false;const text = String(content || '').trim();@@ -13830,12 +14245,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn { gate: publicGate, loopCheck };}+ // A text write that went out but could not be read back exactly is an+ // advisory result (success + unverifiedWrite + a note), not a reason to+ // replan the rest of the batch. Failures, refusals and unknown outcomes+ // still interrupt; so does every unverified result under Strict checks.+ _advisoryTextWriteContinuesBatch(toolName, toolResult) {+ return ['set_field', 'type_ax', 'type_text'].includes(toolName)+ && toolResult?.success === true && toolResult.unverifiedWrite === true && !toolResult.error+ && this._guardAdvises('browser-batch-fresh-turn-interrupt', { decided: true });+ }+_browserActionFreshTurnReason(tier, toolName, toolResult, batch = null) {+ const advisoryWrite = this._advisoryTextWriteContinuesBatch(toolName, toolResult);if (batch) {// Reads and waits can also be prerequisites of the next batched action.if (toolResult?.success === false || toolResult?.error || toolResult?.noProgress|| toolResult?.ambiguous || toolResult?.outcomeUnknown || toolResult?.stale) return 'action_failed';- if (toolResult?.inconclusive || toolResult?.verified === false || toolResult?.remoteStateVerified === false) return 'action_unverified';+ if (!advisoryWrite && (toolResult?.inconclusive || toolResult?.verified === false+ || toolResult?.remoteStateVerified === false)) return 'action_unverified';if (batch.submit && batch.hasRemaining) return 'submit_boundary';if (batch.navigationChanged && batch.hasRemaining&& (!batch.sameNext || !batch.remainingObservations)) return 'navigation_changed';@@ -13868,9 +14295,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn 'action_failed';}if (- toolResult?.inconclusive- || toolResult?.verified === false- || toolResult?.remoteStateVerified === false+ !advisoryWrite && (+ toolResult?.inconclusive+ || toolResult?.verified === false+ || toolResult?.remoteStateVerified === false+ )) {return 'action_unverified';}@@ -14141,6 +14570,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_pureCalculationToolPolicy(tabId, expectedScope = null) {const guard = this._planExecutionGuards.get(tabId);+ // A task whose arithmetic-only scope was released (see+ // _releasePureCalculationScope) is an ordinary task for the rest of its+ // plan guard; a new task gets a fresh guard and its own scope.+ if (guard?.pureCalculationScopeReleased === true) return null;const scope = this._pageFeedbackCalculationResponseScope?.(tabId);const capturedScope = expectedScope || guard?.pureCalculationToolScope || null;if (capturedScope && (!scope || capturedScope.owner !== scope.owner@@ -14187,6 +14620,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._planExecutionGuards.get(tabId)?.pureCalculationReceipt?.fraction);const prematureCompletion = !policy.stale && name === 'done' && !completed && !policy.attempted;if (!policy.stale && policy.names.includes(name) && matchesInput && !missingResult && !missingFormat && !prematureCompletion) return null;+ // A done these arithmetic checks refuse is advised once per run by+ // default, then accepted with a caveat. A stale task authority is a+ // host check and keeps refusing.+ if (!policy.stale && name === 'done' && !this._guardRefusesOnce(tabId, 'pure-calculation-done-checks', {+ decided: !prematureCompletion,+ caveat: prematureCompletion ? 'The result was not computed with the calculator.'+ : missingResult ? 'The answer may not show the calculator\'s exact result.'+ : 'The answer may not use the exact format you asked for.',+ })) return null;return { success: false, skipped: true, denied: true, dispatched: false, noDispatch: true,...(prematureCompletion ? { blockedDone: true } : {}),outcomeUnknown: false, errorCode: 'pure_calculation_tool_denied',@@ -14203,6 +14645,39 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: 'This genuine task only authorizes its literal calculation. Call calculate with that exact expression, then done with the result and an explicit outcome. No browser action or different calculation was dispatched.' };}+ /**+ * pure-calculation-tool-scope (quality): with Strict checks off, a call+ * outside an owned literal-arithmetic task's scope (another tool, another+ * expression, a calculation repeated after its verified result) runs with+ * a note instead of being refused. Returns true when the caller must let+ * the call proceed. The stale-authority refusal (a host check) and the+ * done checks are not this guard and keep refusing.+ */+ _pureCalculationScopeAdvises(tabId, name, args, expectedScope, advisories) {+ if (!name || name === 'done' || name === 'done_json') return false;+ const policy = this._pureCalculationToolPolicy(tabId, expectedScope);+ if (!policy || policy.stale) return false;+ const expression = String(policy.scope?.expression || '').slice(0, 80);+ const note = name !== 'calculate'+ ? `This task only asks for its literal calculation (${expression}); no browser action or other tool was requested. ${name} ran anyway. The answer still needs calculate with that exact expression; report it with done.`+ : policy.names.includes('calculate')+ ? `This calculate is not the task's literal calculation (${expression}), so its result is not the task's verified answer. It ran anyway; the answer needs calculate with that exact expression.`+ : 'The task\'s literal calculation was already verified; this repeated calculate ran anyway. The verified result stands: report it with done.';+ return this._guardAdvisesFor(advisories, 'pure-calculation-tool-scope', note);+ }++ // A page action that runs on an arithmetic-only task (advised above) makes+ // its captured scope permanently stale: the scope requires a run with no+ // action, so every later call, done included, would be refused as a changed+ // authority and the tool list would empty. The task is no longer+ // arithmetic-only, so its scope is released for the rest of this plan guard.+ _releasePureCalculationScope(tabId) {+ const guard = this._planExecutionGuards.get(tabId);+ if (!guard) return;+ guard.pureCalculationScopeReleased = true;+ guard.pureCalculationToolScope = null;+ }+async _executeToolBatchInner(tabId, toolCalls, messages, onUpdate, provider, partialAssistantText, allowedToolNames, step, runOptions, toolSchemas, cancellationState) {// Capture the request's private authority, not a later same-wording task.// Recommended/fast batches also pass this shared boundary.@@ -14216,6 +14691,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst promptTier = this._resolvePromptTier(provider);const readLimits = this._readWindowLimits();const completionBatchStartState = this.completionInvariants.get(tabId) || null;+ // A batch holding a done is a new completion attempt (see+ // _beginCompletionGuardAttempt). A read batch that a tool handler runs+ // on its own keeps the caveats.+ if (toolCalls.some(call => ['done', 'done_json'].includes(call?.function?.name))) {+ this._beginCompletionGuardAttempt(tabId);+ }// Set of tools whose side effect can navigate the page. We snapshot the// URL before these and re-check after, so we can warn the model when an// unintended navigation happens (the most common cause of "model keeps@@ -14311,12 +14792,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst previous = toolCalls[toolIndex - 1];if (previous?._browserBatch) {const priorResult = messages.findLast(message => message.role === 'tool' && message.tool_call_id === previous.id);- if (browserBatchResultStatus(priorResult).failed && this._interruptToolBatchForFreshTurn(+ if (browserBatchResultStatus(priorResult, {+ advisoryWritesContinue: this._guardAdvises('browser-batch-fresh-turn-interrupt', { decided: true }),+ }).failed && this._interruptToolBatchForFreshTurn(tabId, toolCalls, toolIndex, messages, onUpdate, step,{ tier: promptTier, triggeringTool: previous.function.name, reason: 'action_failed', navNotices },)) { navNotices.length = 0; break; }}- const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null };+ const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null, guardAdvisories: [] };cancellationState.active = callState;// Abort check before each tool call.if (this._checkAbort(tabId)) {@@ -14354,7 +14837,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!this._hasPendingSteering(tabId)) {const calculationArgs = this._parseToolCallArgs(tc).args;const calculationBlock = this._pureCalculationToolBlock(tabId, tc.function?.name || '', calculationArgs, calculationRequestScope);- if (calculationBlock) {+ if (calculationBlock && !this._pureCalculationScopeAdvises(tabId, tc.function?.name || '', calculationArgs,+ calculationRequestScope, callState.guardAdvisories)) {const recovery = await recordPreparationFailure(toolIndex, tc.function?.name || '', calculationArgs || {}, calculationBlock);if (recovery) return recovery;if (tc._browserBatch && interruptFailedBrowserAction(toolIndex, tc.function?.name)) { navNotices.length = 0; break; }@@ -14596,7 +15080,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const mediaTargetGuard = await this._downloadPublicMediaExplicitUrlGuard(tabId, fnName, fnArgs);- if (mediaTargetGuard) {+ // A feed/profile URL may save a different item than the one the model+ // means. Without Strict checks the download runs with that warning.+ if (mediaTargetGuard && !this._guardAdvisesFor(callState.guardAdvisories, 'media-download-target-binding',+ 'The download URL is a feed or profile page, not one media item\'s permalink, so the saved file may be a different item than the one you meant. Check the downloaded file (list_downloads) before reporting it.')) {messages.push({role: 'tool',tool_call_id: tc.id,@@ -14822,9 +15309,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const runWorkflowPreSubmitChecks = async () => await this._resourceMutationPreSubmitBlock(tabId, fnName, fnArgs, detectedSubmitAction, provider)|| this._steeringPriorSubmissionBlock(tabId, fnName, fnArgs, detectedSubmitAction)- || await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction)+ || await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction, callState.guardAdvisories)|| await this._workflowPreSubmitDispatchBlock(- tabId, fnName, fnArgs, detectedSubmitAction, provider,+ tabId, fnName, fnArgs, detectedSubmitAction, provider, callState.guardAdvisories,);let workflowPreSubmitBlock = await runWorkflowPreSubmitChecks();if (workflowPreSubmitBlock?.mutationConfirmation@@ -14887,7 +15374,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcorrectedPriorValidationFailure = true;} else {const retryActionKey = this._formValidationActionKey(fnName, fnArgs);- if (retryActionKey && retryActionKey === validationBlock.actionKey) {+ // The earlier submit failed validation, so repeating it cannot+ // duplicate an effect. Without Strict checks it is sent again with+ // a note; a repeated rejection reports the page's messages itself.+ if (retryActionKey && retryActionKey === validationBlock.actionKey+ && !this._guardAdvisesFor(callState.guardAdvisories, 'form-validation-unchanged-repeat',+ this._formValidationRepeatNote(validationBlock))) {const blockedResult = this._formValidationRetryBlockResult(validationBlock);onUpdate('tool_call', { name: fnName, args: fnArgs });onUpdate('tool_result', { name: fnName, result: blockedResult });@@ -15087,10 +15579,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dformValidationBefore = await captureFormValidationWithDeadline(formValidationAllFrames);} catch (error) {if (error?.code !== 'content_action_timeout') throw error;- const loopStop = await recordPagePreparationTimeout(error, 'form-validation snapshot');- if (loopStop) return loopStop;- if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }- continue;+ // The before-snapshot only gives post-submit validation detection+ // its baseline; the action itself does not need it. Without Strict+ // checks the call proceeds with an empty baseline and a note.+ if (this._guardAdvisesFor(callState.guardAdvisories, 'preparation-timeout-generic',+ 'The form-validation snapshot did not finish before this action, so WebBrain has no baseline to tell new validation errors from old ones. Read the form after it to confirm the page accepted it.',+ { decided: false })) {+ formValidationBefore = [];+ } else {+ const loopStop = await recordPagePreparationTimeout(error, 'form-validation snapshot');+ if (loopStop) return loopStop;+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }+ continue;+ }}}if (capabilities.length && !bypassesConsequentialGates) {@@ -15225,7 +15726,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (fnName === 'done' || fnName === 'done_json') {- const invariantBlock = this._completionDoneBlock(tabId, fnName, fnArgs, completionBatchStartState);+ // Each completion invariant gets its own note: one that already advised+ // in this run is accepted, and the next applicable one is checked.+ let invariantBlock = null;+ const acceptedInvariants = new Set();+ for (;;) {+ const block = this._completionDoneBlock(tabId, fnName, fnArgs, completionBatchStartState, { skip: acceptedInvariants });+ if (!block) break;+ if (this._completionInvariantRefuses(tabId, block)) { invariantBlock = block; break; }+ acceptedInvariants.add(block.reason);+ // Accepted over advice. A done that names no outcome claims no success.+ if (block.reason === 'missing_outcome') fnArgs = { ...fnArgs, outcome: 'partial' };+ }if (invariantBlock) {const blockedResult = {success: false,@@ -15264,8 +15776,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}+ // By default the model's answer is kept: the whole-thread check below+ // gives the model one note about the Ask-mode limitation and the final+ // answer carries it. Strict checks replace the answer and end the run.const readLimitation = this._readCompletenessLimitation(tabId);- if (readLimitation) {+ if (readLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {const limitationResult = {success: false,done: true,@@ -15297,7 +15812,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const readBlock = this._readCompletenessBlock(tabId);- if (readBlock) {+ if (readBlock && this._readCoverageGuardRefuses(tabId)) {const blockedResult = {success: false,blockedDone: true,@@ -15333,7 +15848,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst progressBlock = this._shouldBlockDoneForProgress(tabId)? this._progressDoneBlock(tabId, doneOutcome): null;- if (progressBlock) {+ if (progressBlock && this._progressGuardRefuses(tabId)) {const blockedResult = {success: false,blockedDone: true,@@ -15511,7 +16026,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dfnName,fnArgs,provider,- { onUpdate },+ { onUpdate, guardAdvisories: callState.guardAdvisories },);this._throwIfAborted(abortSignal);const socialDispatchBlock = pipelineToolbarPreflight.block ? null@@ -15521,7 +16036,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Recheck after all preparation, before marking or invoking dispatch.if (this._hasPendingSteering(tabId) || await this._refreshPageFeedbackForCall(tabId, tc, onUpdate)) return { steered: true };const genericChatBlock = pipelineToolbarPreflight.block || socialDispatchBlock ? null- : await this._prepareGenericChatDispatch(tabId, fnName, fnArgs, messageRecipientExecutionContext, abortSignal);+ : await this._prepareGenericChatDispatch(tabId, fnName, fnArgs, messageRecipientExecutionContext, abortSignal,+ callState.guardAdvisories);this._throwIfAborted(abortSignal);if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock) {// Save the task's record with this action's sites before it can be@@ -15536,11 +16052,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn { steered: true };}}- const calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);+ let calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);+ if (calculationDispatchBlock && this._pureCalculationScopeAdvises(tabId, fnName, fnArgs,+ calculationRequestScope, callState.guardAdvisories)) {+ calculationDispatchBlock = null;+ callState.pureCalculationScopeAdvised = true;+ }if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock && !calculationDispatchBlock) {if (detectedSubmitAction?.isSubmit === true && detectedSubmitAction.publicationControl === true) {messageRecipientExecutionContext.socialPublicationAuditRetryConsumed = this._consumeSocialPublicationAuditRetry(tabId);}+ if (callState.pureCalculationScopeAdvised === true && isCompletionActionTool(fnName, fnArgs)) {+ this._releasePureCalculationScope(tabId);+ }if (fnName === 'calculate') this._rememberPureCalculationAttempt(tabId, fnArgs, calculationRequestScope);callState.invoked = true;}@@ -15556,9 +16080,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout djevBinding: jevPending?.call.binding,detectedSubmitAction,promptTier,+ guardAdvisories: callState.guardAdvisories,dispatchBinding: pipelineToolbarPreflight.probe?.dispatchBinding || null,...messageRecipientExecutionContext,iframeTargetUnresolved: pipelineToolbarPreflight.iframeTargetUnresolved === true,+ richTextToolbarWrongTargetAdvised: pipelineToolbarPreflight.wrongTargetAdvised === true,imageGenConfig,_contentActionAbortSignal: abortSignal,_contentActionDispatchState: actionDispatchState,@@ -15951,7 +16477,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (toolResult?.blockedDone) {const completionNeedsRead = toolResult.completionDecision || toolResult.completionPageBlock;- if (completionNeedsRead) { const state = this.completionInvariants.get(tabId); if (state) this.completionInvariants.set(tabId, { ...state, verificationDebt: true }); }+ // Strict checks: a negative verdict or page warning reopens verification+ // debt for a forced read-only turn. By default the model only gets the+ // note, and the debt guard does not refuse the next done for it.+ if (completionNeedsRead && !this._guardAdvises('done-verification-debt', { decided: false })) { const state = this.completionInvariants.get(tabId); if (state) this.completionInvariants.set(tabId, { ...state, verificationDebt: true }); }messages.push({ role: 'tool', tool_call_id: tc.id, content: this._wrapUntrusted(fnName, this._limitToolResult(toolResult)) });if (attachedImage) {messages.push({ role: 'user', transientCompletionVerification: true, content: [@@ -16067,7 +16596,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dstatus: planOnlyDecision.status || 'plan_only_output' };}let rawDoneSummary = toolResult.summary || partialAssistantText || 'Task completed.';- if (!scheduledResume && summaryKind === 'meta_only') {+ if (!scheduledResume && summaryKind === 'meta_only' && this._guardRefusesOnce(tabId, 'done-summary-meta-only', {+ caveat: 'The final answer may only say that an answer was given, without the answer itself.',+ })) {const blockedResult = {success: false,blockedDone: true,@@ -16100,17 +16631,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtoolResult.summary = (toolResult.summary || partialAssistantText || '') + '\n\n' + notice;}}+ if (!scheduledResume && toolResult.outcome === 'success'+ && this._guardRunState(tabId).outcomeDowngrades?.size) {+ // Accepted over a guard that knows the claim is wrong: end the run,+ // but as partial so schedules and watches do not count a success.+ toolResult.outcome = 'partial';+ }onUpdate('tool_result', { name: fnName, result: toolResult });this._doneBlockCount.delete(tabId);rawDoneSummary = toolResult.summary || rawDoneSummary;const repairedDoneSummary = fnArgs.data_ref ? rawDoneSummary : repairAssistantDisplayText(rawDoneSummary);- const finalResponse = fnArgs.data_ref ? repairedDoneSummary+ const deliveredSummary = fnArgs.data_ref ? repairedDoneSummary: this._appendProgressLedgerToFinal(tabId, repairedDoneSummary);+ // A completion accepted over a guard's advice tells the user what was+ // not verified. A scheduled resume is a pause, not a completion.+ const finalResponse = scheduledResume ? deliveredSummary : this._withCompletionCaveat(tabId, deliveredSummary);if (repairedDoneSummary !== rawDoneSummary) {// Streaming providers may already have rendered the malformed summary// before the done call. Replace it so the visible bubble matches the// repaired terminal value returned by this batch.onUpdate('text', { content: finalResponse, replace: true });+ } else if (finalResponse !== deliveredSummary) {+ onUpdate('text', { content: finalResponse, replace: true });}messages.push({role: 'tool',@@ -19328,10 +19870,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst normalized = value => String(value || '').replace(/\s+/g, ' ').trim().toLowerCase();const expectedName = normalized(messageRecipientContext.expectedName);const expectedRole = normalized(messageRecipientContext.expectedRole);- if (- (expectedName && normalized(target?.name) !== expectedName)- || (expectedRole && normalized(target?.role) !== expectedRole)- ) {+ const intentMismatch = (expectedName && normalized(target?.name) !== expectedName)+ || (expectedRole && normalized(target?.role) !== expectedRole);+ // click-coordinate-intent (quality): the model's own expected_name /+ // expected_role no longer matches what the point resolves to. Without+ // Strict checks the raw point is clicked, exactly as a coordinate click+ // without those hints would be; recipient, deletion and publication checks+ // still apply to that click.+ if (intentMismatch && this._guardAdvisesFor(messageRecipientContext.guardAdvisories, 'click-coordinate-intent',+ 'The point no longer resolves to the expected_name/expected_role you gave, so WebBrain could not confirm it hits the intended control. The point was clicked anyway; read the page to check what it activated.')) {+ return {+ result: null,+ diagnostic: this._coordinateReconciliationDiagnostic(point, resolution, 'coordinate-fallback', 'intent-mismatch'),+ };+ }+ if (intentMismatch) {return {result: {success: false,@@ -20302,6 +20855,78 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d* wait forever). Invalid values fall back to the product default of 60s.* Stored slider values above 1200 mean Off.*/+ // Settings → General → "Strict checks": every quality guard blocks again.+ _guardStrict() {+ return this.strictGuards === true;+ }++ /**+ * What guard `id` does now: 'block' | 'ask' | 'advise' (guard-policy.js).+ * decided=false when the guard fires because it cannot decide.+ */+ _guardOutcome(id, { decided = true } = {}) {+ return guardOutcome(id, { decided, strict: this._guardStrict() });+ }++ /** True when the guard advises instead of refusing in the current mode. */+ _guardAdvises(id, { decided = true } = {}) {+ return this._guardOutcome(id, { decided }) === 'advise';+ }++ /**+ * An action guard that advises lets the action proceed and leaves its note+ * on this call's tool result. Returns true when the caller must not refuse.+ * `advisories` is the call's list (executionContext.guardAdvisories or the+ * batch call state).+ */+ _guardAdvisesFor(advisories, id, message, { decided = true } = {}) {+ if (!this._guardAdvises(id, { decided })) return false;+ if (Array.isArray(advisories)) advisories.push(guardAdvisory(id, message));+ return true;+ }++ _guardRunState(tabId) {+ // Untraced runs (the default) have no currentRunId; the task token+ // _startTraceRun mints for every run bounds them instead.+ const runId = this.currentRunId?.get?.(tabId) ?? this._taskTokens?.get?.(tabId) ?? null;+ let state = this._guardRunStates.get(tabId);+ if (!state || state.runId !== runId) {+ state = { runId, advised: new Set(), caveats: new Map() };+ this._guardRunStates.set(tabId, state);+ }+ return state;+ }++ /**+ * Completion guards advise once per run: the first refusal is the note the+ * model gets (it can verify, fix or report honestly), and the next+ * completion the same guard would refuse goes through with a caveat for+ * the user. Returns true when this call should still refuse: the first+ * time, or always when the guard blocks in the current mode.+ */+ _guardRefusesOnce(tabId, id, { decided = true, caveat = '' } = {}) {+ if (this._guardOutcome(id, { decided }) !== 'advise') return true;+ const state = this._guardRunState(tabId);+ if (!state.advised.has(id)) {+ state.advised.add(id);+ return true;+ }+ const text = String(caveat || '').replace(/\s+/g, ' ').trim().slice(0, 300);+ if (text) state.caveats.set(id, text);+ // A guard that KNOWS the task is not done (not one that only lacked+ // evidence) lets the completion end the run, but not as a success.+ if (decided === true && OUTCOME_DOWNGRADING_GUARDS.has(id)) (state.outcomeDowngrades ||= new Set()).add(id);+ return false;+ }++ /** One short line for the user about completions accepted over advice. */+ _guardCaveatLine(tabId) {+ const state = this._guardRunStates.get(tabId);+ if (!state?.caveats?.size) return '';+ const items = [...new Set(state.caveats.values())].filter(Boolean).slice(0, 4);+ return items.length ? `WebBrain could not verify everything: ${items.join(' ')}` : '';+ }+_normalizeClarifyTimeoutPolicy(value) {return normalizeClarifyTimeoutPolicy(value);}@@ -27052,7 +27677,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn toolResult;}- _applyVerifyFormRecovery(tabId, result, currentStates) {+ _applyVerifyFormRecovery(tabId, result, currentStates, advisories = null) {const block = this._formValidationBlocks.get(tabId);if (!block || !result || typeof result !== 'object') return result;const stateKey = this._formValidationStateKey(currentStates);@@ -27118,7 +27743,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout duncheckedCheckboxes,instruction: `The form state is unchanged. Do not call verify_form again and do not toggle any checkbox. Use ${recoveryCalls}; Chrome will use one trusted selector-backed click when a state change is needed.`,};- if (block.verifyFormCount > 1) {+ // A repeated read of an unchanged form is reported as a failure only in+ // Strict checks; otherwise the read keeps its result and the note says+ // nothing changed since the last one.+ if (block.verifyFormCount > 1 && !this._guardAdvisesFor(advisories, 'form-validation-unchanged-repeat',+ 'The form is unchanged since the last verify_form, so this read shows nothing new. Correct the reported checkbox with set_checked before verifying or submitting again.')) {result.success = false;result.noProgress = true;result.blockedValidationVerifyRepeat = true;@@ -27127,6 +27756,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn result;}+ // Page validation text is untrusted, so the note only counts the fields;+ // a repeated rejection reports its messages in the result itself.+ _formValidationRepeatNote(block) {+ const count = Array.isArray(block?.invalidFields) ? block.invalidFields.length : 0;+ return `This is the same submit that failed validation before, and the form still shows the same invalid field${count === 1 ? '' : 's'}. It was sent again; if the page rejects it, fix the reported fields before submitting.`;+ }+_formValidationRetryBlockResult(block) {const messages = Array.isArray(block?.validationMessages) && block.validationMessages.length? block.validationMessages@@ -27903,7 +28539,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn result;}- async _prepareGenericChatDispatch(tabId, name, args, context, abortSignal = null) {+ async _prepareGenericChatDispatch(tabId, name, args, context, abortSignal = null, advisories = null) {if (!context?.messageRecipientGuardRequired || name === 'upload_file'|| !['click', 'click_ax', 'press_keys', 'set_field'].includes(name)|| (!context.messageRecipientNativeChatBaseline && !this.chatSessions.has(tabId))) return null;@@ -27919,16 +28555,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& observed.snapshot.threadKey !== context.messageRecipientNativeChatBaseline.threadKey) {return blocked('thread_unverified', 'The observed chat changed after recipient verification. Nothing was sent.');}+ // chat-send-preconditions (quality): without Strict checks an unread+ // incoming message and a missing composer send with a note. The+ // recipient, user-input (credentials, payment, a new user decision),+ // terminal-session, native-baseline, duplicate and draft checks are not+ // waivable and keep refusing below (chat-workflow.js says why).+ const advise = note => this._guardAdvisesFor(advisories, 'chat-send-preconditions', note);if (previous && observed.newMessages.some(message => message.direction === 'incoming')- && !observed.session.pendingOutbound && !observed.session.userInput?.required) {+ && !observed.session.pendingOutbound && !observed.session.userInput?.required+ && !advise('A new incoming message appeared since your last chat observation; this reply was sent without considering it. Read the conversation (chat_observe) before the next reply.')) {return blocked('chat_observe_required','A new incoming message appeared before this send. Call chat_observe and consider that delta before replying.');}// The recipient probe has already bound this exact draft/body to its one-use// dispatch token. It is the intended outbound, not an unrelated user draft.- const decision = decideChatSend(observed.session, {- ...before, composer: { ...before.composer, empty: true },- }, context.messageRecipientBody);+ const decisionSnapshot = { ...before, composer: { ...before.composer, empty: true } };+ const waive = new Set();+ let decision = decideChatSend(observed.session, decisionSnapshot, context.messageRecipientBody);+ const waiverNotes = {+ composer_unavailable: 'WebBrain could not find the conversation composer before this send. Read the conversation to confirm the message was actually sent.',+ };+ while (!decision.ok && WAIVABLE_CHAT_SEND_REASONS.includes(decision.reason) && !waive.has(decision.reason)+ && waiverNotes[decision.reason] && advise(waiverNotes[decision.reason])) {+ waive.add(decision.reason);+ decision = decideChatSend(observed.session, decisionSnapshot, context.messageRecipientBody, Date.now(), { waive });+ }if (!decision.ok) return { ...decision, ...blocked(decision.reason, decision.error) };if (!this._captureNativeWhatsappPending(tabId, decision, before, context.messageRecipientNativeChatBaseline)) {return blocked('native_chat_baseline_unavailable', 'The current native WhatsApp message baseline could not be saved safely. Nothing was sent.');@@ -32938,6 +33589,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvoid this._steeringJournal.discard(tabId);}this._verifiedTextReplacements.delete(tabId);+ // Task-scoped like the proofs it sits beside; it never guarded anything.+ this._unverifiedTextWrites?.delete(tabId);this._lastCdpClickIdent?.delete(tabId);this._lastClickProgress?.delete(tabId);this._clickAxCdpFallbacks?.delete(tabId);@@ -33160,6 +33813,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvalueLength: response.valueLength,valueSha256: String(response.valueSha256).toLowerCase(),verified: response.verified === true,+ // false: the digest hashes the rendered text (innerText fallback).+ ...(typeof response.readbackExact === 'boolean' ? { readbackExact: response.readbackExact } : {}),fieldMeta: response.fieldMeta || null,// Element-derived revalidation locator (unique, content-checked);// consumed for focused proofs whose focus moves before submit.@@ -33202,7 +33857,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst documentToken = String(response?.documentToken || '');const pageUrl = String(response?.refScopeUrl || '');if (!documentToken && !pageUrl) return null;- return { documentToken, pageUrl };+ // A ref/selector probe also digests the field. An unverified write's+ // record keeps it, so no second probe is needed (see+ // _recordUnverifiedTextWrite).+ const digest = response?.success === true && Number.isInteger(response.valueLength) && response.valueLength >= 0+ && /^[0-9a-f]{64}$/i.test(String(response.valueSha256 || ''))+ ? {+ valueLength: response.valueLength,+ valueSha256: String(response.valueSha256).toLowerCase(),+ ...(typeof response.readbackExact === 'boolean' ? { readbackExact: response.readbackExact } : {}),+ fieldMeta: response.fieldMeta || null,+ }+ : null;+ return { documentToken, pageUrl, ...(digest ? { digest } : {}) };} catch {return null;}@@ -33487,8 +34154,222 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn liveScope;}- async _uncertainTextMutationBlock(tabId, name, args = {}) {+ /**+ * The latest text write to one editor that went out but could not be+ * verified. Default mode keeps this record instead of text-write debt and+ * never blocks on it (Strict checks record debt instead). It sits next to+ * the proof map so a commit or publication gate can show the user the+ * content and ask instead of refusing. No raw text is stored; the gate can+ * re-digest the live field and compare. Returns a copy, or null.+ *+ * Shape: {+ * key, // same key as the debt/proof maps: 'ax:<document>:<ref>', 'selector:…', 'focused:…'+ * locatorType, // 'ax' | 'selector' | 'focused'+ * refId, selector, // the write's locator (null when unused)+ * documentToken, pageUrl, // the document the write went to+ * tool, replacesValue, // set_field | type_ax | type_text; false for an append+ * expectedLength, expectedSha256, // the requested text (args.text)+ * observedLength, observedSha256, // live readback digest right after the write, or null+ * readbackExact, // false: that readback was the rendered-text (innerText) fallback; null: unknown+ * reason, // 'readback_mismatch' | 'readback_unproven' | 'element_replaced' | 'readback_unavailable'+ * // | 'page_handled_input' | 'paste_not_consumed' | 'input_unconfirmed' | 'outcome_unknown'+ * // | 'not_inserted' | 'trusted_retry_failed'+ * textSent, // true when the text went out (the result reported success)+ * fieldMeta, // field identity (id, name, labels, contentEditable, codeMirror, …)+ * taskToken, recordedAt, // the task that wrote it; epoch ms+ * }+ * `key` selects one editor. Without it, the newest record on `pageUrl`+ * (any page when empty) that passes `match(record)` wins. Records written+ * by another task are ignored.+ */+ _unverifiedTextWriteRecord(tabId, { key = '', pageUrl = '', match = null } = {}) {+ const records = this._unverifiedTextWrites?.get(tabId);+ if (!(records instanceof Map) || records.size === 0) return null;+ const taskToken = this._taskTokens?.get(tabId) || null;+ const candidates = key ? [records.get(key)] : [...records.values()].reverse();+ for (const record of candidates) {+ if (!record || (record.taskToken || null) !== taskToken) continue;+ if (pageUrl && this._normalizeUrl(record.pageUrl || '') !== this._normalizeUrl(pageUrl)) continue;+ if (typeof match === 'function' && match(record) !== true) continue;+ return { ...record, fieldMeta: record.fieldMeta ? { ...record.fieldMeta } : null };+ }+ return null;+ }++ /**+ * Which converted guard speaks for an uncertain text write in the current+ * mode (guard-policy.js), or null when Strict checks keep today's debt and+ * lock. `textSent`: the text went out and only its settled value is in+ * doubt, so the write is reported as an unverified success. Anything else+ * (an unknown outcome, a replacement that was not inserted) stays a+ * failure report, but locks nothing.+ */+ _textWriteAdvisory(name, args, result) {+ if (!this._guardAdvises('text-write-debt-arm', { decided: false })) return null;+ const unverified = result?.unverified && typeof result.unverified === 'object' ? result.unverified : null;+ const textSent = result.noDispatch !== true && (result.success === true || !!unverified);+ let guard = 'content-action-outcome-unknown';+ let reason = 'outcome_unknown';+ let decided = false;+ if (textSent) {+ guard = 'text-write-readback-unverified';+ reason = String(unverified?.reason || 'readback_unproven');+ // Only an exact reader that read a different value knows it is wrong.+ decided = reason === 'readback_mismatch' && result.readbackExact === true;+ } else if (result.verified === true) {+ // The value verified; a later step (a guarded or vetoed Enter) did not+ // complete. That step's own report stands; only the write lock goes.+ guard = 'text-write-debt-arm';+ reason = 'value_verified_step_incomplete';+ } else if (/no replacement text was inserted|could not be proven (?:empty|fully selected)/i.test(String(result.error || ''))) {+ guard = 'text-write-preinsert-unproven';+ reason = 'not_inserted';+ } else if (result.trustedFallbackAttempted === true) {+ guard = 'trusted-field-retry-guards';+ reason = 'trusted_retry_failed';+ }+ if (!this._guardAdvises(guard, { decided })) return null;+ return { guard, reason, decided, textSent };+ }++ // The model's note for an advised text write: what is unconfirmed and+ // what to check. It never asks for a blind retry; appends are warned+ // about duplicates because their text may already have landed.+ _textWriteAdvisoryNote(name, args, result, advisory) {+ const append = !this._textMutationReplacesValue(name, args);+ const duplicate = append ? ' This was an append: repeating it can add the text twice, so fix the field with one full replacement.' : '';+ if (advisory.textSent) {+ const lead = {+ element_replaced: 'Text sent, but the field re-rendered before it could be read back.',+ readback_unavailable: 'Text sent, but the editor could not be read back.',+ page_handled_input: 'The page applied the text itself; the result could not be read back exactly.',+ paste_not_consumed: 'Text pasted, but the editor did not confirm it handled the paste.',+ input_unconfirmed: 'Text reads back correctly, but the page did not confirm the input finished.',+ }[advisory.reason] || (result.readbackExact === false+ ? 'Text sent, but this editor only reads back its rendered layout (blank lines can show doubled, off-screen lines missing), so it is unconfirmed. Do not rewrite it to match that readback.'+ : result.readbackExact === true+ ? 'Text sent, but the field reads back a different value.'+ : 'Text sent, but its final value could not be read back exactly.');+ const submit = result.submitSkipped === 'value_unverified'+ ? ' The field was written but its submit was NOT sent; submit separately once the value is right.' : '';+ return `${lead} Check the field before relying on it.${submit}${append && !submit ? duplicate : ''}`;+ }+ if (advisory.reason === 'value_verified_step_incomplete') {+ return 'The field value was verified, but the step after it did not complete (see error). Nothing is locked: observe the page before acting again.';+ }+ if (advisory.guard === 'text-write-preinsert-unproven') {+ return 'The field could not be proven empty or fully selected, so the new text was not inserted and part of the old value may be gone. Nothing is locked: re-read the field before writing it.';+ }+ if (advisory.guard === 'trusted-field-retry-guards') {+ return `Trusted typing could not finish (see error), so the field may or may not have changed. Nothing is locked: re-read it before writing again.${duplicate}`;+ }+ return `This write may or may not have reached the page. Nothing is locked: re-read the field before writing again.${duplicate}`;+ }++ // Default-mode shape of an uncertain text write. The lock labels go+ // (default mode arms no lock), and so does the content failureScope, so+ // the loop detector does not count the write as a failed target. A write+ // whose text went out reports success with unverifiedWrite and a note.+ _advisoryTextWriteResult(name, args, result, advisory, { expectedLength, expectedSha256 }) {+ const out = { ...result };+ delete out.repeatBlocked;+ if (out.recoveryRequired === 'verify_or_restore_field') delete out.recoveryRequired;+ delete out.failureScope;+ delete out._expectedValue;+ if (advisory.textSent) {+ for (const field of ['error', 'noDispatch', 'outcomeUnknown', 'mutationMayHaveOccurred', 'retryable', 'trustedTypeRequired']) {+ delete out[field];+ }+ // `verified` stays as the readback reported it: false when it read a+ // different value, absent when it could not prove one (an unproven+ // write is not a refuted one; see cdp-client verifyTextEntry).+ Object.assign(out, { success: true, dispatched: true, unverifiedWrite: true });+ out.unverified = result.unverified && typeof result.unverified === 'object'+ ? result.unverified : { reason: advisory.reason, reader: 'unknown' };+ if (advisory.reason === 'page_handled_input') {+ // The page cancelled the native input and applied it itself; this is+ // not a cancelled action.+ delete out.cancelled;+ out.pageHandledBeforeInput = true;+ }+ // The bundled submit was withheld for the unverified value (content and+ // trusted paths both send Enter only after exact verification).+ if (name === 'set_field' && args?.submit === true && out.submitted !== true) {+ out.submitted = false;+ out.submitSkipped = 'value_unverified';+ }+ } else {+ Object.assign(out, { success: false, outcomeUnknown: true, mutationMayHaveOccurred: true });+ }+ out.expectedLength = expectedLength;+ out.expectedSha256 = expectedSha256;+ const advisories = [];+ this._guardAdvisesFor(advisories, advisory.guard, this._textWriteAdvisoryNote(name, args, out, advisory),+ { decided: advisory.decided });+ return withGuardAdvisories(out, advisories);+ }++ // Default mode: record an uncertain write without a lock (see+ // _unverifiedTextWriteRecord) and return its advisory result. The caller+ // has already invalidated proofs exactly as Strict checks do, so an+ // unverified readback never stands in for a verified one.+ async _recordUnverifiedTextWrite(tabId, name, args, result, advisory,+ { target, replacesValue, text, expectedSha256, enrich, liveDigest = null }) {+ let observed = liveDigest;+ if (!observed && target.locatorType === 'focused') {+ try {+ observed = await enrich(() => this._textMutationValueDigest(tabId, { locatorType: 'focused', ambiguous: false }));+ } catch { observed = null; }+ }+ if (!this._unverifiedTextWrites) this._unverifiedTextWrites = new Map();+ let records = this._unverifiedTextWrites.get(tabId);+ if (!(records instanceof Map)) {+ records = new Map();+ this._unverifiedTextWrites.set(tabId, records);+ }+ records.delete(target.key);+ records.set(target.key, {+ key: target.key,+ locatorType: target.locatorType,+ refId: target.refId ?? null,+ selector: target.selector ?? null,+ documentToken: target.documentToken || '',+ pageUrl: target.pageUrl || '',+ tool: name,+ replacesValue,+ expectedLength: text.length,+ expectedSha256,+ observedLength: Number.isInteger(observed?.valueLength) ? observed.valueLength : null,+ observedSha256: typeof observed?.valueSha256 === 'string' ? observed.valueSha256 : null,+ readbackExact: typeof result.readbackExact === 'boolean' ? result.readbackExact+ : typeof observed?.readbackExact === 'boolean' ? observed.readbackExact : null,+ reason: advisory.reason,+ textSent: advisory.textSent,+ fieldMeta: result.fieldMeta || observed?.fieldMeta || null,+ taskToken: this._taskTokens?.get(tabId) || null,+ recordedAt: Date.now(),+ });+ // Bounded: one entry per edited field; the oldest field yields first.+ while (records.size > 32) records.delete(records.keys().next().value);+ return this._advisoryTextWriteResult(name, args, result, advisory, { expectedLength: text.length, expectedSha256 });+ }++ // Default mode: a write to a field whose last write went out unverified+ // proceeds. Only an append is noted, because its earlier text may already+ // be in the field; a repeated replacement is idempotent.+ _notePriorUnverifiedTextWrite(tabId, name, args, advisories) {+ if (!Array.isArray(advisories) || this._textMutationReplacesValue(name, args)) return;+ const target = this._textMutationTarget(tabId, name, args);+ const prior = this._unverifiedTextWriteRecord(tabId, { key: target.key });+ if (!prior || (prior.documentToken && target.documentToken && prior.documentToken !== target.documentToken)) return;+ this._guardAdvisesFor(advisories, 'text-write-debt-block',+ 'An earlier write to this field was not verified and may already be in it, so this append can duplicate text. Read the field and fix it with one full replacement if needed.',+ { decided: false });+ }++ async _uncertainTextMutationBlock(tabId, name, args = {}, { advisories = null } = {}) {if (!['set_field', 'type_ax', 'type_text'].includes(name)) return null;+ this._notePriorUnverifiedTextWrite(tabId, name, args, advisories);const debts = this._uncertainTextMutations?.get(tabId);if (!(debts instanceof Map) || debts.size === 0) return null;let target = this._textMutationTarget(tabId, name, args);@@ -33627,7 +34508,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& !this._textMutationFieldsProvenDistinct(debt.fieldMeta, original.fieldMeta)) {debts.delete(debt.key);if (debts.size === 0) this._uncertainTextMutations.delete(tabId);- return debts.size ? this._uncertainTextMutationBlock(tabId, name, args) : null;+ return debts.size ? this._uncertainTextMutationBlock(tabId, name, args, { advisories }) : null;}}// Readback-only recovery requires positive same-field identity. The@@ -33735,6 +34616,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!debt) return null;}+ // Default mode: the earlier uncertain write is reported, never a lock+ // (guard-policy.js; default mode records no debt, so this one was left+ // by Strict checks). The recovery shortcuts above still answer an exact+ // repeat that already reads back. A replacement is idempotent; an+ // append may duplicate text.+ if (this._guardAdvisesFor(advisories, 'text-write-debt-block', replacement+ ? 'An earlier write to this field was not verified; this replacement went ahead. Check the field before relying on it.'+ : 'An earlier write to this field was not verified and may already be in it, so this append can duplicate text. Read the field and fix it with one full replacement if needed.',+ { decided: false })) return null;+return {success: false,dispatched: false,@@ -33794,8 +34685,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Refresh to the live scope before recording (adopting clears// old-document debts/proofs through the document-change path when both// tokens exist), then re-derive the target below.+ let liveDigest = null;try {const liveScope = await enrich(() => this._liveTextMutationScope(tabId, name, args));+ liveDigest = liveScope?.digest || null;if (liveScope && (liveScope.documentToken || liveScope.pageUrl)) {const cachedScope = this._lastAxScopes.get(tabId) || {};if (String(liveScope.documentToken || '') !== String(cachedScope.documentToken || '')@@ -33809,6 +34702,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}} catch { /* an unreachable page keeps the cached scope below */ }+ // Proofs are invalidated in every mode: an unverified readback never+ // stands in for a verified one (the GitHub commit gate relies on it).const verifiedReplacements = this._verifiedTextReplacements.get(tabId);if (verifiedReplacements instanceof Map) {if (target.ambiguous) verifiedReplacements.clear();@@ -33820,6 +34715,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} else verifiedReplacements.delete(target.key);}+ // Quality guards advise by default (guard-policy.js): the write is+ // reported (as an unverified success when its text went out) and kept+ // as a non-blocking record instead of debt that refuses later writes.+ // Strict checks fall through to today's debt and lock.+ const advisory = this._textWriteAdvisory(name, args, result);+ if (advisory) {+ return this._recordUnverifiedTextWrite(tabId, name, args, result, advisory,+ { target, replacesValue, text, expectedSha256, enrich, liveDigest });+ }if (!this._uncertainTextMutations) this._uncertainTextMutations = new Map();let debts = this._uncertainTextMutations.get(tabId);if (!(debts instanceof Map)) {@@ -33954,6 +34858,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout delse verifiedReplacements.delete(target.key);}}+ // A verified write supersedes the field's earlier unverified one.+ if (result.success === true && result.verified === true) this._unverifiedTextWrites?.get(tabId)?.delete(target.key);return result;}@@ -33970,6 +34876,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}clearConversation(tabId, { preserveStorage = false } = {}) {+ this._guardRunStates.delete(tabId);this._failureRecovery.clear(tabId);this._cancelClarifications(tabId, 'conversation cleared');this._cancelPendingPlans(tabId, 'conversation cleared');@@ -37486,7 +38393,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// completion judge or the done_summary question); a failed or partial// done may describe what the user still has to do.const runtimeModeContradiction = summaryKind === 'mode_claim';- const looksPlanOnly = this._isStructuredPlanTerminal(content, state)+ const structuredPlan = this._isStructuredPlanTerminal(content, state);+ const looksPlanOnly = structuredPlan|| (summaryKind === 'plan_only' && !terminalFailure) || runtimeModeContradiction;const staleCancellation = !viaDone && this._isLocalCancellationText(content);const missingRequiredSchedulingTool = !terminalFailure@@ -37522,6 +38430,60 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst invalidPlainFinal = !viaDone;const invalidDone = viaDone && (looksPlanOnly || missingEvidence || missingRequiredLedger);if (!invalidPlainFinal && !invalidDone) return null;+ const modeCorrectionNudge = '[RUNTIME MODE CORRECTION: The trusted runtime for this run is Act/Dev, not Ask mode or a read-only mode. Page-changing tools are available. Continue the authorized task with the permitted tools now. If a required value is missing, call clarify without modifying that field. If a genuine blocker remains, call done with outcome partial or failed and explain the concrete blocker without contradicting the trusted runtime mode.]' + recoveryAnchor;+ const recoveryNudge = () => (state.taskDrifted+ ? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'+ : state.conditionalMutationBlocked+ ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]'+ : staleCancellation+ ? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]'+ : missingRequiredSchedulingTool+ ? `[PLAN EXECUTION BLOCK: The approved plan requires a successful ${state.requiredSchedulingTool} call before this task can finish successfully. A one-time read, scroll, send, or other action does not create the scheduled work. Call ${state.requiredSchedulingTool} with the user's requested timing and verify success:true plus scheduled:true. If the schedule is unsupported or still lacks required timing, call done with outcome partial or failed and explain the exact limitation; do not claim it was scheduled.]`+ : missingRequiredDownload+ ? '[PLAN EXECUTION BLOCK: This task requires a file to be downloaded before it can finish successfully. Finding a URL, link, button, or media source is only read evidence. Use an authorized tool call with the DOWNLOAD capability and verify that it returned successful download evidence. If permission is denied or no file can be saved, call done with outcome partial or failed and explain the limitation; do not claim the file was downloaded.]'+ : missingSocialPublishTargets.length+ ? `[PLAN EXECUTION BLOCK: This task requests publication on every named social destination, but job-bound terminal evidence is still missing for: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. Continue with those destinations and verify each published resource before calling done again. Do not republish on a destination already verified in this run.]`+ : missingRequiredSubmission+ ? (this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own publication. ${this._workflowPublicationRecoveryInstruction(state)}]`+ : state.siteWorkflow?.job?.id+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own submit/send/publish/commit contract. Filling fields, another site's submit, or an unrelated success signal is not completion. Dispatch the intended action and observe the job-specific terminal state (for example recipient-bound sent state, saved/published resource, form confirmation, or paid/ticket-issued transaction) before calling done again. If that cannot be verified, use outcome partial or failed and report the exact blocker.]`+ // No site workflow was selected, so there is no job contract to+ // point at.+ : '[PLAN EXECUTION BLOCK: This task requires a submit/send/publish/commit action, and the page state read at completion does not yet show it took effect. No structured site workflow is bound to this run. Read the page that resulted from the action — the published item, the confirmation, or the changed state — in the same browser tab, then call done from there. If the action cannot be confirmed, use outcome partial or failed and report the exact blocker.]')+ : forbiddenSubmission+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job prepares the form and leaves it unsubmitted, but a submit action was dispatched. Do not submit again or try to undo it by submitting anything else. Call done with outcome partial or failed, state plainly that the form was submitted without authorization, and report what the page shows now.]`+ : missingJobEvidence+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job has its own success contract and an unrelated page read does not satisfy it. ${this._workflowJobEvidenceInstruction(state)} Produce that evidence, then call done. If it cannot be produced, call done with outcome partial or failed and report the exact blocker with whatever partial coverage you did verify.]`+ : missingDraftEvidence+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job finishes on the draft itself, not on a tool call. The intended recipients, the requested subject, and the complete body must all be readable in the open composer, and the provider must show its own saved-draft state. Re-read the composer once the app has saved the draft, then call done. If any field or the saved-draft state cannot be verified, call done with outcome partial or failed and report exactly what is unverified; do not send the message.]`+ : missingRequiredLedger+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} site workflow requires complete item-level reconciliation before success. Obtain a complete app-owned workflow inventory, use its exact item ids for one processed or intentionally skipped ledger row per item, then call progress_update with workflowReconciliation {job:"${state.siteWorkflow.job.id}", coverageComplete:true, itemCount:N, basis:"..."}. N and the row ids must exactly match that inventory; model-created rows alone are not coverage evidence, and any failed row requires a partial or failed outcome. If complete coverage cannot be verified, call done with outcome partial or failed and report completed versus unresolved work.]`+ : unknownMutationIntent+ ? '[PLAN EXECUTION BLOCK: Planning failed, so the runtime could not determine whether this task requires a state change. Continue with normally permitted tools. A success outcome now requires a verified consequential tool call; if the useful result is read-only or no safe consequential action is needed, deliver that result with done outcome partial instead of claiming success. Do not invent or perform a mutation merely to satisfy this guard.]'+ : defaultPlanExecutionBlockNudge({+ viaDone,+ missingEvidence,+ requiresStateChange: state.requiresStateChange,+ })) + recoveryAnchor;+ // By default (Strict checks off) each finding behind this refusal gives+ // its note once per run, and the next completion is accepted with a+ // caveat. The one-nudge budget and run-ending statuses below are the+ // strict path.+ const advisory = this._planGuardAdvisory(tabId, state, { viaDone, looksPlanOnly, runtimeModeContradiction,+ structuredPlan: structuredPlan+ || (state.allowsPlannerShapedResult !== true && this._isPlannerShapedJson(content)),+ staleCancellation, missingRequiredSchedulingTool, missingRequiredDownload, missingRequiredSubmission,+ forbiddenSubmission, missingJobEvidence, missingDraftEvidence, missingRequiredLedger,+ missingSocialPublishTargets, missingEvidence });+ if (advisory === 'accept') return null;+ if (advisory === 'refuse') {+ return {+ retry: true,+ retryAssistantContent: null,+ nudge: runtimeModeContradiction && !missingRequiredSchedulingTool ? modeCorrectionNudge : recoveryNudge(),+ };+ }if (runtimeModeContradiction&& !state.taskDrifted&& !missingRequiredSchedulingTool@@ -37531,7 +38493,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn {retry: true,retryAssistantContent: null,- nudge: '[RUNTIME MODE CORRECTION: The trusted runtime for this run is Act/Dev, not Ask mode or a read-only mode. Page-changing tools are available. Continue the authorized task with the permitted tools now. If a required value is missing, call clarify without modifying that field. If a genuine blocker remains, call done with outcome partial or failed and explain the concrete blocker without contradicting the trusted runtime mode.]' + recoveryAnchor,+ nudge: modeCorrectionNudge,};}if (!state.recoveryAttempted) {@@ -37542,41 +38504,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dretryAssistantContent: staleCancellation? '[Stale local cancellation status omitted from execution context.]': null,- nudge: (state.taskDrifted- ? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'- : state.conditionalMutationBlocked- ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]'- : staleCancellation- ? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]'- : missingRequiredSchedulingTool- ? `[PLAN EXECUTION BLOCK: The approved plan requires a successful ${state.requiredSchedulingTool} call before this task can finish successfully. A one-time read, scroll, send, or other action does not create the scheduled work. Call ${state.requiredSchedulingTool} with the user's requested timing and verify success:true plus scheduled:true. If the schedule is unsupported or still lacks required timing, call done with outcome partial or failed and explain the exact limitation; do not claim it was scheduled.]`- : missingRequiredDownload- ? '[PLAN EXECUTION BLOCK: This task requires a file to be downloaded before it can finish successfully. Finding a URL, link, button, or media source is only read evidence. Use an authorized tool call with the DOWNLOAD capability and verify that it returned successful download evidence. If permission is denied or no file can be saved, call done with outcome partial or failed and explain the limitation; do not claim the file was downloaded.]'- : missingSocialPublishTargets.length- ? `[PLAN EXECUTION BLOCK: This task requests publication on every named social destination, but job-bound terminal evidence is still missing for: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. Continue with those destinations and verify each published resource before calling done again. Do not republish on a destination already verified in this run.]`- : missingRequiredSubmission- ? (this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own publication. ${this._workflowPublicationRecoveryInstruction(state)}]`- : state.siteWorkflow?.job?.id- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own submit/send/publish/commit contract. Filling fields, another site's submit, or an unrelated success signal is not completion. Dispatch the intended action and observe the job-specific terminal state (for example recipient-bound sent state, saved/published resource, form confirmation, or paid/ticket-issued transaction) before calling done again. If that cannot be verified, use outcome partial or failed and report the exact blocker.]`- // No site workflow was selected, so there is no job contract to- // point at.- : '[PLAN EXECUTION BLOCK: This task requires a submit/send/publish/commit action, and the page state read at completion does not yet show it took effect. No structured site workflow is bound to this run. Read the page that resulted from the action — the published item, the confirmation, or the changed state — in the same browser tab, then call done from there. If the action cannot be confirmed, use outcome partial or failed and report the exact blocker.]')- : forbiddenSubmission- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job prepares the form and leaves it unsubmitted, but a submit action was dispatched. Do not submit again or try to undo it by submitting anything else. Call done with outcome partial or failed, state plainly that the form was submitted without authorization, and report what the page shows now.]`- : missingJobEvidence- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job has its own success contract and an unrelated page read does not satisfy it. ${this._workflowJobEvidenceInstruction(state)} Produce that evidence, then call done. If it cannot be produced, call done with outcome partial or failed and report the exact blocker with whatever partial coverage you did verify.]`- : missingDraftEvidence- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job finishes on the draft itself, not on a tool call. The intended recipients, the requested subject, and the complete body must all be readable in the open composer, and the provider must show its own saved-draft state. Re-read the composer once the app has saved the draft, then call done. If any field or the saved-draft state cannot be verified, call done with outcome partial or failed and report exactly what is unverified; do not send the message.]`- : missingRequiredLedger- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} site workflow requires complete item-level reconciliation before success. Obtain a complete app-owned workflow inventory, use its exact item ids for one processed or intentionally skipped ledger row per item, then call progress_update with workflowReconciliation {job:"${state.siteWorkflow.job.id}", coverageComplete:true, itemCount:N, basis:"..."}. N and the row ids must exactly match that inventory; model-created rows alone are not coverage evidence, and any failed row requires a partial or failed outcome. If complete coverage cannot be verified, call done with outcome partial or failed and report completed versus unresolved work.]`- : unknownMutationIntent- ? '[PLAN EXECUTION BLOCK: Planning failed, so the runtime could not determine whether this task requires a state change. Continue with normally permitted tools. A success outcome now requires a verified consequential tool call; if the useful result is read-only or no safe consequential action is needed, deliver that result with done outcome partial instead of claiming success. Do not invent or perform a mutation merely to satisfy this guard.]'- : defaultPlanExecutionBlockNudge({- viaDone,- missingEvidence,- requiresStateChange: state.requiresStateChange,- })) + recoveryAnchor,+ nudge: recoveryNudge(),};}if (state.taskDrifted) {@@ -40232,6 +41160,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcontentArgs,upstreamAbortSignal = null,upstreamDispatchState = null,+ guardAdvisories = null,) {if (!response || response.success !== true || response.needsTrustedClick !== true) {return response;@@ -40246,6 +41175,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dupstreamAbortSignal,recoveryState,upstreamDispatchState,+ guardAdvisories,);}try {@@ -40258,6 +41188,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dabortSignal,recoveryState,upstreamDispatchState,+ guardAdvisories,),'set_checked',CONTENT_ACTION_TIMEOUT_MS,@@ -40305,6 +41236,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dabortSignal = null,recoveryState = { clickStarted: false, clickResult: null, trustedClickSucceeded: false },upstreamDispatchState = null,+ guardAdvisories = null,) {this._throwIfAborted(abortSignal);const confirmationSurfacesBefore = Array.isArray(response._confirmationSurfaces)@@ -40324,7 +41256,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._throwIfAborted(abortSignal);if (contentArgs._jevBinding) {const probe = await chrome.tabs.sendMessage(tabId, { target: 'content', action: 'jev_validate_target', params: { _jevBinding: contentArgs._jevBinding } }, { frameId: 0 });- if (probe?.success !== true) return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Checkbox changed before dispatch; observe again.' };+ // The one-shot marker still names the exact checkbox the content+ // script prepared; without Strict checks it is clicked with a note.+ if (probe?.success !== true && !this._guardAdvisesFor(guardAdvisories, 'jev-target-changed',+ JEV_TARGET_CHANGED_NOTE, { decided: probe?.staleJevTarget === true })) {+ return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Checkbox changed before dispatch; observe again.' };+ }}clickResult = await cdpClient.clickElement(tabId, trustedSelector, {trustedOnly: true,@@ -41123,6 +42060,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._throwIfAborted(linked.signal);return { success: false, botMemory: true, noDispatch: true, dispatched: false, error: error.message };}+ // A done that memory refuses because an action's outcome is still+ // uncertain is advised once per run by default; then it goes through+ // with a caveat, and the memory ledger keeps that action uncertain.+ if (prepared.allowed !== true && ['done', 'done_json'].includes(name)+ && !this._guardRefusesOnce(tabId, 'bot-memory-uncertain-done', { decided: false,+ caveat: 'An earlier action\'s result was still uncertain when the task was reported done.' })) {+ prepared = { allowed: true, readOnly: true };+ }if (prepared.allowed !== true) return { success: false, botMemory: true, noDispatch: true,dispatched: false, retryable: false, ...(['done', 'done_json'].includes(name) ? { blockedDone: true } : {}), error: prepared.reason };// Memory acknowledgement adds a prerequisite. The current permission,@@ -41142,6 +42087,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}async _executeToolWithLifecycle(tabId, name, args, onUpdate = null, executionContext = null) {+ // Quality guards that advise instead of refusing leave their notes in+ // this call's list; the result carries them to the model.+ const guardAdvisories = Array.isArray(executionContext?.guardAdvisories) ? executionContext.guardAdvisories : [];+ const result = await this._executeToolWithLifecycleInner(tabId, name, args, onUpdate, { ...(executionContext || {}), guardAdvisories });+ // A note says what went through despite a check. When another check+ // then refused the call, nothing went through and the note would mislead.+ const refused = !!result && typeof result === 'object' && (result.noDispatch === true || result.dispatched === false);+ return refused ? result : withGuardAdvisories(result, guardAdvisories);+ }++ async _executeToolWithLifecycleInner(tabId, name, args, onUpdate = null, executionContext = null) {const linked = this._linkAbortSignals(executionContext?._contentActionAbortSignal, this._runAbortSignal(tabId));const dispatchState = executionContext?._contentActionDispatchState || { started: false };// Every text-write route marks dispatch before content messaging or CDP input.@@ -41157,9 +42113,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (executionContext?.jevBinding) {const probe = await chrome.tabs.sendMessage(tabId, { target: 'content', action: 'jev_validate_target', params: { _jevBinding: executionContext.jevBinding } }, { frameId: 0 });this._throwIfAborted(linked.signal);- if (probe?.success !== true) return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Jev target changed; observe again before acting.' };+ if (probe?.success !== true) {+ if (!this._guardAdvisesFor(executionContext.guardAdvisories, 'jev-target-changed', JEV_TARGET_CHANGED_NOTE,+ { decided: probe?.staleJevTarget === true })) {+ return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Jev target changed; observe again before acting.' };+ }+ // Without Strict checks the fast-path call goes to whatever its+ // ref or selector resolves to now, through the ordinary tool path+ // and its checks; the stale binding would only refuse it again.+ executionContext = { ...executionContext, jevBinding: null };+ }}- const uncertainTextBlock = await this._uncertainTextMutationBlock(tabId, name, args || {});+ // Default mode only notes an earlier unverified write (the call's+ // guardAdvisories); Strict checks still refuse it here.+ const uncertainTextBlock = await this._uncertainTextMutationBlock(tabId, name, args || {},+ { advisories: executionContext.guardAdvisories });if (uncertainTextBlock) return uncertainTextBlock;const context = executionContext && typeof executionContext === 'object'? executionContext@@ -41633,7 +42601,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Who receives a message is never settled by a question and its answer:// WebBrain confirms the send with the user on its own card. A question// declared to be about the recipient cannot repair a technical blocker.- if (technicalRecipientReason && explicitRecipientQuestion) {+ // Asking it is harmless (the send stays guarded), so without Strict+ // checks the question is shown with a note.+ if (technicalRecipientReason && explicitRecipientQuestion+ && !this._guardAdvisesFor(executionContext?.guardAdvisories, 'recipient-clarify-cannot-repair-technical',+ `The user's answer cannot supply the page evidence the message guard is missing (${technicalRecipientReason}); a send still needs that evidence or WebBrain's own recipient card. Re-read the recipient and composer after the answer.`)) {return { success: false, blocked: true, noDispatch: true, dispatched: false, retryable: false,messageRecipientGuard: true, reasonCode: technicalRecipientReason,error: 'Recipient confirmation cannot repair the unresolved technical message guard. No clarification was shown. Re-read the active recipient and composer evidence; if it remains unavailable, report the blocker instead of requesting the same approval again.' };@@ -41935,7 +42907,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst nonMonotonic = previousState && (traversalDirection === 'reverse'? target.requestedIndex >= previousState.minVerifiedIndex: target.requestedIndex <= previousState.maxVerifiedIndex);- if (nonMonotonic) {+ // carousel-traversal-guards (quality): revisiting a slide is navigation,+ // not a repeat of a consequential action. Without Strict checks it runs+ // with a note; the post-navigation route and media checks still report.+ if (nonMonotonic && !this._guardAdvisesFor(executionContext?.guardAdvisories, 'carousel-traversal-guards',+ traversalDirection === 'reverse'+ ? `This reversed carousel scan already processed slides down to ${previousState.minVerifiedIndex}; slide ${target.requestedIndex} was opened anyway. Do not record it again as a new row.`+ : `This forward carousel scan already processed slides up to ${previousState.maxVerifiedIndex}; slide ${target.requestedIndex} was opened anyway. Do not record it again as a new row.`)) {return {success: false, dispatched: false, noDispatch: true, nonMonotonic: true,requestedIndex: target.requestedIndex, highestVerifiedIndex: previousState.maxVerifiedIndex,@@ -42023,7 +43001,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});const expected = this.progressExpectedItems.get(tabId);const session = this._currentProgressSession(tabId);- if (expected && session?.sessionId) {+ // An advised revisit of an already processed slide must not reset its+ // ledger row back to "acted".+ if (expected && session?.sessionId && !nonMonotonic) {const discoveredSlideCount = afterState.discoveredSlideCount;const hasCover = discoveredSlideCount === expected.count + 1|| (/hotel/i.test(expected.item_type)@@ -43372,11 +44352,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// What the page's live messages and the statuses observed after the// submit say, read in any language for the checks below. Success// messages are only ever the agent's own readings, never page data.- const incompleteBlock = await incompleteCompletionBlock(this, tabId, {+ // By default the incomplete-task judge redirects an honest partial or+ // failed ending once per run; later endings are not judged again.+ const incompleteBlock = this._guardHasAdvised(tabId, 'incomplete-task-redirect') ? null : await incompleteCompletionBlock(this, tabId, {terminalOnly: Number.isFinite(executionContext?.traceStep) && executionContext.traceStep >= this.maxSteps,outcome, summary: args.summary, pageState, pageUrl: probe?.url || '',});- if (incompleteBlock) return incompleteBlock;+ if (incompleteBlock && this._incompleteRedirectRefuses(tabId, incompleteBlock)) return incompleteBlock;const readingStartedAt = Date.now();if (outcome === 'success' && pageState) await this._readCompletionFormSubmits(tabId, pageState);if (outcome === 'success' && pageState) await this._readCompletionStatusTexts(tabId, pageState);@@ -43386,7 +44368,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._recordDoneTiming(tabId, { preparationMs: readingStartedAt - doneStartedAt,readingMs: verificationStartedAt - readingStartedAt, verificationMs: Date.now() - verificationStartedAt,...(completionDecision ? { outcome: completionDecision.outcome, engine: completionDecision.engine } : {}) });- if (completionDecision && ['pending', 'failed'].includes(completionDecision.outcome)) return { success: false, blockedDone: true, completionDecision: { outcome: completionDecision.outcome, engine: completionDecision.engine }, error: 'Completion verification reports ' + completionDecision.outcome + '. Inspect the result before any further submission; continue recovery or report partial/failed.' };+ if (completionDecision && ['pending', 'failed'].includes(completionDecision.outcome)+ && this._completionVerdictRefuses(tabId, completionDecision)) return { success: false, blockedDone: true, completionDecision: { outcome: completionDecision.outcome, engine: completionDecision.engine }, error: 'Completion verification reports ' + completionDecision.outcome + '. Inspect the result before any further submission; continue recovery or report partial/failed.' };if (pageState?.nativeChatDeliveryEvidence) {delete pageState.nativeChatDeliveryEvidence;this._planExecutionGuards.get(tabId).nativeChatDeliveryEvidence = null;@@ -43399,7 +44382,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (outcome === 'success' && pageState) pageState.iframeSubmissionEvidence = await this._completionIframeEvidence(tabId);if (outcome === 'success' && this._currentCompletionSubmitState(tabId)?.iframeSubmission&& (!pageState?.iframeSubmissionEvidence || (completionDecision?.outcome === 'succeeded'- && completionDecision.submittedFrameStamp !== pageState.iframeSubmissionEvidence.stamp))) {+ && completionDecision.submittedFrameStamp !== pageState.iframeSubmissionEvidence.stamp))+ && this._iframeResultStaleRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The submitted iframe changed or could not be refreshed at completion. Read its current result again; do not repeat the submission.' };}@@ -43519,18 +44503,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// search/filter bar, not a submit form).if (completionWarning) {const blocks = this._nextCompletionPageBlock(tabId, completionPageBlock.key);- if (blocks <= 2) {+ if (this._completionPageWarningRefuses(tabId, completionPageBlock.key) && blocks <= 2) {return {success: false,blockedDone: true,completionPageBlock: true,- error: verification.completionWarning + ` (block attempt ${blocks}/2 — if you genuinely believe the task is complete and the visible form/dialog is unrelated, re-call done with summary explicitly acknowledging this, e.g. "already-existing product, no submit needed".)`,+ error: verification.completionWarning + this._completionPageWarningSuffix(blocks),pageUrl: verification.pageUrl,pageState: verification.pageState,...(imageDataUrl ? { _attachImage: imageDataUrl } : {}),};}- // After 2 blocks, let done through with a loud note in verification.+ // After 2 blocks (by default after one), let done through with a loud+ // note in verification.}// A request that also expects votes or moderation to go a certain way// asks for something no run can verify. The completion judge reads that@@ -43544,7 +44529,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait trace.recordScreenshot(runId, null, imageDataUrl, 'done verification');}- if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)) {+ if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)+ && this._calculationRefreshRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The verified calculation authority changed before completion. Reconsider the current genuine task; no new action was performed.' };}@@ -43558,14 +44544,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d} catch (error) {if (completionStopError(error, this._runAbortSignal(tabId))) throw error;// Screenshot failed — still allow done but note it- if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)) {+ if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)+ && this._calculationRefreshRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The verified calculation authority changed before completion. Reconsider the current genuine task; no new action was performed.' };}return { done: true, summary: args.summary, outcome, verification: null };}}- if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)) {+ if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)+ && this._calculationRefreshRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The verified calculation authority changed before completion. Reconsider the current genuine task; no new action was performed.' };}@@ -44663,7 +45651,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (this._formValidationBlocks.has(tabId)) {const currentStates = await this._captureFormValidationState(tabId);- this._applyVerifyFormRecovery(tabId, result, currentStates);+ this._applyVerifyFormRecovery(tabId, result, currentStates, executionContext?.guardAdvisories);}return result;} catch (e) {@@ -45225,7 +46213,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout drecommendationKind: result.recommendation?.kind || null,};};- const runDomDownloader = async () => {+ const runDomDownloader = async ({ bound = true } = {}) => {// Inject the SocialMediaDownloader library into the page's main// world so it shares fetch/XHR/cookies with page scripts — same// execution context the script's DevTools-console docs target.@@ -45243,7 +46231,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dlimit: typeof toolArgs.limit === 'number' && toolArgs.limit > 0? toolArgs.limit: (bulkSocialDownload ? Number.MAX_SAFE_INTEGER : 1),- ...(executionContext?._expectedMediaBinding ? { expectedMediaBinding: executionContext._expectedMediaBinding } : {}),+ ...(bound && executionContext?._expectedMediaBinding ? { expectedMediaBinding: executionContext._expectedMediaBinding } : {}),+ // An advised unbound retry of a bound call stays on the DOM item path.+ ...(!bound && executionContext?._expectedMediaBinding ? { domOnly: true } : {}),};const results = await chrome.scripting.executeScript({target: { tabId },@@ -45269,7 +46259,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// recommendation builder so we can tell the agent to// call saveMse() when there's actually a capture.let mseBytes = 0;- try {+ // An advised unbound retry of a bound call stays on the DOM+ // item path, so a recorded stream is neither saved nor offered.+ if (!runOpts.domOnly) try {const rec = window.SocialMediaDownloader.getMseRecording();for (const ms of (rec.mediaSources || [])) {for (const b of (ms.buffers || [])) mseBytes += (b.bytes || 0);@@ -45384,7 +46376,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {// A bound call must never switch resources through MSE or vision fallback.- if (executionContext?._expectedMediaBinding) return await runDomDownloader();+ if (executionContext?._expectedMediaBinding) {+ const boundResult = await runDomDownloader();+ // The focused media changed after the model observed it. Without+ // Strict checks the download runs once more without that binding+ // (still DOM-only, one item) and the model is told what it saved+ // may not be the item it saw.+ if (boundResult?.errorCode === 'media_binding_changed'+ && this._guardAdvisesFor(executionContext?.guardAdvisories, 'media-download-target-binding',+ 'The media in focus changed after your last observation, so WebBrain could not confirm this download is the item you saw. It saved the media now in focus; check the downloaded file (list_downloads) before reporting it.')) {+ this._throwIfAborted?.(executionContext?._contentActionAbortSignal || null);+ return await runDomDownloader({ bound: false });+ }+ return boundResult;+ }const strategy = ['auto', 'dom', 'vision'].includes(toolArgs.strategy) ? toolArgs.strategy : 'auto';const bulkSocialDownload = !!toolArgs.scroll || toolArgs.mode === 'all';const activeProvider = this._activeProvider(tabId);@@ -45916,6 +46921,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dmessageRecipientDispatchBinding,expectedName: args.expected_name,expectedRole: args.expected_role,+ guardAdvisories: dispatchContext.guardAdvisories,}, earlyCdpAbortSignal);throwIfEarlyCdpAborted();if (reconciled.result) return reconciled.result;@@ -47199,7 +48205,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthrowIfEarlyCdpAborted();if (previewCheck?.errorCode === 'truncated_value_replacement') return previewCheck;}- if (focusedBinding?.token) {+ // Leaving this block early (break) falls back to typing into the+ // currently focused field below, as an unbound type_text does.+ boundFocusedTyping: if (focusedBinding?.token) {const frameId = Number.isInteger(focusedBinding.frameId)? focusedBinding.frameId: 0;@@ -47216,6 +48224,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthrowIfEarlyCdpAborted();if (!prepared?.success) {tokenConsumed = !!prepared;+ // The field bound by the toolbar preflight lost focus, or the+ // page gave no answer. By default (typing-target-identity+ // advises) type into the field focused now, which the unbound+ // path still requires to be editable; Strict checks refuse.+ // A clearing write never falls back: the truncated-preview+ // check above ran against the bound field, and select-all ++ // delete on whichever field has focus now could erase a value+ // that check never saw (a deletion-class concern).+ const identityLost = !prepared || prepared.reasonCode === 'focused_target_changed';+ if (identityLost && !args.clear && this._guardAdvisesFor(dispatchContext.guardAdvisories, 'typing-target-identity',+ 'The field focused when this call was checked lost focus before typing, so the text went to the field focused now. Check that the intended field changed.',+ { decided: !!prepared })) {+ break boundFocusedTyping;+ }return prepared || {success: false,dispatched: false,@@ -47369,6 +48391,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (args.selector) {let result;let expectedBackendNodeId = Number(dispatchBinding?.backendNodeId) || null;+ const unpinnedRefusal = {+ success: false,+ dispatched: false,+ noDispatch: true,+ retryable: true,+ error: 'Could not preserve the selector target for safe typing. Re-read the page and retry.',+ };if (!expectedBackendNodeId) {try {const probe = await cdpClient.probeRichTextToolbarSelector(tabId, args.selector, {@@ -47379,23 +48408,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthrowIfEarlyCdpAborted();expectedBackendNodeId = Number(probe?.selectorBackendNodeId) || null;} catch {- return {- success: false,- dispatched: false,- noDispatch: true,- retryable: true,- error: 'Could not preserve the selector target for safe typing. Re-read the page and retry.',- };+ // A stopped or expired action sends nothing in any mode.+ if (earlyCdpAbortSignal?.aborted) return unpinnedRefusal;}}- if (!expectedBackendNodeId) {- return {- success: false,- dispatched: false,- noDispatch: true,- retryable: true,- error: 'Could not preserve the selector target for safe typing. Re-read the page and retry.',- };+ // The node checked before typing could not be pinned. By default+ // (typing-target-identity advises) type into the selector's current+ // match, which typeText still resolves and checks; Strict checks+ // refuse as before.+ if (!expectedBackendNodeId && !this._guardAdvisesFor(dispatchContext.guardAdvisories, 'typing-target-identity',+ 'The field could not be pinned to the element checked before typing, so the text went to the current match of this selector. Check that the intended field changed.',+ { decided: false })) {+ return unpinnedRefusal;}const typeFieldEpoch = this._captureLastTypeFieldEpoch(tabId);try {@@ -48332,6 +49356,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcontentArgs,earlyCdpAbortSignal,earlyCdpDispatchState,+ dispatchContext.guardAdvisories,);}if ((name === 'type_ax' || name === 'set_field') && !dispatchContext.jevBinding) {@@ -49098,6 +50123,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// is an unknown mutation outcome. Retrying here can append a second copy to// controlled or virtualized editors whose first write actually landed.if (response.noDispatch !== true || response.dispatched === true) {+ // WebBrain never retypes on its own here, in any mode. By default the+ // model is not locked out either (trusted-field-retry-guards advises):+ // no repeat lock labels, and the text-write finalizer reports a write+ // whose text went out as unverified so the model decides.+ if (this._guardAdvises('trusted-field-retry-guards', { decided: true })) {+ const unlocked = {+ ...response,+ success: false,+ outcomeUnknown: true,+ mutationMayHaveOccurred: true,+ fallbackAttempted: false,+ trustedFallbackAttempted: false,+ error: `${response.error || 'Field verification failed'} No trusted retry was sent because the original write may already have changed the editor.`,+ };+ delete unlocked.repeatBlocked;+ if (unlocked.recoveryRequired === 'verify_or_restore_field') delete unlocked.recoveryRequired;+ return unlocked;+ }return {...response,success: false,@@ -49317,6 +50360,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._throwIfAborted(abortSignal);}if (!verification?.success || verification.verified !== true) {+ // The trusted text went out. GitHub's CodeMirror lands here with a+ // correct document: its innerText readback doubles blank lines and+ // omits off-screen lines. `unverified` lets the finalizer report it+ // as an unverified success by default (Strict checks: a failure).+ const readable = verification?.success === true;return {...failed,dispatched: true,@@ -49324,6 +50372,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dverified: false,...(verification?.fieldMeta ? { fieldMeta: verification.fieldMeta } : {}),...(Object.prototype.hasOwnProperty.call(verification || {}, 'actual') ? { actual: verification.actual } : {}),+ unverified: { reason: readable ? 'readback_mismatch' : 'readback_unavailable',+ reader: readable ? String(verification.reader || 'unknown') : 'none' },+ ...(readable && typeof verification.readbackExact === 'boolean' ? { readbackExact: verification.readbackExact }+ : !readable ? { readbackExact: false } : {}),error: 'The field value still did not exactly match after trusted typing. Repeat this exact replacement once for readback-only recovery; a generic tree read cannot verify the full value. Restore the editor if the mismatch persists.',};}@@ -51989,6 +53041,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}// Genuine final answer — emit and exit. Repeated-item progress recovery// takes priority so an unresolved ledger can still drive the next tool turn.+ // A plain final is a new completion attempt (see+ // _beginCompletionGuardAttempt).+ this._beginCompletionGuardAttempt(tabId);const clarificationFinalDecision = this._isActionMode(mode)? this._clarificationAuthorizationPlainFinalDecision(tabId): null;@@ -52013,7 +53068,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finalResponse;}const readFinalLimitation = this._readCompletenessLimitation(tabId);- if (readFinalLimitation) {+ if (readFinalLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {finalResponse = readFinalLimitation;_traceStatus = 'read_scope_limited';messages.push({ role: 'assistant', content: finalResponse });@@ -52036,13 +53091,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait this._persistNow(tabId);continue;}- const progressFinalBlock = this._plainFinalProgressBlock(tabId);- const completionFinalBlock = this._completionPlainFinalBlock(tabId);- const readFinalBlock = this._readCompletenessBlock(tabId);- const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), result.content);+ // By default each check refuses at most once per run (_plainFinalGuardBlocks).+ const {+ progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock,+ } = this._plainFinalGuardBlocks(tabId, result.content);const plainFinalBlocks = [progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock].filter(Boolean);if (plainFinalBlocks.length) {- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && this._plainFinalTwoStrikeEnds()) {finalResponse = this._completionPlainFinalPartial(tabId, result.content, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -52056,7 +53111,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finalResponse;}if (completionFinalBlock) completionPlainFinalRecoveryAttempted++;- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps+ && this._plainFinalTwoStrikeEnds()) {finalResponse = this._completionPlainFinalPartial(tabId, result.content, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -52123,7 +53179,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout donUpdate('warning', { message: finalResponse });break;}- if (this._isClearlyIncompleteStandaloneAnswer(result.content, runOptions)) {+ if (this._isClearlyIncompleteStandaloneAnswer(result.content, runOptions) && this._standaloneTruncationRefuses(tabId)) {if (!standaloneIncompleteAnswerRecoveryAttempted) {standaloneIncompleteAnswerRecoveryAttempted = true;messages.push(this._withResponseItems({ role: 'assistant', content: result.content }, result.responseItems, result.reasoningContent, provider));@@ -52154,6 +53210,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout drunOptions,);finalResponse = this._withStandaloneUnverifiedNotice(finalResponse, standaloneGroundingGap, runOptions);+ finalResponse = this._withCompletionCaveat(tabId, finalResponse);messages.push(this._withResponseItems({ role: 'assistant', content: finalResponse }, result.responseItems, result.reasoningContent, provider));onUpdate('text', { content: finalResponse, replace: true });break;@@ -53314,6 +54371,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}emptyOutputRecoveryAttempted = false;compressionPlaceholderRecoveryAttempted = false;+ // A plain final is a new completion attempt (see+ // _beginCompletionGuardAttempt).+ this._beginCompletionGuardAttempt(tabId);const clarificationFinalDecision = this._isActionMode(mode)? this._clarificationAuthorizationPlainFinalDecision(tabId): null;@@ -53340,7 +54400,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finish(clarificationFinalDecision.failure, clarificationFinalDecision.status);}const readFinalLimitation = this._readCompletenessLimitation(tabId);- if (readFinalLimitation) {+ if (readFinalLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {messages.push({ role: 'assistant', content: readFinalLimitation });onUpdate('text', { content: readFinalLimitation, replace: true });onUpdate('warning', { message: 'Ask mode could not verify that every Gmail message was expanded.' });@@ -53363,13 +54423,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait this._persistNow(tabId);continue;}- const progressFinalBlock = this._plainFinalProgressBlock(tabId);- const completionFinalBlock = this._completionPlainFinalBlock(tabId);- const readFinalBlock = this._readCompletenessBlock(tabId);- const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), fullText);+ // By default each check refuses at most once per run (_plainFinalGuardBlocks).+ const {+ progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock,+ } = this._plainFinalGuardBlocks(tabId, fullText);const plainFinalBlocks = [progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock].filter(Boolean);if (plainFinalBlocks.length) {- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && this._plainFinalTwoStrikeEnds()) {const partial = this._completionPlainFinalPartial(tabId, fullText, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -53382,7 +54442,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finish(partial, 'partial');}if (completionFinalBlock) completionPlainFinalRecoveryAttempted++;- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps+ && this._plainFinalTwoStrikeEnds()) {const partial = this._completionPlainFinalPartial(tabId, fullText, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -53453,7 +54514,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._persist(tabId);return finish(visibleFailure, planOnlyDecision.status || 'plan_only_output');}- if (this._isClearlyIncompleteStandaloneAnswer(fullText, runOptions)) {+ if (this._isClearlyIncompleteStandaloneAnswer(fullText, runOptions) && this._standaloneTruncationRefuses(tabId)) {if (!standaloneIncompleteAnswerRecoveryAttempted) {standaloneIncompleteAnswerRecoveryAttempted = true;messages.push(this._withResponseItems({ role: 'assistant', content: fullText }, responseItems, reasoningContent, provider));@@ -53500,6 +54561,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dfullText = attributedFullText;onUpdate('text', { content: fullText, replace: true });}+ const caveatedFullText = this._withCompletionCaveat(tabId, fullText);+ if (caveatedFullText !== fullText) {+ fullText = caveatedFullText;+ onUpdate('text', { content: fullText, replace: true });+ }messages.push(this._withResponseItems({ role: 'assistant', content: fullText }, responseItems, reasoningContent, provider));this._persist(tabId);closeTraceStep({ ok: true });diff --git a/src/chrome/src/agent/browser-batch.js b/src/chrome/src/agent/browser-batch.jsindex 453597015..925b8e148 100644--- a/src/chrome/src/agent/browser-batch.js+++ b/src/chrome/src/agent/browser-batch.js@@ -60,7 +60,12 @@ export function expandBrowserBatchCalls(calls, options) {});}-export function browserBatchResultStatus(message) {+// advisoryWritesContinue: a text write that went out but could not be read+// back exactly (success with unverifiedWrite, see the agent's text-write+// advisories) ran and does not stop the batch. Only that marker is exempt:+// failures, refusals and unknown outcomes still do. The agent passes false+// under Settings → "Strict checks", which never produce that marker anyway.+export function browserBatchResultStatus(message, { advisoryWritesContinue = true } = {}) {if (!message) return { ran: false, reason: 'interrupted' };let text = String(message.content || '');const wrapped = text.match(/^<untrusted_page_content\b[^>]*>([\s\S]*?)<\/untrusted_page_content\b[^>]*>/);@@ -72,7 +77,9 @@ export function browserBatchResultStatus(message) {if (!object(result)) return { ran: true, reason: '', failed: false };const ran = !(result.skipped || result.denied || result.invalidToolArguments || result.invalidArguments|| ((result.noDispatch === true || result.dispatched === false) && result.success !== true));- const unverified = result.inconclusive || result.verified === false || result.remoteStateVerified === false;+ const advisoryWrite = advisoryWritesContinue === true && result.success === true+ && result.unverifiedWrite === true && !result.error;+ const unverified = !advisoryWrite && (result.inconclusive || result.verified === false || result.remoteStateVerified === false);const failed = !!(result.success === false || result.error || result.noProgress || result.ambiguous|| result.outcomeUnknown || result.stale || unverified);const reason = result.cancelled ? 'cancelled'diff --git a/src/chrome/src/agent/chat-workflow.js b/src/chrome/src/agent/chat-workflow.jsindex c7edea2c5..d1b040c7c 100644--- a/src/chrome/src/agent/chat-workflow.js+++ b/src/chrome/src/agent/chat-workflow.js@@ -677,9 +677,25 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {};}-export function decideChatSend(value, rawSnapshot, text, now = Date.now()) {+// Send preconditions a caller may waive with a note (WebBrain's quality+// checks). The empty/over-long body, user input (credentials, payment, a new+// user decision), thread binding, a user's own draft in the composer and the+// duplicate checks are never waivable: an over-long body could not be matched+// to its pending record afterwards, and a draft belongs to the user.+// Only a missing composer may be waived by default (the send then simply+// cannot dispatch). A terminal session and an unverified native message+// baseline stay blocking: the baseline is what delivery matching and+// duplicate-send detection rely on, and a terminal session asked for no+// further message.+export const WAIVABLE_CHAT_SEND_REASONS = Object.freeze([+ 'composer_unavailable',+]);++export function decideChatSend(value, rawSnapshot, text, now = Date.now(), { waive = null } = {}) {const session = normalizeChatSession(value, now);const snapshot = normalizeChatSnapshot(rawSnapshot, now);+ const waived = reason => WAIVABLE_CHAT_SEND_REASONS.includes(reason)+ && (waive instanceof Set ? waive.has(reason) : Array.isArray(waive) && waive.includes(reason));// Normalize one character past the cap so an over-long body is rejected// rather than silently truncated into a different message than requested.const body = normalizeChatText(text, MAX_MESSAGE_TEXT + 1);@@ -688,17 +704,17 @@ export function decideChatSend(value, rawSnapshot, text, now = Date.now()) {if (session.userInput?.required || snapshot.userInput?.required) {return { ok: false, reason: 'user_input_required', error: 'Pause the chat until the user completes the required verification or decision.' };}- if (session.state === 'issue_resolved' || session.state === 'stopped') {+ if ((session.state === 'issue_resolved' || session.state === 'stopped') && !waived('terminal_session')) {return { ok: false, reason: 'terminal_session', error: 'The chat session is terminal; do not send another message.' };}if (!session.threadKey || !snapshot.threadKey || session.threadKey !== snapshot.threadKey) {return { ok: false, reason: 'thread_unverified', error: 'The active conversation is not bound to the stored chat session.' };}- if (snapshot.nativeMessageBaselineComplete === false) {+ if (snapshot.nativeMessageBaselineComplete === false && !waived('native_baseline_unverified')) {return { ok: false, reason: 'native_baseline_unverified',error: 'The latest mounted native message IDs or pending statuses are not verified. Observe the current conversation before sending.' };}- if (snapshot.composer.available !== true) {+ if (snapshot.composer.available !== true && !waived('composer_unavailable')) {return { ok: false, reason: 'composer_unavailable', error: 'The active conversation composer is not available.' };}if (snapshot.composer.empty !== true) {diff --git a/src/chrome/src/agent/completion-invariant.js b/src/chrome/src/agent/completion-invariant.jsindex e112040d1..b30e3cf45 100644--- a/src/chrome/src/agent/completion-invariant.js+++ b/src/chrome/src/agent/completion-invariant.js@@ -1064,17 +1064,20 @@ export function consumeCompletionObservationResult(state) {};}-export function completionDoneBlock(state, toolName, args = {}) {+// `skip`: reasons a caller already accepted over advice (Strict checks off,+// see guard-policy.js), so the next invariant still gets its own note.+export function completionDoneBlock(state, toolName, args = {}, { skip = null } = {}) {+ const skipped = reason => skip?.has?.(reason) === true;const isDoneJson = toolName === 'done_json';const outcome = isDoneJson ? 'success' : normalizedOutcome(args?.outcome);- if (!isDoneJson && !outcome) {+ if (!isDoneJson && !outcome && !skipped('missing_outcome')) {return {reason: 'missing_outcome',error: 'done requires outcome="success", "partial", or "failed". Use partial or failed when the task is not fully verified.',};}if (outcome === 'partial' || outcome === 'failed') return null;- if (state?.iframeFormVerificationDebt) {+ if (state?.iframeFormVerificationDebt && !skipped('iframe_form_verification_required')) {const pendingCount = Array.isArray(state.iframeFormVerificationObligations)? state.iframeFormVerificationObligations.length: 1;@@ -1085,7 +1088,7 @@ export function completionDoneBlock(state, toolName, args = {}) {pendingTargetCount: pendingCount,};}- if (state?.verificationDebt) {+ if (state?.verificationDebt && !skipped('verification_required')) {return {reason: 'verification_required',error: 'The latest consequential action has not been verified by a successful explicit page/state observation. Re-read the relevant state after the action, then call done again; otherwise finish with outcome="partial" or outcome="failed".'diff --git a/src/chrome/src/agent/guard-policy.js b/src/chrome/src/agent/guard-policy.jsnew file mode 100644index 000000000..47f8f61e5--- /dev/null+++ b/src/chrome/src/agent/guard-policy.js@@ -0,0 +1,413 @@+// How WebBrain's own checks treat a model-requested action.+//+// A guard is WebBrain code (not the user) that refuses, defers or stops a+// tool call, a write, a submit or a completion. Every guard is registered+// here with a class and two behaviors:+//+// - onDecided: what it does when it KNOWS the action is wrong.+// - onCannotDecide: what it does when it cannot tell (evidence missing,+// unreadable, stale or timed out).+//+// Only the short list of HARD classes may refuse an action outright: the+// wrong recipient, deleting data, money, credentials, and publishing+// something the user did not ask for. When a hard guard cannot decide it+// asks the user on WebBrain's own card where one exists ('ask'), and+// otherwise refuses ('block').+//+// Every other guard is 'quality' (verification, exact readback, evidence,+// completion checks): it tells the model about the problem instead of+// stopping it ('advise'), or asks the user when it cannot verify a+// consequential step such as a commit or a publish ('ask'). Settings →+// General → "Strict checks" restores blocking for every quality guard.+//+// permission_gate (the user's own permissions, modes and budgets),+// host_check (same-site, frame and task-authority boundaries, CAPTCHA and+// access walls, a human acting in the same tab), budget (loop and observation+// limits), infra (a call that cannot run as given) and user_control (Stop,+// corrections, cancelled cards) are not guards in this sense and keep their+// behavior.+//+// Rule for new guards (enforced by test/guard-policy.mjs): register the id+// here, declare onCannotDecide, and name a test of a legitimate task the+// guard must not block (mustNotBlock: 'test/file.mjs#exact test name').+// See docs/guards.md. Shared verbatim by the Chrome and Firefox builds.++export const HARD_GUARD_CLASSES = Object.freeze(['recipient', 'deletion', 'money', 'credentials', 'unrequested_publication']);+export const NON_GUARD_CLASSES = Object.freeze(['permission_gate', 'host_check', 'budget', 'infra', 'user_control']);+export const GUARD_CLASSES = Object.freeze([...HARD_GUARD_CLASSES, 'quality', ...NON_GUARD_CLASSES]);+export const GUARD_OUTCOMES = Object.freeze(['block', 'ask', 'advise']);++// Guards that existed when this registry was introduced. Each later guard+// must name a mustNotBlock test (see the header).+export const GRANDFATHERED_GUARD_COUNT = 158;++export const GUARDS = Object.freeze({+ "auto-progress-resume": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Two consecutive stalled outputs with unresolved progress rows schedule a resume (scheduler or cloud deferResume) instead of failing." },+ "bot-memory-uncertain-done": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "In a managed Cloud bot run, done(success)/done_json while a dispatched bot-memory action still has an uncertain outcome." },+ "completion-evidence-freshness": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Completion evidence went stale while done was being verified: judged evidence or document identity changed, the pure-calculation receipt authority changed, the submitted iframe snapshot is missing or changed after a succeeded verdict, or calculation evidence captured at done start is no longer…" },+ "completion-failure-only-done": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "When a forced verification turn made no progress, or no observation tool is available, done is advertised with outcome enum partial/failed only; a done(success) is then rejected by schema validation." },+ "completion-page-warning": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Structural page warnings at done(success): an open dialog, a recorded submit that failed validation, a task-relevant form still visible without a verified submit transition, or a create/edit route without success; refused at most twice per key, then accepted with a loud note." },+ "completion-recovery-forced-turns": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a refused completion the next turn is rewritten by _completionRecoveryPolicy: read-only verification tools only (fetch_url forced to GET, or verify_form / download readers) with toolChoice required, then a done-only turn." },+ "completion-verifier-advisory-outputs": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Non-refusing verifier outputs: an uncertain verdict (all engines unsure/unavailable, budget spent, D1 success without confirmation) sets no verified submission evidence, and a sure later_outcome side answer appends a \"future votes/moderation unverified\" note." },+ "completion-verifier-not-done": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The independent completion judge (decision-model sidecar or active LLM) returns a sure pending or failed verdict for done(success): refused and re-armed as verification debt (forced read-only turn)." },+ "done-iframe-form-unverified": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final while edited iframe form targets have not been read back by a matching verify_form (which compares textContent against an expected value that keeps newlines)." },+ "done-invariant-shape-checks": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Act/Dev done without outcome success/partial/failed, or done(success) in the same assistant batch as the action/observation it relies on (or with verification debt at batch start)." },+ "done-rich-text-toolbar-obligation": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final while the last text entry hit a rich-text formatting toolbar and no verified editor-body edit has released the obligation." },+ "done-summary-meta-only": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The done summary only says that an answer was given (\"Explained how...\") without the answer (judge summary_kind or done_summary reading): refused for a fresh answer turn." },+ "done-verification-debt": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final after a consequential action with no later successful explicit observation (downloads need list_downloads/read_downloaded_file)." },+ "exact-table-done": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Exact table export completion: table JSON without a current data_ref from an exact extract, rowCount != rows.length, an unknown/expired/superseded/foreign data_ref, or a fresh re-read that differs from the exported snapshot (done with any outcome and plain finals)." },+ "github-committed-file-verification": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a GitHub edit-file-and-commit, the raw blob at the commit SHA must byte-match the requested text (SHA-256), be on the requested branch, in the expected repository, listed in the commit file list, with a bound verified editor replacement; oversized or unreadable raw files and an unproven scope…" },+ "incomplete-task-check-stale": { class: "host_check", family: "completion", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The task, run, provider, steering or observed document changed before or during the incomplete_task reading: the partial/failed ending is refused and the model reconsiders the current task." },+ "incomplete-task-redirect": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "An honest done(partial/failed) in an Act/Dev execute task is redirected (at most twice) when the incomplete_task judge says the flow is still loading/validating (wait_then_check) or a reasonable permitted next step remains (continue_now); unsure judges accept the ending." },+ "native-chat-receipt-not-durable": { class: "recipient", family: "completion", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "Fresh native chat delivery proof exists but its receipt cannot be persisted: done(success) is refused so a resumed run does not resend the delivered message." },+ "page-feedback-ask-answer-superseded": { class: "host_check", family: "completion", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "An Ask answer written while the page changed (non-passive churn) is discarded and the model re-asked with fresh feedback, unless an ask_response_scope reading says the answer is page-independent." },+ "plain-final-done-protocol": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "An Act/Dev run that executed an action (state observed) ends with plain text: forced into a done-only turn." },+ "plain-final-rejected-text-compaction": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "When another plain-final block fires and the reply repeats a long paragraph three times or hit the output limit, the assistant turn is replaced by a rejection marker and a \"do not repeat\" nudge." },+ "plain-final-two-strike-partial": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The third plain final under a completion block (second at max steps) ends the run as partial, keeping the model text when nothing else is pending." },+ "plain-final-unusable-output": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The model returned no text and no tool call, a context-compression placeholder, or (on-device standalone chat) an answer ending mid-sentence: one nudge, then auto-resume (progress pending) or stop." },+ "plan-done-summary-shape": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The done summary is a plan or planner/policy JSON instead of a result, or a partial/failed summary blames WebBrain's own Ask/read-only mode in an Act/Dev run (one focused correction, then stop)." },+ "plan-execution-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Plan-execution guard default: done(success) with no successful task tool, a state-changing task with no verified consequential tool (an already-correct page cannot be success), evidence recorded under another task key, or planning failed so success needs a verified consequential tool; one nudge,…" },+ "plan-plain-final-protocol": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "In an execute Act/Dev run every plain-text final (including an echoed stale \"[Stopped by user]\" status) gets one done-protocol nudge with the text cleared, then the run stops." },+ "plan-publication-evidence-missing": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success of a publication task needs job-bound terminal evidence for every requested social destination (also when the publication contract could not be compiled) and, for published_resource jobs, a bound dispatch record, same workflow/task, a bound saved resource matching the requested payload…" },+ "plan-required-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Plan-execution guard: success needs job-specific evidence that was not observed: a successful schedule_task/scheduled:true, completed DOWNLOAD-capability evidence, a non-submit job's own evidence (deterministic count, transcript, terminal read coverage, PR diff read, reconciled collection, scoped…" },+ "plan-submission-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success of a submit/send/commit task needs evidence that it took effect: the selected site job's terminal state (recipient-bound sent message, paid/ticket-issued transaction, form confirmation bound to the inventoried form, saved state with bound metadata, resolved threads, verified final submit)…" },+ "plan-task-drifted": { class: "host_check", family: "completion", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Plan-execution guard: the progress task key changed after the run was authorized, so execution evidence no longer binds; one nudge, then the run stops (task_binding_changed)." },+ "plan-unauthorized-mutation-recorded": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success is refused after the fact when a conditional editor repair was blocked for lacking a matching workflow contract, or a prepare-only form job dispatched a submit." },+ "progress-ledger-unresolved": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Act mode with unresolved (pending/acted) rows in the app-owned progress ledger: done with any outcome is refused and plain finals are redirected with the progress_read payload." },+ "progress-success-claim-checks": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) while the expected ordered rows are missing, duplicated, unprocessed or lack required fields (a short value read as \"missing\" counts as absent), or while ledger rows are skipped or failed." },+ "pure-calculation-done-checks": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "done on a literal-arithmetic task before any actual calculate attempt (any outcome), or done(success) whose summary omits/changes the calculator receipt value or breaks the requested literal format." },+ "read-coverage-ask-limitation": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Ask mode, whole-thread Gmail read required, pages covered but message expansion not confirmed: the model answer (done or plain final) is replaced by a fixed limitation and the run ends read_scope_limited." },+ "read-coverage-incomplete": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The user asked for a whole thread/document and read coverage is incomplete (pages missing, or no terminal page / expansion confirmed): done with any outcome and plain finals are refused." },+ "step-limit": { class: "permission_gate", family: "completion", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The user-configured maxSteps budget is reached without a final response: the run ends (max_steps) with Continue offered." },+ "structured-cloud-output-contract": { class: "infra", family: "completion", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "Structured cloud runs: done_json outside a cloud run with an output schema, a result that fails outputSchema (one repair, then cloudFailed), or prose instead of done_json (one nudge, then required_tool_missing)." },+ "terminal-recovery-no-success": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The forced delivery turn after the observation limit, and the step-limit handoff, may only end partial/failed; invalid output falls back to the deterministic ledger partial or a fixed failure text (delivery_recovery_failed)." },+ "content-action-outcome-unknown": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "A content/CDP deadline, lost message channel or Stop after dispatch makes a mutation outcome-unknown; for text writes the finalizer then records debt (also across Stop)." },+ "set-field-bundled-submit-outcome": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "set_field({submit:true}) withholds the bundled Enter/requestSubmit when the value did not verify, and reports a native form that failed checkValidity instead of submitting it." },+ "text-write-debt-arm": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "_finalizeTextMutationResult (every set_field/type_ax/type_text result, timeouts and cancellations included) turns any unverified, unproven or unknown write into success:false + outcomeUnknown + repeatBlocked, records debt for the editor and drops contenteditable proofs; a verified value with an…" },+ "text-write-debt-block": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Any write (any tool, ref or locator) to an editor that has unresolved text-write debt in this document is refused unless it is the identical original replacement and readback-only recovery verifies it (then a no-dispatch \"recovered\" result is returned)." },+ "text-write-preinsert-unproven": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "The write is stopped before its text goes out because the pre-insert state cannot be proven: DraftJS structure unreadable before the write (no dispatch), select-all could not be proven to cover the managed editor, or select-all+Delete could not be proven to empty the field." },+ "text-write-readback-unverified": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Post-write readback cannot confirm the exact text: content set_field/type_ax/contenteditable insert/DraftJS paste mismatches (innerText fallback reader + strict comparator), a replaced element, DraftJS unreadable after the write, CDP verifyTextEntry/focused textContent checks, uncertain…" },+ "truncated-preview-replacement": { class: "deletion", family: "content-write", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A clearing write whose text ends with \"...\" or another truncation marker and whose prefix starts the field's longer current value would erase everything after the preview: nothing is typed (set_field, type_ax, type, CDP type_text, iframe typing)." },+ "trusted-field-retry-guards": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "WebBrain's own trusted CDP retry of a set_field/type_ax write is suppressed after a possibly dispatched original write, or fails its preparation (focus press, reselection, CDP error, preparation veto predicates); an exact readback proving the editor unchanged makes the failure retryable without…" },+ "typing-target-identity": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Typing target identity checks in the type_text/press_keys handlers: the focused editor bound by the toolbar preflight changed or could not be prepared/revalidated, or the selector backend node id cannot be pinned for safe typing." },+ "delivery-observation-checkpoint": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Consecutive read/scroll/wait observations without verified progress (an unverified write does not count as progress): nudge every 4, and at 8 browser tools stop for a done-only (partial/failed) delivery turn; advisory for cloud runs and the WebBrain Cloud provider." },+ "loop-failed-action-target": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The same mutation target (failureScope, else tool + bucketed args) failed, was refused before dispatch or made no progress: nudge at 2, stop the run at 3 (4 for occlusion). Every failureScope-tagged refusal feeds it." },+ "loop-observation-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Observation loops: repeated clicks in the same 5 px coordinate bucket (nudge 5, stop 8), accessibility-tree nodes read one by one without acting (stop at 6 suspicious or 12 non-sequential), the same scroll direction on the same target without movement (nudge 2, stop 3)." },+ "loop-repeat-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "_checkLoop repeat/oscillation stops: the same call key 3x in 6 or ABAB after eight nudges, carousel oscillation, the same verified navigation returning to an unchanged page four times, the same non-retryable failure twice, a checkbox still wrong after three attempts, the same read-only GET resource…" },+ "loop-unavailable-tool": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Repeated calls to a tool this run does not offer (counted by name): nudge at 3, stop at 10." },+ "loop-verification-dialog-reopen": { class: "host_check", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The same verification (CAPTCHA) dialog was dismissed and reopened repeatedly on the same page: nudge, then stop." },+ "page-feedback-supersession-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Budget over no-dispatch supersessions caused by passive churn or unknown attribution (or an unverified action context): nudge at 2, stop the run at 5 with a Retry/Give up failure-recovery card." },+ "api-mutation-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch_url/research_url with a write method in an Ask-mode run, or without /allow-api (conversation or persistent API permission)." },+ "browser-batch-fresh-turn-interrupt": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a failed, refused, unverified or outcome-unknown browser action (a browser_batch child, any multi-call batch, or any pre-dispatch refusal of a browser-mutation tool) every later call in the assistant batch is skipped so the next action is planned on fresh evidence." },+ "browser-control-handoff-stale-batch": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Browser control changed hands (manual takeover or cloud handoff) after the batch was planned: every remaining call is skipped and a fresh app-owned tree is injected." },+ "capability-host-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host." },+ "captcha-gate-action-block": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A supported verification challenge is active (solve_required) or its one solve has not been confirmed cleared (verification_pending): page mutations, network mutations and done(success)/done_json are refused until solve_captcha runs once / a read confirms clearance." },+ "captcha-gate-manual-required": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The challenge needs manual completion (unsupported widget, failed solve, Cloudflare managed challenge, or no CAPTCHA tools in this mode/tier): the gated call is refused and the run stops asking the user to complete it." },+ "chat-send-evidence-unavailable": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "A recipient-verified chat send whose conversation cannot be observed before sending, or whose native WhatsApp message baseline cannot be saved: nothing is sent." },+ "chat-send-preconditions": { class: "quality", family: "predispatch", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Chat send preconditions (generic chat dispatch and decideChatSend): a new incoming message appeared since the last observation, empty or over-long message, terminal chat session, unverified native message baseline, unavailable or non-empty composer." },+ "chat-send-recipient-guards": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Chat send protection of the recipient and against duplicates: the observed thread differs from the recipient-verified baseline or stored session, the exact message is already visible as outgoing or an earlier outbound is still pending verification, the pending message cannot be persisted before…" },+ "chat-user-input-required": { class: "credentials", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The chat counterpart or page asks for a one-time code, PIN, card/CVC, password or login, or an explicit user decision (or the thread changed): replying is paused until the user completes it." },+ "chrome-protected-page": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A DOM/debugger tool on a Chrome-protected page (Web Store developer dashboard; gallery after one retry) gets a non-retryable protected-page failure; repeated hits end the run with a visual-fallback or manual-required handoff." },+ "clarify-timeout-not-authorization": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "After a clarify answer was auto-selected on a waited timeout, consequential capabilities (click, type, script, network, download, upload, schedule), CAPTCHA solve/apply, done(success)/done_json and plain finals are refused; the second attempt or the last step stops the run asking for an explicit…" },+ "consequential-durability-checkpoint": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "Before a consequential call, the run-UI/scheduler recovery checkpoint, or the task-attempt record for an action that may post on X, Bluesky or an unknown site, cannot be saved: the run stops (persistence_degraded) before sending." },+ "coordinate-click-provenance": { class: "infra", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A coordinate click without coordinate_space, with from_screenshot conflicting with css, with normalized 0-1 values, or with a missing/stale capture_id or a point outside the capture is refused before any probe (checked again inside executeTool)." },+ "deletion-confirm-card": { class: "deletion", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "A deletion whose item the latest request does not clearly name (not_requested, other_item, unclear) or whose semantic decision is unavailable goes to WebBrain's deletion card (\"once\" re-runs every workflow check, then dispatches; deny, timeout or auto answer refuses; a change during the card…" },+ "deletion-guard-refusal": { class: "deletion", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Deletion checks in _resourceMutationPreSubmitBlock that refuse without a card: a deletion through coordinates/keys/set_field submit/execute_js (click_required), a Delete/Remove control outside one identifiable record (toolbar, bulk, selection), the same record/permalink already deleted in this…" },+ "form-validation-unchanged-repeat": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The same submit (or verify_form) is retried while the page shows the same invalid fields as the last failed submission." },+ "generate-image-config-invalid": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "generate_image with an unknown provider, missing API key, invalid model or malformed ComfyUI workflow: the provider cannot be called." },+ "github-commit-evidence-binding": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "A commit click in the GitHub edit-file-and-commit workflow is refused unless exactly one verified editor-replacement proof (readbackSha256), the requested commit message summary/body, path and branch are bound to exact pre-submit evidence; proofs are re-digested before every attempt, unverifiable…" },+ "github-commit-split-write-required": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "ask",+ summary: "In the GitHub edit-file-and-commit workflow a submit-capable non-click (execute_js, set_field submit, Enter) that may submit is refused: writes must be verified separately and the commit activated by a separate click." },+ "github-conditional-commit-rearm": { class: "quality", family: "predispatch", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The first editor action of an authorized conditional repair branch arms the edit-file-and-commit workflow (system prompt rebuilt, evidence counters reset) and is itself not dispatched." },+ "github-conditional-commit-unbound": { class: "unrequested_publication", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A scheduled-resume verification task (no state change or submission authorized) tries to mutate a GitHub repo editor or run execute_js/an API mutation on a repo page and no matching conditional edit-file-and-commit job can be bound (none planned, other repository, task drift, opaque mutation)." },+ "grouped-search-card": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A low-risk same-site GET search group (navigate, type, submit) without a standing grant asks once on WebBrain's grouped-search card; deny refuses the unchanged search." },+ "otp-open-message-gate": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "read_email_verification_message open_message is refused in Ask mode (opening can mark mail read) or without the one-use open grant minted by the mailbox permission gate for that message_ref." },+ "owned-native-chat-read-repair": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "While an app-issued native Telegram/WhatsApp read repair is pending (latest messages not verified), the model batch or plain final answer is preempted and the app runs its own exact read first." },+ "permission-host-unidentified": { class: "host_check", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The target frame/host of a call cannot be identified (iframe tools without urlFilter, apply_captcha_solution without frameUrl, WebMCP without a target URL, OTP without a mailbox URL): fail closed instead of charging the top page grant." },+ "preparation-timeout-action-pipeline": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "The shared deadline around the in-pipeline preparation (rich-text toolbar preflight, social publication audit, generic chat send preparation, task-attempt checkpoint) expired before dispatch: nothing was sent." },+ "preparation-timeout-captcha-preflight": { class: "host_check", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The CAPTCHA safety preflight (dialog scan / AWS-WAF gate) did not finish before the content-action deadline: the page mutation is refused (retryable) so a challenge cannot be dismissed or resubmitted unseen." },+ "preparation-timeout-permission-detection": { class: "permission_gate", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "Grouped-search form detection or submit-action detection timed out before the permission/submit cards could be chosen: the call is refused rather than bypassing the submit card." },+ "preparation-timeout-recipient-preflight": { class: "recipient", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "The message-recipient safety preflight (_messageRecipientGuardBlock probe) timed out on a protected messaging page: the send is refused." },+ "preparation-timeout-submit-preflight": { class: "deletion", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "The submit/form-validation preflight (_detectLikelySubmitAction, result baseline, validation snapshot) timed out: the call is refused. This probe is the only source of mutationKind:\"delete\" for the deletion guard and of publicationControl for the X/Bluesky gates." },+ "pure-calculation-stale-authority": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The captured arithmetic task authority (owner, run token or expression) no longer matches the current task (steering or a new turn after the batch was planned): every tool, done included, is refused." },+ "pure-calculation-tool-scope": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "On an owned literal-arithmetic task, any tool other than calculate(exact expression) or done, a calculate with another expression, or a repeated calculate after the result was verified is refused (checked again in-pipeline)." },+ "recipient-active-conversation-pin": { class: "recipient", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "At planning time a task that targets \"the open conversation\" cannot pin it to one verified recipient identity: the run stops before any page tool." },+ "recipient-draft-evidence-unavailable": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "The recipient is authorized (or confirmable) but the composer draft body cannot be read, or the existing-message baseline needed to verify a new send is unavailable." },+ "recipient-guard-refusal": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "_messageRecipientGuardBlock refusals on protected messaging pages (Gmail, X DMs, LinkedIn, Discord, native WhatsApp/Telegram, generic mail/chat): Enter with repeat>1, a send path that cannot be bound to the verified recipient (iframe_click, execute_js, WebMCP, ambiguous upload), no observable…" },+ "recipient-guard-target-preparation": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Recipient-guard target failures that establish no mismatch: the requested control cannot be resolved in the page/frame (message_target_unresolved), or a native Telegram read-only preparation click is not bound to one exact current control/owner/binding token or changed before the click." },+ "recipient-guard-unrequested-send": { class: "unrequested_publication", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A send or public post the task did not ask for: a LinkedIn public Post control in a private-message task, a send the latest request forbids (sending_forbidden reading), and a verifiable send the plan did not authorize or that names no recipient (card with reason unrequested/unnamed; refused when…" },+ "recipient-mismatch-confirm-card": { class: "recipient", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A conclusive send whose observed recipient set differs from the task target and is not user-approved goes to WebBrain's recipient card (once/always re-run the guard, deny records a declined recipient, a changed conversation or Stop refuses/aborts); when the card cannot be offered (unattended run,…" },+ "resource-mutation-task-authority-changed": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "_resourceMutationPreSubmitBlock current() check: a delete control (or a post-correction publish/commit) while the plan guard is not an enabled execute guard, the task key changed, Stop was pressed, or a correction is pending or unvalidated." },+ "rich-text-toolbar-target-unresolved": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "The rich-text toolbar safety preflight cannot resolve or preserve the typing target (ambiguous/unresolved iframe selector, iframe recovery pending, selector-backed or focused type_text, page changed during resolution, trusted resolver cannot attach, iframe toolbar target cannot be scrolled into…" },+ "rich-text-toolbar-wrong-target": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Text about to be typed into a rich-text formatting-toolbar control (font, size, style, color, link) instead of the editor body, by structural score >= 4 plus the optional vision audit: refused and a recovery obligation is recorded." },+ "social-api-publication-route": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "A write-method API call to an X/Bluesky post endpoint (CreateTweet, statuses, createRecord app.bsky.feed.post) is refused even after /allow-api: an API payload cannot pass the composer contract and audit." },+ "social-preflight-context-mismatch": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "The composer post kind (post, reply, quote) or parent target differs from the contract, or could not be observed: a reply or quote would be aimed at the wrong post or person." },+ "social-publication-audit": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Independent LLM audit (social_publication_authorization, up to 2 attempts) of the concrete draft against the request: a denial, or an unavailable/invalid checker, stops the run before Publish with a Retry-without-audit / Give up recovery card (also enforced after a tool result)." },+ "social-publication-authorization-guard": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "X/Bluesky publication contract checks that keep every post on the audited composer path: unidentified control or Enter/Space outside the editor, unobserved composer ownership, unresolved intent (clarify), no eligible authorized contract action (request does not ask to publish here, contract not…" },+ "social-publication-draft-quality": { class: "quality", family: "predispatch", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "X/Bluesky preflight quality checks: a detected submit made with set_field submit/Enter/execute_js/WebMCP instead of a click, and a composer snapshot whose body, media or thread length differs from the contract or cannot be observed (composer_incomplete, body_unobserved, baseline_incomplete)." },+ "social-publication-host-checks": { class: "host_check", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "X/Bluesky publication guard host/authority checks: a write-method fetch whose destination is missing, not http(s) or carries credentials; the task, guard or correction state changed while a resolved preparatory control or the publication audit was being checked." },+ "steer-post-correction-commit-guard": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "After a user correction (guard.steeringPriorSubmission), a publish or form commit is refused when it would repeat or sit beside the earlier attempt: unbound generic commit, replacement account changed, exact same post or form submission already sent, an earlier attempt on this site or unknown…" },+ "steer-prior-submission-target-unresolved": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "After a correction with an earlier dispatched submission, a submit-capable call whose target the probe could not resolve as a link, field, menu item or ordinary button is refused." },+ "steer-prior-submission-unreconciled": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "_steeringPriorSubmissionBlock: after a correction, any network mutation, chrome_web_store_publish or committing submit is refused until the earlier submission is reconciled (or this exact action was authorized and reconciled by _resourceMutationPreSubmitBlock)." },+ "steering-and-page-feedback-call-fence": { class: "host_check", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A user correction is pending, or page-monitor feedback (user input/intervention, unknown attribution, non-passive churn, stale scroll/model state) arrived after the model observation: the stale call (Act done and Ask answers included) and the rest of the batch are skipped and a fresh observation is…" },+ "submit-confirmation-card": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "With consequential confirmation on (not bypassed), a detected submit that is not a low-risk same-site GET search shows WebBrain's submit card (credential, payment and side-effect forms always get a fresh card); deny, timeout or an unexpected answer refuses the submit." },+ "tool-call-malformed": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "The call cannot run as given: invalid browser_batch parent (disabled tier, bad ids, too many/unbatchable children, schema failure), empty function name, arguments that are not valid JSON, an invalid get_accessibility_tree continuationArgs, a closed-schema violation, or a failed per-handler argument…" },+ "tool-not-advertised": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A call to a tool that is not in this run tool set (mode, provider tier, unloaded skill) or to a retired tool is refused without dispatch." },+ "tool-routing-redirects": { class: "infra", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch_url/research_url against an enabled skill HTTPS endpoint is redirected to the skill tool; a single-item download_social_media is redirected to download_public_media when that is available and untried, or skipped after it already succeeded." },+ "user-stop-or-card-cancel": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The user pressed Stop before dispatch, or stopped/corrected the task while a permission, submit, grouped-search, deletion or recipient card was open: the run aborts with nothing dispatched." },+ "webmcp-mode-and-setting-gate": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "execute_webmcp_tool/list_webmcp_tools while Experimental WebMCP is disabled in Settings, or in Ask mode (page readOnly annotations are not trusted): refused in preparation and again in the handler." },+ "webmcp-tool-id-invalid": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "execute_webmcp_tool without an exact registered opaque tool_id (missing, invented, stale) or with a failed CDP registry lookup: nothing to invoke." },+ "sched-reconciliation-required": { class: "unrequested_publication", family: "scheduler", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Unattended scheduled tasks are paused (needs_user_input) instead of re-running an action that may already have happened: a downgraded success after a side effect or pending consequential action, a pending consequential call not settled by an independently verified completion, or a judge context…" },+ "sched-systemone-downgrade": { class: "quality", family: "scheduler", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Opt-in System One judge after a scheduled run reported success: P(task_complete) below threshold or incomplete score downgrades the job outcome to partial (malformed answers or service failure keep success)." },+ "action-no-progress-classification": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Post-dispatch: the same click identity twice with an identical page snapshot, or an unbound arrow key that changed nothing observable, is reclassified as a no-progress failure (feeds the loop detector)." },+ "bot-memory-reservation": { class: "unrequested_publication", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Managed-bot cross-run idempotency: an action remote memory says is already completed, an opaque execute_js/schedule_* call in a memory-protected run, an unobserved/unresolved/changed target, or a reservation/durable dispatch that memory did not confirm." },+ "captcha-paid-solve-protection": { class: "money", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Keeps paid CAPTCHA solving to one dispatch per challenge/page document: the gate refuses solve_captcha after the allowed solve, the handler refuses a second native/automatic solve, an AWS gate that is no longer solve_required, an exhausted AWS provider set, and any provider call whose dispatch lock…" },+ "captcha-solution-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Native solve page URLs must match the active tab/frames and the root document must be bound before a native request; a returned solution is applied only to the same unchanged page/frame; a provider-mandated User-Agent mismatch retains the paid answer without injection and asks for manual completion." },+ "captcha-solve-detection-binding": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "solve_captcha arguments conflict with the detected widget (type, invisibility, enterprise flag, pageAction, rqdata, metadata), token injection has no detected frame, or the hCaptcha frame User-Agent cannot be read: refused before any paid dispatch." },+ "carousel-traversal-guards": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "A forward carousel scan asks for an index at or below the highest verified one (reverse order assumed only on a sure reading), or Instagram did not honor img_index / the media did not change (post-dispatch failure)." },+ "click-coordinate-intent": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "A coordinate click with expected_name/expected_role whose point no longer resolves to that semantic target (resolver errors fall back to the raw point)." },+ "click-duplicate-submit": { class: "unrequested_publication", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A second click within 45 s on a control whose caption reads as commit/publish, on the same unchanged URL, is refused (model escape _allowResubmit:true)." },+ "click-native-os-ui": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Clicks that would open native OS UI the agent cannot control: a native <select> dropdown (refused, or reported as a failure after the click) and a native file chooser (suppressed, with a pointer to upload_file)." },+ "click-text-ambiguous": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "click({text}) matched several elements with no single interactive one." },+ "clickax-native-button-preparation": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Trusted native-button input preparation vetoes: the button changed or moved during preparation, could not be captured or verified while settling, input was observed while it settled, or the task/browser owner changed before the press." },+ "clickax-task-click-lock": { class: "unrequested_publication", family: "tool", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "A trusted click (native button or click_ax trusted fallback) on this exact document+ref earlier in the task may have landed and was never verified: the same target is not clicked again (one trusted fallback per ref per run)." },+ "clickax-trusted-retry-vetoes": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "WebBrain's automatic trusted retry of a click_ax that produced no visible change is skipped for concurrent tab/network/download activity, mutating captions, changed or ineligible targets." },+ "downloaded-file-task-changed": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "read_downloaded_file discards bytes when steering arrived, the page-feedback owner, the download or the pinned document changed during the read, or the reader/document cannot be pinned." },+ "iframe-target-binding": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The iframe selector matches several elements (or none) across matching frames, or the clicked element was replaced after the scroll / the frame monitor is unavailable." },+ "iframe-urlfilter-required": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "iframe_click/iframe_type without urlFilter: the iframe target and permission scope cannot stay stable." },+ "jev-target-changed": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The Jev-bound target (or the checkbox of a set_checked) changed, or its validation probe failed, before dispatch." },+ "media-download-target-binding": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "download_public_media on a feed/profile page without an explicit media permalink, or a social media download whose focused media/document changed between inference and download (media_binding_changed)." },+ "navigation-scheme-and-internal-pages": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "navigate to a non-http(s) scheme or unresolvable relative URL; go_back/go_forward on chrome://, about:, extension or view-source pages." },+ "network-url-safety": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch/research URL safety: metadata and .internal/.local hosts always, localhost/private IPs unless \"Allow local network\", redirects into blocked URLs or across registrable domains (body discarded), cross-origin page resources." },+ "otp-mailbox-scope": { class: "credentials", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The OTP helper only exposes a verification message that visibly matches the named service in one unambiguous, unchanged mailbox tab, and never a truncated message without a safe continuation (skill must be loaded)." },+ "page-blocker-wall": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A read that showed a subscription, registration or sign-in wall WebBrain could not apply returns nothing behind the wall." },+ "page-feedback-dispatch-fence": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Transport-boundary fence (beforePageAgentDispatch, the content page monitor, the execute_js gate, the trusted Enter path): human input or feedback during preparation, a changed document mapping, focus moved into a child frame, an unprepared or rejecting monitor vetoes the dispatch; after input…" },+ "page-feedback-target-binding": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The selector/ref of a state-changing call cannot be bound to the observed action certificate (target_ambiguous, target_unresolved, target_uncovered, capture budget exhausted) or its original owner context was never certified: nothing is dispatched and a bounded fresh capture is queued for the next…" },+ "pdf-viewer-dom-tools": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A DOM/action tool on Chrome's built-in PDF viewer (read_page is redirected to read_pdf)." },+ "preparation-timeout-generic": { class: "quality", family: "tool", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "A non-consequential preparation stage exceeded the content-action deadline before dispatch (form-validation snapshot, executeTool entry deadline, click page snapshot/observation, click_ax content-script injection, coordinate target resolution, set_checked trusted recovery): nothing was sent." },+ "promote-iframe-ambiguous": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "promote_iframe with several matching child frames and no (or an out-of-range) matchIndex." },+ "recipient-clarify-cannot-repair-technical": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "A clarify about the recipient is refused while a technical recipient block (identity/body/baseline/binding unavailable) is active, because approval cannot supply missing page evidence." },+ "recipient-dispatch-binding-revalidate": { class: "recipient", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Last-moment recipient checks at dispatch: the one-use binding token, composer, target, conversation, Telegram baseline or body changed between guard approval and the press/Enter (no CDP fallback for recipient-bound clicks), and recipient-bound uploads whose authorization key, file source, file…" },+ "research-escalation-authorization": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "delegate_research needs escalation enabled in Settings and a one-use authorization token bound to the exact prompt from an explicit clarify consent form for this tab/conversation." },+ "rich-text-toolbar-recovery-obligation": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "While a toolbar recovery obligation is pending, a ref, selector or region belonging to the recorded formatting toolbar is refused (also when the target probe is unresolved or the dispatch binding is not ready)." },+ "schedule-owner-changed": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Scheduling is refused when the owning run, steering revision, plan guard, conversation or active task changed (or Stop) while the job was being created." },+ "schedule-resume-chat-state-not-durable": { class: "recipient", family: "tool", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "schedule_resume is refused when the latest chat workflow state (pending sends, sent keys) cannot be persisted, so a resumed run cannot resend." },+ "stale-ax-ref": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A click_ax/set_checked ref_id belongs to a previous document or route, or several controls match the checkbox marker." },+ "strict-secret-credential-handling": { class: "credentials", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Credential handling: filled password/token/OTP-like field values are removed from results (and noted in strict mode), notes/ledger rows holding them are redacted in strict secret mode, and strict mode refuses exporting credential columns from tables." },+ "tool-feature-availability-gates": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Run-type/tier feature gates inside executeTool: recall_memcode in managed bot runs, skills unavailable for Compact tier or not enabled in this mode, beep outside a /watch run created with /beep (or a second event_key)." },+ "unsaved-changes-data-loss": { class: "deletion", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "navigate/go_back/go_forward on a page with attached files or two or more dirty fields, and promote_iframe on a frame with changed fields, attached files or a known unverified iframe edit, would discard that content (force:true overrides)." },+ "upload-compact-tier-sources": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Compact-tier upload_file accepts only attachmentId plus a targetId from its own discovery phase (no selector, downloadId or filePath; stale targetId rediscovered)." },+ "upload-selector-ambiguity": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The upload selector matched several file inputs (now or on the previous attempt, until an inspection runs)." },+ "upload-source-validation": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The local upload path is missing/unreadable (inconclusive probes pass as unverified), or the file bytes do not match, or cannot be verified against, the input accept types." },+ "viewport-inspection-budget": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "inspect_viewport is skipped once the user-configured maxScreenshotsPerTurn budget is used up." },+ "webmcp-frame-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "WebMCP execution without trusted frame metadata, after the registration frame/origin changed since the permission check, or for a tool id no longer registered." },});++export function guardEntry(id) {+ return Object.hasOwn(GUARDS, id) ? GUARDS[id] : null;+}++export function isHardGuardClass(cls) {+ return HARD_GUARD_CLASSES.includes(cls);+}++/**+ * What a registered guard does when it fires.+ * decided: true when the guard knows the action is wrong, false when it+ * cannot decide. strict: Settings → "Strict checks" (quality guards block).+ * Unknown ids keep today's behavior ('block') so an unregistered refusal is+ * never silently relaxed.+ */+export function guardOutcome(id, { decided = true, strict = false } = {}) {+ const entry = guardEntry(id);+ if (!entry) return 'block';+ const outcome = decided ? entry.onDecided : entry.onCannotDecide;+ if (entry.class === 'quality' && strict) return 'block';+ return GUARD_OUTCOMES.includes(outcome) ? outcome : 'block';+}++/** A note a quality guard leaves for the model instead of refusing. */+export function guardAdvisory(id, message) {+ const text = String(message || '').replace(/\s+/g, ' ').trim().slice(0, 600);+ return { guard: String(id), note: text };+}++/**+ * Attach advisory notes to a tool result. They go first, so a result that+ * is truncated for the model keeps them, and duplicates collapse.+ */+export function withGuardAdvisories(result, advisories) {+ const list = [];+ const seen = new Set();+ for (const item of Array.isArray(advisories) ? advisories : []) {+ if (!item || typeof item !== 'object' || !item.guard) continue;+ const key = `${item.guard}\u0000${item.note || ''}`;+ if (seen.has(key)) continue;+ seen.add(key);+ list.push({ guard: String(item.guard), note: String(item.note || '') });+ }+ if (!list.length || !result || typeof result !== 'object' || Array.isArray(result)) return result;+ const existing = Array.isArray(result.guardAdvisories) ? result.guardAdvisories : [];+ const merged = [...existing];+ for (const item of list) {+ if (!merged.some(prior => prior?.guard === item.guard && prior?.note === item.note)) merged.push(item);+ }+ const { guardAdvisories: _drop, ...rest } = result;+ return { guardAdvisories: merged, ...rest };+}diff --git a/src/chrome/src/agent/loop-detector.js b/src/chrome/src/agent/loop-detector.jsindex 7809cb462..1a9420b98 100644--- a/src/chrome/src/agent/loop-detector.js+++ b/src/chrome/src/agent/loop-detector.js@@ -78,6 +78,12 @@ export class LoopDetector {_isToolResultErroredForLoop(name, _args, result) {if (!result || typeof result !== 'object') return false;+ // A text write that went out but could not be read back exactly is an+ // advisory result (success with unverifiedWrite, see the agent's+ // text-write advisories), not a failed target: a content failureScope+ // such as 'field-value:<ref>' must not count it toward the stop.+ // Refusals and real errors are reported as failures and still count.+ if (result.success === true && result.unverifiedWrite === true && !result.error) return false;if (result.error || result.success === false || result.noProgress) return true;const status = Number(result.status);return URL_FAMILY_TOOLS.has(name) && Number.isFinite(status) && status >= 400;diff --git a/src/chrome/src/agent/page-feedback.js b/src/chrome/src/agent/page-feedback.jsindex ef1b5ce6c..357047f10 100644--- a/src/chrome/src/agent/page-feedback.js+++ b/src/chrome/src/agent/page-feedback.js@@ -1390,12 +1390,33 @@ export const pageFeedbackMethods = {// target the certificate cannot bind at all is answered first and// precisely: a probe of an ambiguous selector could only pick one of its// elements. Anything else is left to the dispatch wrapper.- async _pageFeedbackUnbindableResult(tabId, name, args = {}) {+ async _pageFeedbackUnbindableResult(tabId, name, args = {}, advisories = null) {const run = this._pageFeedbackRuns?.get(tabId);if (!run || typeof args?.selector !== 'string' || !args.selector.trim() || !this.constructor.STATE_CHANGE_TOOLS?.has(name)|| pageFeedbackCallPolicy(name, args, run.modelState, run.latestPage).kind !== 'bound_target') return null;if (await this._validatePageFeedbackAction(tabId, name, args, run.modelState, null, { answerOnly: true }) !== false) return null;- return run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}` ? actionBindingUnavailableResult(run, name) : null;+ if (run.actionBindingUnavailable !== `${name}:${JSON.stringify(args)}`) return null;+ return this._pageFeedbackBindingAdvises(tabId, run, args, advisories) ? null : actionBindingUnavailableResult(run, name);+ },++ // page-feedback-target-binding (quality): the observed action certificate+ // does not cover this call's ref (target_uncovered: the element the model+ // read exists and is unique, but the certified observation did not include+ // it). With nothing else pending (no page activity, so no human input or+ // unknown attribution, and no correction), Strict checks off sends the call+ // with the ordinary unbound semantics and a note; the dispatch fences at the+ // transport still run. A selector may name an element the model never+ // observed (an upload slot it guessed, say), and a selector naming several+ // elements or none has no single element to send to: those keep their+ // answer, as does anything pending.+ _pageFeedbackBindingAdvises(tabId, run, args = {}, advisories = null) {+ if (!run || run.events.size || run.actionBindingUnavailableReason !== 'target_uncovered'+ || typeof args?.ref_id !== 'string' || !/^ref_[A-Za-z0-9_-]+$/.test(args.ref_id)+ || (typeof args?.selector === 'string' && args.selector.trim())+ || this._hasPendingSteering?.(tabId) || typeof this._guardAdvisesFor !== 'function') return false;+ return this._guardAdvisesFor(advisories, 'page-feedback-target-binding',+ 'This target was outside the page observation WebBrain certified for this action, so its binding to what you observed was not checked. It was sent anyway; read the page to confirm what it changed.',+ { decided: false });},_pageFeedbackBlocksCall(tabId, name, args = {}) {@@ -1777,7 +1798,11 @@ export function installPageFeedback(Agent) {let modelBound = !!run && mutation && policy.kind === 'bound_target';if (modelBound) {const validated = await this._validatePageFeedbackAction(tabId, name, args, modelState, batchId);- if (validated === false) return run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}`+ const unbindable = validated === false && run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}`;+ // A pure binding failure with nothing else pending may advise instead+ // (it then dispatches with the ordinary, unbound semantics below).+ if (validated === false && !(unbindable+ && this._pageFeedbackBindingAdvises(tabId, run, args, executionContext?.guardAdvisories))) return unbindable? actionBindingUnavailableResult(run, name): run.actionContextUnverified === true? { ...pageFeedbackPendingResult(), actionContextUnverified: true, errorCode: 'action_context_unverified',diff --git a/src/chrome/src/agent/tools.js b/src/chrome/src/agent/tools.jsindex 9373a4e86..1b15e06de 100644--- a/src/chrome/src/agent/tools.js+++ b/src/chrome/src/agent/tools.js@@ -207,7 +207,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'set_field',- description: 'Focus + (optionally clear) + type text into a form field by ref_id, then verify the exact settled value. Prefer set_field({submit:true}) for search fields. Enter is sent only after verification succeeds. If dispatch occurred but exact readback fails, the result reports mutationMayHaveOccurred:true and recoveryRequired:"verify_or_restore_field"; do not switch typing tools or resend text blindly.',+ description: 'Focus + (optionally clear) + type text into a form field by ref_id, then verify the exact settled value. Prefer set_field({submit:true}) for search fields. Enter is sent only after verification succeeds. If dispatch occurred but exact readback fails, the result reports verified:false and says what to check; do not switch typing tools or resend text blindly.',parameters: {type: 'object',properties: {diff --git a/src/chrome/src/background.js b/src/chrome/src/background.jsindex d3a6c75e6..4a96637ba 100644--- a/src/chrome/src/background.js+++ b/src/chrome/src/background.js@@ -646,8 +646,9 @@ async function loadImageBudget() {const imageBudgetReady = loadImageBudget().catch(() => {});async function loadStrictSecretMode() {- const stored = await chrome.storage.local.get('strictSecretMode').catch(() => ({}));+ const stored = await chrome.storage.local.get(['strictSecretMode', 'strictGuards']).catch(() => ({}));agent.strictSecretMode = stored?.strictSecretMode === true;+ agent.strictGuards = stored?.strictGuards === true;}const strictSecretModeReady = loadStrictSecretMode().catch(() => {});@@ -1349,6 +1350,9 @@ chrome.storage.onChanged.addListener((changes, areaName) => {browserBatchSettingsRevision++;agent.setBrowserBatchEnabled(changes.browserBatchEnabled.newValue !== false);}+ if (changes.strictGuards) {+ agent.strictGuards = changes.strictGuards.newValue === true;+ }if (changes.strictSecretMode) {agent.strictSecretMode = changes.strictSecretMode.newValue === true;// Strict mode also appends a global system note after enabled skills, sodiff --git a/src/chrome/src/cdp/cdp-client.js b/src/chrome/src/cdp/cdp-client.jsindex d683f5688..9f3ada339 100644--- a/src/chrome/src/cdp/cdp-client.js+++ b/src/chrome/src/cdp/cdp-client.js@@ -168,10 +168,19 @@ async function pasteDraftJsText(el, text, clear, readDocument, options = {}) {const accepted = options.dispatch ? options.dispatch(invoke) : invoke();await wait(); await wait();if (expired()) return deadlineFailure();- if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.');+ // From here the paste went out. `unverified` tells the agent the text+ // was sent but its settled value is unconfirmed; its policy decides+ // whether that is a failure (Strict checks) or a noted success.+ if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.',+ { unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });const value = readDocument(el), expected = (clear ? '' : previous) + text;if (accepted || typeof value !== 'string' || value !== expected) {- return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.');+ const readable = typeof value === 'string';+ return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.', {+ unverified: { reason: !readable ? 'readback_unavailable' : value !== expected ? 'readback_mismatch' : 'paste_not_consumed',+ reader: readable ? 'semantic' : 'none' },+ readbackExact: readable,+ });}return { success: true, verified: true, dispatched: true, outcomeUnknown: false,pageHandledPaste: true, method: 'contenteditable-page-handled-paste', value: value.slice(0, 100) };@@ -6629,18 +6638,24 @@ export class CDPClient {clear,beforeSignature,});+ // The text went out in both cases below; `unverified` lets the agent's+ // policy report it as a failure (Strict checks) or a noted success.+ // verifyTextEntry reads textContent for generic editors, which drops+ // block line breaks, so its doubt is not proof of a wrong value.if (verified !== true) {return {success: false,dispatched: true,verified: false,mutationMayHaveOccurred: true,+ unverified: { reason: 'readback_unproven', reader: 'unknown' },error: 'Text was inserted, but the complete settled field value could not be verified exactly.',};}if (finishInput && !await finishInput()) {return { success: false, dispatched: true, verified: false, outcomeUnknown: true,mutationMayHaveOccurred: true, retryable: false,+ unverified: { reason: 'input_unconfirmed', reader: 'unknown' },error: 'The editor value was verified, but its owned input operation could not be completed. Re-observe before acting.' };}return {diff --git a/src/chrome/src/config-transfer.js b/src/chrome/src/config-transfer.jsindex 067127f65..e652102ef 100644--- a/src/chrome/src/config-transfer.js+++ b/src/chrome/src/config-transfer.js@@ -57,6 +57,7 @@ export const DEFAULT_CONFIG_SETTINGS = Object.freeze({tracingEnabled: false,feedbackDiagnosticsEnabled: true,strictSecretMode: false,+ strictGuards: false,agentAllowLocalNetwork: false,scheduledTasksEnabled: true,scheduledRequireConsequentialConfirmation: true,@@ -140,6 +141,7 @@ const BOOLEAN_KEYS = new Set(['tracingEnabled','feedbackDiagnosticsEnabled','strictSecretMode',+ 'strictGuards','agentAllowLocalNetwork','scheduledTasksEnabled','scheduledRequireConsequentialConfirmation',diff --git a/src/chrome/src/content/content.js b/src/chrome/src/content/content.jsindex 5c7faca01..c4fde701e 100644--- a/src/chrome/src/content/content.js+++ b/src/chrome/src/content/content.js@@ -2376,10 +2376,19 @@const accepted = options.dispatch ? options.dispatch(invoke) : invoke();await wait(); await wait();if (expired()) return deadlineFailure();- if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.');+ // From here the paste went out. `unverified` tells the agent the text+ // was sent but its settled value is unconfirmed; its policy decides+ // whether that is a failure (Strict checks) or a noted success.+ if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.',+ { unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });const value = readDocument(el), expected = (clear ? '' : previous) + text;if (accepted || typeof value !== 'string' || value !== expected) {- return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.');+ const readable = typeof value === 'string';+ return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.', {+ unverified: { reason: !readable ? 'readback_unavailable' : value !== expected ? 'readback_mismatch' : 'paste_not_consumed',+ reader: readable ? 'semantic' : 'none' },+ readbackExact: readable,+ });}return { success: true, verified: true, dispatched: true, outcomeUnknown: false,pageHandledPaste: true, method: 'contenteditable-page-handled-paste', value: value.slice(0, 100) };@@ -2439,6 +2448,17 @@}const semanticEditor = readProseMirrorText(el) !== null;const readValue = () => _editableTextValue(el);+ // Which reader readValue used: a document reader is exact, innerText is+ // the browser's rendered layout (block editors read blank lines twice).+ const readbackReader = () => !el.isConnected ? 'none'+ : (draftJsEditor ? readDraftJsText(el) : (readProseMirrorText(el) ?? readCodeMirrorText(el) ?? readEmptyCaretText(el))) !== null+ || _nativeChatCaretValueIsEmpty(el) ? 'semantic' : 'rendered';+ // The text went out but its settled value is unconfirmed; the agent's+ // policy decides between a failure (Strict checks) and a noted success.+ const unverifiedWrite = reason => {+ const reader = readbackReader();+ return { unverified: { reason: reader === 'none' ? 'element_replaced' : reason, reader }, readbackExact: reader === 'semantic' };+ };const previous = readValue();const nativeClearContext = clear && text === '' ? _nativeChatCaretContext(el) : null;const selectContents = (collapse) => {@@ -2492,7 +2512,9 @@&& ((!nativeContextBefore && !nativeContextAfter)|| _sameNativeChatCaretContext(nativeContextBefore, nativeContextAfter));const unknown = () => failure('The editor handled a cancelled beforeinput and changed. Its complete value could not be verified in the same scope. No additional text was dispatched.',- { cancelled: true, recoveryRequired: 'verify_or_restore_field', retryable: false });+ { cancelled: true, recoveryRequired: 'verify_or_restore_field', retryable: false,+ // The page applied the text itself; a handled deletion sent none.+ ...(inputType === 'insertText' ? unverifiedWrite('page_handled_input') : {}) });if (!sameScope || (draftJsEditor && readDraftJsText(el) === null) || (el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return unknown();try {if (verifyNativeObservation) {@@ -2590,17 +2612,19 @@if (actionDeadlineExpired()) return expired();if (draftJsEditor && readDraftJsText(el) === null) {return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { recoveryRequired: 'verify_or_restore_field', retryable: false });+ { recoveryRequired: 'verify_or_restore_field', retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });}if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) {return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { recoveryRequired: 'verify_or_restore_field', retryable: false });+ { recoveryRequired: 'verify_or_restore_field', retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });}const value = readValue();const expected = clear ? text : previous + text;const normalize = value => String(value).replace(/\r\n?/g, '\n');if (!el.isConnected || normalize(value) !== normalize(expected)) {- return failure('The complete settled rich-text value could not be verified exactly.');+ return failure('The complete settled rich-text value could not be verified exactly.', unverifiedWrite('readback_mismatch'));}return {success: true, verified: true, dispatched,@@ -6440,6 +6464,8 @@dispatched: false,noDispatch: true,retryable: true,+ // Lets the agent's policy type into the field focused now instead.+ reasonCode: 'focused_target_changed',error: 'The focused target changed after the rich-text toolbar safety preflight. Focus the intended field again and retry.',};}@@ -9936,19 +9962,25 @@await new Promise(resolve => setTimeout(resolve, SET_FIELD_VERIFY_DELAY_MS));if (actionDeadlineExpired()) return deadlineFailure();+ // Past this point the value went out. `unverified` marks a write+ // whose settled value is unconfirmed; the agent's policy decides+ // whether that is a failure (Strict checks) or a noted success.if (!el.isConnected) {return failure(`ref_id ${ref_id} was replaced while the value was being typed. Re-read the accessibility tree and retry with the current field ref_id.`,- { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false, fieldMeta },+ { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false, fieldMeta,+ unverified: { reason: 'element_replaced', reader: 'none' }, readbackExact: false },);}if (isDraftJsEditor(el) && readDraftJsText(el) === null) return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = selectExpected !== null@@ -9956,6 +9988,10 @@: _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null));const fallbackAttempted = false;if (!verified) {+ // Input values and document readers are exact; innerText is the+ // rendered layout (block editors read blank lines twice).+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return failure('The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{@@ -9970,6 +10006,8 @@recoveryRequired: 'verify_or_restore_field',failureScope: `field-value:${ref_id}`,retryable: false,+ unverified: { reason: 'readback_mismatch', reader },+ readbackExact: reader !== 'rendered',},);}@@ -10148,19 +10186,24 @@// Let that reconciliation settle before verifying the exact result.await new Promise(resolve => setTimeout(resolve, SET_FIELD_VERIFY_DELAY_MS));if (actionDeadlineExpired()) return deadlineFailure();+ // `unverified` marks a value that went out but is unconfirmed (see+ // type_ax); a recovered draft that typed nothing stays no-dispatch.if (!el.isConnected) {return failure(`ref_id ${ref_id} was replaced while the value was being set. Re-read the accessibility tree and retry with the current field ref_id.`,- { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'element_replaced', reader: 'none' }, readbackExact: false },);}if (isDraftJsEditor(el) && readDraftJsText(el) === null) return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null));@@ -10332,6 +10375,11 @@}}if (!verified) {+ // Input values and document readers are exact; innerText is the+ // rendered layout (block editors read blank lines twice). The+ // bundled submit above was withheld for this unverified value.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return failure('The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{@@ -10346,6 +10394,8 @@recoveryRequired: 'verify_or_restore_field',failureScope: `field-value:${ref_id}`,retryable: false,+ unverified: { reason: 'readback_mismatch', reader },+ readbackExact: reader !== 'rendered',},);}@@ -10477,6 +10527,10 @@const expectedPrefix = verifiesAppend? expected.slice(0, expected.length - appendText.length): '';+ // 'rendered' (innerText) readback is the browser's layout, so a+ // mismatch cannot tell a wrong write from a reader artifact.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return {success: true,verified: verifiesAppend && !expected.endsWith(appendText)@@ -10489,6 +10543,8 @@el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null),),actual: actual.slice(0, 200),+ reader,+ readbackExact: reader !== 'rendered',fieldMeta: _fieldMeta(el),};} catch (error) {@@ -10551,6 +10607,9 @@const valueSha256 = [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');+ // A 'rendered' digest hashes innerText, not the editor's document.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return {success: true,...(typeof expected === 'string' ? {@@ -10558,6 +10617,8 @@} : {}),valueLength: value.length,valueSha256,+ reader,+ readbackExact: reader !== 'rendered',fieldMeta: _fieldMeta(el),stableSelector: _stableFieldSelector(el),};diff --git a/src/chrome/src/ui/locales/ar.js b/src/chrome/src/ui/locales/ar.jsindex 7116cf69e..d8a4ca0c7 100644--- a/src/chrome/src/ui/locales/ar.js+++ b/src/chrome/src/ui/locales/ar.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "ماذا يفعل WebBrain عندما لا تجيب عن سؤال في الوقت المحدد. «إنهاء المهمة» يختار الإجابة التي تُبقي المهمة مستمرة، فلا تتوقف أثناء غيابك. «الحذر» يختار الإجابة الآمنة ولا يتخذ خطوات مؤثرة بدونك. في الحالتين، تأخذ الأسئلة المتعلقة بحذف البيانات أو إنفاق المال أو بيانات الاعتماد أو مستلم الرسالة أو نشر شيء لم تطلبه الإجابة الآمنة دائمًا، وتنتظرك بطاقات التأكيد الخاصة بـ WebBrain دائمًا.","st.display.clarify_timeout_policy.finish": "إنهاء المهمة","st.display.clarify_timeout_policy.safe": "الحذر",+ "st.display.strict_guards.label": "فحوص صارمة",+ "st.display.strict_guards.desc": "إيقاف (الافتراضي): فقط فحوص WebBrain المتعلقة بحذف البيانات وإنفاق المال وبيانات الاعتماد والمستلم الخاطئ ونشر شيء لم تطلبه يمكنها إيقاف إجراء؛ وتُمرَّر فحوصه الأخرى إلى النموذج كملاحظات حتى لا تتعطل المهام. تشغيل: يوقف كل فحص الإجراء كلما تعذّر عليه تأكيده، كما في السابق.",'st.display.always_allow_api_mutations.label': "السماح دائمًا بتعديلات API",'st.display.always_allow_api_mutations.desc': "اسمح لـ WebBrain باستخدام POST وPUT وPATCH وDELETE عبر fetch_url أو research_url دون الحاجة إلى /allow-api في كل محادثة. تظل إرشادات أولوية واجهة المستخدم وفحوصات التأكيد سارية. مفعّل افتراضيًا.",'st.display.api_mutation_observer.label': 'مراقب تحولات API',diff --git a/src/chrome/src/ui/locales/bn.js b/src/chrome/src/ui/locales/bn.jsindex 812b37ac8..19f4c86d5 100644--- a/src/chrome/src/ui/locales/bn.js+++ b/src/chrome/src/ui/locales/bn.js@@ -702,6 +702,8 @@ export default {"st.display.clarify_timeout_policy.desc": "সময়মতো কোনো প্রশ্নের উত্তর না দিলে WebBrain কী করবে। “কাজ শেষ করুন” এমন উত্তর বেছে নেয় যা কাজ এগিয়ে নেয়, তাই আপনি দূরে থাকলেও কাজ থেমে থাকে না। “নিরাপদ থাকুন” নিরাপদ উত্তর বেছে নেয় এবং আপনাকে ছাড়া গুরুত্বপূর্ণ পদক্ষেপ নেয় না। যেকোনো ক্ষেত্রে, ডেটা মুছে ফেলা, অর্থ ব্যয়, ক্রেডেনশিয়াল, বার্তার প্রাপক বা আপনি চাননি এমন কিছু প্রকাশ সম্পর্কিত প্রশ্নে সবসময় নিরাপদ উত্তর নেওয়া হয়, আর WebBrain-এর নিজস্ব নিশ্চিতকরণ কার্ড সবসময় আপনার জন্য অপেক্ষা করে।","st.display.clarify_timeout_policy.finish": "কাজ শেষ করুন","st.display.clarify_timeout_policy.safe": "নিরাপদ থাকুন",+ "st.display.strict_guards.label": "কঠোর যাচাই",+ "st.display.strict_guards.desc": "বন্ধ (ডিফল্ট): শুধু ডেটা মুছে ফেলা, অর্থ ব্যয়, ক্রেডেনশিয়াল, ভুল প্রাপক এবং আপনি চাননি এমন কিছু প্রকাশ সম্পর্কিত WebBrain-এর যাচাই কোনো কাজ থামাতে পারে; অন্য যাচাইগুলো মডেলকে নোট হিসেবে জানানো হয়, যাতে কাজ আটকে না যায়। চালু: আগের মতো, নিশ্চিত করতে না পারলে প্রতিটি যাচাই কাজটি থামিয়ে দেয়।",'st.display.verbose.label': "ভার্বোস মোড",'st.display.verbose.desc': "সম্পূর্ণ টুল কল বিশদ বিবরণ, আর্গুমেন্ট, এবং কাঁচা JSON ফলাফল দেখান। ক্লিনার চ্যাটের অভিজ্ঞতার জন্য ডিফল্টরূপে বন্ধ।",'st.display.selection_shortcut.label': "নির্বাচন শর্টকাট",diff --git a/src/chrome/src/ui/locales/de.js b/src/chrome/src/ui/locales/de.jsindex d155ada6c..7dc5d8ada 100644--- a/src/chrome/src/ui/locales/de.js+++ b/src/chrome/src/ui/locales/de.js@@ -699,6 +699,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Was WebBrain tut, wenn Sie eine Frage nicht rechtzeitig beantworten. „Aufgabe abschließen“ wählt die Antwort, mit der die Aufgabe weiterläuft, damit nichts stehen bleibt, während Sie weg sind. „Auf Nummer sicher“ wählt die sichere Antwort und unternimmt ohne Sie keine folgenreichen Schritte. In beiden Fällen nehmen Fragen zum Löschen von Daten, zu Geldausgaben, Zugangsdaten, dem Empfänger einer Nachricht oder zum Veröffentlichen von etwas, das Sie nicht verlangt haben, immer die sichere Antwort, und WebBrains eigene Bestätigungskarten warten immer auf Sie.","st.display.clarify_timeout_policy.finish": "Aufgabe abschließen","st.display.clarify_timeout_policy.safe": "Auf Nummer sicher",+ "st.display.strict_guards.label": "Strenge Prüfungen",+ "st.display.strict_guards.desc": "Aus (Standard): Nur WebBrains Prüfungen zum Löschen von Daten, zu Geldausgaben, Zugangsdaten, dem falschen Empfänger und zum Veröffentlichen von etwas, das Sie nicht verlangt haben, können eine Aktion stoppen; die übrigen Prüfungen gehen als Hinweise an das Modell, damit Aufgaben nicht hängen bleiben. An: Jede Prüfung stoppt die Aktion, sobald sie sie nicht bestätigen kann, wie bisher.",'st.display.verbose.label': 'Ausführlicher Modus','st.display.verbose.desc': 'Zeigt vollständige Tool-Call-Details, Argumente und rohes JSON-Ergebnis. Standardmäßig deaktiviert für ein aufgeräumteres Chat-Erlebnis.','st.display.selection_shortcut.label': 'Auswahlverknüpfung',diff --git a/src/chrome/src/ui/locales/en.js b/src/chrome/src/ui/locales/en.jsindex de7a77bb2..cd1212c00 100644--- a/src/chrome/src/ui/locales/en.js+++ b/src/chrome/src/ui/locales/en.js@@ -707,6 +707,8 @@ export default {"st.display.clarify_timeout_policy.desc": "What WebBrain does when you don’t answer a question in time. Finish the task picks the answer that keeps the task going, so runs don’t stall while you’re away. Play it safe picks the safe answer and won’t take consequential steps without you. Either way, questions about deleting data, spending money, credentials, who receives a message, or publishing something you didn’t ask for always take the safe answer, and WebBrain’s own confirmation cards always wait for you.","st.display.clarify_timeout_policy.finish": "Finish the task","st.display.clarify_timeout_policy.safe": "Play it safe",+ "st.display.strict_guards.label": "Strict checks",+ "st.display.strict_guards.desc": "Off (default): only WebBrain’s checks for deleting data, spending money, credentials, the wrong recipient, and publishing something you didn’t ask for can stop an action; its other checks are passed to the model as notes so runs don’t get stuck. On: every check stops the action whenever it can’t confirm it, as before.",'st.display.verbose.label': 'Verbose Mode','st.display.verbose.desc': 'Show full tool call details, arguments, and raw JSON results. Off by default for a cleaner chat experience.','st.display.selection_shortcut.label': 'Selection shortcut',diff --git a/src/chrome/src/ui/locales/es.js b/src/chrome/src/ui/locales/es.jsindex d297e2999..91d955f93 100644--- a/src/chrome/src/ui/locales/es.js+++ b/src/chrome/src/ui/locales/es.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Qué hace WebBrain cuando no respondes una pregunta a tiempo. «Terminar la tarea» elige la respuesta que mantiene la tarea en marcha, para que no se detenga mientras no estás. «Ir a lo seguro» elige la respuesta segura y no da pasos importantes sin ti. En ambos casos, las preguntas sobre borrar datos, gastar dinero, credenciales, quién recibe un mensaje o publicar algo que no pediste siempre toman la respuesta segura, y las tarjetas de confirmación propias de WebBrain siempre te esperan.","st.display.clarify_timeout_policy.finish": "Terminar la tarea","st.display.clarify_timeout_policy.safe": "Ir a lo seguro",+ "st.display.strict_guards.label": "Comprobaciones estrictas",+ "st.display.strict_guards.desc": "Desactivado (predeterminado): solo las comprobaciones de WebBrain sobre borrar datos, gastar dinero, credenciales, el destinatario equivocado y publicar algo que no pediste pueden detener una acción; las demás se pasan al modelo como notas para que las tareas no se atasquen. Activado: cada comprobación detiene la acción cuando no puede confirmarla, como antes.",'st.display.always_allow_api_mutations.label': "Permitir siempre mutaciones de API",'st.display.always_allow_api_mutations.desc': "Permite que WebBrain use POST, PUT, PATCH y DELETE mediante fetch_url o research_url sin requerir /allow-api en cada conversación. Las directrices de priorizar la interfaz y las comprobaciones de confirmación siguen vigentes. Activado de forma predeterminada.",'st.display.api_mutation_observer.label': 'Observador de mutaciones de API',diff --git a/src/chrome/src/ui/locales/fa.js b/src/chrome/src/ui/locales/fa.jsindex fb6b212f3..14479cfa6 100644--- a/src/chrome/src/ui/locales/fa.js+++ b/src/chrome/src/ui/locales/fa.js@@ -702,6 +702,8 @@ export default {"st.display.clarify_timeout_policy.desc": "اگر به یک سؤال بهموقع پاسخ ندهید، WebBrain چه میکند. «تمام کردن کار» پاسخی را انتخاب میکند که کار را پیش میبرد تا در نبود شما متوقف نشود. «احتیاط» پاسخ امن را انتخاب میکند و بدون شما قدمهای مهم برنمیدارد. در هر دو حالت، سؤالهای مربوط به حذف داده، خرج کردن پول، اطلاعات ورود، گیرنده پیام یا انتشار چیزی که نخواستهاید همیشه پاسخ امن را میگیرند و کارتهای تأیید خود WebBrain همیشه منتظر شما میمانند.","st.display.clarify_timeout_policy.finish": "تمام کردن کار","st.display.clarify_timeout_policy.safe": "احتیاط",+ "st.display.strict_guards.label": "بررسیهای سختگیرانه",+ "st.display.strict_guards.desc": "خاموش (پیشفرض): فقط بررسیهای WebBrain درباره حذف داده، خرج کردن پول، اطلاعات ورود، گیرنده اشتباه و انتشار چیزی که نخواستهاید میتوانند یک اقدام را متوقف کنند؛ بقیه بررسیها بهصورت یادداشت به مدل داده میشوند تا کارها گیر نکنند. روشن: مثل قبل، هر بررسی هر وقت نتواند اقدام را تأیید کند آن را متوقف میکند.",'st.display.verbose.label': "حالت پرمخاطب",'st.display.verbose.desc': "جزئیات تماس کامل ابزار، آرگومان ها و نتایج خام JSON را نمایش دهید. به طور پیشفرض برای تجربه چت تمیزتر خاموش است.",'st.display.selection_shortcut.label': "میانبر انتخاب",diff --git a/src/chrome/src/ui/locales/fr.js b/src/chrome/src/ui/locales/fr.jsindex b48be2b60..bb1d36653 100644--- a/src/chrome/src/ui/locales/fr.js+++ b/src/chrome/src/ui/locales/fr.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Ce que fait WebBrain quand vous ne répondez pas à temps à une question. « Terminer la tâche » choisit la réponse qui fait avancer la tâche, pour qu’elle ne reste pas bloquée en votre absence. « Prudence » choisit la réponse sûre et ne fait rien d’important sans vous. Dans les deux cas, les questions sur la suppression de données, les dépenses, les identifiants, le destinataire d’un message ou la publication de quelque chose que vous n’avez pas demandé prennent toujours la réponse sûre, et les cartes de confirmation de WebBrain vous attendent toujours.","st.display.clarify_timeout_policy.finish": "Terminer la tâche","st.display.clarify_timeout_policy.safe": "Prudence",+ "st.display.strict_guards.label": "Vérifications strictes",+ "st.display.strict_guards.desc": "Désactivé (par défaut) : seules les vérifications de WebBrain sur la suppression de données, les dépenses, les identifiants, le mauvais destinataire et la publication de quelque chose que vous n’avez pas demandé peuvent arrêter une action ; ses autres vérifications sont transmises au modèle sous forme de notes pour que les tâches ne restent pas bloquées. Activé : chaque vérification arrête l’action dès qu’elle ne peut pas la confirmer, comme avant.",'st.display.always_allow_api_mutations.label': "Toujours autoriser les mutations API",'st.display.always_allow_api_mutations.desc': "Autoriser WebBrain à utiliser POST, PUT, PATCH et DELETE via fetch_url ou research_url sans exiger /allow-api dans chaque conversation. Les directives UI-d’abord et les confirmations restent applicables. Activé par défaut.",'st.display.api_mutation_observer.label': 'Observateur de mutations API',diff --git a/src/chrome/src/ui/locales/he.js b/src/chrome/src/ui/locales/he.jsindex 34268934c..c573b28ea 100644--- a/src/chrome/src/ui/locales/he.js+++ b/src/chrome/src/ui/locales/he.js@@ -686,6 +686,8 @@ export default {"st.display.clarify_timeout_policy.desc": "מה WebBrain עושה כשלא עונים לשאלה בזמן. „לסיים את המשימה” בוחר את התשובה שממשיכה את המשימה, כדי שהיא לא תיתקע כשאתם לא ליד המחשב. „ליתר ביטחון” בוחר את התשובה הבטוחה ולא מבצע צעדים משמעותיים בלעדיכם. בכל מקרה, שאלות על מחיקת נתונים, הוצאת כסף, פרטי התחברות, נמען של הודעה או פרסום של משהו שלא ביקשתם תמיד מקבלות את התשובה הבטוחה, וכרטיסי האישור של WebBrain תמיד ממתינים לכם.","st.display.clarify_timeout_policy.finish": "לסיים את המשימה","st.display.clarify_timeout_policy.safe": "ליתר ביטחון",+ "st.display.strict_guards.label": "בדיקות מחמירות",+ "st.display.strict_guards.desc": "כבוי (ברירת מחדל): רק בדיקות של WebBrain על מחיקת נתונים, הוצאת כסף, פרטי התחברות, נמען שגוי ופרסום של משהו שלא ביקשתם יכולות לעצור פעולה; שאר הבדיקות מועברות למודל כהערות כדי שמשימות לא ייתקעו. פועל: כל בדיקה עוצרת את הפעולה כשאינה יכולה לאשר אותה, כמו קודם.","st.display.verbose.label": "מצב מילולי","st.display.verbose.desc": "הצג פרטים מלאים של שיחת הכלים, טיעונים וגולמיים JSON תוצאות. כבוי כברירת מחדל לחוויית צ'אט נקייה יותר.","st.display.selection_shortcut.label": "קיצור דרך לבחירה",diff --git a/src/chrome/src/ui/locales/hi.js b/src/chrome/src/ui/locales/hi.jsindex 85421c6a9..c024b24cc 100644--- a/src/chrome/src/ui/locales/hi.js+++ b/src/chrome/src/ui/locales/hi.js@@ -702,6 +702,8 @@ export default {"st.display.clarify_timeout_policy.desc": "जब आप किसी सवाल का समय पर जवाब नहीं देते, तब WebBrain क्या करे। “काम पूरा करें” वह जवाब चुनता है जिससे काम आगे बढ़ता रहे, ताकि आपकी गैरमौजूदगी में काम न रुके। “सुरक्षित रहें” सुरक्षित जवाब चुनता है और आपके बिना कोई अहम कदम नहीं उठाता। दोनों ही स्थितियों में, डेटा हटाने, पैसे खर्च करने, क्रेडेंशियल, संदेश पाने वाले, या ऐसी चीज़ प्रकाशित करने से जुड़े सवाल जो आपने नहीं मांगी, हमेशा सुरक्षित जवाब लेते हैं, और WebBrain के अपने पुष्टि कार्ड हमेशा आपका इंतज़ार करते हैं।","st.display.clarify_timeout_policy.finish": "काम पूरा करें","st.display.clarify_timeout_policy.safe": "सुरक्षित रहें",+ "st.display.strict_guards.label": "सख्त जांच",+ "st.display.strict_guards.desc": "बंद (डिफ़ॉल्ट): सिर्फ़ डेटा हटाने, पैसे खर्च करने, क्रेडेंशियल, गलत प्राप्तकर्ता और ऐसी चीज़ प्रकाशित करने से जुड़ी WebBrain की जांचें, जो आपने नहीं मांगी, किसी कार्रवाई को रोक सकती हैं; बाकी जांचें मॉडल को नोट के रूप में दी जाती हैं ताकि काम अटके नहीं। चालू: पहले की तरह, हर जांच पुष्टि न कर पाने पर कार्रवाई रोक देती है।",'st.display.verbose.label': "वर्बोज़ मोड",'st.display.verbose.desc': "पूर्ण टूल कॉल विवरण, तर्क और कच्चे JSON परिणाम दिखाएं। बेहतर चैट अनुभव के लिए डिफ़ॉल्ट रूप से बंद।",'st.display.selection_shortcut.label': "चयन शॉर्टकट",diff --git a/src/chrome/src/ui/locales/id.js b/src/chrome/src/ui/locales/id.jsindex a48e7916e..8056cd194 100644--- a/src/chrome/src/ui/locales/id.js+++ b/src/chrome/src/ui/locales/id.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Apa yang dilakukan WebBrain saat Anda tidak menjawab pertanyaan tepat waktu. “Selesaikan tugas” memilih jawaban yang membuat tugas terus berjalan, agar tidak macet saat Anda pergi. “Main aman” memilih jawaban yang aman dan tidak mengambil langkah penting tanpa Anda. Dalam kedua kasus, pertanyaan tentang menghapus data, mengeluarkan uang, kredensial, penerima pesan, atau memublikasikan sesuatu yang tidak Anda minta selalu memakai jawaban yang aman, dan kartu konfirmasi WebBrain sendiri selalu menunggu Anda.","st.display.clarify_timeout_policy.finish": "Selesaikan tugas","st.display.clarify_timeout_policy.safe": "Main aman",+ "st.display.strict_guards.label": "Pemeriksaan ketat",+ "st.display.strict_guards.desc": "Nonaktif (default): hanya pemeriksaan WebBrain tentang menghapus data, mengeluarkan uang, kredensial, penerima yang salah, dan memublikasikan sesuatu yang tidak Anda minta yang dapat menghentikan tindakan; pemeriksaan lainnya diberikan ke model sebagai catatan agar tugas tidak macet. Aktif: setiap pemeriksaan menghentikan tindakan setiap kali tidak dapat memastikannya, seperti sebelumnya.",'st.display.always_allow_api_mutations.label': "Selalu izinkan mutasi API",'st.display.always_allow_api_mutations.desc': "Izinkan WebBrain menggunakan POST, PUT, PATCH, dan DELETE melalui fetch_url atau research_url tanpa memerlukan /allow-api di setiap percakapan. Panduan yang mengutamakan UI dan pemeriksaan konfirmasi tetap berlaku. Aktif secara default.",'st.display.api_mutation_observer.label': 'Pengamat mutasi API',diff --git a/src/chrome/src/ui/locales/ja.js b/src/chrome/src/ui/locales/ja.jsindex 1a7cb98e3..161bc38ee 100644--- a/src/chrome/src/ui/locales/ja.js+++ b/src/chrome/src/ui/locales/ja.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "質問に時間内に答えなかったときの WebBrain の動作です。「タスクを完了」はタスクを進める回答を選ぶので、席を外している間も止まりません。「安全に」は安全な回答を選び、あなたなしで重要な操作はしません。どちらの場合も、データの削除、支払い、認証情報、メッセージの宛先、頼んでいない公開に関する質問は常に安全な回答になり、WebBrain 自身の確認カードは常にあなたの操作を待ちます。","st.display.clarify_timeout_policy.finish": "タスクを完了","st.display.clarify_timeout_policy.safe": "安全に",+ "st.display.strict_guards.label": "厳格なチェック",+ "st.display.strict_guards.desc": "オフ(既定):アクションを止められるのは、データの削除、支払い、認証情報、誤った宛先、頼んでいない公開に関する WebBrain のチェックだけです。その他のチェックはメモとしてモデルに伝えられるので、タスクが止まりません。オン:これまでどおり、確認できないときはすべてのチェックがアクションを止めます。",'st.display.always_allow_api_mutations.label': "API変更を常に許可",'st.display.always_allow_api_mutations.desc': "会話ごとに /allow-api を必要とせず、WebBrain が fetch_url または research_url で POST、PUT、PATCH、DELETE を使用できるようにします。UI優先の指針と確認チェックは引き続き適用されます。既定ではオンです。",'st.display.api_mutation_observer.label': 'API変更オブザーバー',diff --git a/src/chrome/src/ui/locales/ko.js b/src/chrome/src/ui/locales/ko.jsindex 5e16d2319..6d8aa6fac 100644--- a/src/chrome/src/ui/locales/ko.js+++ b/src/chrome/src/ui/locales/ko.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "질문에 제때 답하지 않았을 때 WebBrain이 하는 일입니다. ‘작업 완료’는 작업을 계속 진행하는 답을 골라 자리를 비운 동안에도 멈추지 않게 합니다. ‘안전하게’는 안전한 답을 고르고 사용자 없이 중요한 단계를 진행하지 않습니다. 어느 쪽이든 데이터 삭제, 결제, 자격 증명, 메시지 받는 사람, 요청하지 않은 게시에 관한 질문은 항상 안전한 답을 택하며, WebBrain 자체 확인 카드는 항상 사용자를 기다립니다.","st.display.clarify_timeout_policy.finish": "작업 완료","st.display.clarify_timeout_policy.safe": "안전하게",+ "st.display.strict_guards.label": "엄격한 검사",+ "st.display.strict_guards.desc": "끔(기본값): 데이터 삭제, 결제, 자격 증명, 잘못된 받는 사람, 요청하지 않은 게시에 관한 WebBrain 검사만 작업을 멈출 수 있습니다. 다른 검사는 모델에 메모로 전달되어 작업이 멈추지 않습니다. 켬: 이전처럼 확인할 수 없을 때마다 모든 검사가 작업을 멈춥니다.",'st.display.always_allow_api_mutations.label': "API 변경 항상 허용",'st.display.always_allow_api_mutations.desc': "대화마다 /allow-api를 입력하지 않아도 WebBrain이 fetch_url 또는 research_url을 통해 POST, PUT, PATCH, DELETE를 사용하도록 허용합니다. UI 우선 지침과 확인 검사는 계속 적용됩니다. 기본적으로 켜져 있습니다.",'st.display.api_mutation_observer.label': 'API 변경 관찰자',diff --git a/src/chrome/src/ui/locales/ms.js b/src/chrome/src/ui/locales/ms.jsindex e99dce1c9..7ffa32c85 100644--- a/src/chrome/src/ui/locales/ms.js+++ b/src/chrome/src/ui/locales/ms.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Apa yang WebBrain lakukan apabila anda tidak menjawab soalan tepat pada masanya. “Selesaikan tugas” memilih jawapan yang mengekalkan tugas berjalan, supaya ia tidak tergendala semasa anda tiada. “Berhati-hati” memilih jawapan yang selamat dan tidak mengambil langkah penting tanpa anda. Walau apa pun, soalan tentang memadam data, berbelanja, kelayakan log masuk, penerima mesej atau menerbitkan sesuatu yang anda tidak minta sentiasa mengambil jawapan yang selamat, dan kad pengesahan WebBrain sendiri sentiasa menunggu anda.","st.display.clarify_timeout_policy.finish": "Selesaikan tugas","st.display.clarify_timeout_policy.safe": "Berhati-hati",+ "st.display.strict_guards.label": "Semakan ketat",+ "st.display.strict_guards.desc": "Mati (lalai): hanya semakan WebBrain tentang memadam data, berbelanja, kelayakan log masuk, penerima yang salah dan menerbitkan sesuatu yang anda tidak minta boleh menghentikan tindakan; semakan lain disampaikan kepada model sebagai nota supaya tugas tidak tersekat. Hidup: setiap semakan menghentikan tindakan apabila ia tidak dapat mengesahkannya, seperti sebelum ini.",'st.display.always_allow_api_mutations.label': "Sentiasa benarkan mutasi API",'st.display.always_allow_api_mutations.desc': "Benarkan WebBrain menggunakan POST, PUT, PATCH dan DELETE melalui fetch_url atau research_url tanpa memerlukan /allow-api dalam setiap perbualan. Panduan mengutamakan UI dan semakan pengesahan masih terpakai. Dihidupkan secara lalai.",'st.display.api_mutation_observer.label': 'Pemerhati mutasi API',diff --git a/src/chrome/src/ui/locales/nl.js b/src/chrome/src/ui/locales/nl.jsindex 1874b5366..97919158a 100644--- a/src/chrome/src/ui/locales/nl.js+++ b/src/chrome/src/ui/locales/nl.js@@ -679,6 +679,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Wat WebBrain doet als u een vraag niet op tijd beantwoordt. ‘Taak afmaken’ kiest het antwoord waarmee de taak doorgaat, zodat niets blijft hangen terwijl u weg bent. ‘Op veilig spelen’ kiest het veilige antwoord en zet zonder u geen ingrijpende stappen. Hoe dan ook krijgen vragen over gegevens verwijderen, geld uitgeven, inloggegevens, wie een bericht ontvangt of iets publiceren waar u niet om vroeg altijd het veilige antwoord, en de eigen bevestigingskaarten van WebBrain wachten altijd op u.","st.display.clarify_timeout_policy.finish": "Taak afmaken","st.display.clarify_timeout_policy.safe": "Op veilig spelen",+ "st.display.strict_guards.label": "Strenge controles",+ "st.display.strict_guards.desc": "Uit (standaard): alleen de controles van WebBrain op gegevens verwijderen, geld uitgeven, inloggegevens, de verkeerde ontvanger en iets publiceren waar u niet om vroeg kunnen een actie stoppen; de andere controles gaan als notities naar het model, zodat taken niet vastlopen. Aan: elke controle stopt de actie zodra die haar niet kan bevestigen, zoals voorheen.",'st.display.verbose.label': 'Uitvoerige modus','st.display.verbose.desc': 'Toon volledige toolaanroepdetails, argumenten en onbewerkte JSON-resultaten...','st.display.selection_shortcut.label': 'Selectiesneltoets',diff --git a/src/chrome/src/ui/locales/pl.js b/src/chrome/src/ui/locales/pl.jsindex 2a1bfc3fa..4858a71eb 100644--- a/src/chrome/src/ui/locales/pl.js+++ b/src/chrome/src/ui/locales/pl.js@@ -876,6 +876,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Co robi WebBrain, gdy nie odpowiesz na pytanie na czas. „Dokończ zadanie” wybiera odpowiedź, która pozwala kontynuować zadanie, żeby nie stało w miejscu pod twoją nieobecność. „Ostrożnie” wybiera bezpieczną odpowiedź i nie wykonuje bez ciebie żadnych ważnych kroków. W obu przypadkach pytania o usuwanie danych, wydawanie pieniędzy, dane logowania, odbiorcę wiadomości lub publikację czegoś, o co nie prosiłeś, zawsze dostają bezpieczną odpowiedź, a własne karty potwierdzeń WebBrain zawsze czekają na ciebie.","st.display.clarify_timeout_policy.finish": "Dokończ zadanie","st.display.clarify_timeout_policy.safe": "Ostrożnie",+ "st.display.strict_guards.label": "Ścisłe kontrole",+ "st.display.strict_guards.desc": "Wył. (domyślnie): akcję mogą zatrzymać tylko kontrole WebBrain dotyczące usuwania danych, wydawania pieniędzy, danych logowania, złego odbiorcy i publikacji czegoś, o co nie prosiłeś; pozostałe kontrole trafiają do modelu jako uwagi, żeby zadania nie utykały. Wł.: jak dotąd każda kontrola zatrzymuje akcję, gdy nie może jej potwierdzić.",'st.display.always_allow_api_mutations.label': "Zawsze zezwalaj na mutacje API",'st.display.always_allow_api_mutations.desc': "Zezwól WebBrain na używanie POST, PUT, PATCH i DELETE przez fetch_url lub research_url bez wymagania /allow-api w każdej rozmowie. Nadal obowiązują wskazówki preferujące interfejs oraz kontrole potwierdzeń. Domyślnie włączone.",'st.display.api_mutation_observer.label': 'Obserwator mutacji API',diff --git a/src/chrome/src/ui/locales/pt.js b/src/chrome/src/ui/locales/pt.jsindex 26dc63092..e761db526 100644--- a/src/chrome/src/ui/locales/pt.js+++ b/src/chrome/src/ui/locales/pt.js@@ -702,6 +702,8 @@ export default {"st.display.clarify_timeout_policy.desc": "O que o WebBrain faz quando você não responde a uma pergunta a tempo. “Concluir a tarefa” escolhe a resposta que mantém a tarefa andando, para que ela não fique parada enquanto você está fora. “Jogar seguro” escolhe a resposta segura e não dá passos importantes sem você. Em qualquer caso, perguntas sobre excluir dados, gastar dinheiro, credenciais, quem recebe uma mensagem ou publicar algo que você não pediu sempre ficam com a resposta segura, e os cartões de confirmação do próprio WebBrain sempre esperam por você.","st.display.clarify_timeout_policy.finish": "Concluir a tarefa","st.display.clarify_timeout_policy.safe": "Jogar seguro",+ "st.display.strict_guards.label": "Verificações rigorosas",+ "st.display.strict_guards.desc": "Desligado (padrão): só as verificações do WebBrain sobre excluir dados, gastar dinheiro, credenciais, destinatário errado e publicar algo que você não pediu podem interromper uma ação; as demais são passadas ao modelo como notas, para que as tarefas não travem. Ligado: cada verificação interrompe a ação sempre que não consegue confirmá-la, como antes.",'st.display.verbose.label': "Modo detalhado",'st.display.verbose.desc': "Mostre detalhes completos da chamada da ferramenta, argumentos e resultados JSON brutos. Desativado por padrão para uma experiência de bate-papo mais limpa.",'st.display.selection_shortcut.label': "Atalho de seleção",diff --git a/src/chrome/src/ui/locales/ru.js b/src/chrome/src/ui/locales/ru.jsindex 1db08044b..8e52bfda3 100644--- a/src/chrome/src/ui/locales/ru.js+++ b/src/chrome/src/ui/locales/ru.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Что делает WebBrain, если вы не ответили на вопрос вовремя. «Завершить задачу» выбирает ответ, при котором задача продолжается, чтобы она не простаивала, пока вас нет. «Осторожно» выбирает безопасный ответ и не делает важных шагов без вас. В любом случае вопросы об удалении данных, тратах, учётных данных, получателе сообщения или публикации того, о чём вы не просили, всегда получают безопасный ответ, а собственные карточки подтверждения WebBrain всегда ждут вас.","st.display.clarify_timeout_policy.finish": "Завершить задачу","st.display.clarify_timeout_policy.safe": "Осторожно",+ "st.display.strict_guards.label": "Строгие проверки",+ "st.display.strict_guards.desc": "Выкл. (по умолчанию): остановить действие могут только проверки WebBrain, касающиеся удаления данных, трат, учётных данных, неверного получателя и публикации того, о чём вы не просили; остальные проверки передаются модели как заметки, чтобы задачи не зависали. Вкл.: как раньше, каждая проверка останавливает действие, если не может его подтвердить.",'st.display.always_allow_api_mutations.label': "Всегда разрешать изменения через API",'st.display.always_allow_api_mutations.desc': "Разрешить WebBrain использовать POST, PUT, PATCH и DELETE через fetch_url или research_url без команды /allow-api в каждом разговоре. Правило приоритета интерфейса и проверки подтверждения продолжают действовать. По умолчанию включено.",'st.display.api_mutation_observer.label': 'Наблюдатель мутаций API',diff --git a/src/chrome/src/ui/locales/th.js b/src/chrome/src/ui/locales/th.jsindex e3fc9e502..438e3159b 100644--- a/src/chrome/src/ui/locales/th.js+++ b/src/chrome/src/ui/locales/th.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "สิ่งที่ WebBrain ทำเมื่อคุณไม่ได้ตอบคำถามทันเวลา “ทำงานให้เสร็จ” จะเลือกคำตอบที่ทำให้งานเดินต่อ งานจึงไม่ค้างขณะที่คุณไม่อยู่ “เล่นอย่างปลอดภัย” จะเลือกคำตอบที่ปลอดภัยและไม่ทำขั้นตอนสำคัญโดยไม่มีคุณ ไม่ว่าแบบใด คำถามเกี่ยวกับการลบข้อมูล การใช้เงิน ข้อมูลรับรอง ผู้รับข้อความ หรือการเผยแพร่สิ่งที่คุณไม่ได้ขอ จะใช้คำตอบที่ปลอดภัยเสมอ และการ์ดยืนยันของ WebBrain เองจะรอคุณเสมอ","st.display.clarify_timeout_policy.finish": "ทำงานให้เสร็จ","st.display.clarify_timeout_policy.safe": "เล่นอย่างปลอดภัย",+ "st.display.strict_guards.label": "การตรวจสอบแบบเข้มงวด",+ "st.display.strict_guards.desc": "ปิด (ค่าเริ่มต้น): มีเพียงการตรวจสอบของ WebBrain เกี่ยวกับการลบข้อมูล การใช้เงิน ข้อมูลรับรอง ผู้รับที่ไม่ถูกต้อง และการเผยแพร่สิ่งที่คุณไม่ได้ขอ ที่หยุดการกระทำได้ การตรวจสอบอื่นจะส่งให้โมเดลเป็นบันทึก งานจึงไม่ค้าง เปิด: ทุกการตรวจสอบจะหยุดการกระทำเมื่อยืนยันไม่ได้ เหมือนเดิม",'st.display.always_allow_api_mutations.label': "อนุญาตการเปลี่ยนแปลง API เสมอ",'st.display.always_allow_api_mutations.desc': "อนุญาตให้ WebBrain ใช้ POST, PUT, PATCH และ DELETE ผ่าน fetch_url หรือ research_url โดยไม่ต้องใช้ /allow-api ในทุกการสนทนา แนวทางที่ให้ความสำคัญกับ UI และการตรวจสอบการยืนยันยังคงมีผล เปิดไว้โดยค่าเริ่มต้น",'st.display.api_mutation_observer.label': 'ตัวสังเกตการกลายพันธุ์ของ API',diff --git a/src/chrome/src/ui/locales/tl.js b/src/chrome/src/ui/locales/tl.jsindex 7a6092c60..f99a22de4 100644--- a/src/chrome/src/ui/locales/tl.js+++ b/src/chrome/src/ui/locales/tl.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Ano ang ginagawa ng WebBrain kapag hindi mo nasagot ang isang tanong sa oras. Pinipili ng “Tapusin ang gawain” ang sagot na nagpapatuloy sa gawain, para hindi ito tumigil habang wala ka. Pinipili ng “Mag-ingat” ang ligtas na sagot at hindi ito gagawa ng mahahalagang hakbang nang wala ka. Alinman dito, ang mga tanong tungkol sa pagbura ng data, paggastos ng pera, credentials, kung sino ang tatanggap ng mensahe, o pag-publish ng bagay na hindi mo hiningi ay laging kumukuha ng ligtas na sagot, at laging naghihintay sa iyo ang sariling confirmation cards ng WebBrain.","st.display.clarify_timeout_policy.finish": "Tapusin ang gawain","st.display.clarify_timeout_policy.safe": "Mag-ingat",+ "st.display.strict_guards.label": "Mahigpit na pagsusuri",+ "st.display.strict_guards.desc": "Naka-off (default): ang mga pagsusuri lang ng WebBrain tungkol sa pagbura ng data, paggastos ng pera, credentials, maling tatanggap, at pag-publish ng bagay na hindi mo hiningi ang makakapigil sa isang aksyon; ipinapasa sa model bilang mga tala ang iba pang pagsusuri para hindi maipit ang mga gawain. Naka-on: gaya ng dati, pinapahinto ng bawat pagsusuri ang aksyon kapag hindi nito ito makumpirma.",'st.display.always_allow_api_mutations.label': "Palaging payagan ang mga pagbabago sa API",'st.display.always_allow_api_mutations.desc': "Payagan ang WebBrain na gumamit ng POST, PUT, PATCH, at DELETE sa pamamagitan ng fetch_url o research_url nang hindi kailangan ang /allow-api sa bawat usapan. Nalalapat pa rin ang gabay na unahin ang UI at mga pagsusuri sa kumpirmasyon. Naka-on bilang default.",'st.display.api_mutation_observer.label': 'Tagamasid ng mutasyon ng API',diff --git a/src/chrome/src/ui/locales/tr.js b/src/chrome/src/ui/locales/tr.jsindex 1d00ccfbf..97f5796c5 100644--- a/src/chrome/src/ui/locales/tr.js+++ b/src/chrome/src/ui/locales/tr.js@@ -893,6 +893,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Bir soruyu zamanında yanıtlamadığınızda WebBrain’in ne yapacağı. “Görevi tamamla”, görevi ilerleten yanıtı seçer; böylece siz yokken iş durmaz. “Temkinli ol”, güvenli yanıtı seçer ve siz olmadan önemli adımlar atmaz. Her iki durumda da veri silme, para harcama, kimlik bilgileri, mesajın alıcısı veya istemediğiniz bir şeyi yayınlama ile ilgili sorular her zaman güvenli yanıtı alır ve WebBrain’in kendi onay kartları her zaman sizi bekler.","st.display.clarify_timeout_policy.finish": "Görevi tamamla","st.display.clarify_timeout_policy.safe": "Temkinli ol",+ "st.display.strict_guards.label": "Katı denetimler",+ "st.display.strict_guards.desc": "Kapalı (varsayılan): bir eylemi yalnızca WebBrain’in veri silme, para harcama, kimlik bilgileri, yanlış alıcı ve istemediğiniz bir şeyi yayınlama ile ilgili denetimleri durdurabilir; diğer denetimler görevler takılmasın diye modele not olarak iletilir. Açık: önceden olduğu gibi her denetim, eylemi doğrulayamadığında durdurur.",'st.display.always_allow_api_mutations.label': "API değişikliklerine her zaman izin ver",'st.display.always_allow_api_mutations.desc': "WebBrain’in her konuşmada /allow-api gerektirmeden fetch_url veya research_url üzerinden POST, PUT, PATCH ve DELETE kullanmasına izin verin. Önce arayüz yaklaşımı ve onay kontrolleri uygulanmaya devam eder. Varsayılan olarak açıktır.",'st.display.api_mutation_observer.label': 'API mutasyon gözlemcisi',diff --git a/src/chrome/src/ui/locales/uk.js b/src/chrome/src/ui/locales/uk.jsindex 32440118b..6703ed065 100644--- a/src/chrome/src/ui/locales/uk.js+++ b/src/chrome/src/ui/locales/uk.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Що робить WebBrain, якщо ви не відповіли на запитання вчасно. «Завершити завдання» обирає відповідь, з якою завдання триває, щоб воно не стояло, поки вас немає. «Обережно» обирає безпечну відповідь і не робить важливих кроків без вас. У будь-якому разі запитання про видалення даних, витрати, облікові дані, отримувача повідомлення або публікацію того, про що ви не просили, завжди отримують безпечну відповідь, а власні картки підтвердження WebBrain завжди чекають на вас.","st.display.clarify_timeout_policy.finish": "Завершити завдання","st.display.clarify_timeout_policy.safe": "Обережно",+ "st.display.strict_guards.label": "Суворі перевірки",+ "st.display.strict_guards.desc": "Вимк. (типово): зупинити дію можуть лише перевірки WebBrain щодо видалення даних, витрат, облікових даних, хибного отримувача та публікації того, про що ви не просили; решта перевірок передається моделі як нотатки, щоб завдання не застрягали. Увімк.: як раніше, кожна перевірка зупиняє дію, коли не може її підтвердити.",'st.display.always_allow_api_mutations.label': "Завжди дозволяти зміни через API",'st.display.always_allow_api_mutations.desc': "Дозволити WebBrain використовувати POST, PUT, PATCH і DELETE через fetch_url або research_url без команди /allow-api в кожній розмові. Правило пріоритету інтерфейсу та перевірки підтвердження залишаються чинними. Типово ввімкнено.",'st.display.api_mutation_observer.label': 'Спостерігач мутацій API',diff --git a/src/chrome/src/ui/locales/vi.js b/src/chrome/src/ui/locales/vi.jsindex 50049d6ab..068456ab9 100644--- a/src/chrome/src/ui/locales/vi.js+++ b/src/chrome/src/ui/locales/vi.js@@ -702,6 +702,8 @@ export default {"st.display.clarify_timeout_policy.desc": "WebBrain làm gì khi bạn không trả lời câu hỏi kịp thời. “Hoàn thành tác vụ” chọn câu trả lời giúp tác vụ tiếp tục, để nó không bị dừng khi bạn vắng mặt. “Cẩn thận” chọn câu trả lời an toàn và không thực hiện bước quan trọng nào khi không có bạn. Dù chọn cách nào, các câu hỏi về xóa dữ liệu, chi tiền, thông tin đăng nhập, người nhận tin nhắn hoặc đăng thứ bạn không yêu cầu luôn nhận câu trả lời an toàn, và các thẻ xác nhận riêng của WebBrain luôn chờ bạn.","st.display.clarify_timeout_policy.finish": "Hoàn thành tác vụ","st.display.clarify_timeout_policy.safe": "Cẩn thận",+ "st.display.strict_guards.label": "Kiểm tra nghiêm ngặt",+ "st.display.strict_guards.desc": "Tắt (mặc định): chỉ các kiểm tra của WebBrain về xóa dữ liệu, chi tiền, thông tin đăng nhập, người nhận sai và đăng thứ bạn không yêu cầu mới có thể dừng một hành động; các kiểm tra khác được chuyển cho mô hình dưới dạng ghi chú để tác vụ không bị kẹt. Bật: như trước, mỗi kiểm tra dừng hành động bất cứ khi nào không xác nhận được.",'st.display.verbose.label': "Chế độ dài dòng",'st.display.verbose.desc': "Hiển thị đầy đủ chi tiết lệnh gọi công cụ, đối số và kết quả JSON thô. Tắt theo mặc định để có trải nghiệm trò chuyện rõ ràng hơn.",'st.display.selection_shortcut.label': "Phím tắt lựa chọn",diff --git a/src/chrome/src/ui/locales/zh.js b/src/chrome/src/ui/locales/zh.jsindex 7ad8ac1f7..1ed9f54e4 100644--- a/src/chrome/src/ui/locales/zh.js+++ b/src/chrome/src/ui/locales/zh.js@@ -884,6 +884,8 @@ export default {"st.display.clarify_timeout_policy.desc": "当你没有及时回答问题时 WebBrain 的做法。“完成任务”会选择能让任务继续的答案,这样你不在时任务也不会停滞。“稳妥为先”会选择安全的答案,不会在没有你的情况下执行重要操作。无论哪种设置,涉及删除数据、花钱、凭据、消息收件人或发布你未要求发布的内容的问题,始终采用安全答案;WebBrain 自己的确认卡片始终会等待你。","st.display.clarify_timeout_policy.finish": "完成任务","st.display.clarify_timeout_policy.safe": "稳妥为先",+ "st.display.strict_guards.label": "严格检查",+ "st.display.strict_guards.desc": "关闭(默认):只有 WebBrain 关于删除数据、花钱、凭据、收件人错误以及发布你未要求发布的内容的检查才能阻止操作;其他检查会作为备注交给模型,任务不会卡住。开启:与以前一样,任何检查在无法确认时都会阻止操作。",'st.display.always_allow_api_mutations.label': "始终允许 API 变更",'st.display.always_allow_api_mutations.desc': "允许 WebBrain 通过 fetch_url 或 research_url 使用 POST、PUT、PATCH 和 DELETE,无需在每个对话中输入 /allow-api。仍会遵循 UI 优先指引和确认检查。默认开启。",'st.display.api_mutation_observer.label': 'API 变更观察器',diff --git a/src/chrome/src/ui/settings.html b/src/chrome/src/ui/settings.htmlindex 75fe2f0c5..20d9117d8 100644--- a/src/chrome/src/ui/settings.html+++ b/src/chrome/src/ui/settings.html@@ -1776,6 +1776,16 @@<option value="safe" data-i18n="st.display.clarify_timeout_policy.safe"></option></select></div>+ <div class="setting-row">+ <div class="setting-info">+ <div class="setting-label" data-i18n="st.display.strict_guards.label"></div>+ <div class="setting-desc" data-i18n="st.display.strict_guards.desc"></div>+ </div>+ <label class="toggle">+ <input type="checkbox" id="toggle-strict-guards">+ <span class="toggle-slider"></span>+ </label>+ </div><div class="setting-row"><div class="setting-info"><div class="setting-label" data-i18n="st.display.site_adapters.label"></div>diff --git a/src/chrome/src/ui/settings.js b/src/chrome/src/ui/settings.jsindex b7cc86c94..430f490b9 100644--- a/src/chrome/src/ui/settings.js+++ b/src/chrome/src/ui/settings.js@@ -144,6 +144,7 @@ const tracingToggle = document.getElementById('toggle-tracing');const feedbackDiagnosticsToggle = document.getElementById('toggle-feedback-diagnostics');const losslessTracingToggle = document.getElementById('toggle-lossless-tracing');const strictSecretToggle = document.getElementById('toggle-strict-secret');+const strictGuardsToggle = document.getElementById('toggle-strict-guards');const allowLocalNetworkToggle = document.getElementById('toggle-allow-local-network');const scheduledTasksToggle = document.getElementById('toggle-scheduled-tasks');const scheduledConfirmToggle = document.getElementById('toggle-scheduled-confirm');@@ -631,7 +632,7 @@ async function init() {chrome.storage.local.remove(['authToken', 'authEmail', 'authDefaultModel']).catch(() => {});// Load display settings- const stored = await chrome.storage.local.get([...DECISION_SETTINGS_KEYS, 'verboseMode', 'composerDeliveryMode', 'selectionShortcutEnabled', 'pdfViewerEnabled', AUTO_GROUP_TABS_KEY, 'helpImproveWebBrain', 'screenshotFallback', 'maxAgentSteps', 'autoScreenshot', 'useSiteAdapters', 'researchEscalationEnabled', 'researchEscalationEngine', 'voiceInputEnabled', 'alwaysAllowApiMutations', 'apiMutationObserverEnabled', 'webMcpEnabled', 'openaiAskStreamingEnabled', 'planBeforeActMode', 'planBeforeAct', 'planReviewMode', 'planReviewConfidenceThreshold', DOWNLOAD_DIRECTORY_STORAGE_KEY, 'notifySound', 'completionConfetti', 'completionFlashTab', 'tracingEnabled', 'feedbackDiagnosticsEnabled', 'losslessTrace', 'strictSecretMode', 'agentAllowLocalNetwork', 'scheduledTasksEnabled', 'scheduledRequireConsequentialConfirmation', 'systemOneEnabled', 'systemOneWatchEnabled', 'systemOneCompletionEnabled', 'systemOneFastClassifications', 'systemOneFastBrowser', 'systemOneWatchThreshold', 'systemOneCompletionThreshold', 'typesafeApiKey', 'providerFilter', 'requestTimeoutMs', 'clarifyTimeoutSec', 'clarifyTimeoutSemanticsV2', 'clarifyTimeoutPolicy', 'costAllowanceSessionUsd', 'costAllowanceTotalUsd', 'meteredProviderCostSpentUsd', 'screenshotRedaction', 'imageDetail', 'maxScreenshotsPerTurn', 'maxImageDimension']);+ const stored = await chrome.storage.local.get([...DECISION_SETTINGS_KEYS, 'verboseMode', 'composerDeliveryMode', 'selectionShortcutEnabled', 'pdfViewerEnabled', AUTO_GROUP_TABS_KEY, 'helpImproveWebBrain', 'screenshotFallback', 'maxAgentSteps', 'autoScreenshot', 'useSiteAdapters', 'researchEscalationEnabled', 'researchEscalationEngine', 'voiceInputEnabled', 'alwaysAllowApiMutations', 'apiMutationObserverEnabled', 'webMcpEnabled', 'openaiAskStreamingEnabled', 'planBeforeActMode', 'planBeforeAct', 'planReviewMode', 'planReviewConfidenceThreshold', DOWNLOAD_DIRECTORY_STORAGE_KEY, 'notifySound', 'completionConfetti', 'completionFlashTab', 'tracingEnabled', 'feedbackDiagnosticsEnabled', 'losslessTrace', 'strictSecretMode', 'strictGuards', 'agentAllowLocalNetwork', 'scheduledTasksEnabled', 'scheduledRequireConsequentialConfirmation', 'systemOneEnabled', 'systemOneWatchEnabled', 'systemOneCompletionEnabled', 'systemOneFastClassifications', 'systemOneFastBrowser', 'systemOneWatchThreshold', 'systemOneCompletionThreshold', 'typesafeApiKey', 'providerFilter', 'requestTimeoutMs', 'clarifyTimeoutSec', 'clarifyTimeoutSemanticsV2', 'clarifyTimeoutPolicy', 'costAllowanceSessionUsd', 'costAllowanceTotalUsd', 'meteredProviderCostSpentUsd', 'screenshotRedaction', 'imageDetail', 'maxScreenshotsPerTurn', 'maxImageDimension']);if (typeof stored.providerFilter === 'string' && ['all','active','local','cloud','router'].includes(stored.providerFilter)) {providerFilter = stored.providerFilter;}@@ -726,6 +727,9 @@ async function init() {if (strictSecretToggle) {strictSecretToggle.checked = stored.strictSecretMode === true; // off by default}+ if (strictGuardsToggle) {+ strictGuardsToggle.checked = stored.strictGuards === true; // off by default+ }if (allowLocalNetworkToggle) {allowLocalNetworkToggle.checked = stored.agentAllowLocalNetwork === true; // off by default}@@ -1545,6 +1549,10 @@ if (strictSecretToggle) {});}+strictGuardsToggle?.addEventListener('change', async () => {+ await chrome.storage.local.set({ strictGuards: strictGuardsToggle.checked }).catch(() => {});+});+if (allowLocalNetworkToggle) {allowLocalNetworkToggle.addEventListener('change', async () => {await chrome.storage.local.set({ agentAllowLocalNetwork: allowLocalNetworkToggle.checked }).catch(() => {});diff --git a/src/firefox/src/agent/agent.js b/src/firefox/src/agent/agent.jsindex bcf240b52..33a3cb265 100644--- a/src/firefox/src/agent/agent.js+++ b/src/firefox/src/agent/agent.js@@ -73,7 +73,7 @@ import {workflowRequiredRowsAreProcessed,} from './adapter-workflow-evidence.js';import { messageTargetMatchesObservedIdentities, messageRecipientUploadSourceKey, normalizeMessageTarget, normalizeRecipientIdentity } from './message-recipient-guard.js';-import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession } from './chat-workflow.js';+import { advanceChatSession, chatRunEndedNotice, createOwnedNativeChatReadRepair, createChatSession, decideChatSend, markChatSendPending, normalizeChatSession, normalizeChatSnapshot, normalizeNativeOpaqueBaseline, serializeChatSession, WAIVABLE_CHAT_SEND_REASONS } from './chat-workflow.js';import {fetchUrl,executeHttpSkillTool,@@ -156,6 +156,7 @@ import { GENERATIVE_MEDIA_SETUP_NOTE, isImageGenConfigured, mediaPermissionUrl,import { extractFirstJsonObject } from './json-extract.js';import { repairAssistantDisplayText, repairClarifyText, sanitizeText as sanitizePlannerText } from './text-sanitize.js';import { clarifyQuestionIsHard, clarifyTimedAnswer, clarifyTimeoutChoice, normalizeClarifyConsequence, normalizeClarifyTimeoutPolicy } from './clarify-timeout.js';+import { guardAdvisory, guardEntry, guardOutcome, withGuardAdvisories } from './guard-policy.js';import { emptyOutputFailureMessage, modelOutputDiagnostics } from './model-output-diagnostics.js';import { stepLimitUserMessage, terminalGuardUserMessage } from './terminal-messages.js';import { buildCustomSkillsPrompt, buildSkillLoaderDefinition, buildSkillToolDefinitions, buildSkillToolRegistry, getEligibleCustomSkills, getEligibleSkillCatalog, normalizeCustomSkills } from './skills.js';@@ -224,6 +225,9 @@ const CONTROL_READING_TIMEOUT_MS = 4_000;// not each wait for it.const PAGE_BLOCKER_RETRY_MS = 30_000;const CONTENT_ACTION_RESPONSE_GRACE_MS = 5_000;+// jev-target-changed advice: the fast path planned this call against an+// observation the page no longer matches.+const JEV_TARGET_CHANGED_NOTE = 'The page changed after WebBrain\'s fast path planned this action, so its target could not be confirmed as the one it observed. It was sent to the element its ref or selector resolves to now; read the page before relying on the result.';const ASK_MODE_HANDOFF_TIMEOUT_MS = 5_000;const CONTENT_ACTION_SIGNAL_DEADLINES = new WeakMap();const SAVED_WORKFLOW_MESSAGE_DISPATCH_TOOLS = new Set([@@ -326,6 +330,17 @@ function selectionScopedResponseLanguagePolicy(locale) {};}+// What the user is told when a run ends with plain text after the "end with+// done" note was given once (Strict checks off).+// Completion guards whose decided case means the task is not done (a+// judge's sure verdict, a forbidden submission, failed or missing items,+// text typed into a toolbar). Accepted over their advice, a success claim+// ends the run as partial.+const OUTCOME_DOWNGRADING_GUARDS = new Set(['completion-verifier-not-done', 'plan-unauthorized-mutation-recorded',+ 'progress-success-claim-checks', 'done-rich-text-toolbar-obligation']);++const PLAIN_FINAL_PROTOCOL_CAVEAT = 'The task ended with a plain answer instead of a checked completion.';+function defaultPlanExecutionBlockNudge({viaDone = false,missingEvidence = false,@@ -663,6 +678,10 @@ export class Agent extends LoopDetector {// Settings → General → "When a question times out": 'finish' (default)// keeps the task moving, 'safe' takes the safe default. See clarify-timeout.js.this.clarifyTimeoutPolicy = 'finish';+ // Settings → General → "Strict checks" (off by default): quality+ // guards advise instead of refusing. See guard-policy.js.+ this.strictGuards = false;+ this._guardRunStates = new Map();this.maxContextMessages = 50; // minimum soft cap; larger provider windows scale this upthis._debugLog = []; // ring buffer for deep verbose (LLM requests/responses)this._debugLogMax = 200; // max entries before oldest are dropped@@ -769,6 +788,10 @@ export class Agent extends LoopDetector {this._lastAxScopes = new Map(); // tabId -> { documentToken, pageUrl }, captured by the latest AX readthis._uncertainTextMutations = new Map(); // tabId -> Map(target -> unresolved, potentially applied text write; no raw text)this._verifiedTextReplacements = new Map(); // tabId -> exact replacement digest bound to the live document+ // tabId -> Map(target -> latest write that went out but could not be+ // verified; no raw text). Default mode keeps this instead of debt and+ // never blocks on it; see _unverifiedTextWriteRecord.+ this._unverifiedTextWrites = new Map();// tabId -> recent document tokens (bounded) whose mutation records are// retained so a back-forward cache return restores their guards.this._recentTextMutationDocuments = new Map();@@ -990,24 +1013,41 @@ export class Agent extends LoopDetector {}async _resolveExactTableDone(tabId, args, onUpdate = null) {+ // exact-table-done: by default each refusal below is given once per+ // run; the next done is accepted with what can be delivered and a+ // caveat for the user.if (typeof args?.data_ref !== 'string' || !args.data_ref) {const error = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), args?.summary);- return error ? { success: false, blockedDone: true, exactTableUnverified: true, error } : null;+ return error && this._exactTableAnswerRefuses(tabId, error)+ ? { success: false, blockedDone: true, exactTableUnverified: true, error } : null;}const state = this.readCompletenessStates.get(tabId);const record = state?.exactTableExports?.get(args.data_ref);const owner = this._exactTableOwner(tabId);if (!record || !record.owner.current() || !owner?.current() || record.runToken !== owner.runToken) {- return { success: false, blockedDone: true, exactTableUnverified: true,- error: 'Unknown, expired, or superseded table data_ref. Extract the table in this current task first.' };+ // Accepted, it delivers only the model's own summary, never rows+ // another task or run extracted.+ return this._guardRefusesOnce(tabId, 'exact-table-done', { decided: false,+ caveat: 'The table reference had expired, so the exact table could not be delivered.' })+ ? { success: false, blockedDone: true, exactTableUnverified: true,+ error: 'Unknown, expired, or superseded table data_ref. Extract the table in this current task first.' }+ : null;}onUpdate?.('tool_call', { name: 'extract_data', args: record.args, verification: true });const verified = await this.executeTool(tabId, 'extract_data', record.args, onUpdate,{ _exactTableVerificationRecord: record });onUpdate?.('tool_result', { name: 'extract_data', result: verified, verification: true });if (!owner.current() || verified?.verifiedExactTable !== true) {- return { success: false, blockedDone: true, exactTableUnverified: true,- error: verified?.error || 'Table freshness could not be verified in the owning task. Extract again.' };+ if (this._guardRefusesOnce(tabId, 'exact-table-done', { decided: false,+ caveat: 'The table on the page may have changed after it was extracted.' })) {+ return { success: false, blockedDone: true, exactTableUnverified: true,+ error: verified?.error || 'Table freshness could not be verified in the owning task. Extract again.' };+ }+ // Accepted: the stored snapshot is delivered while its task still owns+ // it, unless Strict secret mode now applies (the snapshot predates it,+ // and its re-projection may be what failed).+ if (owner.current() && this.strictSecretMode !== true) args.summary = record.summary;+ return null;}args.summary = record.summary;return null;@@ -2109,12 +2149,12 @@ export class Agent extends LoopDetector {pageUrl, currentUrl: submit.currentUrl }, text => this._sha256TextSync(text));}- _completionDoneBlock(tabId, name, args, batchStartState = null) {+ _completionDoneBlock(tabId, name, args, batchStartState = null, { skip = null } = {}) {const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;const outcome = name === 'done_json' ? 'success' : String(args?.outcome || '').trim().toLowerCase();const toolbarObligation = this._richTextToolbarGuard.completionAction(tabId);- if (outcome === 'success' && toolbarObligation) {+ if (outcome === 'success' && toolbarObligation && skip?.has?.('rich_text_toolbar_target_unresolved') !== true) {return {reason: 'rich_text_toolbar_target_unresolved',error: 'Success is blocked because the last text-entry attempt targeted a rich-text formatting toolbar. Enter the requested content in the editor body, verify that non-toolbar edit on a fresh turn, then complete; otherwise report a partial or failed outcome.',@@ -2122,12 +2162,15 @@ export class Agent extends LoopDetector {};}const state = this.completionInvariants.get(tabId);- const block = completionDoneBlock(state, name, args);+ const block = completionDoneBlock(state, name, args, { skip });if (block) return block;- if (outcome !== 'success' || !batchStartState) return null;+ if (outcome !== 'success' || !batchStartState || skip?.has?.('prior_turn_verification_required') === true) return null;const batchStartSequence = Number(batchStartState.sequence || 0);const lastActionSequence = Number(state?.lastAction?.sequence || 0);- if (batchStartState.verificationDebt || lastActionSequence > batchStartSequence) {+ // Debt carried into this batch that was just accepted over its note+ // (verification_required) is the same concern, not a second one.+ const carriedDebtAccepted = skip?.has?.('verification_required') === true && state?.verificationDebt === true;+ if ((batchStartState.verificationDebt && !carriedDebtAccepted) || lastActionSequence > batchStartSequence) {return {reason: 'prior_turn_verification_required',error: 'A success completion cannot rely on action or observation results from the same assistant tool batch. Let this batch finish, inspect the returned evidence on the next model turn, then call done again; otherwise use outcome="partial" or outcome="failed".',@@ -2567,7 +2610,7 @@ export class Agent extends LoopDetector {};}- async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null) {+ async _conditionalGithubCommitTransition(tabId, name, args = {}, detectedSubmit = null, advisories = null) {const guard = this._planExecutionGuards.get(tabId);if (!guard?.enabled || !guard.scheduledResume || guard.siteWorkflow|| guard.requiresStateChange !== false || guard.requiresSubmission !== false) return null;@@ -2618,6 +2661,14 @@ export class Agent extends LoopDetector {await this._ensureWorkflowMetadataRequirements(tabId, {provider: this._activeProvider(tabId), costState: this.currentCostState.get(tabId) || null,}, guard.taskText, pageUrl);+ // github-conditional-commit-rearm (quality): the contract is armed above,+ // before this first write, so its proof and every later commit already+ // bind to it. Without Strict checks the action is sent now under that+ // contract, and the note tells the model what the rebuilt prompt requires.+ if (this._guardAdvisesFor(advisories, 'github-conditional-commit-rearm',+ 'WebBrain switched this resumed task to its conditional file-edit-and-commit contract before this action. Success now needs a verified file edit, a commit, and a readback of the exact committed file; verify the editor change before committing.')) {+ return null;+ }return {success: false, noDispatch: true, dispatched: false, retryable: true,workflowRearmed: true, workflowJob: 'edit-file-and-commit',@@ -2625,7 +2676,7 @@ export class Agent extends LoopDetector {};}- async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId)) {+ async _workflowPreSubmitDispatchBlock(tabId, name, args = {}, detectedSubmit = null, provider = this._activeProvider(tabId), advisories = null) {const socialBlock = await this._socialPublicationPreSubmitBlock(tabId, name, args, detectedSubmit, provider);if (socialBlock) return socialBlock;await this._captureMastodonPublicationAttempt(tabId, name, args, detectedSubmit, provider);@@ -2677,7 +2728,25 @@ export class Agent extends LoopDetector {// authorize bytes that were never hashed, so only a non-mutating final// activation may use an existing binding. Anything else must split into// a plain write (verified on its own) followed by a separate click.+ // github-commit-split-write-required (quality): when the action does look+ // like the commit and the verified file and message binding a commit click+ // would need is in place, Strict checks off lets it run with a note; the+ // committed raw file is then checked against that binding after the commit.+ // An inconclusive detection is the cannot-decide case and keeps refusing,+ // and so does a missing binding (github-commit-evidence-binding).if (name !== 'click' && name !== 'click_ax' && name !== 'iframe_click') {+ if (looksLikeSubmit && this._guardAdvises('github-commit-split-write-required')) {+ const pageUrl = await this._currentUrl(tabId);+ await this._refreshGithubTextReplacementProofs(tabId, pageUrl);+ const binding = this._workflowSubmitBindingForAttempt(tabId, pageUrl, {}, detectedSubmit);+ if (binding?.metadataRequirementsIncomplete !== true && binding?.githubFileCommit+ && this._guardAdvisesFor(advisories, 'github-commit-split-write-required',+ name === 'execute_js'+ ? 'This script may change the editor or commit message while it commits, so the earlier verified file and message proofs do not cover it. It ran anyway; read the committed file and commit message back before reporting success.'+ : 'This action can change field values while it submits the commit, so the earlier verified file and message proofs do not cover it. It ran anyway; read the committed file and commit message back before reporting success.')) {+ return null;+ }+ }return {success: false,dispatched: false,@@ -4751,6 +4820,277 @@ export class Agent extends LoopDetector {};}+ // Completion guards under the default policy (Settings → General →+ // "Strict checks" off; see guard-policy.js). A completion guard refuses a+ // done or a plain final at most once per run, and that refusal is the+ // model's note. The next completion the same guard would refuse is+ // accepted, and its final answer tells the user what was not verified.+ // Strict checks keep every refusal, its budget and its forced turns.++ // Only an accepted completion ends a run, so a caveat a completion guard+ // recorded while an earlier attempt was still refused by another guard is+ // stale. A guard that fires again records it again during this attempt.+ // Caveats of other guard families are kept.+ _beginCompletionGuardAttempt(tabId) {+ const state = this._guardRunState(tabId);+ for (const id of [...state.caveats.keys()]) {+ if (guardEntry(id)?.family === 'completion') state.caveats.delete(id);+ }+ state.outcomeDowngrades?.clear();+ }++ // True once guard `id` advises and has used its one refusal in this run.+ _guardHasAdvised(tabId, id, { decided = true } = {}) {+ return this._guardAdvises(id, { decided }) && this._guardRunState(tabId).advised.has(id);+ }++ // Adds the "WebBrain could not verify everything" line, if any, to the+ // answer of an accepted completion. _guardRunState first drops a previous+ // run's caveats.+ _withCompletionCaveat(tabId, text) {+ const line = this._guardRunState(tabId) && this._guardCaveatLine(tabId);+ if (!line) return text;+ const base = String(text ?? '').trimEnd();+ return base ? `${base}\n\n${line}` : line;+ }++ // The guard behind a completion-invariant refusal, with the sentence the+ // user sees when a completion is accepted over it.+ _completionInvariantGuard(tabId, reason) {+ if (reason === 'rich_text_toolbar_target_unresolved') {+ return { id: 'done-rich-text-toolbar-obligation', decided: true,+ caveat: 'The last text may have gone into a formatting toolbar instead of the editor.' };+ }+ if (reason === 'iframe_form_verification_required') {+ return { id: 'done-iframe-form-unverified', decided: false,+ caveat: 'The form fields edited inside an embedded frame were not read back.' };+ }+ if (reason === 'verification_required') {+ return { id: 'done-verification-debt', decided: false,+ caveat: this.completionInvariants.get(tabId)?.lastAction?.downloadAction === true+ ? 'The download was not checked after it started.'+ : 'The page was not checked again after the last action.' };+ }+ if (reason === 'prior_turn_verification_required') {+ return { id: 'done-invariant-shape-checks', decided: false,+ caveat: 'Success was reported in the same step as the last action, before its result was seen.' };+ }+ if (reason === 'missing_outcome') {+ return { id: 'done-invariant-shape-checks', decided: true,+ caveat: 'The final report did not say whether the task succeeded, so it counts as partial.' };+ }+ return null;+ }++ _completionInvariantRefuses(tabId, block) {+ const guard = this._completionInvariantGuard(tabId, block?.reason);+ return !guard || this._guardRefusesOnce(tabId, guard.id, { decided: guard.decided, caveat: guard.caveat });+ }++ // A plain final in an Act/Dev run that acted. The "end with done, not+ // plain text" note is given once per run, shared with the plan guard's+ // plain-final protocol.+ _completionPlainFinalRefuses(tabId) {+ const state = this.completionInvariants.get(tabId);+ // Every applicable invariant gets its note in priority order: one+ // that already advised is accepted and the next one is checked.+ const guards = [];+ if (this._richTextToolbarGuard.hasPending(tabId)) guards.push(this._completionInvariantGuard(tabId, 'rich_text_toolbar_target_unresolved'));+ if (state?.iframeFormVerificationDebt) guards.push(this._completionInvariantGuard(tabId, 'iframe_form_verification_required'));+ if (state?.verificationDebt) guards.push(this._completionInvariantGuard(tabId, 'verification_required'));+ if (guards.length) {+ return guards.some(guard => this._guardRefusesOnce(tabId, guard.id, { decided: guard.decided, caveat: guard.caveat }));+ }+ const refuses = this._guardRefusesOnce(tabId, 'plain-final-done-protocol', { decided: true, caveat: PLAIN_FINAL_PROTOCOL_CAVEAT });+ const planProtocolRefuses = this._guardRefusesOnce(tabId, 'plan-plain-final-protocol', {+ caveat: PLAIN_FINAL_PROTOCOL_CAVEAT,+ });+ return refuses && planProtocolRefuses;+ }++ // progress-ledger-unresolved: rows still pending or acted (any outcome).+ // progress-success-claim-checks: success over missing, incomplete,+ // duplicate, skipped or failed rows.+ _progressGuardRefuses(tabId) {+ const rows = this._currentTaskLedgerRows(tabId);+ if (ledgerDoneBlock(rows, { limit: 1 })) {+ const counts = progressCounts(rows);+ return this._guardRefusesOnce(tabId, 'progress-ledger-unresolved', {+ caveat: `${counts.unresolved} of ${counts.total} items in the task's progress list were not finished.`,+ });+ }+ return this._guardRefusesOnce(tabId, 'progress-success-claim-checks', {+ caveat: 'Some items in the task\'s progress list are missing, incomplete, skipped or failed.',+ });+ }++ // read-coverage-incomplete: pages of a requested whole-thread read are+ // missing (it knows), or Gmail's expansion was not confirmed (it cannot+ // tell). Ask mode cannot expand Gmail messages, so by default that+ // limitation reaches the user through this caveat.+ _readCoverageGuardRefuses(tabId) {+ const state = this.readCompletenessStates.get(tabId);+ const expansionUnverified = state?.requiresExpansionEvidence === true+ && state.treeCoverageComplete === true && state.expansionConfirmed !== true;+ return this._guardRefusesOnce(tabId, 'read-coverage-incomplete', {+ decided: !expansionUnverified,+ caveat: !expansionUnverified ? 'Not every part of the conversation was confirmed as read.'+ : this._isActionMode(this._effectiveRunMode(tabId))+ ? 'Some Gmail messages may have stayed collapsed, so the whole conversation was not confirmed as read.'+ : 'Ask mode cannot expand collapsed Gmail messages, so some messages in the conversation may be missing.',+ });+ }++ // exact-table-done for table JSON given without the app's data_ref.+ _exactTableAnswerRefuses(tabId, error) {+ const rowCountMismatch = /^The JSON rowCount /.test(String(error || ''));+ return this._guardRefusesOnce(tabId, 'exact-table-done', {+ decided: rowCountMismatch,+ caveat: rowCountMismatch ? 'The table\'s row count does not match its rows.'+ : 'The table was not checked against the exact rows on the page.',+ });+ }++ // The checks a plain final passes before the plan guard. By default each+ // one drops out once its guard has refused in this run.+ _plainFinalGuardBlocks(tabId, content) {+ const progressFinalBlock = this._plainFinalProgressBlock(tabId);+ const completionFinalBlock = this._completionPlainFinalBlock(tabId);+ const readFinalBlock = this._readCompletenessBlock(tabId);+ const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), content);+ return {+ progressFinalBlock: progressFinalBlock && this._progressGuardRefuses(tabId) ? progressFinalBlock : null,+ completionFinalBlock: completionFinalBlock && this._completionPlainFinalRefuses(tabId) ? completionFinalBlock : null,+ readFinalBlock: readFinalBlock && this._readCoverageGuardRefuses(tabId) ? readFinalBlock : null,+ exactTableFinalBlock: exactTableFinalBlock && this._exactTableAnswerRefuses(tabId, exactTableFinalBlock)+ ? exactTableFinalBlock : null,+ };+ }++ // Strict checks: the third plain final under a completion block ends the+ // run as partial. By default each block refuses once and the next plain+ // final is accepted, so the run never needs this stop.+ _plainFinalTwoStrikeEnds() {+ return !this._guardAdvises('plain-final-two-strike-partial');+ }++ // completion-verifier-not-done: the completion judge's sure pending or+ // failed verdict. completion-evidence-freshness: the judged evidence+ // changed while it was being judged (engine 'freshness').+ _completionVerdictRefuses(tabId, decision) {+ const freshness = decision?.engine === 'freshness';+ return this._guardRefusesOnce(tabId, freshness ? 'completion-evidence-freshness' : 'completion-verifier-not-done', {+ decided: !freshness,+ caveat: freshness ? 'The page changed while the result was being checked.'+ : decision?.outcome === 'failed' ? 'An independent check of the page suggested that the task did not succeed.'+ : 'An independent check of the page could not confirm that the task had finished.',+ });+ }++ _iframeResultStaleRefuses(tabId) {+ return this._guardRefusesOnce(tabId, 'completion-evidence-freshness', { decided: false,+ caveat: 'The submitted form inside an embedded frame could not be read again at the end.' });+ }++ _calculationRefreshRefuses(tabId) {+ return this._guardRefusesOnce(tabId, 'completion-evidence-freshness', { decided: false,+ caveat: 'The calculation could not be checked again against the current page.' });+ }++ // completion-page-warning: an open dialog or a failed validation the page+ // shows (it knows), or a visible form or edit route without a verified+ // submit (it cannot tell).+ _completionPageWarningRefuses(tabId, key) {+ const text = String(key || '');+ const known = /\|dialog\|\d+$/.test(text) || text.endsWith('|submit-validation-failed');+ const caveat = /\|dialog\|\d+$/.test(text) ? 'A dialog was still open on the page at the end.'+ : text.endsWith('|submit-validation-failed') ? 'The form showed a validation error after it was submitted.'+ : text.includes('|pending-form|') ? 'The form still looked unsubmitted at the end.'+ : 'The page was still on an edit screen with no sign that the change was saved.';+ return this._guardRefusesOnce(tabId, 'completion-page-warning', { decided: known, caveat });+ }++ _completionPageWarningSuffix(blocks) {+ return this._guardAdvises('completion-page-warning')+ ? ' (If the task is complete and this form or dialog is unrelated to it, say so in the done summary.)'+ : ` (block attempt ${blocks}/2 — if you genuinely believe the task is complete and the visible form/dialog is unrelated, re-call done with summary explicitly acknowledging this, e.g. "already-existing product, no submit needed".)`;+ }++ // incomplete-task-redirect: the judge's continue_now or wait_then_check+ // reading of an honest partial or failed ending. A block without+ // `recovery` is incomplete-task-check-stale (the task or page changed+ // while it was read): a host check that always stands.+ _incompleteRedirectRefuses(tabId, block) {+ if (!block?.recovery) return true;+ return this._guardRefusesOnce(tabId, 'incomplete-task-redirect', {+ caveat: 'WebBrain judged that more of the task could still be done.',+ });+ }++ // The guards behind a plan-execution refusal, each with the sentence the+ // user sees when a completion is accepted over it.+ _planGuardFindings(state, flags) {+ const findings = [];+ const add = (id, decided, caveat) => {+ const prior = findings.find(finding => finding.id === id);+ if (prior) prior.caveat = `${prior.caveat} ${caveat}`;+ else findings.push({ id, decided, caveat });+ };+ if (!flags.viaDone) add('plan-plain-final-protocol', true, PLAIN_FINAL_PROTOCOL_CAVEAT);+ else if (flags.looksPlanOnly) {+ add('plan-done-summary-shape', true, flags.runtimeModeContradiction+ ? 'The final answer blamed a read-only mode that was not in use.'+ : 'The final answer looked like a plan rather than a result.');+ }+ if (flags.forbiddenSubmission) {+ add('plan-unauthorized-mutation-recorded', true, 'The form was submitted even though the task was to leave it unsubmitted.');+ } else if (state.conditionalMutationBlocked) {+ add('plan-unauthorized-mutation-recorded', true, 'The planned repair was not made because no matching workflow allowed it.');+ }+ if (flags.missingRequiredSchedulingTool) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the scheduled task was created.');+ if (flags.missingRequiredDownload) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the file was downloaded.');+ if (flags.missingJobEvidence) add('plan-required-evidence-missing', false, 'The result was not checked the way this kind of task requires.');+ if (flags.missingDraftEvidence) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that the draft was saved with every requested field.');+ if (flags.missingRequiredLedger) add('plan-required-evidence-missing', false, 'I couldn\'t confirm that every item was handled.');+ if (flags.missingSocialPublishTargets.length) {+ add('plan-publication-evidence-missing', false, `I couldn't confirm the post on ${flags.missingSocialPublishTargets+ .map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}.`);+ }+ if (flags.missingRequiredSubmission && this._workflowVerificationKind(state.siteWorkflow) === 'published_resource') {+ // The byte-exact raw-blob check stays the evidence for a GitHub file+ // commit; only its refusal is advised.+ const githubFile = state.siteWorkflow?.adapterName === 'github' && state.siteWorkflow?.job?.id === 'edit-file-and-commit';+ const caveat = githubFile ? 'I couldn\'t confirm that the committed file matches the requested text.'+ : 'I couldn\'t confirm that the published result matches the request.';+ add('plan-publication-evidence-missing', false, caveat);+ if (githubFile) add('github-committed-file-verification', false, caveat);+ } else if (flags.missingRequiredSubmission && !flags.missingSocialPublishTargets.length) {+ add('plan-submission-evidence-missing', false, 'I couldn\'t confirm that the submission went through.');+ }+ if (flags.missingEvidence && findings.every(finding => ['plan-plain-final-protocol', 'plan-done-summary-shape'].includes(finding.id))) {+ add('plan-execution-evidence-missing', false, state.requiresStateChange === false+ ? 'No successful page read or tool result backs this answer.'+ : 'I couldn\'t confirm that the requested change was made.');+ }+ return findings;+ }++ // Default mode for the plan-execution guard: each finding gives its note+ // once per run and is then accepted with its caveat, so this guard never+ // ends the run itself. null keeps the strict path: Strict checks, a+ // drifted task (a host check), and the two endings that hold no answer to+ // accept, a planner or policy object and a stale cancellation echo.+ _planGuardAdvisory(tabId, state, flags) {+ if (state.taskDrifted || flags.staleCancellation || flags.structuredPlan) return null;+ const findings = this._planGuardFindings(state, flags);+ if (!findings.length || findings.some(finding => !this._guardAdvises(finding.id, finding))) return null;+ let refuses = false;+ for (const finding of findings) {+ if (this._guardRefusesOnce(tabId, finding.id, finding)) refuses = true;+ }+ return refuses ? 'refuse' : 'accept';+ }+_completionPlainFinalBlock(tabId) {const mode = this._effectiveRunMode(tabId);if (!this._isActionMode(mode)) return null;@@ -4762,6 +5102,11 @@ export class Agent extends LoopDetector {_completionRecoveryPolicy(tabId, tools, { verification = false, done = false, failure = false } = {}) {if (!this._isActionMode(this._effectiveRunMode(tabId))) return null;+ // By default a refused completion only leaves its note: the model keeps+ // every tool and may still report success. Strict checks restore the+ // forced read-only turn, the done-only turn and the failure-only done.+ if (this._guardAdvises('completion-recovery-forced-turns', { decided: false })+ && this._guardAdvises('completion-failure-only-done', { decided: false })) return null;const state = this.completionInvariants.get(tabId);const available = Array.isArray(tools) ? tools : [];const failureOnlyTerminalTool = () => {@@ -8892,6 +9237,7 @@ export class Agent extends LoopDetector {for (const [owner, map] of [[this._uncertainTextMutations, this._uncertainTextMutations.get(tabId)],[this._verifiedTextReplacements, this._verifiedTextReplacements.get(tabId)],+ [this._unverifiedTextWrites, this._unverifiedTextWrites?.get(tabId)],]) {if (!(map instanceof Map)) continue;for (const [key, entry] of map) {@@ -8948,6 +9294,18 @@ export class Agent extends LoopDetector {async _richTextToolbarToolBlock(tabId, toolName, args = {}, executionContext = null) {if (!this._richTextToolbarGuard.hasPending(tabId)) return null;if (!RICH_TEXT_TOOLBAR_GUARDED_TOOLS.has(toolName)) return null;+ // The preflight already advised this exact call and recorded its+ // obligation; checking it again would only repeat that note.+ if (executionContext?.richTextToolbarWrongTargetAdvised === true) return null;+ // rich-text-toolbar-recovery-obligation (quality): while an earlier text+ // entry into a formatting toolbar is unresolved, a call on that toolbar,+ // or one whose target cannot be checked, is refused only in Strict+ // checks. Otherwise it runs unbound with a note; the obligation stays+ // until a verified editor-body edit releases it.+ const advises = (note, decided) => this._guardAdvisesFor(executionContext?.guardAdvisories,+ 'rich-text-toolbar-recovery-obligation', note, { decided });+ const toolbarNote = 'This target belongs to the rich-text formatting toolbar that received the earlier text entry, not the editor body. It was used anyway; the requested content still has to be entered in the editor body and verified there.';+ const uncheckedNote = 'An earlier text entry went into a rich-text formatting toolbar, and WebBrain could not check that this target is not that toolbar. It was sent anyway; enter the requested content in the editor body and verify it there.';const probe = await this._probeRichTextToolbarRetryTarget(tabId, toolName, args);if (!probe?.resolved) {const knownRefBlock = this._richTextToolbarGuard.blockRef(@@ -8956,7 +9314,9 @@ export class Agent extends LoopDetector {args,this._lastAxScopes.get(tabId)?.documentToken || '',);- if (knownRefBlock) return knownRefBlock;+ if (knownRefBlock) return advises(toolbarNote, true) ? null : knownRefBlock;+ // A selector matching several frames has no single target to send to.+ if (DISPATCH_BINDING_TOOLS.has(toolName) && probe?.ambiguous !== true && advises(uncheckedNote, false)) return null;return DISPATCH_BINDING_TOOLS.has(toolName)? {success: false,@@ -8990,7 +9350,7 @@ export class Agent extends LoopDetector {}if (evaluation.block) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);- return evaluation.block;+ return advises(toolbarNote, true) ? null : evaluation.block;}if (evaluation.guarded !== true) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);@@ -9001,6 +9361,7 @@ export class Agent extends LoopDetector {&& !richTextToolbarDispatchBindingReady(toolName, args, probe.dispatchBinding)) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);+ if (advises(uncheckedNote, false)) return null;return {success: false,dispatched: false,@@ -9056,7 +9417,10 @@ export class Agent extends LoopDetector {return true;}- _applyRichTextToolbarWrongTarget(tabId, toolName, args, result, candidate, decision, audit, identity = {}) {+ // The recovery obligation is evidence that the requested content may not be+ // in the editor body, so it is recorded whether the entry is refused or+ // (Strict checks off) sent with a note.+ _recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, identity = {}, { advised = false } = {}) {const recorded = this._richTextToolbarGuard.recordWrongTarget(tabId, {toolName,args,@@ -9064,6 +9428,25 @@ export class Agent extends LoopDetector {decision,identity,});+ const runId = this.currentRunId.get(tabId);+ if (runId) {+ trace.recordNote(runId, null, 'rich_text_toolbar_wrong_target', {+ toolName,+ refId: typeof args?.ref_id === 'string' ? args.ref_id : '',+ targetKind: recorded.obligation.targetKind,+ source: decision.source,+ confidence: audit?.confidence ?? null,+ blockedRefCount: recorded.blockedRefCount,+ persistentRecoveryObligation: true,+ recoveryTargetUnknown: !recorded.hasExactRecoveryTarget,+ ...(advised ? { advised: true } : {}),+ });+ }+ return recorded;+ }++ _applyRichTextToolbarWrongTarget(tabId, toolName, args, result, candidate, decision, audit, identity = {}) {+ const recorded = this._recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, identity);const obligation = recorded.obligation;const associatedEditorRef = typeof candidate?.associatedEditorRef === 'string'&& /^ref_\d+$/.test(candidate.associatedEditorRef)@@ -9091,19 +9474,6 @@ export class Agent extends LoopDetector {? `This edit was blocked before dispatch because the target is a rich-text formatting toolbar control, not the editor body. Do not retry this ref or another font-family, font-size, style, color, or link control in the same toolbar. Use the associated editor body ${associatedEditorRef}, enter the requested content there, and verify that exact editor edit.`: 'This edit was blocked before dispatch because the target is a rich-text formatting toolbar control, not the editor body. Do not retry this ref or another font-family, font-size, style, color, or link control in the same toolbar. Re-read the tree, focus the associated editor body, enter the requested content there, and verify that exact editor edit.',});- const runId = this.currentRunId.get(tabId);- if (runId) {- trace.recordNote(runId, null, 'rich_text_toolbar_wrong_target', {- toolName,- refId: typeof args?.ref_id === 'string' ? args.ref_id : '',- targetKind: obligation.targetKind,- source: decision.source,- confidence: audit?.confidence ?? null,- blockedRefCount: recorded.blockedRefCount,- persistentRecoveryObligation: true,- recoveryTargetUnknown: !recorded.hasExactRecoveryTarget,- });- }}async _classifyRichTextToolbarTarget(tabId, provider, dataUrl) {@@ -9166,9 +9536,17 @@ export class Agent extends LoopDetector {if (!['set_field', 'type_ax', 'type_text', 'iframe_type'].includes(toolName)) {return { block: null, shot: null };}+ const advisories = captureOptions?.guardAdvisories || null;+ // rich-text-toolbar-target-unresolved (quality, cannot decide): when this+ // safety preflight cannot resolve or keep the typing target, Strict checks+ // off skips the toolbar check and lets the tool resolve its target itself+ // (an iframe goes to the handler's own single-target census).+ const unresolvedAdvises = note => this._guardAdvisesFor(advisories, 'rich-text-toolbar-target-unresolved',+ note, { decided: false });+ const unresolvedNote = 'WebBrain could not resolve this typing target for its rich-text toolbar check, so it could not confirm the text goes into the editor body rather than a formatting control. It was sent anyway; read the field back to verify.';// A target the observed certificate cannot bind (such as a selector that// names several elements) gets that answer before any probe of it.- const unbindable = await this._pageFeedbackUnbindableResult?.(tabId, toolName, args);+ const unbindable = await this._pageFeedbackUnbindableResult?.(tabId, toolName, args, advisories);if (unbindable) return { block: unbindable, shot: null };const selectorBackedType = toolName === 'type_text'&& typeof args?.selector === 'string'@@ -9183,7 +9561,13 @@ export class Agent extends LoopDetector {: await this._probeRichTextToolbarRetryTarget(tabId, toolName, args, { mapAnnotation: true });if (!probe?.resolved) {const ambiguousIframeTarget = toolName === 'iframe_type' && probe?.ambiguous === true;- return ambiguousIframeTarget || (toolName === 'iframe_type' && recoveryPending) || selectorBackedType || focusedType+ const refusable = ambiguousIframeTarget || (toolName === 'iframe_type' && recoveryPending) || selectorBackedType || focusedType;+ // An iframe selector naming several elements has no single target to+ // send to and keeps its answer.+ if (refusable && !ambiguousIframeTarget && unresolvedAdvises(unresolvedNote)) {+ return { block: null, shot: null, iframeTargetUnresolved: toolName === 'iframe_type' };+ }+ return refusable? {block: {success: false,@@ -9212,6 +9596,9 @@ export class Agent extends LoopDetector {}if ((toolName === 'iframe_type' || selectorBackedType || focusedType) && !probe.dispatchBinding?.token) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);+ // Advised: the released probe is not passed on, so the tool resolves+ // its own target without a preserved identity.+ if (unresolvedAdvises(unresolvedNote)) return { block: null, shot: null };return {block: {success: false,@@ -9240,9 +9627,15 @@ export class Agent extends LoopDetector {|| (!Number.isInteger(probe.frameId) || probe.frameId === 0 ? probe.rect : null);const visionAvailable = !!(await this._resolveVisionRoute(tabId, provider)).provider;const visualAuditAllowanceAvailable = this._canTakeToolbarAuditScreenshot(tabId);- const visualAuditEligible = this._shouldAutoScreenshot(toolName)+ let visualAuditEligible = this._shouldAutoScreenshot(toolName)&& visualAuditAllowanceAvailable&& visionAvailable;+ // Advised: the visual check is skipped and the page-structure score below+ // decides alone, as it does when no vision model is configured.+ if (visualAuditEligible && toolName === 'iframe_type' && !annotationRect+ && unresolvedAdvises('The matching iframe target could not be brought into view for WebBrain\'s visual toolbar check, so it was classified by page structure only. Read the field back to verify the text went into the editor body.')) {+ visualAuditEligible = false;+ }if (visualAuditEligible && toolName === 'iframe_type' && !annotationRect) {await this._releaseRichTextToolbarProbeTarget(tabId, probe);return {@@ -9342,6 +9735,15 @@ export class Agent extends LoopDetector {audit,);if (decision.wrongTarget) {+ // rich-text-toolbar-wrong-target (quality): Strict checks off types into+ // the probed target with a note instead of refusing. The obligation is+ // still recorded, so later toolbar calls and completion know the+ // requested content may not be in the editor body.+ if (this._guardAdvisesFor(advisories, 'rich-text-toolbar-wrong-target',+ 'WebBrain\'s check reads this target as a rich-text formatting toolbar control (font, size, style, color or link), not the editor body. The text was typed there anyway; enter the requested content in the editor body and verify it there.')) {+ this._recordRichTextToolbarWrongTarget(tabId, toolName, args, candidate, decision, audit, probe, { advised: true });+ return { block: null, shot, audit, decision, traceCapture, probe, wrongTargetAdvised: true };+ }const block = {};this._applyRichTextToolbarWrongTarget(tabId, toolName, args, block, candidate, decision, audit, probe);await this._releaseRichTextToolbarProbeTarget(tabId, probe);@@ -12203,12 +12605,24 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn { gate: publicGate, loopCheck };}+ // A text write that went out but could not be read back exactly is an+ // advisory result (success + unverifiedWrite + a note), not a reason to+ // replan the rest of the batch. Failures, refusals and unknown outcomes+ // still interrupt; so does every unverified result under Strict checks.+ _advisoryTextWriteContinuesBatch(toolName, toolResult) {+ return ['set_field', 'type_ax', 'type_text'].includes(toolName)+ && toolResult?.success === true && toolResult.unverifiedWrite === true && !toolResult.error+ && this._guardAdvises('browser-batch-fresh-turn-interrupt', { decided: true });+ }+_browserActionFreshTurnReason(tier, toolName, toolResult, batch = null) {+ const advisoryWrite = this._advisoryTextWriteContinuesBatch(toolName, toolResult);if (batch) {// Reads and waits can also be prerequisites of the next batched action.if (toolResult?.success === false || toolResult?.error || toolResult?.noProgress|| toolResult?.ambiguous || toolResult?.outcomeUnknown || toolResult?.stale) return 'action_failed';- if (toolResult?.inconclusive || toolResult?.verified === false || toolResult?.remoteStateVerified === false) return 'action_unverified';+ if (!advisoryWrite && (toolResult?.inconclusive || toolResult?.verified === false+ || toolResult?.remoteStateVerified === false)) return 'action_unverified';if (batch.submit && batch.hasRemaining) return 'submit_boundary';if (batch.navigationChanged && batch.hasRemaining&& (!batch.sameNext || !batch.remainingObservations)) return 'navigation_changed';@@ -12241,9 +12655,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn 'action_failed';}if (- toolResult?.inconclusive- || toolResult?.verified === false- || toolResult?.remoteStateVerified === false+ !advisoryWrite && (+ toolResult?.inconclusive+ || toolResult?.verified === false+ || toolResult?.remoteStateVerified === false+ )) {return 'action_unverified';}@@ -12519,6 +12935,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d_pureCalculationToolPolicy(tabId, expectedScope = null) {const guard = this._planExecutionGuards.get(tabId);+ // A task whose arithmetic-only scope was released (see+ // _releasePureCalculationScope) is an ordinary task for the rest of its+ // plan guard; a new task gets a fresh guard and its own scope.+ if (guard?.pureCalculationScopeReleased === true) return null;const scope = this._pageFeedbackCalculationResponseScope?.(tabId);const capturedScope = expectedScope || guard?.pureCalculationToolScope || null;if (capturedScope && (!scope || capturedScope.owner !== scope.owner@@ -12565,6 +12985,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._planExecutionGuards.get(tabId)?.pureCalculationReceipt?.fraction);const prematureCompletion = !policy.stale && name === 'done' && !completed && !policy.attempted;if (!policy.stale && policy.names.includes(name) && matchesInput && !missingResult && !missingFormat && !prematureCompletion) return null;+ // A done these arithmetic checks refuse is advised once per run by+ // default, then accepted with a caveat. A stale task authority is a+ // host check and keeps refusing.+ if (!policy.stale && name === 'done' && !this._guardRefusesOnce(tabId, 'pure-calculation-done-checks', {+ decided: !prematureCompletion,+ caveat: prematureCompletion ? 'The result was not computed with the calculator.'+ : missingResult ? 'The answer may not show the calculator\'s exact result.'+ : 'The answer may not use the exact format you asked for.',+ })) return null;return { success: false, skipped: true, denied: true, dispatched: false, noDispatch: true,...(prematureCompletion ? { blockedDone: true } : {}),outcomeUnknown: false, errorCode: 'pure_calculation_tool_denied',@@ -12581,6 +13010,39 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d: 'This genuine task only authorizes its literal calculation. Call calculate with that exact expression, then done with the result and an explicit outcome. No browser action or different calculation was dispatched.' };}+ /**+ * pure-calculation-tool-scope (quality): with Strict checks off, a call+ * outside an owned literal-arithmetic task's scope (another tool, another+ * expression, a calculation repeated after its verified result) runs with+ * a note instead of being refused. Returns true when the caller must let+ * the call proceed. The stale-authority refusal (a host check) and the+ * done checks are not this guard and keep refusing.+ */+ _pureCalculationScopeAdvises(tabId, name, args, expectedScope, advisories) {+ if (!name || name === 'done' || name === 'done_json') return false;+ const policy = this._pureCalculationToolPolicy(tabId, expectedScope);+ if (!policy || policy.stale) return false;+ const expression = String(policy.scope?.expression || '').slice(0, 80);+ const note = name !== 'calculate'+ ? `This task only asks for its literal calculation (${expression}); no browser action or other tool was requested. ${name} ran anyway. The answer still needs calculate with that exact expression; report it with done.`+ : policy.names.includes('calculate')+ ? `This calculate is not the task's literal calculation (${expression}), so its result is not the task's verified answer. It ran anyway; the answer needs calculate with that exact expression.`+ : 'The task\'s literal calculation was already verified; this repeated calculate ran anyway. The verified result stands: report it with done.';+ return this._guardAdvisesFor(advisories, 'pure-calculation-tool-scope', note);+ }++ // A page action that runs on an arithmetic-only task (advised above) makes+ // its captured scope permanently stale: the scope requires a run with no+ // action, so every later call, done included, would be refused as a changed+ // authority and the tool list would empty. The task is no longer+ // arithmetic-only, so its scope is released for the rest of this plan guard.+ _releasePureCalculationScope(tabId) {+ const guard = this._planExecutionGuards.get(tabId);+ if (!guard) return;+ guard.pureCalculationScopeReleased = true;+ guard.pureCalculationToolScope = null;+ }+async _executeToolBatchInner(tabId, toolCalls, messages, onUpdate, provider, partialAssistantText, allowedToolNames, step, runOptions, toolSchemas, cancellationState) {// Capture the request's private authority, not a later same-wording task.// Recommended/fast batches also pass this shared boundary.@@ -12594,6 +13056,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst promptTier = this._resolvePromptTier(provider);const readLimits = this._readWindowLimits();const completionBatchStartState = this.completionInvariants.get(tabId) || null;+ // A batch holding a done is a new completion attempt (see+ // _beginCompletionGuardAttempt). A read batch that a tool handler runs+ // on its own keeps the caveats.+ if (toolCalls.some(call => ['done', 'done_json'].includes(call?.function?.name))) {+ this._beginCompletionGuardAttempt(tabId);+ }const navNotices = [];const failedApiMutationLoopKeysThisBatch = new Set();const navigatedBrowserBatches = new Set();@@ -12685,12 +13153,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst previous = toolCalls[toolIndex - 1];if (previous?._browserBatch) {const priorResult = messages.findLast(message => message.role === 'tool' && message.tool_call_id === previous.id);- if (browserBatchResultStatus(priorResult).failed && this._interruptToolBatchForFreshTurn(+ if (browserBatchResultStatus(priorResult, {+ advisoryWritesContinue: this._guardAdvises('browser-batch-fresh-turn-interrupt', { decided: true }),+ }).failed && this._interruptToolBatchForFreshTurn(tabId, toolCalls, toolIndex, messages, onUpdate, step,{ tier: promptTier, triggeringTool: previous.function.name, reason: 'action_failed', navNotices },)) { navNotices.length = 0; break; }}- const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null };+ const callState = { index: toolIndex, invoked: false, consequential: false, result: null, dispatchState: null, guardAdvisories: [] };cancellationState.active = callState;if (this._checkAbort(tabId)) {const value = '[Stopped by user before executing requested tool calls.]';@@ -12726,7 +13196,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!this._hasPendingSteering(tabId)) {const calculationArgs = this._parseToolCallArgs(tc).args;const calculationBlock = this._pureCalculationToolBlock(tabId, tc.function?.name || '', calculationArgs, calculationRequestScope);- if (calculationBlock) {+ if (calculationBlock && !this._pureCalculationScopeAdvises(tabId, tc.function?.name || '', calculationArgs,+ calculationRequestScope, callState.guardAdvisories)) {const recovery = await recordPreparationFailure(toolIndex, tc.function?.name || '', calculationArgs || {}, calculationBlock);if (recovery) return recovery;if (tc._browserBatch && interruptFailedBrowserAction(toolIndex, tc.function?.name)) { navNotices.length = 0; break; }@@ -12937,7 +13408,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const mediaTargetGuard = await this._downloadPublicMediaExplicitUrlGuard(tabId, fnName, fnArgs);- if (mediaTargetGuard) {+ // A feed/profile URL may save a different item than the one the model+ // means. Without Strict checks the download runs with that warning.+ if (mediaTargetGuard && !this._guardAdvisesFor(callState.guardAdvisories, 'media-download-target-binding',+ 'The download URL is a feed or profile page, not one media item\'s permalink, so the saved file may be a different item than the one you meant. Check the downloaded file (list_downloads) before reporting it.')) {messages.push({role: 'tool',tool_call_id: tc.id,@@ -13134,9 +13608,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const runWorkflowPreSubmitChecks = async () => await this._resourceMutationPreSubmitBlock(tabId, fnName, fnArgs, detectedSubmitAction, provider)|| this._steeringPriorSubmissionBlock(tabId, fnName, fnArgs, detectedSubmitAction)- || await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction)+ || await this._conditionalGithubCommitTransition(tabId, fnName, fnArgs, detectedSubmitAction, callState.guardAdvisories)|| await this._workflowPreSubmitDispatchBlock(- tabId, fnName, fnArgs, detectedSubmitAction, provider,+ tabId, fnName, fnArgs, detectedSubmitAction, provider, callState.guardAdvisories,);let workflowPreSubmitBlock = await runWorkflowPreSubmitChecks();if (workflowPreSubmitBlock?.mutationConfirmation@@ -13199,7 +13673,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dcorrectedPriorValidationFailure = true;} else {const retryActionKey = this._formValidationActionKey(fnName, fnArgs);- if (retryActionKey && retryActionKey === validationBlock.actionKey) {+ // The earlier submit failed validation, so repeating it cannot+ // duplicate an effect. Without Strict checks it is sent again with+ // a note; a repeated rejection reports the page's messages itself.+ if (retryActionKey && retryActionKey === validationBlock.actionKey+ && !this._guardAdvisesFor(callState.guardAdvisories, 'form-validation-unchanged-repeat',+ this._formValidationRepeatNote(validationBlock))) {const blockedResult = this._formValidationRetryBlockResult(validationBlock);onUpdate('tool_call', { name: fnName, args: fnArgs });onUpdate('tool_result', { name: fnName, result: blockedResult });@@ -13393,10 +13872,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dformValidationBefore = await captureFormValidationWithDeadline(formValidationAllFrames);} catch (error) {if (error?.code !== 'content_action_timeout') throw error;- const loopStop = await recordPagePreparationTimeout(error, 'form-validation snapshot');- if (loopStop) return loopStop;- if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }- continue;+ // The before-snapshot only gives post-submit validation detection+ // its baseline; the action itself does not need it. Without Strict+ // checks the call proceeds with an empty baseline and a note.+ if (this._guardAdvisesFor(callState.guardAdvisories, 'preparation-timeout-generic',+ 'The form-validation snapshot did not finish before this action, so WebBrain has no baseline to tell new validation errors from old ones. Read the form after it to confirm the page accepted it.',+ { decided: false })) {+ formValidationBefore = [];+ } else {+ const loopStop = await recordPagePreparationTimeout(error, 'form-validation snapshot');+ if (loopStop) return loopStop;+ if (interruptFailedBrowserAction(toolIndex, fnName)) { navNotices.length = 0; break; }+ continue;+ }}}if (capabilities.length && !this._skipPermissionGate && !scheduledBypassesGate) {@@ -13531,7 +14019,18 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (fnName === 'done' || fnName === 'done_json') {- const invariantBlock = this._completionDoneBlock(tabId, fnName, fnArgs, completionBatchStartState);+ // Each completion invariant gets its own note: one that already advised+ // in this run is accepted, and the next applicable one is checked.+ let invariantBlock = null;+ const acceptedInvariants = new Set();+ for (;;) {+ const block = this._completionDoneBlock(tabId, fnName, fnArgs, completionBatchStartState, { skip: acceptedInvariants });+ if (!block) break;+ if (this._completionInvariantRefuses(tabId, block)) { invariantBlock = block; break; }+ acceptedInvariants.add(block.reason);+ // Accepted over advice. A done that names no outcome claims no success.+ if (block.reason === 'missing_outcome') fnArgs = { ...fnArgs, outcome: 'partial' };+ }if (invariantBlock) {const blockedResult = {success: false,@@ -13570,8 +14069,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d};}+ // By default the model's answer is kept: the whole-thread check below+ // gives the model one note about the Ask-mode limitation and the final+ // answer carries it. Strict checks replace the answer and end the run.const readLimitation = this._readCompletenessLimitation(tabId);- if (readLimitation) {+ if (readLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {const limitationResult = {success: false,done: true,@@ -13603,7 +14105,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}const readBlock = this._readCompletenessBlock(tabId);- if (readBlock) {+ if (readBlock && this._readCoverageGuardRefuses(tabId)) {const blockedResult = {success: false,blockedDone: true,@@ -13639,7 +14141,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst progressBlock = this._shouldBlockDoneForProgress(tabId)? this._progressDoneBlock(tabId, doneOutcome): null;- if (progressBlock) {+ if (progressBlock && this._progressGuardRefuses(tabId)) {const blockedResult = {success: false,blockedDone: true,@@ -13804,7 +14306,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dfnName,fnArgs,provider,- { onUpdate },+ { onUpdate, guardAdvisories: callState.guardAdvisories },);this._throwIfAborted(abortSignal);const socialDispatchBlock = pipelineToolbarPreflight.block ? null@@ -13814,7 +14316,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Recheck after all preparation, before marking or invoking dispatch.if (this._hasPendingSteering(tabId) || await this._refreshPageFeedbackForCall(tabId, tc, onUpdate)) return { steered: true };const genericChatBlock = pipelineToolbarPreflight.block || socialDispatchBlock ? null- : await this._prepareGenericChatDispatch(tabId, fnName, fnArgs, messageRecipientExecutionContext, abortSignal);+ : await this._prepareGenericChatDispatch(tabId, fnName, fnArgs, messageRecipientExecutionContext, abortSignal,+ callState.guardAdvisories);this._throwIfAborted(abortSignal);if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock) {// Save the task's record with this action's sites before it can be@@ -13829,11 +14332,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn { steered: true };}}- const calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);+ let calculationDispatchBlock = this._pureCalculationToolBlock(tabId, fnName, fnArgs, calculationRequestScope);+ if (calculationDispatchBlock && this._pureCalculationScopeAdvises(tabId, fnName, fnArgs,+ calculationRequestScope, callState.guardAdvisories)) {+ calculationDispatchBlock = null;+ callState.pureCalculationScopeAdvised = true;+ }if (!pipelineToolbarPreflight.block && !socialDispatchBlock && !genericChatBlock && !calculationDispatchBlock) {if (detectedSubmitAction?.isSubmit === true && detectedSubmitAction.publicationControl === true) {messageRecipientExecutionContext.socialPublicationAuditRetryConsumed = this._consumeSocialPublicationAuditRetry(tabId);}+ if (callState.pureCalculationScopeAdvised === true && isCompletionActionTool(fnName, fnArgs)) {+ this._releasePureCalculationScope(tabId);+ }if (fnName === 'calculate') this._rememberPureCalculationAttempt(tabId, fnArgs, calculationRequestScope);callState.invoked = true;}@@ -13848,9 +14359,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout djevBinding: jevPending?.call.binding,detectedSubmitAction,promptTier,+ guardAdvisories: callState.guardAdvisories,dispatchBinding: pipelineToolbarPreflight.probe?.dispatchBinding || null,...messageRecipientExecutionContext,iframeTargetUnresolved: pipelineToolbarPreflight.iframeTargetUnresolved === true,+ richTextToolbarWrongTargetAdvised: pipelineToolbarPreflight.wrongTargetAdvised === true,imageGenConfig,_contentActionAbortSignal: abortSignal,_contentActionDispatchState: actionDispatchState,@@ -14232,7 +14745,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (toolResult?.blockedDone) {const completionNeedsRead = toolResult.completionDecision || toolResult.completionPageBlock;- if (completionNeedsRead) { const state = this.completionInvariants.get(tabId); if (state) this.completionInvariants.set(tabId, { ...state, verificationDebt: true }); }+ // Strict checks: a negative verdict or page warning reopens verification+ // debt for a forced read-only turn. By default the model only gets the+ // note, and the debt guard does not refuse the next done for it.+ if (completionNeedsRead && !this._guardAdvises('done-verification-debt', { decided: false })) { const state = this.completionInvariants.get(tabId); if (state) this.completionInvariants.set(tabId, { ...state, verificationDebt: true }); }messages.push({ role: 'tool', tool_call_id: tc.id, content: this._wrapUntrusted(fnName, this._limitToolResult(toolResult)) });if (attachedImage) {messages.push({ role: 'user', transientCompletionVerification: true, content: [@@ -14347,7 +14863,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dstatus: planOnlyDecision.status || 'plan_only_output' };}let rawDoneSummary = toolResult.summary || partialAssistantText || 'Task completed.';- if (!scheduledResume && summaryKind === 'meta_only') {+ if (!scheduledResume && summaryKind === 'meta_only' && this._guardRefusesOnce(tabId, 'done-summary-meta-only', {+ caveat: 'The final answer may only say that an answer was given, without the answer itself.',+ })) {const blockedResult = {success: false,blockedDone: true,@@ -14380,17 +14898,28 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtoolResult.summary = (toolResult.summary || partialAssistantText || '') + '\n\n' + notice;}}+ if (!scheduledResume && toolResult.outcome === 'success'+ && this._guardRunState(tabId).outcomeDowngrades?.size) {+ // Accepted over a guard that knows the claim is wrong: end the run,+ // but as partial so schedules and watches do not count a success.+ toolResult.outcome = 'partial';+ }onUpdate('tool_result', { name: fnName, result: toolResult });this._doneBlockCount.delete(tabId);rawDoneSummary = toolResult.summary || rawDoneSummary;const repairedDoneSummary = fnArgs.data_ref ? rawDoneSummary : repairAssistantDisplayText(rawDoneSummary);- const finalResponse = fnArgs.data_ref ? repairedDoneSummary+ const deliveredSummary = fnArgs.data_ref ? repairedDoneSummary: this._appendProgressLedgerToFinal(tabId, repairedDoneSummary);+ // A completion accepted over a guard's advice tells the user what was+ // not verified. A scheduled resume is a pause, not a completion.+ const finalResponse = scheduledResume ? deliveredSummary : this._withCompletionCaveat(tabId, deliveredSummary);if (repairedDoneSummary !== rawDoneSummary) {// Streaming providers may already have rendered the malformed summary// before the done call. Replace it so the visible bubble matches the// repaired terminal value returned by this batch.onUpdate('text', { content: finalResponse, replace: true });+ } else if (finalResponse !== deliveredSummary) {+ onUpdate('text', { content: finalResponse, replace: true });}messages.push({role: 'tool',@@ -15488,10 +16017,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst normalized = value => String(value || '').replace(/\s+/g, ' ').trim().toLowerCase();const expectedName = normalized(messageRecipientContext.expectedName);const expectedRole = normalized(messageRecipientContext.expectedRole);- if (- (expectedName && normalized(target?.name) !== expectedName)- || (expectedRole && normalized(target?.role) !== expectedRole)- ) {+ const intentMismatch = (expectedName && normalized(target?.name) !== expectedName)+ || (expectedRole && normalized(target?.role) !== expectedRole);+ // click-coordinate-intent (quality): the model's own expected_name /+ // expected_role no longer matches what the point resolves to. Without+ // Strict checks the raw point is clicked, exactly as a coordinate click+ // without those hints would be; recipient, deletion and publication checks+ // still apply to that click.+ if (intentMismatch && this._guardAdvisesFor(messageRecipientContext.guardAdvisories, 'click-coordinate-intent',+ 'The point no longer resolves to the expected_name/expected_role you gave, so WebBrain could not confirm it hits the intended control. The point was clicked anyway; read the page to check what it activated.')) {+ return {+ result: null,+ diagnostic: this._coordinateReconciliationDiagnostic(point, resolution, 'coordinate-fallback', 'intent-mismatch'),+ };+ }+ if (intentMismatch) {return {result: {success: false,@@ -17478,6 +18018,78 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d* wait forever). Invalid values fall back to the product default of 60s.* Stored slider values above 1200 mean Off.*/+ // Settings → General → "Strict checks": every quality guard blocks again.+ _guardStrict() {+ return this.strictGuards === true;+ }++ /**+ * What guard `id` does now: 'block' | 'ask' | 'advise' (guard-policy.js).+ * decided=false when the guard fires because it cannot decide.+ */+ _guardOutcome(id, { decided = true } = {}) {+ return guardOutcome(id, { decided, strict: this._guardStrict() });+ }++ /** True when the guard advises instead of refusing in the current mode. */+ _guardAdvises(id, { decided = true } = {}) {+ return this._guardOutcome(id, { decided }) === 'advise';+ }++ /**+ * An action guard that advises lets the action proceed and leaves its note+ * on this call's tool result. Returns true when the caller must not refuse.+ * `advisories` is the call's list (executionContext.guardAdvisories or the+ * batch call state).+ */+ _guardAdvisesFor(advisories, id, message, { decided = true } = {}) {+ if (!this._guardAdvises(id, { decided })) return false;+ if (Array.isArray(advisories)) advisories.push(guardAdvisory(id, message));+ return true;+ }++ _guardRunState(tabId) {+ // Untraced runs (the default) have no currentRunId; the task token+ // _startTraceRun mints for every run bounds them instead.+ const runId = this.currentRunId?.get?.(tabId) ?? this._taskTokens?.get?.(tabId) ?? null;+ let state = this._guardRunStates.get(tabId);+ if (!state || state.runId !== runId) {+ state = { runId, advised: new Set(), caveats: new Map() };+ this._guardRunStates.set(tabId, state);+ }+ return state;+ }++ /**+ * Completion guards advise once per run: the first refusal is the note the+ * model gets (it can verify, fix or report honestly), and the next+ * completion the same guard would refuse goes through with a caveat for+ * the user. Returns true when this call should still refuse: the first+ * time, or always when the guard blocks in the current mode.+ */+ _guardRefusesOnce(tabId, id, { decided = true, caveat = '' } = {}) {+ if (this._guardOutcome(id, { decided }) !== 'advise') return true;+ const state = this._guardRunState(tabId);+ if (!state.advised.has(id)) {+ state.advised.add(id);+ return true;+ }+ const text = String(caveat || '').replace(/\s+/g, ' ').trim().slice(0, 300);+ if (text) state.caveats.set(id, text);+ // A guard that KNOWS the task is not done (not one that only lacked+ // evidence) lets the completion end the run, but not as a success.+ if (decided === true && OUTCOME_DOWNGRADING_GUARDS.has(id)) (state.outcomeDowngrades ||= new Set()).add(id);+ return false;+ }++ /** One short line for the user about completions accepted over advice. */+ _guardCaveatLine(tabId) {+ const state = this._guardRunStates.get(tabId);+ if (!state?.caveats?.size) return '';+ const items = [...new Set(state.caveats.values())].filter(Boolean).slice(0, 4);+ return items.length ? `WebBrain could not verify everything: ${items.join(' ')}` : '';+ }+_normalizeClarifyTimeoutPolicy(value) {return normalizeClarifyTimeoutPolicy(value);}@@ -24171,7 +24783,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn toolResult;}- _applyVerifyFormRecovery(tabId, result, currentStates) {+ _applyVerifyFormRecovery(tabId, result, currentStates, advisories = null) {const block = this._formValidationBlocks.get(tabId);if (!block || !result || typeof result !== 'object') return result;const stateKey = this._formValidationStateKey(currentStates);@@ -24237,7 +24849,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout duncheckedCheckboxes,instruction: `The form state is unchanged. Do not call verify_form again and do not toggle any checkbox. Use ${recoveryCalls}, then submit only after every checkedAfter is true.`,};- if (block.verifyFormCount > 1) {+ // A repeated read of an unchanged form is reported as a failure only in+ // Strict checks; otherwise the read keeps its result and the note says+ // nothing changed since the last one.+ if (block.verifyFormCount > 1 && !this._guardAdvisesFor(advisories, 'form-validation-unchanged-repeat',+ 'The form is unchanged since the last verify_form, so this read shows nothing new. Correct the reported checkbox with set_checked before verifying or submitting again.')) {result.success = false;result.noProgress = true;result.blockedValidationVerifyRepeat = true;@@ -24246,6 +24862,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn result;}+ // Page validation text is untrusted, so the note only counts the fields;+ // a repeated rejection reports its messages in the result itself.+ _formValidationRepeatNote(block) {+ const count = Array.isArray(block?.invalidFields) ? block.invalidFields.length : 0;+ return `This is the same submit that failed validation before, and the form still shows the same invalid field${count === 1 ? '' : 's'}. It was sent again; if the page rejects it, fix the reported fields before submitting.`;+ }+_formValidationRetryBlockResult(block) {const messages = Array.isArray(block?.validationMessages) && block.validationMessages.length? block.validationMessages@@ -25024,7 +25647,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn result;}- async _prepareGenericChatDispatch(tabId, name, args, context, abortSignal = null) {+ async _prepareGenericChatDispatch(tabId, name, args, context, abortSignal = null, advisories = null) {if (!context?.messageRecipientGuardRequired || name === 'upload_file'|| !['click', 'click_ax', 'press_keys', 'set_field'].includes(name)|| (!context.messageRecipientNativeChatBaseline && !this.chatSessions.has(tabId))) return null;@@ -25040,16 +25663,31 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& observed.snapshot.threadKey !== context.messageRecipientNativeChatBaseline.threadKey) {return blocked('thread_unverified', 'The observed chat changed after recipient verification. Nothing was sent.');}+ // chat-send-preconditions (quality): without Strict checks an unread+ // incoming message and a missing composer send with a note. The+ // recipient, user-input (credentials, payment, a new user decision),+ // terminal-session, native-baseline, duplicate and draft checks are not+ // waivable and keep refusing below (chat-workflow.js says why).+ const advise = note => this._guardAdvisesFor(advisories, 'chat-send-preconditions', note);if (previous && observed.newMessages.some(message => message.direction === 'incoming')- && !observed.session.pendingOutbound && !observed.session.userInput?.required) {+ && !observed.session.pendingOutbound && !observed.session.userInput?.required+ && !advise('A new incoming message appeared since your last chat observation; this reply was sent without considering it. Read the conversation (chat_observe) before the next reply.')) {return blocked('chat_observe_required','A new incoming message appeared before this send. Call chat_observe and consider that delta before replying.');}// The recipient probe has already bound this exact draft/body to its one-use// dispatch token. It is the intended outbound, not an unrelated user draft.- const decision = decideChatSend(observed.session, {- ...before, composer: { ...before.composer, empty: true },- }, context.messageRecipientBody);+ const decisionSnapshot = { ...before, composer: { ...before.composer, empty: true } };+ const waive = new Set();+ let decision = decideChatSend(observed.session, decisionSnapshot, context.messageRecipientBody);+ const waiverNotes = {+ composer_unavailable: 'WebBrain could not find the conversation composer before this send. Read the conversation to confirm the message was actually sent.',+ };+ while (!decision.ok && WAIVABLE_CHAT_SEND_REASONS.includes(decision.reason) && !waive.has(decision.reason)+ && waiverNotes[decision.reason] && advise(waiverNotes[decision.reason])) {+ waive.add(decision.reason);+ decision = decideChatSend(observed.session, decisionSnapshot, context.messageRecipientBody, Date.now(), { waive });+ }if (!decision.ok) return { ...decision, ...blocked(decision.reason, decision.error) };if (!this._captureNativeWhatsappPending(tabId, decision, before, context.messageRecipientNativeChatBaseline)) {return blocked('native_chat_baseline_unavailable', 'The current native WhatsApp message baseline could not be saved safely. Nothing was sent.');@@ -29810,6 +30448,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d* Clear conversation for a tab.*/clearConversation(tabId, { preserveStorage = false } = {}) {+ this._guardRunStates.delete(tabId);this._failureRecovery.clear(tabId);this._cancelClarifications(tabId, 'conversation cleared');this._cancelUploadPickers(tabId, 'conversation cleared');@@ -29987,6 +30626,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvalueLength: response.valueLength,valueSha256: String(response.valueSha256).toLowerCase(),verified: response.verified === true,+ // false: the digest hashes the rendered text (innerText fallback).+ ...(typeof response.readbackExact === 'boolean' ? { readbackExact: response.readbackExact } : {}),fieldMeta: response.fieldMeta || null,// Element-derived revalidation locator (unique, content-checked);// consumed for focused proofs whose focus moves before submit.@@ -30029,7 +30670,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst documentToken = String(response?.documentToken || '');const pageUrl = String(response?.refScopeUrl || '');if (!documentToken && !pageUrl) return null;- return { documentToken, pageUrl };+ // A ref/selector probe also digests the field. An unverified write's+ // record keeps it, so no second probe is needed (see+ // _recordUnverifiedTextWrite).+ const digest = response?.success === true && Number.isInteger(response.valueLength) && response.valueLength >= 0+ && /^[0-9a-f]{64}$/i.test(String(response.valueSha256 || ''))+ ? {+ valueLength: response.valueLength,+ valueSha256: String(response.valueSha256).toLowerCase(),+ ...(typeof response.readbackExact === 'boolean' ? { readbackExact: response.readbackExact } : {}),+ fieldMeta: response.fieldMeta || null,+ }+ : null;+ return { documentToken, pageUrl, ...(digest ? { digest } : {}) };} catch {return null;}@@ -30314,8 +30967,222 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn liveScope;}- async _uncertainTextMutationBlock(tabId, name, args = {}) {+ /**+ * The latest text write to one editor that went out but could not be+ * verified. Default mode keeps this record instead of text-write debt and+ * never blocks on it (Strict checks record debt instead). It sits next to+ * the proof map so a commit or publication gate can show the user the+ * content and ask instead of refusing. No raw text is stored; the gate can+ * re-digest the live field and compare. Returns a copy, or null.+ *+ * Shape: {+ * key, // same key as the debt/proof maps: 'ax:<document>:<ref>', 'selector:…', 'focused:…'+ * locatorType, // 'ax' | 'selector' | 'focused'+ * refId, selector, // the write's locator (null when unused)+ * documentToken, pageUrl, // the document the write went to+ * tool, replacesValue, // set_field | type_ax | type_text; false for an append+ * expectedLength, expectedSha256, // the requested text (args.text)+ * observedLength, observedSha256, // live readback digest right after the write, or null+ * readbackExact, // false: that readback was the rendered-text (innerText) fallback; null: unknown+ * reason, // 'readback_mismatch' | 'readback_unproven' | 'element_replaced' | 'readback_unavailable'+ * // | 'page_handled_input' | 'paste_not_consumed' | 'input_unconfirmed' | 'outcome_unknown'+ * // | 'not_inserted' | 'trusted_retry_failed'+ * textSent, // true when the text went out (the result reported success)+ * fieldMeta, // field identity (id, name, labels, contentEditable, codeMirror, …)+ * taskToken, recordedAt, // the task that wrote it; epoch ms+ * }+ * `key` selects one editor. Without it, the newest record on `pageUrl`+ * (any page when empty) that passes `match(record)` wins. Records written+ * by another task are ignored.+ */+ _unverifiedTextWriteRecord(tabId, { key = '', pageUrl = '', match = null } = {}) {+ const records = this._unverifiedTextWrites?.get(tabId);+ if (!(records instanceof Map) || records.size === 0) return null;+ const taskToken = this._taskTokens?.get(tabId) || null;+ const candidates = key ? [records.get(key)] : [...records.values()].reverse();+ for (const record of candidates) {+ if (!record || (record.taskToken || null) !== taskToken) continue;+ if (pageUrl && this._normalizeUrl(record.pageUrl || '') !== this._normalizeUrl(pageUrl)) continue;+ if (typeof match === 'function' && match(record) !== true) continue;+ return { ...record, fieldMeta: record.fieldMeta ? { ...record.fieldMeta } : null };+ }+ return null;+ }++ /**+ * Which converted guard speaks for an uncertain text write in the current+ * mode (guard-policy.js), or null when Strict checks keep today's debt and+ * lock. `textSent`: the text went out and only its settled value is in+ * doubt, so the write is reported as an unverified success. Anything else+ * (an unknown outcome, a replacement that was not inserted) stays a+ * failure report, but locks nothing.+ */+ _textWriteAdvisory(name, args, result) {+ if (!this._guardAdvises('text-write-debt-arm', { decided: false })) return null;+ const unverified = result?.unverified && typeof result.unverified === 'object' ? result.unverified : null;+ const textSent = result.noDispatch !== true && (result.success === true || !!unverified);+ let guard = 'content-action-outcome-unknown';+ let reason = 'outcome_unknown';+ let decided = false;+ if (textSent) {+ guard = 'text-write-readback-unverified';+ reason = String(unverified?.reason || 'readback_unproven');+ // Only an exact reader that read a different value knows it is wrong.+ decided = reason === 'readback_mismatch' && result.readbackExact === true;+ } else if (result.verified === true) {+ // The value verified; a later step (a guarded or vetoed Enter) did not+ // complete. That step's own report stands; only the write lock goes.+ guard = 'text-write-debt-arm';+ reason = 'value_verified_step_incomplete';+ } else if (/no replacement text was inserted|could not be proven (?:empty|fully selected)/i.test(String(result.error || ''))) {+ guard = 'text-write-preinsert-unproven';+ reason = 'not_inserted';+ } else if (result.trustedFallbackAttempted === true) {+ guard = 'trusted-field-retry-guards';+ reason = 'trusted_retry_failed';+ }+ if (!this._guardAdvises(guard, { decided })) return null;+ return { guard, reason, decided, textSent };+ }++ // The model's note for an advised text write: what is unconfirmed and+ // what to check. It never asks for a blind retry; appends are warned+ // about duplicates because their text may already have landed.+ _textWriteAdvisoryNote(name, args, result, advisory) {+ const append = !this._textMutationReplacesValue(name, args);+ const duplicate = append ? ' This was an append: repeating it can add the text twice, so fix the field with one full replacement.' : '';+ if (advisory.textSent) {+ const lead = {+ element_replaced: 'Text sent, but the field re-rendered before it could be read back.',+ readback_unavailable: 'Text sent, but the editor could not be read back.',+ page_handled_input: 'The page applied the text itself; the result could not be read back exactly.',+ paste_not_consumed: 'Text pasted, but the editor did not confirm it handled the paste.',+ input_unconfirmed: 'Text reads back correctly, but the page did not confirm the input finished.',+ }[advisory.reason] || (result.readbackExact === false+ ? 'Text sent, but this editor only reads back its rendered layout (blank lines can show doubled, off-screen lines missing), so it is unconfirmed. Do not rewrite it to match that readback.'+ : result.readbackExact === true+ ? 'Text sent, but the field reads back a different value.'+ : 'Text sent, but its final value could not be read back exactly.');+ const submit = result.submitSkipped === 'value_unverified'+ ? ' The field was written but its submit was NOT sent; submit separately once the value is right.' : '';+ return `${lead} Check the field before relying on it.${submit}${append && !submit ? duplicate : ''}`;+ }+ if (advisory.reason === 'value_verified_step_incomplete') {+ return 'The field value was verified, but the step after it did not complete (see error). Nothing is locked: observe the page before acting again.';+ }+ if (advisory.guard === 'text-write-preinsert-unproven') {+ return 'The field could not be proven empty or fully selected, so the new text was not inserted and part of the old value may be gone. Nothing is locked: re-read the field before writing it.';+ }+ if (advisory.guard === 'trusted-field-retry-guards') {+ return `Trusted typing could not finish (see error), so the field may or may not have changed. Nothing is locked: re-read it before writing again.${duplicate}`;+ }+ return `This write may or may not have reached the page. Nothing is locked: re-read the field before writing again.${duplicate}`;+ }++ // Default-mode shape of an uncertain text write. The lock labels go+ // (default mode arms no lock), and so does the content failureScope, so+ // the loop detector does not count the write as a failed target. A write+ // whose text went out reports success with unverifiedWrite and a note.+ _advisoryTextWriteResult(name, args, result, advisory, { expectedLength, expectedSha256 }) {+ const out = { ...result };+ delete out.repeatBlocked;+ if (out.recoveryRequired === 'verify_or_restore_field') delete out.recoveryRequired;+ delete out.failureScope;+ delete out._expectedValue;+ if (advisory.textSent) {+ for (const field of ['error', 'noDispatch', 'outcomeUnknown', 'mutationMayHaveOccurred', 'retryable', 'trustedTypeRequired']) {+ delete out[field];+ }+ // `verified` stays as the readback reported it: false when it read a+ // different value, absent when it could not prove one (an unproven+ // write is not a refuted one; see cdp-client verifyTextEntry).+ Object.assign(out, { success: true, dispatched: true, unverifiedWrite: true });+ out.unverified = result.unverified && typeof result.unverified === 'object'+ ? result.unverified : { reason: advisory.reason, reader: 'unknown' };+ if (advisory.reason === 'page_handled_input') {+ // The page cancelled the native input and applied it itself; this is+ // not a cancelled action.+ delete out.cancelled;+ out.pageHandledBeforeInput = true;+ }+ // The bundled submit was withheld for the unverified value (content and+ // trusted paths both send Enter only after exact verification).+ if (name === 'set_field' && args?.submit === true && out.submitted !== true) {+ out.submitted = false;+ out.submitSkipped = 'value_unverified';+ }+ } else {+ Object.assign(out, { success: false, outcomeUnknown: true, mutationMayHaveOccurred: true });+ }+ out.expectedLength = expectedLength;+ out.expectedSha256 = expectedSha256;+ const advisories = [];+ this._guardAdvisesFor(advisories, advisory.guard, this._textWriteAdvisoryNote(name, args, out, advisory),+ { decided: advisory.decided });+ return withGuardAdvisories(out, advisories);+ }++ // Default mode: record an uncertain write without a lock (see+ // _unverifiedTextWriteRecord) and return its advisory result. The caller+ // has already invalidated proofs exactly as Strict checks do, so an+ // unverified readback never stands in for a verified one.+ async _recordUnverifiedTextWrite(tabId, name, args, result, advisory,+ { target, replacesValue, text, expectedSha256, enrich, liveDigest = null }) {+ let observed = liveDigest;+ if (!observed && target.locatorType === 'focused') {+ try {+ observed = await enrich(() => this._textMutationValueDigest(tabId, { locatorType: 'focused', ambiguous: false }));+ } catch { observed = null; }+ }+ if (!this._unverifiedTextWrites) this._unverifiedTextWrites = new Map();+ let records = this._unverifiedTextWrites.get(tabId);+ if (!(records instanceof Map)) {+ records = new Map();+ this._unverifiedTextWrites.set(tabId, records);+ }+ records.delete(target.key);+ records.set(target.key, {+ key: target.key,+ locatorType: target.locatorType,+ refId: target.refId ?? null,+ selector: target.selector ?? null,+ documentToken: target.documentToken || '',+ pageUrl: target.pageUrl || '',+ tool: name,+ replacesValue,+ expectedLength: text.length,+ expectedSha256,+ observedLength: Number.isInteger(observed?.valueLength) ? observed.valueLength : null,+ observedSha256: typeof observed?.valueSha256 === 'string' ? observed.valueSha256 : null,+ readbackExact: typeof result.readbackExact === 'boolean' ? result.readbackExact+ : typeof observed?.readbackExact === 'boolean' ? observed.readbackExact : null,+ reason: advisory.reason,+ textSent: advisory.textSent,+ fieldMeta: result.fieldMeta || observed?.fieldMeta || null,+ taskToken: this._taskTokens?.get(tabId) || null,+ recordedAt: Date.now(),+ });+ // Bounded: one entry per edited field; the oldest field yields first.+ while (records.size > 32) records.delete(records.keys().next().value);+ return this._advisoryTextWriteResult(name, args, result, advisory, { expectedLength: text.length, expectedSha256 });+ }++ // Default mode: a write to a field whose last write went out unverified+ // proceeds. Only an append is noted, because its earlier text may already+ // be in the field; a repeated replacement is idempotent.+ _notePriorUnverifiedTextWrite(tabId, name, args, advisories) {+ if (!Array.isArray(advisories) || this._textMutationReplacesValue(name, args)) return;+ const target = this._textMutationTarget(tabId, name, args);+ const prior = this._unverifiedTextWriteRecord(tabId, { key: target.key });+ if (!prior || (prior.documentToken && target.documentToken && prior.documentToken !== target.documentToken)) return;+ this._guardAdvisesFor(advisories, 'text-write-debt-block',+ 'An earlier write to this field was not verified and may already be in it, so this append can duplicate text. Read the field and fix it with one full replacement if needed.',+ { decided: false });+ }++ async _uncertainTextMutationBlock(tabId, name, args = {}, { advisories = null } = {}) {if (!['set_field', 'type_ax', 'type_text'].includes(name)) return null;+ this._notePriorUnverifiedTextWrite(tabId, name, args, advisories);const debts = this._uncertainTextMutations?.get(tabId);if (!(debts instanceof Map) || debts.size === 0) return null;let target = this._textMutationTarget(tabId, name, args);@@ -30454,7 +31321,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d&& !this._textMutationFieldsProvenDistinct(debt.fieldMeta, original.fieldMeta)) {debts.delete(debt.key);if (debts.size === 0) this._uncertainTextMutations.delete(tabId);- return debts.size ? this._uncertainTextMutationBlock(tabId, name, args) : null;+ return debts.size ? this._uncertainTextMutationBlock(tabId, name, args, { advisories }) : null;}}// Readback-only recovery requires positive same-field identity. The@@ -30567,6 +31434,16 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (!debt) return null;}+ // Default mode: the earlier uncertain write is reported, never a lock+ // (guard-policy.js; default mode records no debt, so this one was left+ // by Strict checks). The recovery shortcuts above still answer an exact+ // repeat that already reads back. A replacement is idempotent; an+ // append may duplicate text.+ if (this._guardAdvisesFor(advisories, 'text-write-debt-block', replacement+ ? 'An earlier write to this field was not verified; this replacement went ahead. Check the field before relying on it.'+ : 'An earlier write to this field was not verified and may already be in it, so this append can duplicate text. Read the field and fix it with one full replacement if needed.',+ { decided: false })) return null;+return {success: false,dispatched: false,@@ -30617,8 +31494,10 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Refresh to the live scope before recording (adopting clears// old-document debts/proofs through the document-change path when both// tokens exist), then re-derive the target below.+ let liveDigest = null;try {const liveScope = await enrich(() => this._liveTextMutationScope(tabId, name, args));+ liveDigest = liveScope?.digest || null;if (liveScope && (liveScope.documentToken || liveScope.pageUrl)) {const cachedScope = this._lastAxScopes.get(tabId) || {};if (String(liveScope.documentToken || '') !== String(cachedScope.documentToken || '')@@ -30632,6 +31511,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}}} catch { /* an unreachable page keeps the cached scope below */ }+ // Proofs are invalidated in every mode: an unverified readback never+ // stands in for a verified one (the GitHub commit gate relies on it).const verifiedReplacements = this._verifiedTextReplacements.get(tabId);if (verifiedReplacements instanceof Map) {if (target.ambiguous) verifiedReplacements.clear();@@ -30643,6 +31524,15 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}} else verifiedReplacements.delete(target.key);}+ // Quality guards advise by default (guard-policy.js): the write is+ // reported (as an unverified success when its text went out) and kept+ // as a non-blocking record instead of debt that refuses later writes.+ // Strict checks fall through to today's debt and lock.+ const advisory = this._textWriteAdvisory(name, args, result);+ if (advisory) {+ return this._recordUnverifiedTextWrite(tabId, name, args, result, advisory,+ { target, replacesValue, text, expectedSha256, enrich, liveDigest });+ }if (!this._uncertainTextMutations) this._uncertainTextMutations = new Map();let debts = this._uncertainTextMutations.get(tabId);if (!(debts instanceof Map)) {@@ -30777,6 +31667,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout delse verifiedReplacements.delete(target.key);}}+ // A verified write supersedes the field's earlier unverified one.+ if (result.success === true && result.verified === true) this._unverifiedTextWrites?.get(tabId)?.delete(target.key);return result;}@@ -30817,6 +31709,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dvoid this._steeringJournal.discard(tabId);}this._verifiedTextReplacements.delete(tabId);+ // Task-scoped like the proofs it sits beside; it never guarded anything.+ this._unverifiedTextWrites?.delete(tabId);this.progressPageScopes.delete(tabId);this.progressSessions.delete(tabId);this.progressExpectedItems.delete(tabId);@@ -34369,7 +35263,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// completion judge or the done_summary question); a failed or partial// done may describe what the user still has to do.const runtimeModeContradiction = summaryKind === 'mode_claim';- const looksPlanOnly = this._isStructuredPlanTerminal(content, state)+ const structuredPlan = this._isStructuredPlanTerminal(content, state);+ const looksPlanOnly = structuredPlan|| (summaryKind === 'plan_only' && !terminalFailure) || runtimeModeContradiction;const staleCancellation = !viaDone && this._isLocalCancellationText(content);const missingRequiredSchedulingTool = !terminalFailure@@ -34405,6 +35300,60 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst invalidPlainFinal = !viaDone;const invalidDone = viaDone && (looksPlanOnly || missingEvidence || missingRequiredLedger);if (!invalidPlainFinal && !invalidDone) return null;+ const modeCorrectionNudge = '[RUNTIME MODE CORRECTION: The trusted runtime for this run is Act/Dev, not Ask mode or a read-only mode. Page-changing tools are available. Continue the authorized task with the permitted tools now. If a required value is missing, call clarify without modifying that field. If a genuine blocker remains, call done with outcome partial or failed and explain the concrete blocker without contradicting the trusted runtime mode.]' + recoveryAnchor;+ const recoveryNudge = () => (state.taskDrifted+ ? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'+ : state.conditionalMutationBlocked+ ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]'+ : staleCancellation+ ? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]'+ : missingRequiredSchedulingTool+ ? `[PLAN EXECUTION BLOCK: The approved plan requires a successful ${state.requiredSchedulingTool} call before this task can finish successfully. A one-time read, scroll, send, or other action does not create the scheduled work. Call ${state.requiredSchedulingTool} with the user's requested timing and verify success:true plus scheduled:true. If the schedule is unsupported or still lacks required timing, call done with outcome partial or failed and explain the exact limitation; do not claim it was scheduled.]`+ : missingRequiredDownload+ ? '[PLAN EXECUTION BLOCK: This task requires a file to be downloaded before it can finish successfully. Finding a URL, link, button, or media source is only read evidence. Use an authorized tool call with the DOWNLOAD capability and verify that it returned successful download evidence. If permission is denied or no file can be saved, call done with outcome partial or failed and explain the limitation; do not claim the file was downloaded.]'+ : missingSocialPublishTargets.length+ ? `[PLAN EXECUTION BLOCK: This task requests publication on every named social destination, but job-bound terminal evidence is still missing for: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. Continue with those destinations and verify each published resource before calling done again. Do not republish on a destination already verified in this run.]`+ : missingRequiredSubmission+ ? (this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own publication. ${this._workflowPublicationRecoveryInstruction(state)}]`+ : state.siteWorkflow?.job?.id+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own submit/send/publish/commit contract. Filling fields, another site's submit, or an unrelated success signal is not completion. Dispatch the intended action and observe the job-specific terminal state (for example recipient-bound sent state, saved/published resource, form confirmation, or paid/ticket-issued transaction) before calling done again. If that cannot be verified, use outcome partial or failed and report the exact blocker.]`+ // No site workflow was selected, so there is no job contract to+ // point at.+ : '[PLAN EXECUTION BLOCK: This task requires a submit/send/publish/commit action, and the page state read at completion does not yet show it took effect. No structured site workflow is bound to this run. Read the page that resulted from the action — the published item, the confirmation, or the changed state — in the same browser tab, then call done from there. If the action cannot be confirmed, use outcome partial or failed and report the exact blocker.]')+ : forbiddenSubmission+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job prepares the form and leaves it unsubmitted, but a submit action was dispatched. Do not submit again or try to undo it by submitting anything else. Call done with outcome partial or failed, state plainly that the form was submitted without authorization, and report what the page shows now.]`+ : missingJobEvidence+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job has its own success contract and an unrelated page read does not satisfy it. ${this._workflowJobEvidenceInstruction(state)} Produce that evidence, then call done. If it cannot be produced, call done with outcome partial or failed and report the exact blocker with whatever partial coverage you did verify.]`+ : missingDraftEvidence+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job finishes on the draft itself, not on a tool call. The intended recipients, the requested subject, and the complete body must all be readable in the open composer, and the provider must show its own saved-draft state. Re-read the composer once the app has saved the draft, then call done. If any field or the saved-draft state cannot be verified, call done with outcome partial or failed and report exactly what is unverified; do not send the message.]`+ : missingRequiredLedger+ ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} site workflow requires complete item-level reconciliation before success. Obtain a complete app-owned workflow inventory, use its exact item ids for one processed or intentionally skipped ledger row per item, then call progress_update with workflowReconciliation {job:"${state.siteWorkflow.job.id}", coverageComplete:true, itemCount:N, basis:"..."}. N and the row ids must exactly match that inventory; model-created rows alone are not coverage evidence, and any failed row requires a partial or failed outcome. If complete coverage cannot be verified, call done with outcome partial or failed and report completed versus unresolved work.]`+ : unknownMutationIntent+ ? '[PLAN EXECUTION BLOCK: Planning failed, so the runtime could not determine whether this task requires a state change. Continue with normally permitted tools. A success outcome now requires a verified consequential tool call; if the useful result is read-only or no safe consequential action is needed, deliver that result with done outcome partial instead of claiming success. Do not invent or perform a mutation merely to satisfy this guard.]'+ : defaultPlanExecutionBlockNudge({+ viaDone,+ missingEvidence,+ requiresStateChange: state.requiresStateChange,+ })) + recoveryAnchor;+ // By default (Strict checks off) each finding behind this refusal gives+ // its note once per run, and the next completion is accepted with a+ // caveat. The one-nudge budget and run-ending statuses below are the+ // strict path.+ const advisory = this._planGuardAdvisory(tabId, state, { viaDone, looksPlanOnly, runtimeModeContradiction,+ structuredPlan: structuredPlan+ || (state.allowsPlannerShapedResult !== true && this._isPlannerShapedJson(content)),+ staleCancellation, missingRequiredSchedulingTool, missingRequiredDownload, missingRequiredSubmission,+ forbiddenSubmission, missingJobEvidence, missingDraftEvidence, missingRequiredLedger,+ missingSocialPublishTargets, missingEvidence });+ if (advisory === 'accept') return null;+ if (advisory === 'refuse') {+ return {+ retry: true,+ retryAssistantContent: null,+ nudge: runtimeModeContradiction && !missingRequiredSchedulingTool ? modeCorrectionNudge : recoveryNudge(),+ };+ }if (runtimeModeContradiction&& !state.taskDrifted&& !missingRequiredSchedulingTool@@ -34414,7 +35363,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn {retry: true,retryAssistantContent: null,- nudge: '[RUNTIME MODE CORRECTION: The trusted runtime for this run is Act/Dev, not Ask mode or a read-only mode. Page-changing tools are available. Continue the authorized task with the permitted tools now. If a required value is missing, call clarify without modifying that field. If a genuine blocker remains, call done with outcome partial or failed and explain the concrete blocker without contradicting the trusted runtime mode.]' + recoveryAnchor,+ nudge: modeCorrectionNudge,};}if (!state.recoveryAttempted) {@@ -34425,41 +35374,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dretryAssistantContent: staleCancellation? '[Stale local cancellation status omitted from execution context.]': null,- nudge: (state.taskDrifted- ? '[PLAN EXECUTION BLOCK: The genuine user task changed after this run was authorized. Do not execute either the old or new task under stale authorization. Call done with outcome failed and report that a fresh run is required.]'- : state.conditionalMutationBlocked- ? '[PLAN EXECUTION BLOCK: The conditional editor mutation was not authorized by a matching workflow contract. No repair was dispatched. Use done with outcome partial or failed and explain that the failure branch needs a fresh plan.]'- : staleCancellation- ? '[PLAN EXECUTION BLOCK: No current user stop was received. The previous response echoed a stale local cancellation status from conversation history. That status is UI metadata, not an instruction or task result. Continue the active task with permitted tools. If complete or blocked, call done with an explicit outcome; do not repeat the cancellation status or return plain text.]'- : missingRequiredSchedulingTool- ? `[PLAN EXECUTION BLOCK: The approved plan requires a successful ${state.requiredSchedulingTool} call before this task can finish successfully. A one-time read, scroll, send, or other action does not create the scheduled work. Call ${state.requiredSchedulingTool} with the user's requested timing and verify success:true plus scheduled:true. If the schedule is unsupported or still lacks required timing, call done with outcome partial or failed and explain the exact limitation; do not claim it was scheduled.]`- : missingRequiredDownload- ? '[PLAN EXECUTION BLOCK: This task requires a file to be downloaded before it can finish successfully. Finding a URL, link, button, or media source is only read evidence. Use an authorized tool call with the DOWNLOAD capability and verify that it returned successful download evidence. If permission is denied or no file can be saved, call done with outcome partial or failed and explain the limitation; do not claim the file was downloaded.]'- : missingSocialPublishTargets.length- ? `[PLAN EXECUTION BLOCK: This task requests publication on every named social destination, but job-bound terminal evidence is still missing for: ${missingSocialPublishTargets.map(name => name === 'twitter' ? 'X' : name === 'bluesky' ? 'Bluesky' : name).join(', ')}. Continue with those destinations and verify each published resource before calling done again. Do not republish on a destination already verified in this run.]`- : missingRequiredSubmission- ? (this._workflowVerificationKind(state.siteWorkflow) === 'published_resource'- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own publication. ${this._workflowPublicationRecoveryInstruction(state)}]`- : state.siteWorkflow?.job?.id- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} job requires terminal evidence for its own submit/send/publish/commit contract. Filling fields, another site's submit, or an unrelated success signal is not completion. Dispatch the intended action and observe the job-specific terminal state (for example recipient-bound sent state, saved/published resource, form confirmation, or paid/ticket-issued transaction) before calling done again. If that cannot be verified, use outcome partial or failed and report the exact blocker.]`- // No site workflow was selected, so there is no job contract to- // point at.- : '[PLAN EXECUTION BLOCK: This task requires a submit/send/publish/commit action, and the page state read at completion does not yet show it took effect. No structured site workflow is bound to this run. Read the page that resulted from the action — the published item, the confirmation, or the changed state — in the same browser tab, then call done from there. If the action cannot be confirmed, use outcome partial or failed and report the exact blocker.]')- : forbiddenSubmission- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job prepares the form and leaves it unsubmitted, but a submit action was dispatched. Do not submit again or try to undo it by submitting anything else. Call done with outcome partial or failed, state plainly that the form was submitted without authorization, and report what the page shows now.]`- : missingJobEvidence- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job has its own success contract and an unrelated page read does not satisfy it. ${this._workflowJobEvidenceInstruction(state)} Produce that evidence, then call done. If it cannot be produced, call done with outcome partial or failed and report the exact blocker with whatever partial coverage you did verify.]`- : missingDraftEvidence- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow?.job?.id || 'workflow'} job finishes on the draft itself, not on a tool call. The intended recipients, the requested subject, and the complete body must all be readable in the open composer, and the provider must show its own saved-draft state. Re-read the composer once the app has saved the draft, then call done. If any field or the saved-draft state cannot be verified, call done with outcome partial or failed and report exactly what is unverified; do not send the message.]`- : missingRequiredLedger- ? `[PLAN EXECUTION BLOCK: The selected ${state.siteWorkflow.job.id} site workflow requires complete item-level reconciliation before success. Obtain a complete app-owned workflow inventory, use its exact item ids for one processed or intentionally skipped ledger row per item, then call progress_update with workflowReconciliation {job:"${state.siteWorkflow.job.id}", coverageComplete:true, itemCount:N, basis:"..."}. N and the row ids must exactly match that inventory; model-created rows alone are not coverage evidence, and any failed row requires a partial or failed outcome. If complete coverage cannot be verified, call done with outcome partial or failed and report completed versus unresolved work.]`- : unknownMutationIntent- ? '[PLAN EXECUTION BLOCK: Planning failed, so the runtime could not determine whether this task requires a state change. Continue with normally permitted tools. A success outcome now requires a verified consequential tool call; if the useful result is read-only or no safe consequential action is needed, deliver that result with done outcome partial instead of claiming success. Do not invent or perform a mutation merely to satisfy this guard.]'- : defaultPlanExecutionBlockNudge({- viaDone,- missingEvidence,- requiresStateChange: state.requiresStateChange,- })) + recoveryAnchor,+ nudge: recoveryNudge(),};}if (state.taskDrifted) {@@ -37299,6 +38214,14 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._throwIfAborted(linked.signal);return { success: false, botMemory: true, noDispatch: true, dispatched: false, error: error.message };}+ // A done that memory refuses because an action's outcome is still+ // uncertain is advised once per run by default; then it goes through+ // with a caveat, and the memory ledger keeps that action uncertain.+ if (prepared.allowed !== true && ['done', 'done_json'].includes(name)+ && !this._guardRefusesOnce(tabId, 'bot-memory-uncertain-done', { decided: false,+ caveat: 'An earlier action\'s result was still uncertain when the task was reported done.' })) {+ prepared = { allowed: true, readOnly: true };+ }if (prepared.allowed !== true) return { success: false, botMemory: true, noDispatch: true,dispatched: false, retryable: false, ...(['done', 'done_json'].includes(name) ? { blockedDone: true } : {}), error: prepared.reason };// Memory acknowledgement adds a prerequisite. The current permission,@@ -37318,6 +38241,17 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}async _executeToolWithLifecycle(tabId, name, args, onUpdate = null, executionContext = null) {+ // Quality guards that advise instead of refusing leave their notes in+ // this call's list; the result carries them to the model.+ const guardAdvisories = Array.isArray(executionContext?.guardAdvisories) ? executionContext.guardAdvisories : [];+ const result = await this._executeToolWithLifecycleInner(tabId, name, args, onUpdate, { ...(executionContext || {}), guardAdvisories });+ // A note says what went through despite a check. When another check+ // then refused the call, nothing went through and the note would mislead.+ const refused = !!result && typeof result === 'object' && (result.noDispatch === true || result.dispatched === false);+ return refused ? result : withGuardAdvisories(result, guardAdvisories);+ }++ async _executeToolWithLifecycleInner(tabId, name, args, onUpdate = null, executionContext = null) {const linked = this._linkAbortSignals(executionContext?._contentActionAbortSignal, this._runAbortSignal(tabId));const dispatchState = executionContext?._contentActionDispatchState || { started: false };// Every text-write route marks dispatch before content messaging or CDP input.@@ -37333,9 +38267,21 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (executionContext?.jevBinding) {const probe = await browser.tabs.sendMessage(tabId, { target: 'content', action: 'jev_validate_target', params: { _jevBinding: executionContext.jevBinding } }, { frameId: 0 });this._throwIfAborted(linked.signal);- if (probe?.success !== true) return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Jev target changed; observe again before acting.' };+ if (probe?.success !== true) {+ if (!this._guardAdvisesFor(executionContext.guardAdvisories, 'jev-target-changed', JEV_TARGET_CHANGED_NOTE,+ { decided: probe?.staleJevTarget === true })) {+ return { success: false, noDispatch: true, dispatched: false, staleJevTarget: true, error: 'Jev target changed; observe again before acting.' };+ }+ // Without Strict checks the fast-path call goes to whatever its+ // ref or selector resolves to now, through the ordinary tool path+ // and its checks; the stale binding would only refuse it again.+ executionContext = { ...executionContext, jevBinding: null };+ }}- const uncertainTextBlock = await this._uncertainTextMutationBlock(tabId, name, args || {});+ // Default mode only notes an earlier unverified write (the call's+ // guardAdvisories); Strict checks still refuse it here.+ const uncertainTextBlock = await this._uncertainTextMutationBlock(tabId, name, args || {},+ { advisories: executionContext.guardAdvisories });if (uncertainTextBlock) return uncertainTextBlock;const result = await this._executeToolImpl(tabId, name, args, onUpdate, executionContext);return await this._finalizeToolResultOnce(tabId, name, args, result, dispatchState);@@ -37601,7 +38547,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Who receives a message is never settled by a question and its answer:// WebBrain confirms the send with the user on its own card. A question// declared to be about the recipient cannot repair a technical blocker.- if (technicalRecipientReason && explicitRecipientQuestion) {+ // Asking it is harmless (the send stays guarded), so without Strict+ // checks the question is shown with a note.+ if (technicalRecipientReason && explicitRecipientQuestion+ && !this._guardAdvisesFor(executionContext?.guardAdvisories, 'recipient-clarify-cannot-repair-technical',+ `The user's answer cannot supply the page evidence the message guard is missing (${technicalRecipientReason}); a send still needs that evidence or WebBrain's own recipient card. Re-read the recipient and composer after the answer.`)) {return { success: false, blocked: true, noDispatch: true, dispatched: false, retryable: false,messageRecipientGuard: true, reasonCode: technicalRecipientReason,error: 'Recipient confirmation cannot repair the unresolved technical message guard. No clarification was shown. Re-read the active recipient and composer evidence; if it remains unavailable, report the blocker instead of requesting the same approval again.' };@@ -37902,7 +38852,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dconst nonMonotonic = previousState && (traversalDirection === 'reverse'? target.requestedIndex >= previousState.minVerifiedIndex: target.requestedIndex <= previousState.maxVerifiedIndex);- if (nonMonotonic) {+ // carousel-traversal-guards (quality): revisiting a slide is navigation,+ // not a repeat of a consequential action. Without Strict checks it runs+ // with a note; the post-navigation route and media checks still report.+ if (nonMonotonic && !this._guardAdvisesFor(executionContext?.guardAdvisories, 'carousel-traversal-guards',+ traversalDirection === 'reverse'+ ? `This reversed carousel scan already processed slides down to ${previousState.minVerifiedIndex}; slide ${target.requestedIndex} was opened anyway. Do not record it again as a new row.`+ : `This forward carousel scan already processed slides up to ${previousState.maxVerifiedIndex}; slide ${target.requestedIndex} was opened anyway. Do not record it again as a new row.`)) {return {success: false, dispatched: false, noDispatch: true, nonMonotonic: true,requestedIndex: target.requestedIndex, highestVerifiedIndex: previousState.maxVerifiedIndex,@@ -37990,7 +38946,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d});const expected = this.progressExpectedItems.get(tabId);const session = this._currentProgressSession(tabId);- if (expected && session?.sessionId) {+ // An advised revisit of an already processed slide must not reset its+ // ledger row back to "acted".+ if (expected && session?.sessionId && !nonMonotonic) {const discoveredSlideCount = afterState.discoveredSlideCount;const hasCover = discoveredSlideCount === expected.count + 1|| (/hotel/i.test(expected.item_type)@@ -39025,11 +39983,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// What the page's live messages and the statuses observed after the// submit say, read in any language for the checks below. Success// messages are only ever the agent's own readings, never page data.- const incompleteBlock = await incompleteCompletionBlock(this, tabId, {+ // By default the incomplete-task judge redirects an honest partial or+ // failed ending once per run; later endings are not judged again.+ const incompleteBlock = this._guardHasAdvised(tabId, 'incomplete-task-redirect') ? null : await incompleteCompletionBlock(this, tabId, {terminalOnly: Number.isFinite(executionContext?.traceStep) && executionContext.traceStep >= this.maxSteps,outcome, summary: args.summary, pageState, pageUrl: pageState?.url || '',});- if (incompleteBlock) return incompleteBlock;+ if (incompleteBlock && this._incompleteRedirectRefuses(tabId, incompleteBlock)) return incompleteBlock;const readingStartedAt = Date.now();if (outcome === 'success' && pageState) await this._readCompletionFormSubmits(tabId, pageState);if (outcome === 'success' && pageState) await this._readCompletionStatusTexts(tabId, pageState);@@ -39039,7 +39999,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dthis._recordDoneTiming(tabId, { preparationMs: readingStartedAt - doneStartedAt,readingMs: verificationStartedAt - readingStartedAt, verificationMs: Date.now() - verificationStartedAt,...(completionDecision ? { outcome: completionDecision.outcome, engine: completionDecision.engine } : {}) });- if (completionDecision && ['pending', 'failed'].includes(completionDecision.outcome)) return { success: false, blockedDone: true, completionDecision: { outcome: completionDecision.outcome, engine: completionDecision.engine }, error: 'Completion verification reports ' + completionDecision.outcome + '. Inspect the result before any further submission; continue recovery or report partial/failed.' };+ if (completionDecision && ['pending', 'failed'].includes(completionDecision.outcome)+ && this._completionVerdictRefuses(tabId, completionDecision)) return { success: false, blockedDone: true, completionDecision: { outcome: completionDecision.outcome, engine: completionDecision.engine }, error: 'Completion verification reports ' + completionDecision.outcome + '. Inspect the result before any further submission; continue recovery or report partial/failed.' };if (pageState?.nativeChatDeliveryEvidence) {delete pageState.nativeChatDeliveryEvidence;this._planExecutionGuards.get(tabId).nativeChatDeliveryEvidence = null;@@ -39052,7 +40013,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (outcome === 'success' && pageState) pageState.iframeSubmissionEvidence = await this._completionIframeEvidence(tabId);if (outcome === 'success' && this._currentCompletionSubmitState(tabId)?.iframeSubmission&& (!pageState?.iframeSubmissionEvidence || (completionDecision?.outcome === 'succeeded'- && completionDecision.submittedFrameStamp !== pageState.iframeSubmissionEvidence.stamp))) {+ && completionDecision.submittedFrameStamp !== pageState.iframeSubmissionEvidence.stamp))+ && this._iframeResultStaleRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The submitted iframe changed or could not be refreshed at completion. Read its current result again; do not repeat the submission.' };}@@ -39168,18 +40130,19 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// search/filter bar, not a submit form).if (completionWarning) {const blocks = this._nextCompletionPageBlock(tabId, completionPageBlock.key);- if (blocks <= 2) {+ if (this._completionPageWarningRefuses(tabId, completionPageBlock.key) && blocks <= 2) {return {success: false,blockedDone: true,completionPageBlock: true,- error: verification.completionWarning + ` (block attempt ${blocks}/2 — if you genuinely believe the task is complete and the visible form/dialog is unrelated, re-call done with summary explicitly acknowledging this, e.g. "already-existing product, no submit needed".)`,+ error: verification.completionWarning + this._completionPageWarningSuffix(blocks),pageUrl: verification.pageUrl,pageState: verification.pageState,...(dataUrl ? { _attachImage: dataUrl } : {}),};}- // After 2 blocks, let done through with a loud note in verification.+ // After 2 blocks (by default after one), let done through with a loud+ // note in verification.}// A request that also expects votes or moderation to go a certain way// asks for something no run can verify. The completion judge reads that@@ -39193,7 +40156,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait trace.recordScreenshot(runId, null, dataUrl, 'done verification');}- if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)) {+ if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)+ && this._calculationRefreshRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The verified calculation authority changed before completion. Reconsider the current genuine task; no new action was performed.' };}@@ -39210,7 +40174,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// Screenshot failed — still allow done but note it}}- if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)) {+ if (calculationEvidence && !await refreshCalculationEvidence(this, tabId, calculationEvidence)+ && this._calculationRefreshRefuses(tabId)) {return { success: false, blockedDone: true, completionDecision: { outcome: 'pending', engine: 'freshness' },error: 'The verified calculation authority changed before completion. Reconsider the current genuine task; no new action was performed.' };}@@ -40451,7 +41416,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout drecommendationKind: result.recommendation?.kind || null,};};- const runDomDownloader = async () => {+ const runDomDownloader = async ({ bound = true } = {}) => {// Inject the SocialMediaDownloader library into the page (isolated// content-script world — Firefox MV2 has no MAIN-world option for// executeScript). The script defines window.SocialMediaDownloader,@@ -40468,7 +41433,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dlimit: typeof toolArgs.limit === 'number' && toolArgs.limit > 0? toolArgs.limit: (bulkSocialDownload ? Number.MAX_SAFE_INTEGER : 1),- ...(executionContext?._expectedMediaBinding ? { expectedMediaBinding: executionContext._expectedMediaBinding } : {}),+ ...(bound && executionContext?._expectedMediaBinding ? { expectedMediaBinding: executionContext._expectedMediaBinding } : {}),+ // An advised unbound retry of a bound call stays on the DOM item path.+ ...(!bound && executionContext?._expectedMediaBinding ? { domOnly: true } : {}),};const code = `(async () => {@@ -40491,7 +41458,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d// tell the agent to call saveMse() when there's actually// a capture worth saving.let mseBytes = 0;- try {+ // An advised unbound retry of a bound call stays on the DOM+ // item path, so a recorded stream is neither saved nor offered.+ if (!runOpts.domOnly) try {const rec = window.SocialMediaDownloader.getMseRecording();for (const ms of (rec.mediaSources || [])) {for (const b of (ms.buffers || [])) mseBytes += (b.bytes || 0);@@ -40594,7 +41563,20 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dtry {// A bound call must never switch resources through MSE or vision fallback.- if (executionContext?._expectedMediaBinding) return await runDomDownloader();+ if (executionContext?._expectedMediaBinding) {+ const boundResult = await runDomDownloader();+ // The focused media changed after the model observed it. Without+ // Strict checks the download runs once more without that binding+ // (still DOM-only, one item) and the model is told what it saved+ // may not be the item it saw.+ if (boundResult?.errorCode === 'media_binding_changed'+ && this._guardAdvisesFor(executionContext?.guardAdvisories, 'media-download-target-binding',+ 'The media in focus changed after your last observation, so WebBrain could not confirm this download is the item you saw. It saved the media now in focus; check the downloaded file (list_downloads) before reporting it.')) {+ this._throwIfAborted?.(executionContext?._contentActionAbortSignal || null);+ return await runDomDownloader({ bound: false });+ }+ return boundResult;+ }const strategy = ['auto', 'dom', 'vision'].includes(toolArgs.strategy) ? toolArgs.strategy : 'auto';const bulkSocialDownload = !!toolArgs.scroll || toolArgs.mode === 'all';const activeProvider = this.providerManager.getActive();@@ -41028,7 +42010,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}if (this._formValidationBlocks.has(tabId)) {const currentStates = await this._captureFormValidationState(tabId);- this._applyVerifyFormRecovery(tabId, result, currentStates);+ this._applyVerifyFormRecovery(tabId, result, currentStates, executionContext?.guardAdvisories);}return result;} catch (e) {@@ -41624,6 +42606,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dmessageRecipientDispatchBinding,expectedName: args.expected_name,expectedRole: args.expected_role,+ guardAdvisories: dispatchContext.guardAdvisories,}, contentPipelineAbortSignal);if (reconciled.result) return reconciled.result;coordinateDiagnostic = reconciled.diagnostic;@@ -41641,7 +42624,12 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dif (name === 'type_text' && args?.selector && !dispatchBinding?.token) {const probe = await this._probeRichTextToolbarRetryTarget(tabId, name, args, { mapAnnotation: false });dispatchBinding = probe?.dispatchBinding || null;- if (!dispatchBinding?.token) {+ // The element checked before typing could not be pinned. By default+ // (typing-target-identity advises) the content handler types into the+ // selector's current match without a binding; Strict checks refuse.+ if (!dispatchBinding?.token && !this._guardAdvisesFor(dispatchContext.guardAdvisories, 'typing-target-identity',+ 'The field could not be pinned to the element checked before typing, so the text went to the current match of this selector. Check that the intended field changed.',+ { decided: false })) {return {success: false,dispatched: false,@@ -43708,6 +44696,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}// Repeated-item progress recovery takes priority so an unresolved ledger// can still drive the next tool turn.+ // A plain final is a new completion attempt (see+ // _beginCompletionGuardAttempt).+ this._beginCompletionGuardAttempt(tabId);const clarificationFinalDecision = this._isActionMode(mode)? this._clarificationAuthorizationPlainFinalDecision(tabId): null;@@ -43732,7 +44723,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finalResponse;}const readFinalLimitation = this._readCompletenessLimitation(tabId);- if (readFinalLimitation) {+ if (readFinalLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {finalResponse = readFinalLimitation;_traceStatus = 'read_scope_limited';messages.push({ role: 'assistant', content: finalResponse });@@ -43755,13 +44746,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait this._persistNow(tabId);continue;}- const progressFinalBlock = this._plainFinalProgressBlock(tabId);- const completionFinalBlock = this._completionPlainFinalBlock(tabId);- const readFinalBlock = this._readCompletenessBlock(tabId);- const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), result.content);+ // By default each check refuses at most once per run (_plainFinalGuardBlocks).+ const {+ progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock,+ } = this._plainFinalGuardBlocks(tabId, result.content);const plainFinalBlocks = [progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock].filter(Boolean);if (plainFinalBlocks.length) {- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && this._plainFinalTwoStrikeEnds()) {finalResponse = this._completionPlainFinalPartial(tabId, result.content, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -43775,7 +44766,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finalResponse;}if (completionFinalBlock) completionPlainFinalRecoveryAttempted++;- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps+ && this._plainFinalTwoStrikeEnds()) {finalResponse = this._completionPlainFinalPartial(tabId, result.content, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -43848,6 +44840,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dfinalResponse = result.costAllowanceMessage? `${repairedFinalContent}\n\n${result.costAllowanceMessage}`: repairedFinalContent;+ finalResponse = this._withCompletionCaveat(tabId, finalResponse);messages.push(this._withResponseItems({ role: 'assistant', content: finalResponse }, result.responseItems, result.reasoningContent, provider));onUpdate('text', { content: finalResponse });break;@@ -44873,6 +45866,9 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout d}emptyOutputRecoveryAttempted = false;compressionPlaceholderRecoveryAttempted = false;+ // A plain final is a new completion attempt (see+ // _beginCompletionGuardAttempt).+ this._beginCompletionGuardAttempt(tabId);const clarificationFinalDecision = this._isActionMode(mode)? this._clarificationAuthorizationPlainFinalDecision(tabId): null;@@ -44899,7 +45895,7 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finish(clarificationFinalDecision.failure, clarificationFinalDecision.status);}const readFinalLimitation = this._readCompletenessLimitation(tabId);- if (readFinalLimitation) {+ if (readFinalLimitation && !this._guardAdvises('read-coverage-ask-limitation', { decided: false })) {messages.push({ role: 'assistant', content: readFinalLimitation });onUpdate('text', { content: readFinalLimitation, replace: true });onUpdate('warning', { message: 'Ask mode could not verify that every Gmail message was expanded.' });@@ -44922,13 +45918,13 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dawait this._persistNow(tabId);continue;}- const progressFinalBlock = this._plainFinalProgressBlock(tabId);- const completionFinalBlock = this._completionPlainFinalBlock(tabId);- const readFinalBlock = this._readCompletenessBlock(tabId);- const exactTableFinalBlock = structuredTableAnswerBlock(this.readCompletenessStates.get(tabId), fullText);+ // By default each check refuses at most once per run (_plainFinalGuardBlocks).+ const {+ progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock,+ } = this._plainFinalGuardBlocks(tabId, fullText);const plainFinalBlocks = [progressFinalBlock, completionFinalBlock, readFinalBlock, exactTableFinalBlock].filter(Boolean);if (plainFinalBlocks.length) {- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && this._plainFinalTwoStrikeEnds()) {const partial = this._completionPlainFinalPartial(tabId, fullText, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -44941,7 +45937,8 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout dreturn finish(partial, 'partial');}if (completionFinalBlock) completionPlainFinalRecoveryAttempted++;- if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps) {+ if (completionFinalBlock && completionPlainFinalRecoveryAttempted >= 2 && steps >= this.maxSteps+ && this._plainFinalTwoStrikeEnds()) {const partial = this._completionPlainFinalPartial(tabId, fullText, {progressBlocked: !!progressFinalBlock,readBlocked: !!readFinalBlock,@@ -45025,6 +46022,11 @@ Rules: no prose intro, no conclusion, no "this screenshot shows...", no layout donUpdate('text_delta', { content: `\n\n${costStopMessage}` });fullText = `${fullText}\n\n${costStopMessage}`;}+ const caveatedFullText = this._withCompletionCaveat(tabId, fullText);+ if (caveatedFullText !== fullText) {+ fullText = caveatedFullText;+ onUpdate('text', { content: fullText, replace: true });+ }messages.push(this._withResponseItems({ role: 'assistant', content: fullText }, responseItems, reasoningContent, provider));this._persist(tabId);closeTraceStep({ ok: true });diff --git a/src/firefox/src/agent/browser-batch.js b/src/firefox/src/agent/browser-batch.jsindex 453597015..925b8e148 100644--- a/src/firefox/src/agent/browser-batch.js+++ b/src/firefox/src/agent/browser-batch.js@@ -60,7 +60,12 @@ export function expandBrowserBatchCalls(calls, options) {});}-export function browserBatchResultStatus(message) {+// advisoryWritesContinue: a text write that went out but could not be read+// back exactly (success with unverifiedWrite, see the agent's text-write+// advisories) ran and does not stop the batch. Only that marker is exempt:+// failures, refusals and unknown outcomes still do. The agent passes false+// under Settings → "Strict checks", which never produce that marker anyway.+export function browserBatchResultStatus(message, { advisoryWritesContinue = true } = {}) {if (!message) return { ran: false, reason: 'interrupted' };let text = String(message.content || '');const wrapped = text.match(/^<untrusted_page_content\b[^>]*>([\s\S]*?)<\/untrusted_page_content\b[^>]*>/);@@ -72,7 +77,9 @@ export function browserBatchResultStatus(message) {if (!object(result)) return { ran: true, reason: '', failed: false };const ran = !(result.skipped || result.denied || result.invalidToolArguments || result.invalidArguments|| ((result.noDispatch === true || result.dispatched === false) && result.success !== true));- const unverified = result.inconclusive || result.verified === false || result.remoteStateVerified === false;+ const advisoryWrite = advisoryWritesContinue === true && result.success === true+ && result.unverifiedWrite === true && !result.error;+ const unverified = !advisoryWrite && (result.inconclusive || result.verified === false || result.remoteStateVerified === false);const failed = !!(result.success === false || result.error || result.noProgress || result.ambiguous|| result.outcomeUnknown || result.stale || unverified);const reason = result.cancelled ? 'cancelled'diff --git a/src/firefox/src/agent/chat-workflow.js b/src/firefox/src/agent/chat-workflow.jsindex c7edea2c5..d1b040c7c 100644--- a/src/firefox/src/agent/chat-workflow.js+++ b/src/firefox/src/agent/chat-workflow.js@@ -677,9 +677,25 @@ export function advanceChatSession(value, rawSnapshot, now = Date.now()) {};}-export function decideChatSend(value, rawSnapshot, text, now = Date.now()) {+// Send preconditions a caller may waive with a note (WebBrain's quality+// checks). The empty/over-long body, user input (credentials, payment, a new+// user decision), thread binding, a user's own draft in the composer and the+// duplicate checks are never waivable: an over-long body could not be matched+// to its pending record afterwards, and a draft belongs to the user.+// Only a missing composer may be waived by default (the send then simply+// cannot dispatch). A terminal session and an unverified native message+// baseline stay blocking: the baseline is what delivery matching and+// duplicate-send detection rely on, and a terminal session asked for no+// further message.+export const WAIVABLE_CHAT_SEND_REASONS = Object.freeze([+ 'composer_unavailable',+]);++export function decideChatSend(value, rawSnapshot, text, now = Date.now(), { waive = null } = {}) {const session = normalizeChatSession(value, now);const snapshot = normalizeChatSnapshot(rawSnapshot, now);+ const waived = reason => WAIVABLE_CHAT_SEND_REASONS.includes(reason)+ && (waive instanceof Set ? waive.has(reason) : Array.isArray(waive) && waive.includes(reason));// Normalize one character past the cap so an over-long body is rejected// rather than silently truncated into a different message than requested.const body = normalizeChatText(text, MAX_MESSAGE_TEXT + 1);@@ -688,17 +704,17 @@ export function decideChatSend(value, rawSnapshot, text, now = Date.now()) {if (session.userInput?.required || snapshot.userInput?.required) {return { ok: false, reason: 'user_input_required', error: 'Pause the chat until the user completes the required verification or decision.' };}- if (session.state === 'issue_resolved' || session.state === 'stopped') {+ if ((session.state === 'issue_resolved' || session.state === 'stopped') && !waived('terminal_session')) {return { ok: false, reason: 'terminal_session', error: 'The chat session is terminal; do not send another message.' };}if (!session.threadKey || !snapshot.threadKey || session.threadKey !== snapshot.threadKey) {return { ok: false, reason: 'thread_unverified', error: 'The active conversation is not bound to the stored chat session.' };}- if (snapshot.nativeMessageBaselineComplete === false) {+ if (snapshot.nativeMessageBaselineComplete === false && !waived('native_baseline_unverified')) {return { ok: false, reason: 'native_baseline_unverified',error: 'The latest mounted native message IDs or pending statuses are not verified. Observe the current conversation before sending.' };}- if (snapshot.composer.available !== true) {+ if (snapshot.composer.available !== true && !waived('composer_unavailable')) {return { ok: false, reason: 'composer_unavailable', error: 'The active conversation composer is not available.' };}if (snapshot.composer.empty !== true) {diff --git a/src/firefox/src/agent/completion-invariant.js b/src/firefox/src/agent/completion-invariant.jsindex e112040d1..b30e3cf45 100644--- a/src/firefox/src/agent/completion-invariant.js+++ b/src/firefox/src/agent/completion-invariant.js@@ -1064,17 +1064,20 @@ export function consumeCompletionObservationResult(state) {};}-export function completionDoneBlock(state, toolName, args = {}) {+// `skip`: reasons a caller already accepted over advice (Strict checks off,+// see guard-policy.js), so the next invariant still gets its own note.+export function completionDoneBlock(state, toolName, args = {}, { skip = null } = {}) {+ const skipped = reason => skip?.has?.(reason) === true;const isDoneJson = toolName === 'done_json';const outcome = isDoneJson ? 'success' : normalizedOutcome(args?.outcome);- if (!isDoneJson && !outcome) {+ if (!isDoneJson && !outcome && !skipped('missing_outcome')) {return {reason: 'missing_outcome',error: 'done requires outcome="success", "partial", or "failed". Use partial or failed when the task is not fully verified.',};}if (outcome === 'partial' || outcome === 'failed') return null;- if (state?.iframeFormVerificationDebt) {+ if (state?.iframeFormVerificationDebt && !skipped('iframe_form_verification_required')) {const pendingCount = Array.isArray(state.iframeFormVerificationObligations)? state.iframeFormVerificationObligations.length: 1;@@ -1085,7 +1088,7 @@ export function completionDoneBlock(state, toolName, args = {}) {pendingTargetCount: pendingCount,};}- if (state?.verificationDebt) {+ if (state?.verificationDebt && !skipped('verification_required')) {return {reason: 'verification_required',error: 'The latest consequential action has not been verified by a successful explicit page/state observation. Re-read the relevant state after the action, then call done again; otherwise finish with outcome="partial" or outcome="failed".'diff --git a/src/firefox/src/agent/guard-policy.js b/src/firefox/src/agent/guard-policy.jsnew file mode 100644index 000000000..47f8f61e5--- /dev/null+++ b/src/firefox/src/agent/guard-policy.js@@ -0,0 +1,413 @@+// How WebBrain's own checks treat a model-requested action.+//+// A guard is WebBrain code (not the user) that refuses, defers or stops a+// tool call, a write, a submit or a completion. Every guard is registered+// here with a class and two behaviors:+//+// - onDecided: what it does when it KNOWS the action is wrong.+// - onCannotDecide: what it does when it cannot tell (evidence missing,+// unreadable, stale or timed out).+//+// Only the short list of HARD classes may refuse an action outright: the+// wrong recipient, deleting data, money, credentials, and publishing+// something the user did not ask for. When a hard guard cannot decide it+// asks the user on WebBrain's own card where one exists ('ask'), and+// otherwise refuses ('block').+//+// Every other guard is 'quality' (verification, exact readback, evidence,+// completion checks): it tells the model about the problem instead of+// stopping it ('advise'), or asks the user when it cannot verify a+// consequential step such as a commit or a publish ('ask'). Settings →+// General → "Strict checks" restores blocking for every quality guard.+//+// permission_gate (the user's own permissions, modes and budgets),+// host_check (same-site, frame and task-authority boundaries, CAPTCHA and+// access walls, a human acting in the same tab), budget (loop and observation+// limits), infra (a call that cannot run as given) and user_control (Stop,+// corrections, cancelled cards) are not guards in this sense and keep their+// behavior.+//+// Rule for new guards (enforced by test/guard-policy.mjs): register the id+// here, declare onCannotDecide, and name a test of a legitimate task the+// guard must not block (mustNotBlock: 'test/file.mjs#exact test name').+// See docs/guards.md. Shared verbatim by the Chrome and Firefox builds.++export const HARD_GUARD_CLASSES = Object.freeze(['recipient', 'deletion', 'money', 'credentials', 'unrequested_publication']);+export const NON_GUARD_CLASSES = Object.freeze(['permission_gate', 'host_check', 'budget', 'infra', 'user_control']);+export const GUARD_CLASSES = Object.freeze([...HARD_GUARD_CLASSES, 'quality', ...NON_GUARD_CLASSES]);+export const GUARD_OUTCOMES = Object.freeze(['block', 'ask', 'advise']);++// Guards that existed when this registry was introduced. Each later guard+// must name a mustNotBlock test (see the header).+export const GRANDFATHERED_GUARD_COUNT = 158;++export const GUARDS = Object.freeze({+ "auto-progress-resume": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Two consecutive stalled outputs with unresolved progress rows schedule a resume (scheduler or cloud deferResume) instead of failing." },+ "bot-memory-uncertain-done": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "In a managed Cloud bot run, done(success)/done_json while a dispatched bot-memory action still has an uncertain outcome." },+ "completion-evidence-freshness": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Completion evidence went stale while done was being verified: judged evidence or document identity changed, the pure-calculation receipt authority changed, the submitted iframe snapshot is missing or changed after a succeeded verdict, or calculation evidence captured at done start is no longer…" },+ "completion-failure-only-done": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "When a forced verification turn made no progress, or no observation tool is available, done is advertised with outcome enum partial/failed only; a done(success) is then rejected by schema validation." },+ "completion-page-warning": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Structural page warnings at done(success): an open dialog, a recorded submit that failed validation, a task-relevant form still visible without a verified submit transition, or a create/edit route without success; refused at most twice per key, then accepted with a loud note." },+ "completion-recovery-forced-turns": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a refused completion the next turn is rewritten by _completionRecoveryPolicy: read-only verification tools only (fetch_url forced to GET, or verify_form / download readers) with toolChoice required, then a done-only turn." },+ "completion-verifier-advisory-outputs": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Non-refusing verifier outputs: an uncertain verdict (all engines unsure/unavailable, budget spent, D1 success without confirmation) sets no verified submission evidence, and a sure later_outcome side answer appends a \"future votes/moderation unverified\" note." },+ "completion-verifier-not-done": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The independent completion judge (decision-model sidecar or active LLM) returns a sure pending or failed verdict for done(success): refused and re-armed as verification debt (forced read-only turn)." },+ "done-iframe-form-unverified": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final while edited iframe form targets have not been read back by a matching verify_form (which compares textContent against an expected value that keeps newlines)." },+ "done-invariant-shape-checks": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Act/Dev done without outcome success/partial/failed, or done(success) in the same assistant batch as the action/observation it relies on (or with verification debt at batch start)." },+ "done-rich-text-toolbar-obligation": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final while the last text entry hit a rich-text formatting toolbar and no verified editor-body edit has released the obligation." },+ "done-summary-meta-only": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The done summary only says that an answer was given (\"Explained how...\") without the answer (judge summary_kind or done_summary reading): refused for a fresh answer turn." },+ "done-verification-debt": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) or a plain final after a consequential action with no later successful explicit observation (downloads need list_downloads/read_downloaded_file)." },+ "exact-table-done": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Exact table export completion: table JSON without a current data_ref from an exact extract, rowCount != rows.length, an unknown/expired/superseded/foreign data_ref, or a fresh re-read that differs from the exported snapshot (done with any outcome and plain finals)." },+ "github-committed-file-verification": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a GitHub edit-file-and-commit, the raw blob at the commit SHA must byte-match the requested text (SHA-256), be on the requested branch, in the expected repository, listed in the commit file list, with a bound verified editor replacement; oversized or unreadable raw files and an unproven scope…" },+ "incomplete-task-check-stale": { class: "host_check", family: "completion", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The task, run, provider, steering or observed document changed before or during the incomplete_task reading: the partial/failed ending is refused and the model reconsiders the current task." },+ "incomplete-task-redirect": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "An honest done(partial/failed) in an Act/Dev execute task is redirected (at most twice) when the incomplete_task judge says the flow is still loading/validating (wait_then_check) or a reasonable permitted next step remains (continue_now); unsure judges accept the ending." },+ "native-chat-receipt-not-durable": { class: "recipient", family: "completion", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "Fresh native chat delivery proof exists but its receipt cannot be persisted: done(success) is refused so a resumed run does not resend the delivered message." },+ "page-feedback-ask-answer-superseded": { class: "host_check", family: "completion", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "An Ask answer written while the page changed (non-passive churn) is discarded and the model re-asked with fresh feedback, unless an ask_response_scope reading says the answer is page-independent." },+ "plain-final-done-protocol": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "An Act/Dev run that executed an action (state observed) ends with plain text: forced into a done-only turn." },+ "plain-final-rejected-text-compaction": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "When another plain-final block fires and the reply repeats a long paragraph three times or hit the output limit, the assistant turn is replaced by a rejection marker and a \"do not repeat\" nudge." },+ "plain-final-two-strike-partial": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The third plain final under a completion block (second at max steps) ends the run as partial, keeping the model text when nothing else is pending." },+ "plain-final-unusable-output": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The model returned no text and no tool call, a context-compression placeholder, or (on-device standalone chat) an answer ending mid-sentence: one nudge, then auto-resume (progress pending) or stop." },+ "plan-done-summary-shape": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The done summary is a plan or planner/policy JSON instead of a result, or a partial/failed summary blames WebBrain's own Ask/read-only mode in an Act/Dev run (one focused correction, then stop)." },+ "plan-execution-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Plan-execution guard default: done(success) with no successful task tool, a state-changing task with no verified consequential tool (an already-correct page cannot be success), evidence recorded under another task key, or planning failed so success needs a verified consequential tool; one nudge,…" },+ "plan-plain-final-protocol": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "In an execute Act/Dev run every plain-text final (including an echoed stale \"[Stopped by user]\" status) gets one done-protocol nudge with the text cleared, then the run stops." },+ "plan-publication-evidence-missing": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success of a publication task needs job-bound terminal evidence for every requested social destination (also when the publication contract could not be compiled) and, for published_resource jobs, a bound dispatch record, same workflow/task, a bound saved resource matching the requested payload…" },+ "plan-required-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Plan-execution guard: success needs job-specific evidence that was not observed: a successful schedule_task/scheduled:true, completed DOWNLOAD-capability evidence, a non-submit job's own evidence (deterministic count, transcript, terminal read coverage, PR diff read, reconciled collection, scoped…" },+ "plan-submission-evidence-missing": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success of a submit/send/commit task needs evidence that it took effect: the selected site job's terminal state (recipient-bound sent message, paid/ticket-issued transaction, form confirmation bound to the inventoried form, saved state with bound metadata, resolved threads, verified final submit)…" },+ "plan-task-drifted": { class: "host_check", family: "completion", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Plan-execution guard: the progress task key changed after the run was authorized, so execution evidence no longer binds; one nudge, then the run stops (task_binding_changed)." },+ "plan-unauthorized-mutation-recorded": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Success is refused after the fact when a conditional editor repair was blocked for lacking a matching workflow contract, or a prepare-only form job dispatched a submit." },+ "progress-ledger-unresolved": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Act mode with unresolved (pending/acted) rows in the app-owned progress ledger: done with any outcome is refused and plain finals are redirected with the progress_read payload." },+ "progress-success-claim-checks": { class: "quality", family: "completion", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "done(success) while the expected ordered rows are missing, duplicated, unprocessed or lack required fields (a short value read as \"missing\" counts as absent), or while ledger rows are skipped or failed." },+ "pure-calculation-done-checks": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "done on a literal-arithmetic task before any actual calculate attempt (any outcome), or done(success) whose summary omits/changes the calculator receipt value or breaks the requested literal format." },+ "read-coverage-ask-limitation": { class: "quality", family: "completion", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Ask mode, whole-thread Gmail read required, pages covered but message expansion not confirmed: the model answer (done or plain final) is replaced by a fixed limitation and the run ends read_scope_limited." },+ "read-coverage-incomplete": { class: "quality", family: "completion", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The user asked for a whole thread/document and read coverage is incomplete (pages missing, or no terminal page / expansion confirmed): done with any outcome and plain finals are refused." },+ "step-limit": { class: "permission_gate", family: "completion", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The user-configured maxSteps budget is reached without a final response: the run ends (max_steps) with Continue offered." },+ "structured-cloud-output-contract": { class: "infra", family: "completion", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "Structured cloud runs: done_json outside a cloud run with an output schema, a result that fails outputSchema (one repair, then cloudFailed), or prose instead of done_json (one nudge, then required_tool_missing)." },+ "terminal-recovery-no-success": { class: "quality", family: "completion", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The forced delivery turn after the observation limit, and the step-limit handoff, may only end partial/failed; invalid output falls back to the deterministic ledger partial or a fixed failure text (delivery_recovery_failed)." },+ "content-action-outcome-unknown": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "A content/CDP deadline, lost message channel or Stop after dispatch makes a mutation outcome-unknown; for text writes the finalizer then records debt (also across Stop)." },+ "set-field-bundled-submit-outcome": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "set_field({submit:true}) withholds the bundled Enter/requestSubmit when the value did not verify, and reports a native form that failed checkValidity instead of submitting it." },+ "text-write-debt-arm": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "_finalizeTextMutationResult (every set_field/type_ax/type_text result, timeouts and cancellations included) turns any unverified, unproven or unknown write into success:false + outcomeUnknown + repeatBlocked, records debt for the editor and drops contenteditable proofs; a verified value with an…" },+ "text-write-debt-block": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Any write (any tool, ref or locator) to an editor that has unresolved text-write debt in this document is refused unless it is the identical original replacement and readback-only recovery verifies it (then a no-dispatch \"recovered\" result is returned)." },+ "text-write-preinsert-unproven": { class: "quality", family: "content-write", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "The write is stopped before its text goes out because the pre-insert state cannot be proven: DraftJS structure unreadable before the write (no dispatch), select-all could not be proven to cover the managed editor, or select-all+Delete could not be proven to empty the field." },+ "text-write-readback-unverified": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Post-write readback cannot confirm the exact text: content set_field/type_ax/contenteditable insert/DraftJS paste mismatches (innerText fallback reader + strict comparator), a replaced element, DraftJS unreadable after the write, CDP verifyTextEntry/focused textContent checks, uncertain…" },+ "truncated-preview-replacement": { class: "deletion", family: "content-write", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A clearing write whose text ends with \"...\" or another truncation marker and whose prefix starts the field's longer current value would erase everything after the preview: nothing is typed (set_field, type_ax, type, CDP type_text, iframe typing)." },+ "trusted-field-retry-guards": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "WebBrain's own trusted CDP retry of a set_field/type_ax write is suppressed after a possibly dispatched original write, or fails its preparation (focus press, reselection, CDP error, preparation veto predicates); an exact readback proving the editor unchanged makes the failure retryable without…" },+ "typing-target-identity": { class: "quality", family: "content-write", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Typing target identity checks in the type_text/press_keys handlers: the focused editor bound by the toolbar preflight changed or could not be prepared/revalidated, or the selector backend node id cannot be pinned for safe typing." },+ "delivery-observation-checkpoint": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Consecutive read/scroll/wait observations without verified progress (an unverified write does not count as progress): nudge every 4, and at 8 browser tools stop for a done-only (partial/failed) delivery turn; advisory for cloud runs and the WebBrain Cloud provider." },+ "loop-failed-action-target": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The same mutation target (failureScope, else tool + bucketed args) failed, was refused before dispatch or made no progress: nudge at 2, stop the run at 3 (4 for occlusion). Every failureScope-tagged refusal feeds it." },+ "loop-observation-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Observation loops: repeated clicks in the same 5 px coordinate bucket (nudge 5, stop 8), accessibility-tree nodes read one by one without acting (stop at 6 suspicious or 12 non-sequential), the same scroll direction on the same target without movement (nudge 2, stop 3)." },+ "loop-repeat-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "_checkLoop repeat/oscillation stops: the same call key 3x in 6 or ABAB after eight nudges, carousel oscillation, the same verified navigation returning to an unchanged page four times, the same non-retryable failure twice, a checkbox still wrong after three attempts, the same read-only GET resource…" },+ "loop-unavailable-tool": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Repeated calls to a tool this run does not offer (counted by name): nudge at 3, stop at 10." },+ "loop-verification-dialog-reopen": { class: "host_check", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The same verification (CAPTCHA) dialog was dismissed and reopened repeatedly on the same page: nudge, then stop." },+ "page-feedback-supersession-stop": { class: "budget", family: "loop", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Budget over no-dispatch supersessions caused by passive churn or unknown attribution (or an unverified action context): nudge at 2, stop the run at 5 with a Retry/Give up failure-recovery card." },+ "api-mutation-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch_url/research_url with a write method in an Ask-mode run, or without /allow-api (conversation or persistent API permission)." },+ "browser-batch-fresh-turn-interrupt": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "After a failed, refused, unverified or outcome-unknown browser action (a browser_batch child, any multi-call batch, or any pre-dispatch refusal of a browser-mutation tool) every later call in the assistant batch is skipped so the next action is planned on fresh evidence." },+ "browser-control-handoff-stale-batch": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Browser control changed hands (manual takeover or cloud handoff) after the batch was planned: every remaining call is skipped and a fresh app-owned tree is injected." },+ "capability-host-permission": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Capability x host permission gate: a standing deny or a Deny on the capability card (navigate, click, type, execute_js, dev_patch, network, download, upload, window, schedule) refuses the call on that host." },+ "captcha-gate-action-block": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A supported verification challenge is active (solve_required) or its one solve has not been confirmed cleared (verification_pending): page mutations, network mutations and done(success)/done_json are refused until solve_captcha runs once / a read confirms clearance." },+ "captcha-gate-manual-required": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The challenge needs manual completion (unsupported widget, failed solve, Cloudflare managed challenge, or no CAPTCHA tools in this mode/tier): the gated call is refused and the run stops asking the user to complete it." },+ "chat-send-evidence-unavailable": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "A recipient-verified chat send whose conversation cannot be observed before sending, or whose native WhatsApp message baseline cannot be saved: nothing is sent." },+ "chat-send-preconditions": { class: "quality", family: "predispatch", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Chat send preconditions (generic chat dispatch and decideChatSend): a new incoming message appeared since the last observation, empty or over-long message, terminal chat session, unverified native message baseline, unavailable or non-empty composer." },+ "chat-send-recipient-guards": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Chat send protection of the recipient and against duplicates: the observed thread differs from the recipient-verified baseline or stored session, the exact message is already visible as outgoing or an earlier outbound is still pending verification, the pending message cannot be persisted before…" },+ "chat-user-input-required": { class: "credentials", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The chat counterpart or page asks for a one-time code, PIN, card/CVC, password or login, or an explicit user decision (or the thread changed): replying is paused until the user completes it." },+ "chrome-protected-page": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A DOM/debugger tool on a Chrome-protected page (Web Store developer dashboard; gallery after one retry) gets a non-retryable protected-page failure; repeated hits end the run with a visual-fallback or manual-required handoff." },+ "clarify-timeout-not-authorization": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "After a clarify answer was auto-selected on a waited timeout, consequential capabilities (click, type, script, network, download, upload, schedule), CAPTCHA solve/apply, done(success)/done_json and plain finals are refused; the second attempt or the last step stops the run asking for an explicit…" },+ "consequential-durability-checkpoint": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "Before a consequential call, the run-UI/scheduler recovery checkpoint, or the task-attempt record for an action that may post on X, Bluesky or an unknown site, cannot be saved: the run stops (persistence_degraded) before sending." },+ "coordinate-click-provenance": { class: "infra", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A coordinate click without coordinate_space, with from_screenshot conflicting with css, with normalized 0-1 values, or with a missing/stale capture_id or a point outside the capture is refused before any probe (checked again inside executeTool)." },+ "deletion-confirm-card": { class: "deletion", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "A deletion whose item the latest request does not clearly name (not_requested, other_item, unclear) or whose semantic decision is unavailable goes to WebBrain's deletion card (\"once\" re-runs every workflow check, then dispatches; deny, timeout or auto answer refuses; a change during the card…" },+ "deletion-guard-refusal": { class: "deletion", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Deletion checks in _resourceMutationPreSubmitBlock that refuse without a card: a deletion through coordinates/keys/set_field submit/execute_js (click_required), a Delete/Remove control outside one identifiable record (toolbar, bulk, selection), the same record/permalink already deleted in this…" },+ "form-validation-unchanged-repeat": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "The same submit (or verify_form) is retried while the page shows the same invalid fields as the last failed submission." },+ "generate-image-config-invalid": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "generate_image with an unknown provider, missing API key, invalid model or malformed ComfyUI workflow: the provider cannot be called." },+ "github-commit-evidence-binding": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "A commit click in the GitHub edit-file-and-commit workflow is refused unless exactly one verified editor-replacement proof (readbackSha256), the requested commit message summary/body, path and branch are bound to exact pre-submit evidence; proofs are re-digested before every attempt, unverifiable…" },+ "github-commit-split-write-required": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "ask",+ summary: "In the GitHub edit-file-and-commit workflow a submit-capable non-click (execute_js, set_field submit, Enter) that may submit is refused: writes must be verified separately and the commit activated by a separate click." },+ "github-conditional-commit-rearm": { class: "quality", family: "predispatch", decides: "protocol", onDecided: "advise", onCannotDecide: "advise",+ summary: "The first editor action of an authorized conditional repair branch arms the edit-file-and-commit workflow (system prompt rebuilt, evidence counters reset) and is itself not dispatched." },+ "github-conditional-commit-unbound": { class: "unrequested_publication", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A scheduled-resume verification task (no state change or submission authorized) tries to mutate a GitHub repo editor or run execute_js/an API mutation on a repo page and no matching conditional edit-file-and-commit job can be bound (none planned, other repository, task drift, opaque mutation)." },+ "grouped-search-card": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A low-risk same-site GET search group (navigate, type, submit) without a standing grant asks once on WebBrain's grouped-search card; deny refuses the unchanged search." },+ "otp-open-message-gate": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "read_email_verification_message open_message is refused in Ask mode (opening can mark mail read) or without the one-use open grant minted by the mailbox permission gate for that message_ref." },+ "owned-native-chat-read-repair": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "While an app-issued native Telegram/WhatsApp read repair is pending (latest messages not verified), the model batch or plain final answer is preempted and the app runs its own exact read first." },+ "permission-host-unidentified": { class: "host_check", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The target frame/host of a call cannot be identified (iframe tools without urlFilter, apply_captcha_solution without frameUrl, WebMCP without a target URL, OTP without a mailbox URL): fail closed instead of charging the top page grant." },+ "preparation-timeout-action-pipeline": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "The shared deadline around the in-pipeline preparation (rich-text toolbar preflight, social publication audit, generic chat send preparation, task-attempt checkpoint) expired before dispatch: nothing was sent." },+ "preparation-timeout-captcha-preflight": { class: "host_check", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "The CAPTCHA safety preflight (dialog scan / AWS-WAF gate) did not finish before the content-action deadline: the page mutation is refused (retryable) so a challenge cannot be dismissed or resubmitted unseen." },+ "preparation-timeout-permission-detection": { class: "permission_gate", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "Grouped-search form detection or submit-action detection timed out before the permission/submit cards could be chosen: the call is refused rather than bypassing the submit card." },+ "preparation-timeout-recipient-preflight": { class: "recipient", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "The message-recipient safety preflight (_messageRecipientGuardBlock probe) timed out on a protected messaging page: the send is refused." },+ "preparation-timeout-submit-preflight": { class: "deletion", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "The submit/form-validation preflight (_detectLikelySubmitAction, result baseline, validation snapshot) timed out: the call is refused. This probe is the only source of mutationKind:\"delete\" for the deletion guard and of publicationControl for the X/Bluesky gates." },+ "pure-calculation-stale-authority": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The captured arithmetic task authority (owner, run token or expression) no longer matches the current task (steering or a new turn after the batch was planned): every tool, done included, is refused." },+ "pure-calculation-tool-scope": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "On an owned literal-arithmetic task, any tool other than calculate(exact expression) or done, a calculate with another expression, or a repeated calculate after the result was verified is refused (checked again in-pipeline)." },+ "recipient-active-conversation-pin": { class: "recipient", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "At planning time a task that targets \"the open conversation\" cannot pin it to one verified recipient identity: the run stops before any page tool." },+ "recipient-draft-evidence-unavailable": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "The recipient is authorized (or confirmable) but the composer draft body cannot be read, or the existing-message baseline needed to verify a new send is unavailable." },+ "recipient-guard-refusal": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "_messageRecipientGuardBlock refusals on protected messaging pages (Gmail, X DMs, LinkedIn, Discord, native WhatsApp/Telegram, generic mail/chat): Enter with repeat>1, a send path that cannot be bound to the verified recipient (iframe_click, execute_js, WebMCP, ambiguous upload), no observable…" },+ "recipient-guard-target-preparation": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "Recipient-guard target failures that establish no mismatch: the requested control cannot be resolved in the page/frame (message_target_unresolved), or a native Telegram read-only preparation click is not bound to one exact current control/owner/binding token or changed before the click." },+ "recipient-guard-unrequested-send": { class: "unrequested_publication", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A send or public post the task did not ask for: a LinkedIn public Post control in a private-message task, a send the latest request forbids (sending_forbidden reading), and a verifiable send the plan did not authorize or that names no recipient (card with reason unrequested/unnamed; refused when…" },+ "recipient-mismatch-confirm-card": { class: "recipient", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A conclusive send whose observed recipient set differs from the task target and is not user-approved goes to WebBrain's recipient card (once/always re-run the guard, deny records a declined recipient, a changed conversation or Stop refuses/aborts); when the card cannot be offered (unattended run,…" },+ "resource-mutation-task-authority-changed": { class: "host_check", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "_resourceMutationPreSubmitBlock current() check: a delete control (or a post-correction publish/commit) while the plan guard is not an enabled execute guard, the task key changed, Stop was pressed, or a correction is pending or unvalidated." },+ "rich-text-toolbar-target-unresolved": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "The rich-text toolbar safety preflight cannot resolve or preserve the typing target (ambiguous/unresolved iframe selector, iframe recovery pending, selector-backed or focused type_text, page changed during resolution, trusted resolver cannot attach, iframe toolbar target cannot be scrolled into…" },+ "rich-text-toolbar-wrong-target": { class: "quality", family: "predispatch", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Text about to be typed into a rich-text formatting-toolbar control (font, size, style, color, link) instead of the editor body, by structural score >= 4 plus the optional vision audit: refused and a recovery obligation is recorded." },+ "social-api-publication-route": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "A write-method API call to an X/Bluesky post endpoint (CreateTweet, statuses, createRecord app.bsky.feed.post) is refused even after /allow-api: an API payload cannot pass the composer contract and audit." },+ "social-preflight-context-mismatch": { class: "recipient", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "The composer post kind (post, reply, quote) or parent target differs from the contract, or could not be observed: a reply or quote would be aimed at the wrong post or person." },+ "social-publication-audit": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Independent LLM audit (social_publication_authorization, up to 2 attempts) of the concrete draft against the request: a denial, or an unavailable/invalid checker, stops the run before Publish with a Retry-without-audit / Give up recovery card (also enforced after a tool result)." },+ "social-publication-authorization-guard": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "X/Bluesky publication contract checks that keep every post on the audited composer path: unidentified control or Enter/Space outside the editor, unobserved composer ownership, unresolved intent (clarify), no eligible authorized contract action (request does not ask to publish here, contract not…" },+ "social-publication-draft-quality": { class: "quality", family: "predispatch", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "X/Bluesky preflight quality checks: a detected submit made with set_field submit/Enter/execute_js/WebMCP instead of a click, and a composer snapshot whose body, media or thread length differs from the contract or cannot be observed (composer_incomplete, body_unobserved, baseline_incomplete)." },+ "social-publication-host-checks": { class: "host_check", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "X/Bluesky publication guard host/authority checks: a write-method fetch whose destination is missing, not http(s) or carries credentials; the task, guard or correction state changed while a resolved preparatory control or the publication audit was being checked." },+ "steer-post-correction-commit-guard": { class: "unrequested_publication", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "After a user correction (guard.steeringPriorSubmission), a publish or form commit is refused when it would repeat or sit beside the earlier attempt: unbound generic commit, replacement account changed, exact same post or form submission already sent, an earlier attempt on this site or unknown…" },+ "steer-prior-submission-target-unresolved": { class: "quality", family: "predispatch", decides: "no-evidence", onDecided: "advise", onCannotDecide: "ask",+ summary: "After a correction with an earlier dispatched submission, a submit-capable call whose target the probe could not resolve as a link, field, menu item or ordinary button is refused." },+ "steer-prior-submission-unreconciled": { class: "unrequested_publication", family: "predispatch", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "_steeringPriorSubmissionBlock: after a correction, any network mutation, chrome_web_store_publish or committing submit is refused until the earlier submission is reconciled (or this exact action was authorized and reconciled by _resourceMutationPreSubmitBlock)." },+ "steering-and-page-feedback-call-fence": { class: "host_check", family: "predispatch", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A user correction is pending, or page-monitor feedback (user input/intervention, unknown attribution, non-passive churn, stale scroll/model state) arrived after the model observation: the stale call (Act done and Ask answers included) and the rest of the batch are skipped and a fresh observation is…" },+ "submit-confirmation-card": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "With consequential confirmation on (not bypassed), a detected submit that is not a low-risk same-site GET search shows WebBrain's submit card (credential, payment and side-effect forms always get a fresh card); deny, timeout or an unexpected answer refuses the submit." },+ "tool-call-malformed": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "The call cannot run as given: invalid browser_batch parent (disabled tier, bad ids, too many/unbatchable children, schema failure), empty function name, arguments that are not valid JSON, an invalid get_accessibility_tree continuationArgs, a closed-schema violation, or a failed per-handler argument…" },+ "tool-not-advertised": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A call to a tool that is not in this run tool set (mode, provider tier, unloaded skill) or to a retired tool is refused without dispatch." },+ "tool-routing-redirects": { class: "infra", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch_url/research_url against an enabled skill HTTPS endpoint is redirected to the skill tool; a single-item download_social_media is redirected to download_public_media when that is available and untried, or skipped after it already succeeded." },+ "user-stop-or-card-cancel": { class: "user_control", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The user pressed Stop before dispatch, or stopped/corrected the task while a permission, submit, grouped-search, deletion or recipient card was open: the run aborts with nothing dispatched." },+ "webmcp-mode-and-setting-gate": { class: "permission_gate", family: "predispatch", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "execute_webmcp_tool/list_webmcp_tools while Experimental WebMCP is disabled in Settings, or in Ask mode (page readOnly annotations are not trusted): refused in preparation and again in the handler." },+ "webmcp-tool-id-invalid": { class: "infra", family: "predispatch", decides: "protocol", onDecided: "block", onCannotDecide: "block",+ summary: "execute_webmcp_tool without an exact registered opaque tool_id (missing, invented, stale) or with a failed CDP registry lookup: nothing to invoke." },+ "sched-reconciliation-required": { class: "unrequested_publication", family: "scheduler", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Unattended scheduled tasks are paused (needs_user_input) instead of re-running an action that may already have happened: a downgraded success after a side effect or pending consequential action, a pending consequential call not settled by an independently verified completion, or a judge context…" },+ "sched-systemone-downgrade": { class: "quality", family: "scheduler", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Opt-in System One judge after a scheduled run reported success: P(task_complete) below threshold or incomplete score downgrades the job outcome to partial (malformed answers or service failure keep success)." },+ "action-no-progress-classification": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "Post-dispatch: the same click identity twice with an identical page snapshot, or an unbound arrow key that changed nothing observable, is reclassified as a no-progress failure (feeds the loop detector)." },+ "bot-memory-reservation": { class: "unrequested_publication", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Managed-bot cross-run idempotency: an action remote memory says is already completed, an opaque execute_js/schedule_* call in a memory-protected run, an unobserved/unresolved/changed target, or a reservation/durable dispatch that memory did not confirm." },+ "captcha-paid-solve-protection": { class: "money", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Keeps paid CAPTCHA solving to one dispatch per challenge/page document: the gate refuses solve_captcha after the allowed solve, the handler refuses a second native/automatic solve, an AWS gate that is no longer solve_required, an exhausted AWS provider set, and any provider call whose dispatch lock…" },+ "captcha-solution-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Native solve page URLs must match the active tab/frames and the root document must be bound before a native request; a returned solution is applied only to the same unchanged page/frame; a provider-mandated User-Agent mismatch retains the paid answer without injection and asks for manual completion." },+ "captcha-solve-detection-binding": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "ask",+ summary: "solve_captcha arguments conflict with the detected widget (type, invisibility, enterprise flag, pageAction, rqdata, metadata), token injection has no detected frame, or the hCaptcha frame User-Agent cannot be read: refused before any paid dispatch." },+ "carousel-traversal-guards": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "A forward carousel scan asks for an index at or below the highest verified one (reverse order assumed only on a sure reading), or Instagram did not honor img_index / the media did not change (post-dispatch failure)." },+ "click-coordinate-intent": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "A coordinate click with expected_name/expected_role whose point no longer resolves to that semantic target (resolver errors fall back to the raw point)." },+ "click-duplicate-submit": { class: "unrequested_publication", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "ask",+ summary: "A second click within 45 s on a control whose caption reads as commit/publish, on the same unchanged URL, is refused (model escape _allowResubmit:true)." },+ "click-native-os-ui": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Clicks that would open native OS UI the agent cannot control: a native <select> dropdown (refused, or reported as a failure after the click) and a native file chooser (suppressed, with a pointer to upload_file)." },+ "click-text-ambiguous": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "click({text}) matched several elements with no single interactive one." },+ "clickax-native-button-preparation": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "Trusted native-button input preparation vetoes: the button changed or moved during preparation, could not be captured or verified while settling, input was observed while it settled, or the task/browser owner changed before the press." },+ "clickax-task-click-lock": { class: "unrequested_publication", family: "tool", decides: "no-evidence", onDecided: "block", onCannotDecide: "ask",+ summary: "A trusted click (native button or click_ax trusted fallback) on this exact document+ref earlier in the task may have landed and was never verified: the same target is not clicked again (one trusted fallback per ref per run)." },+ "clickax-trusted-retry-vetoes": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "WebBrain's automatic trusted retry of a click_ax that produced no visible change is skipped for concurrent tab/network/download activity, mutating captions, changed or ineligible targets." },+ "downloaded-file-task-changed": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "read_downloaded_file discards bytes when steering arrived, the page-feedback owner, the download or the pinned document changed during the read, or the reader/document cannot be pinned." },+ "iframe-target-binding": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The iframe selector matches several elements (or none) across matching frames, or the clicked element was replaced after the scroll / the frame monitor is unavailable." },+ "iframe-urlfilter-required": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "iframe_click/iframe_type without urlFilter: the iframe target and permission scope cannot stay stable." },+ "jev-target-changed": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The Jev-bound target (or the checkbox of a set_checked) changed, or its validation probe failed, before dispatch." },+ "media-download-target-binding": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "download_public_media on a feed/profile page without an explicit media permalink, or a social media download whose focused media/document changed between inference and download (media_binding_changed)." },+ "navigation-scheme-and-internal-pages": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "navigate to a non-http(s) scheme or unresolvable relative URL; go_back/go_forward on chrome://, about:, extension or view-source pages." },+ "network-url-safety": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "fetch/research URL safety: metadata and .internal/.local hosts always, localhost/private IPs unless \"Allow local network\", redirects into blocked URLs or across registrable domains (body discarded), cross-origin page resources." },+ "otp-mailbox-scope": { class: "credentials", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The OTP helper only exposes a verification message that visibly matches the named service in one unambiguous, unchanged mailbox tab, and never a truncated message without a safe continuation (skill must be loaded)." },+ "page-blocker-wall": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "A read that showed a subscription, registration or sign-in wall WebBrain could not apply returns nothing behind the wall." },+ "page-feedback-dispatch-fence": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "Transport-boundary fence (beforePageAgentDispatch, the content page monitor, the execute_js gate, the trusted Enter path): human input or feedback during preparation, a changed document mapping, focus moved into a child frame, an unprepared or rejecting monitor vetoes the dispatch; after input…" },+ "page-feedback-target-binding": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "The selector/ref of a state-changing call cannot be bound to the observed action certificate (target_ambiguous, target_unresolved, target_uncovered, capture budget exhausted) or its original owner context was never certified: nothing is dispatched and a bounded fresh capture is queued for the next…" },+ "pdf-viewer-dom-tools": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A DOM/action tool on Chrome's built-in PDF viewer (read_page is redirected to read_pdf)." },+ "preparation-timeout-generic": { class: "quality", family: "tool", decides: "no-evidence", onDecided: "advise", onCannotDecide: "advise",+ summary: "A non-consequential preparation stage exceeded the content-action deadline before dispatch (form-validation snapshot, executeTool entry deadline, click page snapshot/observation, click_ax content-script injection, coordinate target resolution, set_checked trusted recovery): nothing was sent." },+ "promote-iframe-ambiguous": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "promote_iframe with several matching child frames and no (or an out-of-range) matchIndex." },+ "recipient-clarify-cannot-repair-technical": { class: "quality", family: "tool", decides: "knows", onDecided: "advise", onCannotDecide: "advise",+ summary: "A clarify about the recipient is refused while a technical recipient block (identity/body/baseline/binding unavailable) is active, because approval cannot supply missing page evidence." },+ "recipient-dispatch-binding-revalidate": { class: "recipient", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "ask",+ summary: "Last-moment recipient checks at dispatch: the one-use binding token, composer, target, conversation, Telegram baseline or body changed between guard approval and the press/Enter (no CDP fallback for recipient-bound clicks), and recipient-bound uploads whose authorization key, file source, file…" },+ "research-escalation-authorization": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "delegate_research needs escalation enabled in Settings and a one-use authorization token bound to the exact prompt from an explicit clarify consent form for this tab/conversation." },+ "rich-text-toolbar-recovery-obligation": { class: "quality", family: "tool", decides: "mixed", onDecided: "advise", onCannotDecide: "advise",+ summary: "While a toolbar recovery obligation is pending, a ref, selector or region belonging to the recorded formatting toolbar is refused (also when the target probe is unresolved or the dispatch binding is not ready)." },+ "schedule-owner-changed": { class: "host_check", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Scheduling is refused when the owning run, steering revision, plan guard, conversation or active task changed (or Stop) while the job was being created." },+ "schedule-resume-chat-state-not-durable": { class: "recipient", family: "tool", decides: "no-evidence", onDecided: "block", onCannotDecide: "block",+ summary: "schedule_resume is refused when the latest chat workflow state (pending sends, sent keys) cannot be persisted, so a resumed run cannot resend." },+ "stale-ax-ref": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "A click_ax/set_checked ref_id belongs to a previous document or route, or several controls match the checkbox marker." },+ "strict-secret-credential-handling": { class: "credentials", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Credential handling: filled password/token/OTP-like field values are removed from results (and noted in strict mode), notes/ledger rows holding them are redacted in strict secret mode, and strict mode refuses exporting credential columns from tables." },+ "tool-feature-availability-gates": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Run-type/tier feature gates inside executeTool: recall_memcode in managed bot runs, skills unavailable for Compact tier or not enabled in this mode, beep outside a /watch run created with /beep (or a second event_key)." },+ "unsaved-changes-data-loss": { class: "deletion", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "navigate/go_back/go_forward on a page with attached files or two or more dirty fields, and promote_iframe on a frame with changed fields, attached files or a known unverified iframe edit, would discard that content (force:true overrides)." },+ "upload-compact-tier-sources": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "Compact-tier upload_file accepts only attachmentId plus a targetId from its own discovery phase (no selector, downloadId or filePath; stale targetId rediscovered)." },+ "upload-selector-ambiguity": { class: "infra", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "The upload selector matched several file inputs (now or on the previous attempt, until an inspection runs)." },+ "upload-source-validation": { class: "infra", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "The local upload path is missing/unreadable (inconclusive probes pass as unverified), or the file bytes do not match, or cannot be verified against, the input accept types." },+ "viewport-inspection-budget": { class: "permission_gate", family: "tool", decides: "knows", onDecided: "block", onCannotDecide: "block",+ summary: "inspect_viewport is skipped once the user-configured maxScreenshotsPerTurn budget is used up." },+ "webmcp-frame-binding": { class: "host_check", family: "tool", decides: "mixed", onDecided: "block", onCannotDecide: "block",+ summary: "WebMCP execution without trusted frame metadata, after the registration frame/origin changed since the permission check, or for a tool id no longer registered." },});++export function guardEntry(id) {+ return Object.hasOwn(GUARDS, id) ? GUARDS[id] : null;+}++export function isHardGuardClass(cls) {+ return HARD_GUARD_CLASSES.includes(cls);+}++/**+ * What a registered guard does when it fires.+ * decided: true when the guard knows the action is wrong, false when it+ * cannot decide. strict: Settings → "Strict checks" (quality guards block).+ * Unknown ids keep today's behavior ('block') so an unregistered refusal is+ * never silently relaxed.+ */+export function guardOutcome(id, { decided = true, strict = false } = {}) {+ const entry = guardEntry(id);+ if (!entry) return 'block';+ const outcome = decided ? entry.onDecided : entry.onCannotDecide;+ if (entry.class === 'quality' && strict) return 'block';+ return GUARD_OUTCOMES.includes(outcome) ? outcome : 'block';+}++/** A note a quality guard leaves for the model instead of refusing. */+export function guardAdvisory(id, message) {+ const text = String(message || '').replace(/\s+/g, ' ').trim().slice(0, 600);+ return { guard: String(id), note: text };+}++/**+ * Attach advisory notes to a tool result. They go first, so a result that+ * is truncated for the model keeps them, and duplicates collapse.+ */+export function withGuardAdvisories(result, advisories) {+ const list = [];+ const seen = new Set();+ for (const item of Array.isArray(advisories) ? advisories : []) {+ if (!item || typeof item !== 'object' || !item.guard) continue;+ const key = `${item.guard}\u0000${item.note || ''}`;+ if (seen.has(key)) continue;+ seen.add(key);+ list.push({ guard: String(item.guard), note: String(item.note || '') });+ }+ if (!list.length || !result || typeof result !== 'object' || Array.isArray(result)) return result;+ const existing = Array.isArray(result.guardAdvisories) ? result.guardAdvisories : [];+ const merged = [...existing];+ for (const item of list) {+ if (!merged.some(prior => prior?.guard === item.guard && prior?.note === item.note)) merged.push(item);+ }+ const { guardAdvisories: _drop, ...rest } = result;+ return { guardAdvisories: merged, ...rest };+}diff --git a/src/firefox/src/agent/loop-detector.js b/src/firefox/src/agent/loop-detector.jsindex 7809cb462..1a9420b98 100644--- a/src/firefox/src/agent/loop-detector.js+++ b/src/firefox/src/agent/loop-detector.js@@ -78,6 +78,12 @@ export class LoopDetector {_isToolResultErroredForLoop(name, _args, result) {if (!result || typeof result !== 'object') return false;+ // A text write that went out but could not be read back exactly is an+ // advisory result (success with unverifiedWrite, see the agent's+ // text-write advisories), not a failed target: a content failureScope+ // such as 'field-value:<ref>' must not count it toward the stop.+ // Refusals and real errors are reported as failures and still count.+ if (result.success === true && result.unverifiedWrite === true && !result.error) return false;if (result.error || result.success === false || result.noProgress) return true;const status = Number(result.status);return URL_FAMILY_TOOLS.has(name) && Number.isFinite(status) && status >= 400;diff --git a/src/firefox/src/agent/page-feedback.js b/src/firefox/src/agent/page-feedback.jsindex ef1b5ce6c..357047f10 100644--- a/src/firefox/src/agent/page-feedback.js+++ b/src/firefox/src/agent/page-feedback.js@@ -1390,12 +1390,33 @@ export const pageFeedbackMethods = {// target the certificate cannot bind at all is answered first and// precisely: a probe of an ambiguous selector could only pick one of its// elements. Anything else is left to the dispatch wrapper.- async _pageFeedbackUnbindableResult(tabId, name, args = {}) {+ async _pageFeedbackUnbindableResult(tabId, name, args = {}, advisories = null) {const run = this._pageFeedbackRuns?.get(tabId);if (!run || typeof args?.selector !== 'string' || !args.selector.trim() || !this.constructor.STATE_CHANGE_TOOLS?.has(name)|| pageFeedbackCallPolicy(name, args, run.modelState, run.latestPage).kind !== 'bound_target') return null;if (await this._validatePageFeedbackAction(tabId, name, args, run.modelState, null, { answerOnly: true }) !== false) return null;- return run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}` ? actionBindingUnavailableResult(run, name) : null;+ if (run.actionBindingUnavailable !== `${name}:${JSON.stringify(args)}`) return null;+ return this._pageFeedbackBindingAdvises(tabId, run, args, advisories) ? null : actionBindingUnavailableResult(run, name);+ },++ // page-feedback-target-binding (quality): the observed action certificate+ // does not cover this call's ref (target_uncovered: the element the model+ // read exists and is unique, but the certified observation did not include+ // it). With nothing else pending (no page activity, so no human input or+ // unknown attribution, and no correction), Strict checks off sends the call+ // with the ordinary unbound semantics and a note; the dispatch fences at the+ // transport still run. A selector may name an element the model never+ // observed (an upload slot it guessed, say), and a selector naming several+ // elements or none has no single element to send to: those keep their+ // answer, as does anything pending.+ _pageFeedbackBindingAdvises(tabId, run, args = {}, advisories = null) {+ if (!run || run.events.size || run.actionBindingUnavailableReason !== 'target_uncovered'+ || typeof args?.ref_id !== 'string' || !/^ref_[A-Za-z0-9_-]+$/.test(args.ref_id)+ || (typeof args?.selector === 'string' && args.selector.trim())+ || this._hasPendingSteering?.(tabId) || typeof this._guardAdvisesFor !== 'function') return false;+ return this._guardAdvisesFor(advisories, 'page-feedback-target-binding',+ 'This target was outside the page observation WebBrain certified for this action, so its binding to what you observed was not checked. It was sent anyway; read the page to confirm what it changed.',+ { decided: false });},_pageFeedbackBlocksCall(tabId, name, args = {}) {@@ -1777,7 +1798,11 @@ export function installPageFeedback(Agent) {let modelBound = !!run && mutation && policy.kind === 'bound_target';if (modelBound) {const validated = await this._validatePageFeedbackAction(tabId, name, args, modelState, batchId);- if (validated === false) return run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}`+ const unbindable = validated === false && run.actionBindingUnavailable === `${name}:${JSON.stringify(args)}`;+ // A pure binding failure with nothing else pending may advise instead+ // (it then dispatches with the ordinary, unbound semantics below).+ if (validated === false && !(unbindable+ && this._pageFeedbackBindingAdvises(tabId, run, args, executionContext?.guardAdvisories))) return unbindable? actionBindingUnavailableResult(run, name): run.actionContextUnverified === true? { ...pageFeedbackPendingResult(), actionContextUnverified: true, errorCode: 'action_context_unverified',diff --git a/src/firefox/src/agent/tools.js b/src/firefox/src/agent/tools.jsindex 9f984ae17..02eb0dab0 100644--- a/src/firefox/src/agent/tools.js+++ b/src/firefox/src/agent/tools.js@@ -207,7 +207,7 @@ export const AGENT_TOOLS = [type: 'function',function: {name: 'set_field',- description: 'Focus + (optionally clear) + type text into a form field by ref_id, then verify the exact settled value. Prefer set_field({submit:true}) for search fields. Enter is sent only after verification succeeds. If dispatch occurred but exact readback fails, the result reports mutationMayHaveOccurred:true and recoveryRequired:"verify_or_restore_field"; do not switch typing tools or resend text blindly.',+ description: 'Focus + (optionally clear) + type text into a form field by ref_id, then verify the exact settled value. Prefer set_field({submit:true}) for search fields. Enter is sent only after verification succeeds. If dispatch occurred but exact readback fails, the result reports verified:false and says what to check; do not switch typing tools or resend text blindly.',parameters: {type: 'object',properties: {diff --git a/src/firefox/src/background.js b/src/firefox/src/background.jsindex 1c8cda1b4..e0829da69 100644--- a/src/firefox/src/background.js+++ b/src/firefox/src/background.js@@ -533,8 +533,9 @@ async function loadResearchEscalation() {const researchEscalationReady = loadResearchEscalation().catch(() => {});async function loadStrictSecretMode() {- const stored = await browser.storage.local.get('strictSecretMode').catch(() => ({}));+ const stored = await browser.storage.local.get(['strictSecretMode', 'strictGuards']).catch(() => ({}));agent.strictSecretMode = stored?.strictSecretMode === true;+ agent.strictGuards = stored?.strictGuards === true;}const strictSecretModeReady = loadStrictSecretMode().catch(() => {});@@ -1208,6 +1209,9 @@ browser.storage.onChanged.addListener((changes, areaName) => {browserBatchSettingsRevision++;agent.setBrowserBatchEnabled(changes.browserBatchEnabled.newValue !== false);}+ if (changes.strictGuards) {+ agent.strictGuards = changes.strictGuards.newValue === true;+ }if (changes.strictSecretMode) {agent.strictSecretMode = changes.strictSecretMode.newValue === true;// Strict mode also appends a global system note after enabled skills, sodiff --git a/src/firefox/src/bidi/client.js b/src/firefox/src/bidi/client.jsindex a5a7188b5..087cdd4a2 100644--- a/src/firefox/src/bidi/client.js+++ b/src/firefox/src/bidi/client.js@@ -201,14 +201,22 @@ export class FirefoxBidiClient {if (message.actionDeadlineAt && Date.now() >= message.actionDeadlineAt) return { success: false, dispatched: false, noDispatch: true, deadlineExpired: true };const metadata = { fieldMeta: prepared.fieldMeta, ...(message.params?.ref_id ? { ref_id: message.params.ref_id } : {}) };try {- return { ...metadata, ...await this.perform(tabId, action, {+ const performed = await this.perform(tabId, action, {...message.params,token, frameId: options?.frameId || 0,url: prepared.url,point: prepared.point || null,checkable: prepared.checkable || null,deadlineAt: message.actionDeadlineAt || 0,- }, { onDispatch }), ...(prepared.rect ? { rect: prepared.rect } : {}), ...(prepared._filePickerGuardId ? { _filePickerGuardId: prepared._filePickerGuardId } : {}) };+ }, { onDispatch });+ // The companion answers verified:false only from its settled readback+ // after trusted typing went out. Its rich-text reader falls back to+ // innerText, so the agent's policy decides whether that is a failure+ // (Strict checks) or a noted, unverified success.+ const unverified = (action === 'type' || action === 'field') && performed?.success === false+ && performed.dispatched === true && performed.verified === false && !performed.unverified+ ? { unverified: { reason: 'readback_mismatch', reader: 'unknown' } } : {};+ return { ...metadata, ...performed, ...unverified, ...(prepared.rect ? { rect: prepared.rect } : {}), ...(prepared._filePickerGuardId ? { _filePickerGuardId: prepared._filePickerGuardId } : {}) };} catch (error) {if (error?.name === 'AbortError' && isBidiRequestNotSentError(error)) throw error;// A refusal before the native request was posted sent nothing. Adiff --git a/src/firefox/src/config-transfer.js b/src/firefox/src/config-transfer.jsindex 067127f65..e652102ef 100644--- a/src/firefox/src/config-transfer.js+++ b/src/firefox/src/config-transfer.js@@ -57,6 +57,7 @@ export const DEFAULT_CONFIG_SETTINGS = Object.freeze({tracingEnabled: false,feedbackDiagnosticsEnabled: true,strictSecretMode: false,+ strictGuards: false,agentAllowLocalNetwork: false,scheduledTasksEnabled: true,scheduledRequireConsequentialConfirmation: true,@@ -140,6 +141,7 @@ const BOOLEAN_KEYS = new Set(['tracingEnabled','feedbackDiagnosticsEnabled','strictSecretMode',+ 'strictGuards','agentAllowLocalNetwork','scheduledTasksEnabled','scheduledRequireConsequentialConfirmation',diff --git a/src/firefox/src/content/content.js b/src/firefox/src/content/content.jsindex f64a164dd..3c3ca5b56 100644--- a/src/firefox/src/content/content.js+++ b/src/firefox/src/content/content.js@@ -2983,10 +2983,19 @@const accepted = options.dispatch ? options.dispatch(invoke) : invoke();await wait(); await wait();if (expired()) return deadlineFailure();- if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.');+ // From here the paste went out. `unverified` tells the agent the text+ // was sent but its settled value is unconfirmed; its policy decides+ // whether that is a failure (Strict checks) or a noted success.+ if (!current() || active() !== el || !within(range())) return failure('The editor scope changed during plain-text paste.',+ { unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });const value = readDocument(el), expected = (clear ? '' : previous) + text;if (accepted || typeof value !== 'string' || value !== expected) {- return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.');+ const readable = typeof value === 'string';+ return failure('The complete settled DraftJS value could not be verified after plain-text paste. No additional text was sent.', {+ unverified: { reason: !readable ? 'readback_unavailable' : value !== expected ? 'readback_mismatch' : 'paste_not_consumed',+ reader: readable ? 'semantic' : 'none' },+ readbackExact: readable,+ });}return { success: true, verified: true, dispatched: true, outcomeUnknown: false,pageHandledPaste: true, method: 'contenteditable-page-handled-paste', value: value.slice(0, 100) };@@ -3039,6 +3048,17 @@}const semanticEditor = readProseMirrorText(el) !== null;const readValue = () => _editableTextValue(el);+ // Which reader readValue used: a document reader is exact, innerText is+ // the browser's rendered layout (block editors read blank lines twice).+ const readbackReader = () => !el.isConnected ? 'none'+ : (draftJsEditor ? readDraftJsText(el) : (readProseMirrorText(el) ?? readCodeMirrorText(el) ?? readEmptyCaretText(el))) !== null+ || _nativeChatCaretValueIsEmpty(el) ? 'semantic' : 'rendered';+ // The text went out but its settled value is unconfirmed; the agent's+ // policy decides between a failure (Strict checks) and a noted success.+ const unverifiedWrite = reason => {+ const reader = readbackReader();+ return { unverified: { reason: reader === 'none' ? 'element_replaced' : reason, reader }, readbackExact: reader === 'semantic' };+ };const previous = readValue();const nativeClearContext = clear && text === '' ? _nativeChatCaretContext(el) : null;const selectContents = (collapse) => {@@ -3092,7 +3112,9 @@&& ((!nativeContextBefore && !nativeContextAfter)|| _sameNativeChatCaretContext(nativeContextBefore, nativeContextAfter));const unknown = () => failure('The editor handled a cancelled beforeinput and changed. Its complete value could not be verified in the same scope. No additional text was dispatched.',- { cancelled: true, recoveryRequired: 'verify_or_restore_field', retryable: false });+ { cancelled: true, recoveryRequired: 'verify_or_restore_field', retryable: false,+ // The page applied the text itself; a handled deletion sent none.+ ...(inputType === 'insertText' ? unverifiedWrite('page_handled_input') : {}) });if (!sameScope || (draftJsEditor && readDraftJsText(el) === null) || (el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return unknown();try {if (verifyNativeObservation) {@@ -3190,17 +3212,19 @@if (actionDeadlineExpired()) return expired();if (draftJsEditor && readDraftJsText(el) === null) {return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { recoveryRequired: 'verify_or_restore_field', retryable: false });+ { recoveryRequired: 'verify_or_restore_field', retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });}if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) {return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { recoveryRequired: 'verify_or_restore_field', retryable: false });+ { recoveryRequired: 'verify_or_restore_field', retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false });}const value = readValue();const expected = clear ? text : previous + text;const normalize = value => String(value).replace(/\r\n?/g, '\n');if (!el.isConnected || normalize(value) !== normalize(expected)) {- return failure('The complete settled rich-text value could not be verified exactly.');+ return failure('The complete settled rich-text value could not be verified exactly.', unverifiedWrite('readback_mismatch'));}return {success: true, verified: true, dispatched,@@ -8995,19 +9019,25 @@await new Promise(resolve => setTimeout(resolve, SET_FIELD_VERIFY_DELAY_MS));if (actionDeadlineExpired()) return deadlineFailure();+ // Past this point the value went out. `unverified` marks a write+ // whose settled value is unconfirmed; the agent's policy decides+ // whether that is a failure (Strict checks) or a noted success.if (!el.isConnected) {return failure(`ref_id ${ref_id} was replaced while the value was being typed. Re-read the accessibility tree and retry with the current field ref_id.`,- { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false, fieldMeta },+ { ref_id, verified: false, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false, fieldMeta,+ unverified: { reason: 'element_replaced', reader: 'none' }, readbackExact: false },);}if (isDraftJsEditor(el) && readDraftJsText(el) === null) return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = selectExpected !== null@@ -9015,6 +9045,10 @@: _setFieldValueMatches(actual, previous, text, !!clear, el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null));const fallbackAttempted = false;if (!verified) {+ // Input values and document readers are exact; innerText is the+ // rendered layout (block editors read blank lines twice).+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return failure('The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{@@ -9028,6 +9062,8 @@recoveryRequired: 'verify_or_restore_field',failureScope: `field-value:${ref_id}`,retryable: false,+ unverified: { reason: 'readback_mismatch', reader },+ readbackExact: reader !== 'rendered',},);}@@ -9182,6 +9218,8 @@// value rather than accepting a matching substring.await new Promise(resolve => setTimeout(resolve, SET_FIELD_VERIFY_DELAY_MS));if (actionDeadlineExpired()) return deadlineFailure();+ // `unverified` marks a value that went out but is unconfirmed (see+ // type_ax); a recovered draft that typed nothing stays no-dispatch.if (!el.isConnected) {return failure(`ref_id ${ref_id} was replaced while the value was being set. Re-read the accessibility tree and retry with the current field ref_id.`,@@ -9191,17 +9229,21 @@recoveryRequired: 'verify_or_restore_field',failureScope: `field-value:${ref_id}`,retryable: false,+ unverified: { reason: 'element_replaced', reader: 'none' },+ readbackExact: false,},);}const fieldMeta = _fieldMeta(el);if (isDraftJsEditor(el) && readDraftJsText(el) === null) return failure('The DraftJS editor structure changed during typing and cannot establish its exact document text.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);if ((el.isContentEditable && el.classList?.contains('cm-content') && readCodeMirrorText(el) === null)) return failure('The CodeMirror editor shows only part of its document (a viewport gap or folded text), so its exact text cannot be read.',- { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false },+ { ref_id, verified: false, fieldMeta, recoveryRequired: 'verify_or_restore_field', failureScope: `field-value:${ref_id}`, retryable: false,+ unverified: { reason: 'readback_unavailable', reader: 'none' }, readbackExact: false },);const actual = el.isContentEditable ? _editableTextValue(el) : (el.value || '');const verified = _setFieldValueMatches(actual, prevValue, text, clear, el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null));@@ -9367,6 +9409,11 @@}}if (!verified) {+ // Input values and document readers are exact; innerText is the+ // rendered layout (block editors read blank lines twice). The+ // bundled submit above was withheld for this unverified value.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return failure('The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.',{@@ -9380,6 +9427,8 @@recoveryRequired: 'verify_or_restore_field',failureScope: `field-value:${ref_id}`,retryable: false,+ unverified: { reason: 'readback_mismatch', reader },+ readbackExact: reader !== 'rendered',},);}@@ -9427,6 +9476,10 @@const expectedPrefix = verifiesAppend? expected.slice(0, expected.length - appendText.length): '';+ // 'rendered' (innerText) readback is the browser's layout, so a+ // mismatch cannot tell a wrong write from a reader artifact.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return {success: true,verified: verifiesAppend && !expected.endsWith(appendText)@@ -9439,6 +9492,8 @@el.isContentEditable, (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null),),actual: actual.slice(0, 200),+ reader,+ readbackExact: reader !== 'rendered',fieldMeta: _fieldMeta(el),};} catch (error) {@@ -9501,6 +9556,9 @@const valueSha256 = [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');+ // A 'rendered' digest hashes innerText, not the editor's document.+ const reader = !el.isContentEditable ? 'exact'+ : (readProseMirrorText(el) !== null || readCodeMirrorText(el) !== null || readDraftJsText(el) !== null || readEmptyCaretText(el) !== null) ? 'semantic' : 'rendered';return {success: true,...(typeof expected === 'string' ? {@@ -9508,6 +9566,8 @@} : {}),valueLength: value.length,valueSha256,+ reader,+ readbackExact: reader !== 'rendered',fieldMeta: _fieldMeta(el),stableSelector: _stableFieldSelector(el),};diff --git a/src/firefox/src/ui/locales/ar.js b/src/firefox/src/ui/locales/ar.jsindex 0e4aace07..b27bccb27 100644--- a/src/firefox/src/ui/locales/ar.js+++ b/src/firefox/src/ui/locales/ar.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "ماذا يفعل WebBrain عندما لا تجيب عن سؤال في الوقت المحدد. «إنهاء المهمة» يختار الإجابة التي تُبقي المهمة مستمرة، فلا تتوقف أثناء غيابك. «الحذر» يختار الإجابة الآمنة ولا يتخذ خطوات مؤثرة بدونك. في الحالتين، تأخذ الأسئلة المتعلقة بحذف البيانات أو إنفاق المال أو بيانات الاعتماد أو مستلم الرسالة أو نشر شيء لم تطلبه الإجابة الآمنة دائمًا، وتنتظرك بطاقات التأكيد الخاصة بـ WebBrain دائمًا.","st.display.clarify_timeout_policy.finish": "إنهاء المهمة","st.display.clarify_timeout_policy.safe": "الحذر",+ "st.display.strict_guards.label": "فحوص صارمة",+ "st.display.strict_guards.desc": "إيقاف (الافتراضي): فقط فحوص WebBrain المتعلقة بحذف البيانات وإنفاق المال وبيانات الاعتماد والمستلم الخاطئ ونشر شيء لم تطلبه يمكنها إيقاف إجراء؛ وتُمرَّر فحوصه الأخرى إلى النموذج كملاحظات حتى لا تتعطل المهام. تشغيل: يوقف كل فحص الإجراء كلما تعذّر عليه تأكيده، كما في السابق.",'st.display.always_allow_api_mutations.label': "السماح دائمًا بتعديلات API",'st.display.always_allow_api_mutations.desc': "اسمح لـ WebBrain باستخدام POST وPUT وPATCH وDELETE عبر fetch_url أو research_url دون الحاجة إلى /allow-api في كل محادثة. تظل إرشادات أولوية واجهة المستخدم وفحوصات التأكيد سارية. مفعّل افتراضيًا.",'st.display.api_mutation_observer.label': 'مراقب تحولات API',diff --git a/src/firefox/src/ui/locales/bn.js b/src/firefox/src/ui/locales/bn.jsindex bea42595c..375b787cb 100644--- a/src/firefox/src/ui/locales/bn.js+++ b/src/firefox/src/ui/locales/bn.js@@ -700,6 +700,8 @@ export default {"st.display.clarify_timeout_policy.desc": "সময়মতো কোনো প্রশ্নের উত্তর না দিলে WebBrain কী করবে। “কাজ শেষ করুন” এমন উত্তর বেছে নেয় যা কাজ এগিয়ে নেয়, তাই আপনি দূরে থাকলেও কাজ থেমে থাকে না। “নিরাপদ থাকুন” নিরাপদ উত্তর বেছে নেয় এবং আপনাকে ছাড়া গুরুত্বপূর্ণ পদক্ষেপ নেয় না। যেকোনো ক্ষেত্রে, ডেটা মুছে ফেলা, অর্থ ব্যয়, ক্রেডেনশিয়াল, বার্তার প্রাপক বা আপনি চাননি এমন কিছু প্রকাশ সম্পর্কিত প্রশ্নে সবসময় নিরাপদ উত্তর নেওয়া হয়, আর WebBrain-এর নিজস্ব নিশ্চিতকরণ কার্ড সবসময় আপনার জন্য অপেক্ষা করে।","st.display.clarify_timeout_policy.finish": "কাজ শেষ করুন","st.display.clarify_timeout_policy.safe": "নিরাপদ থাকুন",+ "st.display.strict_guards.label": "কঠোর যাচাই",+ "st.display.strict_guards.desc": "বন্ধ (ডিফল্ট): শুধু ডেটা মুছে ফেলা, অর্থ ব্যয়, ক্রেডেনশিয়াল, ভুল প্রাপক এবং আপনি চাননি এমন কিছু প্রকাশ সম্পর্কিত WebBrain-এর যাচাই কোনো কাজ থামাতে পারে; অন্য যাচাইগুলো মডেলকে নোট হিসেবে জানানো হয়, যাতে কাজ আটকে না যায়। চালু: আগের মতো, নিশ্চিত করতে না পারলে প্রতিটি যাচাই কাজটি থামিয়ে দেয়।",'st.display.verbose.label': "ভার্বোস মোড",'st.display.verbose.desc': "সম্পূর্ণ টুল কল বিশদ বিবরণ, আর্গুমেন্ট, এবং কাঁচা JSON ফলাফল দেখান। ক্লিনার চ্যাটের অভিজ্ঞতার জন্য ডিফল্টরূপে বন্ধ।",'st.display.selection_shortcut.label': "নির্বাচন শর্টকাট",diff --git a/src/firefox/src/ui/locales/de.js b/src/firefox/src/ui/locales/de.jsindex ea233b13e..83fd4b77e 100644--- a/src/firefox/src/ui/locales/de.js+++ b/src/firefox/src/ui/locales/de.js@@ -697,6 +697,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Was WebBrain tut, wenn Sie eine Frage nicht rechtzeitig beantworten. „Aufgabe abschließen“ wählt die Antwort, mit der die Aufgabe weiterläuft, damit nichts stehen bleibt, während Sie weg sind. „Auf Nummer sicher“ wählt die sichere Antwort und unternimmt ohne Sie keine folgenreichen Schritte. In beiden Fällen nehmen Fragen zum Löschen von Daten, zu Geldausgaben, Zugangsdaten, dem Empfänger einer Nachricht oder zum Veröffentlichen von etwas, das Sie nicht verlangt haben, immer die sichere Antwort, und WebBrains eigene Bestätigungskarten warten immer auf Sie.","st.display.clarify_timeout_policy.finish": "Aufgabe abschließen","st.display.clarify_timeout_policy.safe": "Auf Nummer sicher",+ "st.display.strict_guards.label": "Strenge Prüfungen",+ "st.display.strict_guards.desc": "Aus (Standard): Nur WebBrains Prüfungen zum Löschen von Daten, zu Geldausgaben, Zugangsdaten, dem falschen Empfänger und zum Veröffentlichen von etwas, das Sie nicht verlangt haben, können eine Aktion stoppen; die übrigen Prüfungen gehen als Hinweise an das Modell, damit Aufgaben nicht hängen bleiben. An: Jede Prüfung stoppt die Aktion, sobald sie sie nicht bestätigen kann, wie bisher.",'st.display.verbose.label': 'Ausführlicher Modus','st.display.verbose.desc': 'Zeigt vollständige Tool-Call-Details, Argumente und rohes JSON-Ergebnis. Standardmäßig deaktiviert für ein aufgeräumteres Chat-Erlebnis.','st.display.selection_shortcut.label': 'Auswahlverknüpfung',diff --git a/src/firefox/src/ui/locales/en.js b/src/firefox/src/ui/locales/en.jsindex 520f6b31f..9acc98371 100644--- a/src/firefox/src/ui/locales/en.js+++ b/src/firefox/src/ui/locales/en.js@@ -705,6 +705,8 @@ export default {"st.display.clarify_timeout_policy.desc": "What WebBrain does when you don’t answer a question in time. Finish the task picks the answer that keeps the task going, so runs don’t stall while you’re away. Play it safe picks the safe answer and won’t take consequential steps without you. Either way, questions about deleting data, spending money, credentials, who receives a message, or publishing something you didn’t ask for always take the safe answer, and WebBrain’s own confirmation cards always wait for you.","st.display.clarify_timeout_policy.finish": "Finish the task","st.display.clarify_timeout_policy.safe": "Play it safe",+ "st.display.strict_guards.label": "Strict checks",+ "st.display.strict_guards.desc": "Off (default): only WebBrain’s checks for deleting data, spending money, credentials, the wrong recipient, and publishing something you didn’t ask for can stop an action; its other checks are passed to the model as notes so runs don’t get stuck. On: every check stops the action whenever it can’t confirm it, as before.",'st.display.verbose.label': 'Verbose Mode','st.display.verbose.desc': 'Show full tool call details, arguments, and raw JSON results. Off by default for a cleaner chat experience.','st.display.selection_shortcut.label': 'Selection shortcut',diff --git a/src/firefox/src/ui/locales/es.js b/src/firefox/src/ui/locales/es.jsindex fa6aa8c07..504f1c70b 100644--- a/src/firefox/src/ui/locales/es.js+++ b/src/firefox/src/ui/locales/es.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Qué hace WebBrain cuando no respondes una pregunta a tiempo. «Terminar la tarea» elige la respuesta que mantiene la tarea en marcha, para que no se detenga mientras no estás. «Ir a lo seguro» elige la respuesta segura y no da pasos importantes sin ti. En ambos casos, las preguntas sobre borrar datos, gastar dinero, credenciales, quién recibe un mensaje o publicar algo que no pediste siempre toman la respuesta segura, y las tarjetas de confirmación propias de WebBrain siempre te esperan.","st.display.clarify_timeout_policy.finish": "Terminar la tarea","st.display.clarify_timeout_policy.safe": "Ir a lo seguro",+ "st.display.strict_guards.label": "Comprobaciones estrictas",+ "st.display.strict_guards.desc": "Desactivado (predeterminado): solo las comprobaciones de WebBrain sobre borrar datos, gastar dinero, credenciales, el destinatario equivocado y publicar algo que no pediste pueden detener una acción; las demás se pasan al modelo como notas para que las tareas no se atasquen. Activado: cada comprobación detiene la acción cuando no puede confirmarla, como antes.",'st.display.always_allow_api_mutations.label': "Permitir siempre mutaciones de API",'st.display.always_allow_api_mutations.desc': "Permite que WebBrain use POST, PUT, PATCH y DELETE mediante fetch_url o research_url sin requerir /allow-api en cada conversación. Las directrices de priorizar la interfaz y las comprobaciones de confirmación siguen vigentes. Activado de forma predeterminada.",'st.display.api_mutation_observer.label': 'Observador de mutaciones de API',diff --git a/src/firefox/src/ui/locales/fa.js b/src/firefox/src/ui/locales/fa.jsindex b80be1538..994e2245a 100644--- a/src/firefox/src/ui/locales/fa.js+++ b/src/firefox/src/ui/locales/fa.js@@ -700,6 +700,8 @@ export default {"st.display.clarify_timeout_policy.desc": "اگر به یک سؤال بهموقع پاسخ ندهید، WebBrain چه میکند. «تمام کردن کار» پاسخی را انتخاب میکند که کار را پیش میبرد تا در نبود شما متوقف نشود. «احتیاط» پاسخ امن را انتخاب میکند و بدون شما قدمهای مهم برنمیدارد. در هر دو حالت، سؤالهای مربوط به حذف داده، خرج کردن پول، اطلاعات ورود، گیرنده پیام یا انتشار چیزی که نخواستهاید همیشه پاسخ امن را میگیرند و کارتهای تأیید خود WebBrain همیشه منتظر شما میمانند.","st.display.clarify_timeout_policy.finish": "تمام کردن کار","st.display.clarify_timeout_policy.safe": "احتیاط",+ "st.display.strict_guards.label": "بررسیهای سختگیرانه",+ "st.display.strict_guards.desc": "خاموش (پیشفرض): فقط بررسیهای WebBrain درباره حذف داده، خرج کردن پول، اطلاعات ورود، گیرنده اشتباه و انتشار چیزی که نخواستهاید میتوانند یک اقدام را متوقف کنند؛ بقیه بررسیها بهصورت یادداشت به مدل داده میشوند تا کارها گیر نکنند. روشن: مثل قبل، هر بررسی هر وقت نتواند اقدام را تأیید کند آن را متوقف میکند.",'st.display.verbose.label': "حالت پرمخاطب",'st.display.verbose.desc': "جزئیات تماس کامل ابزار، آرگومان ها و نتایج خام JSON را نمایش دهید. به طور پیشفرض برای تجربه چت تمیزتر خاموش است.",'st.display.selection_shortcut.label': "میانبر انتخاب",diff --git a/src/firefox/src/ui/locales/fr.js b/src/firefox/src/ui/locales/fr.jsindex 448b30609..6503f6742 100644--- a/src/firefox/src/ui/locales/fr.js+++ b/src/firefox/src/ui/locales/fr.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Ce que fait WebBrain quand vous ne répondez pas à temps à une question. « Terminer la tâche » choisit la réponse qui fait avancer la tâche, pour qu’elle ne reste pas bloquée en votre absence. « Prudence » choisit la réponse sûre et ne fait rien d’important sans vous. Dans les deux cas, les questions sur la suppression de données, les dépenses, les identifiants, le destinataire d’un message ou la publication de quelque chose que vous n’avez pas demandé prennent toujours la réponse sûre, et les cartes de confirmation de WebBrain vous attendent toujours.","st.display.clarify_timeout_policy.finish": "Terminer la tâche","st.display.clarify_timeout_policy.safe": "Prudence",+ "st.display.strict_guards.label": "Vérifications strictes",+ "st.display.strict_guards.desc": "Désactivé (par défaut) : seules les vérifications de WebBrain sur la suppression de données, les dépenses, les identifiants, le mauvais destinataire et la publication de quelque chose que vous n’avez pas demandé peuvent arrêter une action ; ses autres vérifications sont transmises au modèle sous forme de notes pour que les tâches ne restent pas bloquées. Activé : chaque vérification arrête l’action dès qu’elle ne peut pas la confirmer, comme avant.",'st.display.always_allow_api_mutations.label': "Toujours autoriser les mutations API",'st.display.always_allow_api_mutations.desc': "Autoriser WebBrain à utiliser POST, PUT, PATCH et DELETE via fetch_url ou research_url sans exiger /allow-api dans chaque conversation. Les directives UI-d’abord et les confirmations restent applicables. Activé par défaut.",'st.display.api_mutation_observer.label': 'Observateur de mutations API',diff --git a/src/firefox/src/ui/locales/he.js b/src/firefox/src/ui/locales/he.jsindex 4586cbff2..a9c2bde4b 100644--- a/src/firefox/src/ui/locales/he.js+++ b/src/firefox/src/ui/locales/he.js@@ -677,6 +677,8 @@ export default {"st.display.clarify_timeout_policy.desc": "מה WebBrain עושה כשלא עונים לשאלה בזמן. „לסיים את המשימה” בוחר את התשובה שממשיכה את המשימה, כדי שהיא לא תיתקע כשאתם לא ליד המחשב. „ליתר ביטחון” בוחר את התשובה הבטוחה ולא מבצע צעדים משמעותיים בלעדיכם. בכל מקרה, שאלות על מחיקת נתונים, הוצאת כסף, פרטי התחברות, נמען של הודעה או פרסום של משהו שלא ביקשתם תמיד מקבלות את התשובה הבטוחה, וכרטיסי האישור של WebBrain תמיד ממתינים לכם.","st.display.clarify_timeout_policy.finish": "לסיים את המשימה","st.display.clarify_timeout_policy.safe": "ליתר ביטחון",+ "st.display.strict_guards.label": "בדיקות מחמירות",+ "st.display.strict_guards.desc": "כבוי (ברירת מחדל): רק בדיקות של WebBrain על מחיקת נתונים, הוצאת כסף, פרטי התחברות, נמען שגוי ופרסום של משהו שלא ביקשתם יכולות לעצור פעולה; שאר הבדיקות מועברות למודל כהערות כדי שמשימות לא ייתקעו. פועל: כל בדיקה עוצרת את הפעולה כשאינה יכולה לאשר אותה, כמו קודם.","st.display.verbose.label": "מצב מילולי","st.display.verbose.desc": "הצג פרטים מלאים של שיחת הכלים, טיעונים וגולמיים JSON תוצאות. כבוי כברירת מחדל לחוויית צ'אט נקייה יותר.","st.display.selection_shortcut.label": "קיצור דרך לבחירה",diff --git a/src/firefox/src/ui/locales/hi.js b/src/firefox/src/ui/locales/hi.jsindex b2c5361b0..8ee2b8cc8 100644--- a/src/firefox/src/ui/locales/hi.js+++ b/src/firefox/src/ui/locales/hi.js@@ -700,6 +700,8 @@ export default {"st.display.clarify_timeout_policy.desc": "जब आप किसी सवाल का समय पर जवाब नहीं देते, तब WebBrain क्या करे। “काम पूरा करें” वह जवाब चुनता है जिससे काम आगे बढ़ता रहे, ताकि आपकी गैरमौजूदगी में काम न रुके। “सुरक्षित रहें” सुरक्षित जवाब चुनता है और आपके बिना कोई अहम कदम नहीं उठाता। दोनों ही स्थितियों में, डेटा हटाने, पैसे खर्च करने, क्रेडेंशियल, संदेश पाने वाले, या ऐसी चीज़ प्रकाशित करने से जुड़े सवाल जो आपने नहीं मांगी, हमेशा सुरक्षित जवाब लेते हैं, और WebBrain के अपने पुष्टि कार्ड हमेशा आपका इंतज़ार करते हैं।","st.display.clarify_timeout_policy.finish": "काम पूरा करें","st.display.clarify_timeout_policy.safe": "सुरक्षित रहें",+ "st.display.strict_guards.label": "सख्त जांच",+ "st.display.strict_guards.desc": "बंद (डिफ़ॉल्ट): सिर्फ़ डेटा हटाने, पैसे खर्च करने, क्रेडेंशियल, गलत प्राप्तकर्ता और ऐसी चीज़ प्रकाशित करने से जुड़ी WebBrain की जांचें, जो आपने नहीं मांगी, किसी कार्रवाई को रोक सकती हैं; बाकी जांचें मॉडल को नोट के रूप में दी जाती हैं ताकि काम अटके नहीं। चालू: पहले की तरह, हर जांच पुष्टि न कर पाने पर कार्रवाई रोक देती है।",'st.display.verbose.label': "वर्बोज़ मोड",'st.display.verbose.desc': "पूर्ण टूल कॉल विवरण, तर्क और कच्चे JSON परिणाम दिखाएं। बेहतर चैट अनुभव के लिए डिफ़ॉल्ट रूप से बंद।",'st.display.selection_shortcut.label': "चयन शॉर्टकट",diff --git a/src/firefox/src/ui/locales/id.js b/src/firefox/src/ui/locales/id.jsindex 34b6a7fa7..fe18f05bd 100644--- a/src/firefox/src/ui/locales/id.js+++ b/src/firefox/src/ui/locales/id.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Apa yang dilakukan WebBrain saat Anda tidak menjawab pertanyaan tepat waktu. “Selesaikan tugas” memilih jawaban yang membuat tugas terus berjalan, agar tidak macet saat Anda pergi. “Main aman” memilih jawaban yang aman dan tidak mengambil langkah penting tanpa Anda. Dalam kedua kasus, pertanyaan tentang menghapus data, mengeluarkan uang, kredensial, penerima pesan, atau memublikasikan sesuatu yang tidak Anda minta selalu memakai jawaban yang aman, dan kartu konfirmasi WebBrain sendiri selalu menunggu Anda.","st.display.clarify_timeout_policy.finish": "Selesaikan tugas","st.display.clarify_timeout_policy.safe": "Main aman",+ "st.display.strict_guards.label": "Pemeriksaan ketat",+ "st.display.strict_guards.desc": "Nonaktif (default): hanya pemeriksaan WebBrain tentang menghapus data, mengeluarkan uang, kredensial, penerima yang salah, dan memublikasikan sesuatu yang tidak Anda minta yang dapat menghentikan tindakan; pemeriksaan lainnya diberikan ke model sebagai catatan agar tugas tidak macet. Aktif: setiap pemeriksaan menghentikan tindakan setiap kali tidak dapat memastikannya, seperti sebelumnya.",'st.display.always_allow_api_mutations.label': "Selalu izinkan mutasi API",'st.display.always_allow_api_mutations.desc': "Izinkan WebBrain menggunakan POST, PUT, PATCH, dan DELETE melalui fetch_url atau research_url tanpa memerlukan /allow-api di setiap percakapan. Panduan yang mengutamakan UI dan pemeriksaan konfirmasi tetap berlaku. Aktif secara default.",'st.display.api_mutation_observer.label': 'Pengamat mutasi API',diff --git a/src/firefox/src/ui/locales/ja.js b/src/firefox/src/ui/locales/ja.jsindex aed9c440f..c592ed582 100644--- a/src/firefox/src/ui/locales/ja.js+++ b/src/firefox/src/ui/locales/ja.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "質問に時間内に答えなかったときの WebBrain の動作です。「タスクを完了」はタスクを進める回答を選ぶので、席を外している間も止まりません。「安全に」は安全な回答を選び、あなたなしで重要な操作はしません。どちらの場合も、データの削除、支払い、認証情報、メッセージの宛先、頼んでいない公開に関する質問は常に安全な回答になり、WebBrain 自身の確認カードは常にあなたの操作を待ちます。","st.display.clarify_timeout_policy.finish": "タスクを完了","st.display.clarify_timeout_policy.safe": "安全に",+ "st.display.strict_guards.label": "厳格なチェック",+ "st.display.strict_guards.desc": "オフ(既定):アクションを止められるのは、データの削除、支払い、認証情報、誤った宛先、頼んでいない公開に関する WebBrain のチェックだけです。その他のチェックはメモとしてモデルに伝えられるので、タスクが止まりません。オン:これまでどおり、確認できないときはすべてのチェックがアクションを止めます。",'st.display.always_allow_api_mutations.label': "API変更を常に許可",'st.display.always_allow_api_mutations.desc': "会話ごとに /allow-api を必要とせず、WebBrain が fetch_url または research_url で POST、PUT、PATCH、DELETE を使用できるようにします。UI優先の指針と確認チェックは引き続き適用されます。既定ではオンです。",'st.display.api_mutation_observer.label': 'API変更オブザーバー',diff --git a/src/firefox/src/ui/locales/ko.js b/src/firefox/src/ui/locales/ko.jsindex 249dcec1e..8a7081e07 100644--- a/src/firefox/src/ui/locales/ko.js+++ b/src/firefox/src/ui/locales/ko.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "질문에 제때 답하지 않았을 때 WebBrain이 하는 일입니다. ‘작업 완료’는 작업을 계속 진행하는 답을 골라 자리를 비운 동안에도 멈추지 않게 합니다. ‘안전하게’는 안전한 답을 고르고 사용자 없이 중요한 단계를 진행하지 않습니다. 어느 쪽이든 데이터 삭제, 결제, 자격 증명, 메시지 받는 사람, 요청하지 않은 게시에 관한 질문은 항상 안전한 답을 택하며, WebBrain 자체 확인 카드는 항상 사용자를 기다립니다.","st.display.clarify_timeout_policy.finish": "작업 완료","st.display.clarify_timeout_policy.safe": "안전하게",+ "st.display.strict_guards.label": "엄격한 검사",+ "st.display.strict_guards.desc": "끔(기본값): 데이터 삭제, 결제, 자격 증명, 잘못된 받는 사람, 요청하지 않은 게시에 관한 WebBrain 검사만 작업을 멈출 수 있습니다. 다른 검사는 모델에 메모로 전달되어 작업이 멈추지 않습니다. 켬: 이전처럼 확인할 수 없을 때마다 모든 검사가 작업을 멈춥니다.",'st.display.always_allow_api_mutations.label': "API 변경 항상 허용",'st.display.always_allow_api_mutations.desc': "대화마다 /allow-api를 입력하지 않아도 WebBrain이 fetch_url 또는 research_url을 통해 POST, PUT, PATCH, DELETE를 사용하도록 허용합니다. UI 우선 지침과 확인 검사는 계속 적용됩니다. 기본적으로 켜져 있습니다.",'st.display.api_mutation_observer.label': 'API 변경 관찰자',diff --git a/src/firefox/src/ui/locales/ms.js b/src/firefox/src/ui/locales/ms.jsindex 1d88303a1..2cfd03b7c 100644--- a/src/firefox/src/ui/locales/ms.js+++ b/src/firefox/src/ui/locales/ms.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Apa yang WebBrain lakukan apabila anda tidak menjawab soalan tepat pada masanya. “Selesaikan tugas” memilih jawapan yang mengekalkan tugas berjalan, supaya ia tidak tergendala semasa anda tiada. “Berhati-hati” memilih jawapan yang selamat dan tidak mengambil langkah penting tanpa anda. Walau apa pun, soalan tentang memadam data, berbelanja, kelayakan log masuk, penerima mesej atau menerbitkan sesuatu yang anda tidak minta sentiasa mengambil jawapan yang selamat, dan kad pengesahan WebBrain sendiri sentiasa menunggu anda.","st.display.clarify_timeout_policy.finish": "Selesaikan tugas","st.display.clarify_timeout_policy.safe": "Berhati-hati",+ "st.display.strict_guards.label": "Semakan ketat",+ "st.display.strict_guards.desc": "Mati (lalai): hanya semakan WebBrain tentang memadam data, berbelanja, kelayakan log masuk, penerima yang salah dan menerbitkan sesuatu yang anda tidak minta boleh menghentikan tindakan; semakan lain disampaikan kepada model sebagai nota supaya tugas tidak tersekat. Hidup: setiap semakan menghentikan tindakan apabila ia tidak dapat mengesahkannya, seperti sebelum ini.",'st.display.always_allow_api_mutations.label': "Sentiasa benarkan mutasi API",'st.display.always_allow_api_mutations.desc': "Benarkan WebBrain menggunakan POST, PUT, PATCH dan DELETE melalui fetch_url atau research_url tanpa memerlukan /allow-api dalam setiap perbualan. Panduan mengutamakan UI dan semakan pengesahan masih terpakai. Dihidupkan secara lalai.",'st.display.api_mutation_observer.label': 'Pemerhati mutasi API',diff --git a/src/firefox/src/ui/locales/nl.js b/src/firefox/src/ui/locales/nl.jsindex 15ca315de..7f2e65f94 100644--- a/src/firefox/src/ui/locales/nl.js+++ b/src/firefox/src/ui/locales/nl.js@@ -677,6 +677,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Wat WebBrain doet als u een vraag niet op tijd beantwoordt. ‘Taak afmaken’ kiest het antwoord waarmee de taak doorgaat, zodat niets blijft hangen terwijl u weg bent. ‘Op veilig spelen’ kiest het veilige antwoord en zet zonder u geen ingrijpende stappen. Hoe dan ook krijgen vragen over gegevens verwijderen, geld uitgeven, inloggegevens, wie een bericht ontvangt of iets publiceren waar u niet om vroeg altijd het veilige antwoord, en de eigen bevestigingskaarten van WebBrain wachten altijd op u.","st.display.clarify_timeout_policy.finish": "Taak afmaken","st.display.clarify_timeout_policy.safe": "Op veilig spelen",+ "st.display.strict_guards.label": "Strenge controles",+ "st.display.strict_guards.desc": "Uit (standaard): alleen de controles van WebBrain op gegevens verwijderen, geld uitgeven, inloggegevens, de verkeerde ontvanger en iets publiceren waar u niet om vroeg kunnen een actie stoppen; de andere controles gaan als notities naar het model, zodat taken niet vastlopen. Aan: elke controle stopt de actie zodra die haar niet kan bevestigen, zoals voorheen.",'st.display.verbose.label': 'Uitvoerige modus','st.display.verbose.desc': 'Toon volledige toolaanroepdetails, argumenten en onbewerkte JSON-resultaten...','st.display.selection_shortcut.label': 'Selectiesneltoets',diff --git a/src/firefox/src/ui/locales/pl.js b/src/firefox/src/ui/locales/pl.jsindex 36a152788..2b5be98ce 100644--- a/src/firefox/src/ui/locales/pl.js+++ b/src/firefox/src/ui/locales/pl.js@@ -862,6 +862,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Co robi WebBrain, gdy nie odpowiesz na pytanie na czas. „Dokończ zadanie” wybiera odpowiedź, która pozwala kontynuować zadanie, żeby nie stało w miejscu pod twoją nieobecność. „Ostrożnie” wybiera bezpieczną odpowiedź i nie wykonuje bez ciebie żadnych ważnych kroków. W obu przypadkach pytania o usuwanie danych, wydawanie pieniędzy, dane logowania, odbiorcę wiadomości lub publikację czegoś, o co nie prosiłeś, zawsze dostają bezpieczną odpowiedź, a własne karty potwierdzeń WebBrain zawsze czekają na ciebie.","st.display.clarify_timeout_policy.finish": "Dokończ zadanie","st.display.clarify_timeout_policy.safe": "Ostrożnie",+ "st.display.strict_guards.label": "Ścisłe kontrole",+ "st.display.strict_guards.desc": "Wył. (domyślnie): akcję mogą zatrzymać tylko kontrole WebBrain dotyczące usuwania danych, wydawania pieniędzy, danych logowania, złego odbiorcy i publikacji czegoś, o co nie prosiłeś; pozostałe kontrole trafiają do modelu jako uwagi, żeby zadania nie utykały. Wł.: jak dotąd każda kontrola zatrzymuje akcję, gdy nie może jej potwierdzić.",'st.display.always_allow_api_mutations.label': "Zawsze zezwalaj na mutacje API",'st.display.always_allow_api_mutations.desc': "Zezwól WebBrain na używanie POST, PUT, PATCH i DELETE przez fetch_url lub research_url bez wymagania /allow-api w każdej rozmowie. Nadal obowiązują wskazówki preferujące interfejs oraz kontrole potwierdzeń. Domyślnie włączone.",'st.display.api_mutation_observer.label': 'Obserwator mutacji API',diff --git a/src/firefox/src/ui/locales/pt.js b/src/firefox/src/ui/locales/pt.jsindex 9c597a713..667fd4610 100644--- a/src/firefox/src/ui/locales/pt.js+++ b/src/firefox/src/ui/locales/pt.js@@ -700,6 +700,8 @@ export default {"st.display.clarify_timeout_policy.desc": "O que o WebBrain faz quando você não responde a uma pergunta a tempo. “Concluir a tarefa” escolhe a resposta que mantém a tarefa andando, para que ela não fique parada enquanto você está fora. “Jogar seguro” escolhe a resposta segura e não dá passos importantes sem você. Em qualquer caso, perguntas sobre excluir dados, gastar dinheiro, credenciais, quem recebe uma mensagem ou publicar algo que você não pediu sempre ficam com a resposta segura, e os cartões de confirmação do próprio WebBrain sempre esperam por você.","st.display.clarify_timeout_policy.finish": "Concluir a tarefa","st.display.clarify_timeout_policy.safe": "Jogar seguro",+ "st.display.strict_guards.label": "Verificações rigorosas",+ "st.display.strict_guards.desc": "Desligado (padrão): só as verificações do WebBrain sobre excluir dados, gastar dinheiro, credenciais, destinatário errado e publicar algo que você não pediu podem interromper uma ação; as demais são passadas ao modelo como notas, para que as tarefas não travem. Ligado: cada verificação interrompe a ação sempre que não consegue confirmá-la, como antes.",'st.display.verbose.label': "Modo detalhado",'st.display.verbose.desc': "Mostre detalhes completos da chamada da ferramenta, argumentos e resultados JSON brutos. Desativado por padrão para uma experiência de bate-papo mais limpa.",'st.display.selection_shortcut.label': "Atalho de seleção",diff --git a/src/firefox/src/ui/locales/ru.js b/src/firefox/src/ui/locales/ru.jsindex ecfcae5b9..028accc98 100644--- a/src/firefox/src/ui/locales/ru.js+++ b/src/firefox/src/ui/locales/ru.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Что делает WebBrain, если вы не ответили на вопрос вовремя. «Завершить задачу» выбирает ответ, при котором задача продолжается, чтобы она не простаивала, пока вас нет. «Осторожно» выбирает безопасный ответ и не делает важных шагов без вас. В любом случае вопросы об удалении данных, тратах, учётных данных, получателе сообщения или публикации того, о чём вы не просили, всегда получают безопасный ответ, а собственные карточки подтверждения WebBrain всегда ждут вас.","st.display.clarify_timeout_policy.finish": "Завершить задачу","st.display.clarify_timeout_policy.safe": "Осторожно",+ "st.display.strict_guards.label": "Строгие проверки",+ "st.display.strict_guards.desc": "Выкл. (по умолчанию): остановить действие могут только проверки WebBrain, касающиеся удаления данных, трат, учётных данных, неверного получателя и публикации того, о чём вы не просили; остальные проверки передаются модели как заметки, чтобы задачи не зависали. Вкл.: как раньше, каждая проверка останавливает действие, если не может его подтвердить.",'st.display.always_allow_api_mutations.label': "Всегда разрешать изменения через API",'st.display.always_allow_api_mutations.desc': "Разрешить WebBrain использовать POST, PUT, PATCH и DELETE через fetch_url или research_url без команды /allow-api в каждом разговоре. Правило приоритета интерфейса и проверки подтверждения продолжают действовать. По умолчанию включено.",'st.display.api_mutation_observer.label': 'Наблюдатель мутаций API',diff --git a/src/firefox/src/ui/locales/th.js b/src/firefox/src/ui/locales/th.jsindex eceb7856c..8ca3c29f1 100644--- a/src/firefox/src/ui/locales/th.js+++ b/src/firefox/src/ui/locales/th.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "สิ่งที่ WebBrain ทำเมื่อคุณไม่ได้ตอบคำถามทันเวลา “ทำงานให้เสร็จ” จะเลือกคำตอบที่ทำให้งานเดินต่อ งานจึงไม่ค้างขณะที่คุณไม่อยู่ “เล่นอย่างปลอดภัย” จะเลือกคำตอบที่ปลอดภัยและไม่ทำขั้นตอนสำคัญโดยไม่มีคุณ ไม่ว่าแบบใด คำถามเกี่ยวกับการลบข้อมูล การใช้เงิน ข้อมูลรับรอง ผู้รับข้อความ หรือการเผยแพร่สิ่งที่คุณไม่ได้ขอ จะใช้คำตอบที่ปลอดภัยเสมอ และการ์ดยืนยันของ WebBrain เองจะรอคุณเสมอ","st.display.clarify_timeout_policy.finish": "ทำงานให้เสร็จ","st.display.clarify_timeout_policy.safe": "เล่นอย่างปลอดภัย",+ "st.display.strict_guards.label": "การตรวจสอบแบบเข้มงวด",+ "st.display.strict_guards.desc": "ปิด (ค่าเริ่มต้น): มีเพียงการตรวจสอบของ WebBrain เกี่ยวกับการลบข้อมูล การใช้เงิน ข้อมูลรับรอง ผู้รับที่ไม่ถูกต้อง และการเผยแพร่สิ่งที่คุณไม่ได้ขอ ที่หยุดการกระทำได้ การตรวจสอบอื่นจะส่งให้โมเดลเป็นบันทึก งานจึงไม่ค้าง เปิด: ทุกการตรวจสอบจะหยุดการกระทำเมื่อยืนยันไม่ได้ เหมือนเดิม",'st.display.always_allow_api_mutations.label': "อนุญาตการเปลี่ยนแปลง API เสมอ",'st.display.always_allow_api_mutations.desc': "อนุญาตให้ WebBrain ใช้ POST, PUT, PATCH และ DELETE ผ่าน fetch_url หรือ research_url โดยไม่ต้องใช้ /allow-api ในทุกการสนทนา แนวทางที่ให้ความสำคัญกับ UI และการตรวจสอบการยืนยันยังคงมีผล เปิดไว้โดยค่าเริ่มต้น",'st.display.api_mutation_observer.label': 'ตัวสังเกตการกลายพันธุ์ของ API',diff --git a/src/firefox/src/ui/locales/tl.js b/src/firefox/src/ui/locales/tl.jsindex 9f34a2096..58305bf1f 100644--- a/src/firefox/src/ui/locales/tl.js+++ b/src/firefox/src/ui/locales/tl.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Ano ang ginagawa ng WebBrain kapag hindi mo nasagot ang isang tanong sa oras. Pinipili ng “Tapusin ang gawain” ang sagot na nagpapatuloy sa gawain, para hindi ito tumigil habang wala ka. Pinipili ng “Mag-ingat” ang ligtas na sagot at hindi ito gagawa ng mahahalagang hakbang nang wala ka. Alinman dito, ang mga tanong tungkol sa pagbura ng data, paggastos ng pera, credentials, kung sino ang tatanggap ng mensahe, o pag-publish ng bagay na hindi mo hiningi ay laging kumukuha ng ligtas na sagot, at laging naghihintay sa iyo ang sariling confirmation cards ng WebBrain.","st.display.clarify_timeout_policy.finish": "Tapusin ang gawain","st.display.clarify_timeout_policy.safe": "Mag-ingat",+ "st.display.strict_guards.label": "Mahigpit na pagsusuri",+ "st.display.strict_guards.desc": "Naka-off (default): ang mga pagsusuri lang ng WebBrain tungkol sa pagbura ng data, paggastos ng pera, credentials, maling tatanggap, at pag-publish ng bagay na hindi mo hiningi ang makakapigil sa isang aksyon; ipinapasa sa model bilang mga tala ang iba pang pagsusuri para hindi maipit ang mga gawain. Naka-on: gaya ng dati, pinapahinto ng bawat pagsusuri ang aksyon kapag hindi nito ito makumpirma.",'st.display.always_allow_api_mutations.label': "Palaging payagan ang mga pagbabago sa API",'st.display.always_allow_api_mutations.desc': "Payagan ang WebBrain na gumamit ng POST, PUT, PATCH, at DELETE sa pamamagitan ng fetch_url o research_url nang hindi kailangan ang /allow-api sa bawat usapan. Nalalapat pa rin ang gabay na unahin ang UI at mga pagsusuri sa kumpirmasyon. Naka-on bilang default.",'st.display.api_mutation_observer.label': 'Tagamasid ng mutasyon ng API',diff --git a/src/firefox/src/ui/locales/tr.js b/src/firefox/src/ui/locales/tr.jsindex b35f8b063..8a1ea77d4 100644--- a/src/firefox/src/ui/locales/tr.js+++ b/src/firefox/src/ui/locales/tr.js@@ -879,6 +879,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Bir soruyu zamanında yanıtlamadığınızda WebBrain’in ne yapacağı. “Görevi tamamla”, görevi ilerleten yanıtı seçer; böylece siz yokken iş durmaz. “Temkinli ol”, güvenli yanıtı seçer ve siz olmadan önemli adımlar atmaz. Her iki durumda da veri silme, para harcama, kimlik bilgileri, mesajın alıcısı veya istemediğiniz bir şeyi yayınlama ile ilgili sorular her zaman güvenli yanıtı alır ve WebBrain’in kendi onay kartları her zaman sizi bekler.","st.display.clarify_timeout_policy.finish": "Görevi tamamla","st.display.clarify_timeout_policy.safe": "Temkinli ol",+ "st.display.strict_guards.label": "Katı denetimler",+ "st.display.strict_guards.desc": "Kapalı (varsayılan): bir eylemi yalnızca WebBrain’in veri silme, para harcama, kimlik bilgileri, yanlış alıcı ve istemediğiniz bir şeyi yayınlama ile ilgili denetimleri durdurabilir; diğer denetimler görevler takılmasın diye modele not olarak iletilir. Açık: önceden olduğu gibi her denetim, eylemi doğrulayamadığında durdurur.",'st.display.always_allow_api_mutations.label': "API değişikliklerine her zaman izin ver",'st.display.always_allow_api_mutations.desc': "WebBrain’in her konuşmada /allow-api gerektirmeden fetch_url veya research_url üzerinden POST, PUT, PATCH ve DELETE kullanmasına izin verin. Önce arayüz yaklaşımı ve onay kontrolleri uygulanmaya devam eder. Varsayılan olarak açıktır.",'st.display.api_mutation_observer.label': 'API mutasyon gözlemcisi',diff --git a/src/firefox/src/ui/locales/uk.js b/src/firefox/src/ui/locales/uk.jsindex b95aca2ab..20c497363 100644--- a/src/firefox/src/ui/locales/uk.js+++ b/src/firefox/src/ui/locales/uk.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "Що робить WebBrain, якщо ви не відповіли на запитання вчасно. «Завершити завдання» обирає відповідь, з якою завдання триває, щоб воно не стояло, поки вас немає. «Обережно» обирає безпечну відповідь і не робить важливих кроків без вас. У будь-якому разі запитання про видалення даних, витрати, облікові дані, отримувача повідомлення або публікацію того, про що ви не просили, завжди отримують безпечну відповідь, а власні картки підтвердження WebBrain завжди чекають на вас.","st.display.clarify_timeout_policy.finish": "Завершити завдання","st.display.clarify_timeout_policy.safe": "Обережно",+ "st.display.strict_guards.label": "Суворі перевірки",+ "st.display.strict_guards.desc": "Вимк. (типово): зупинити дію можуть лише перевірки WebBrain щодо видалення даних, витрат, облікових даних, хибного отримувача та публікації того, про що ви не просили; решта перевірок передається моделі як нотатки, щоб завдання не застрягали. Увімк.: як раніше, кожна перевірка зупиняє дію, коли не може її підтвердити.",'st.display.always_allow_api_mutations.label': "Завжди дозволяти зміни через API",'st.display.always_allow_api_mutations.desc': "Дозволити WebBrain використовувати POST, PUT, PATCH і DELETE через fetch_url або research_url без команди /allow-api в кожній розмові. Правило пріоритету інтерфейсу та перевірки підтвердження залишаються чинними. Типово ввімкнено.",'st.display.api_mutation_observer.label': 'Спостерігач мутацій API',diff --git a/src/firefox/src/ui/locales/vi.js b/src/firefox/src/ui/locales/vi.jsindex 351c7271d..aebcc0c24 100644--- a/src/firefox/src/ui/locales/vi.js+++ b/src/firefox/src/ui/locales/vi.js@@ -700,6 +700,8 @@ export default {"st.display.clarify_timeout_policy.desc": "WebBrain làm gì khi bạn không trả lời câu hỏi kịp thời. “Hoàn thành tác vụ” chọn câu trả lời giúp tác vụ tiếp tục, để nó không bị dừng khi bạn vắng mặt. “Cẩn thận” chọn câu trả lời an toàn và không thực hiện bước quan trọng nào khi không có bạn. Dù chọn cách nào, các câu hỏi về xóa dữ liệu, chi tiền, thông tin đăng nhập, người nhận tin nhắn hoặc đăng thứ bạn không yêu cầu luôn nhận câu trả lời an toàn, và các thẻ xác nhận riêng của WebBrain luôn chờ bạn.","st.display.clarify_timeout_policy.finish": "Hoàn thành tác vụ","st.display.clarify_timeout_policy.safe": "Cẩn thận",+ "st.display.strict_guards.label": "Kiểm tra nghiêm ngặt",+ "st.display.strict_guards.desc": "Tắt (mặc định): chỉ các kiểm tra của WebBrain về xóa dữ liệu, chi tiền, thông tin đăng nhập, người nhận sai và đăng thứ bạn không yêu cầu mới có thể dừng một hành động; các kiểm tra khác được chuyển cho mô hình dưới dạng ghi chú để tác vụ không bị kẹt. Bật: như trước, mỗi kiểm tra dừng hành động bất cứ khi nào không xác nhận được.",'st.display.verbose.label': "Chế độ dài dòng",'st.display.verbose.desc': "Hiển thị đầy đủ chi tiết lệnh gọi công cụ, đối số và kết quả JSON thô. Tắt theo mặc định để có trải nghiệm trò chuyện rõ ràng hơn.",'st.display.selection_shortcut.label': "Phím tắt lựa chọn",diff --git a/src/firefox/src/ui/locales/zh.js b/src/firefox/src/ui/locales/zh.jsindex ae87a48dc..bbb421806 100644--- a/src/firefox/src/ui/locales/zh.js+++ b/src/firefox/src/ui/locales/zh.js@@ -870,6 +870,8 @@ export default {"st.display.clarify_timeout_policy.desc": "当你没有及时回答问题时 WebBrain 的做法。“完成任务”会选择能让任务继续的答案,这样你不在时任务也不会停滞。“稳妥为先”会选择安全的答案,不会在没有你的情况下执行重要操作。无论哪种设置,涉及删除数据、花钱、凭据、消息收件人或发布你未要求发布的内容的问题,始终采用安全答案;WebBrain 自己的确认卡片始终会等待你。","st.display.clarify_timeout_policy.finish": "完成任务","st.display.clarify_timeout_policy.safe": "稳妥为先",+ "st.display.strict_guards.label": "严格检查",+ "st.display.strict_guards.desc": "关闭(默认):只有 WebBrain 关于删除数据、花钱、凭据、收件人错误以及发布你未要求发布的内容的检查才能阻止操作;其他检查会作为备注交给模型,任务不会卡住。开启:与以前一样,任何检查在无法确认时都会阻止操作。",'st.display.always_allow_api_mutations.label': "始终允许 API 变更",'st.display.always_allow_api_mutations.desc': "允许 WebBrain 通过 fetch_url 或 research_url 使用 POST、PUT、PATCH 和 DELETE,无需在每个对话中输入 /allow-api。仍会遵循 UI 优先指引和确认检查。默认开启。",'st.display.api_mutation_observer.label': 'API 变更观察器',diff --git a/src/firefox/src/ui/settings.html b/src/firefox/src/ui/settings.htmlindex a20a7846e..5c720a571 100644--- a/src/firefox/src/ui/settings.html+++ b/src/firefox/src/ui/settings.html@@ -1657,6 +1657,16 @@<option value="safe" data-i18n="st.display.clarify_timeout_policy.safe"></option></select></div>+ <div class="setting-row">+ <div class="setting-info">+ <div class="setting-label" data-i18n="st.display.strict_guards.label"></div>+ <div class="setting-desc" data-i18n="st.display.strict_guards.desc"></div>+ </div>+ <label class="toggle">+ <input type="checkbox" id="toggle-strict-guards">+ <span class="toggle-slider"></span>+ </label>+ </div><div class="setting-row"><div class="setting-info"><div class="setting-label" data-i18n="st.display.site_adapters.label"></div>diff --git a/src/firefox/src/ui/settings.js b/src/firefox/src/ui/settings.jsindex 63ee4d508..6e3f8cc51 100644--- a/src/firefox/src/ui/settings.js+++ b/src/firefox/src/ui/settings.js@@ -132,6 +132,7 @@ const tracingToggle = document.getElementById('toggle-tracing');const feedbackDiagnosticsToggle = document.getElementById('toggle-feedback-diagnostics');const losslessTracingToggle = document.getElementById('toggle-lossless-tracing');const strictSecretToggle = document.getElementById('toggle-strict-secret');+const strictGuardsToggle = document.getElementById('toggle-strict-guards');const allowLocalNetworkToggle = document.getElementById('toggle-allow-local-network');const scheduledTasksToggle = document.getElementById('toggle-scheduled-tasks');const scheduledConfirmToggle = document.getElementById('toggle-scheduled-confirm');@@ -607,7 +608,7 @@ async function init() {browser.storage.local.remove(['authToken', 'authEmail', 'authDefaultModel']).catch(() => {});// Load display settings- const stored = await browser.storage.local.get([...DECISION_SETTINGS_KEYS, 'verboseMode', 'composerDeliveryMode', 'selectionShortcutEnabled', AUTO_GROUP_TABS_KEY, 'helpImproveWebBrain', 'screenshotFallback', 'maxAgentSteps', 'autoScreenshot', 'useSiteAdapters', 'researchEscalationEnabled', 'researchEscalationEngine', 'voiceInputEnabled', 'alwaysAllowApiMutations', 'apiMutationObserverEnabled', 'openaiAskStreamingEnabled', 'planBeforeActMode', 'planBeforeAct', 'planReviewMode', 'planReviewConfidenceThreshold', DOWNLOAD_DIRECTORY_STORAGE_KEY, 'notifySound', 'completionConfetti', 'completionFlashTab', 'tracingEnabled', 'feedbackDiagnosticsEnabled', 'losslessTrace', 'strictSecretMode', 'agentAllowLocalNetwork', 'scheduledTasksEnabled', 'scheduledRequireConsequentialConfirmation', 'systemOneEnabled', 'systemOneWatchEnabled', 'systemOneCompletionEnabled', 'systemOneFastClassifications', 'systemOneFastBrowser', 'systemOneWatchThreshold', 'systemOneCompletionThreshold', 'typesafeApiKey', 'providerFilter', 'requestTimeoutMs', 'clarifyTimeoutSec', 'clarifyTimeoutSemanticsV2', 'clarifyTimeoutPolicy', 'costAllowanceSessionUsd', 'costAllowanceTotalUsd', 'meteredProviderCostSpentUsd', 'screenshotRedaction', 'imageDetail', 'maxScreenshotsPerTurn', 'maxImageDimension']);+ const stored = await browser.storage.local.get([...DECISION_SETTINGS_KEYS, 'verboseMode', 'composerDeliveryMode', 'selectionShortcutEnabled', AUTO_GROUP_TABS_KEY, 'helpImproveWebBrain', 'screenshotFallback', 'maxAgentSteps', 'autoScreenshot', 'useSiteAdapters', 'researchEscalationEnabled', 'researchEscalationEngine', 'voiceInputEnabled', 'alwaysAllowApiMutations', 'apiMutationObserverEnabled', 'openaiAskStreamingEnabled', 'planBeforeActMode', 'planBeforeAct', 'planReviewMode', 'planReviewConfidenceThreshold', DOWNLOAD_DIRECTORY_STORAGE_KEY, 'notifySound', 'completionConfetti', 'completionFlashTab', 'tracingEnabled', 'feedbackDiagnosticsEnabled', 'losslessTrace', 'strictSecretMode', 'strictGuards', 'agentAllowLocalNetwork', 'scheduledTasksEnabled', 'scheduledRequireConsequentialConfirmation', 'systemOneEnabled', 'systemOneWatchEnabled', 'systemOneCompletionEnabled', 'systemOneFastClassifications', 'systemOneFastBrowser', 'systemOneWatchThreshold', 'systemOneCompletionThreshold', 'typesafeApiKey', 'providerFilter', 'requestTimeoutMs', 'clarifyTimeoutSec', 'clarifyTimeoutSemanticsV2', 'clarifyTimeoutPolicy', 'costAllowanceSessionUsd', 'costAllowanceTotalUsd', 'meteredProviderCostSpentUsd', 'screenshotRedaction', 'imageDetail', 'maxScreenshotsPerTurn', 'maxImageDimension']);if (typeof stored.providerFilter === 'string' && ['all','active','local','cloud','router'].includes(stored.providerFilter)) {providerFilter = stored.providerFilter;}@@ -695,6 +696,7 @@ async function init() {if (costTotalLimitInput) costTotalLimitInput.value = totalLimit.toFixed(2);renderCostAllowanceSpent(totalSpent, totalLimit);if (strictSecretToggle) strictSecretToggle.checked = stored.strictSecretMode === true; // off by default+ if (strictGuardsToggle) strictGuardsToggle.checked = stored.strictGuards === true; // off by defaultif (allowLocalNetworkToggle) allowLocalNetworkToggle.checked = stored.agentAllowLocalNetwork === true;if (scheduledTasksToggle) scheduledTasksToggle.checked = stored.scheduledTasksEnabled !== false;if (scheduledConfirmToggle) scheduledConfirmToggle.checked = stored.scheduledRequireConsequentialConfirmation !== false;@@ -1493,6 +1495,10 @@ strictSecretToggle?.addEventListener('change', async () => {await browser.storage.local.set({ strictSecretMode: strictSecretToggle.checked }).catch(() => {});});+strictGuardsToggle?.addEventListener('change', async () => {+ await browser.storage.local.set({ strictGuards: strictGuardsToggle.checked }).catch(() => {});+});+allowLocalNetworkToggle?.addEventListener('change', async () => {await browser.storage.local.set({ agentAllowLocalNetwork: allowLocalNetworkToggle.checked }).catch(() => {});});diff --git a/test/bot-memory.mjs b/test/bot-memory.mjsindex 83aea60ae..5d9c1f105 100644--- a/test/bot-memory.mjs+++ b/test/bot-memory.mjs@@ -153,6 +153,8 @@ for (const browser of ['chrome', 'firefox']) {});test(`${browser}: unverified actions block successful completion, but an honest partial outcome can finish`, async () => {const h = harness();+ // Strict checks: the guard's refusal itself is under test.+ h.agent.strictGuards = true;await h.agent.executeTool(7, 'click_ax', { ref_id: 'ref_5' });const done = await h.agent.executeTool(7, 'done', { outcome: 'success', summary: 'Sent.' });assert.equal(done.blockedDone, true);diff --git a/test/chat-generic-dispatch.mjs b/test/chat-generic-dispatch.mjsindex 429561339..f6281596d 100644--- a/test/chat-generic-dispatch.mjs+++ b/test/chat-generic-dispatch.mjs@@ -87,6 +87,8 @@ for (const build of ['chrome', 'firefox']) {test(`${build}: generic send observes new incoming and OTP gates without consuming the delta`, async () => {const gated = harness(); await gated.agent._observeChatWorkflow(tabId);+ // Strict checks: the guard's refusal itself is under test.+ gated.agent.strictGuards = true;gated.observed.messages.push({ id: 'telegram:k:123456:0:2:rnext', direction: 'incoming', text: 'New fixture question' });await gated.call(); assert.equal(gated.sends, 0);gated.observed.userInput = { required: true, reason: 'otp' };diff --git a/test/chat-send-dispatch-result.mjs b/test/chat-send-dispatch-result.mjsindex d11fd3cfe..ecb46c4b9 100644--- a/test/chat-send-dispatch-result.mjs+++ b/test/chat-send-dispatch-result.mjs@@ -11,6 +11,7 @@ for (const build of ['chrome', 'firefox']) {const { Agent } = await import(`../src/${build}/src/agent/agent.js`);test(`${build}: structured send preserves an actual nested rich-text recovery block without inventing a send`, async () => {const agent = new Agent({}), tabId = 755;+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const observed = { success: true, url, threadKey, composer: { available: true, empty: true, ref: 'ref_composer' },nativeChatMessageBaseline: { threadKey, coverage: 'mounted_native_id_floor', complete: true,messageIds: ['telegram:k:123456:0:1'] },diff --git a/test/cloud-act-completion.mjs b/test/cloud-act-completion.mjsindex 23cfae68e..33dd831b1 100644--- a/test/cloud-act-completion.mjs+++ b/test/cloud-act-completion.mjs@@ -79,6 +79,8 @@ for (const browser of ['chrome', 'firefox']) {test(`${browser}: Cloud Act rejects Qwen's prose tool promise and stops after bounded recovery`, async () => {const h = harness([{ content: promiseOnly, toolCalls: [] }, { content: promiseOnly, toolCalls: [] }]);+ // Strict checks: the guard's refusal itself is under test.+ h.agent.strictGuards = true;const run = await h.controller.startRun({ task: 'Read the current page and return observed video URLs.', mode: 'act' });const snapshot = await finish(h.controller, run);assert.equal(snapshot.status, 'failed');@@ -154,6 +156,8 @@ for (const browser of ['chrome', 'firefox']) {tool('done', { summary: 'Videos found.', outcome: 'success' }),tool('done', { summary: 'Videos found.', outcome: 'success' }),]);+ // Strict checks: the guard's refusal itself is under test.+ h.agent.strictGuards = true;const run = await h.controller.startRun({ task: 'Read the current page and return observed video URLs.', mode: 'act' });const snapshot = await finish(h.controller, run);assert.equal(snapshot.status, 'failed');@@ -307,6 +311,8 @@ for (const browser of ['chrome', 'firefox']) {for (const toolChoice of ['none', { type: 'function', function: { name: 'unavailable_tool' } }]) {const normalized = normalizeQwenToolResult(config, { tools, toolChoice }, { content, finishReason: 'stop' });const h = harness([normalized, normalized, normalized]);+ // Strict checks: the guard's refusal itself is under test.+ h.agent.strictGuards = true;h.agent._gateSettingLoaded = true;h.agent._shouldAutoScreenshot = () => false;h.agent._observeCaptchaChallenge = async () => ({ gate: null, loopCheck: { kind: 'none' } });diff --git a/test/delivery-cdp-input.mjs b/test/delivery-cdp-input.mjsindex 744e66b8e..9192a9785 100644--- a/test/delivery-cdp-input.mjs+++ b/test/delivery-cdp-input.mjs@@ -424,6 +424,7 @@ test('[mocked transport] type_text: a fence veto before Input.insertText is unditest('[mocked transport] type_text: a lost Input.insertText acknowledgement stays uncertain and blocks a blind repeat', async () => {const agent = newAgent();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.focusedTypingMocks({ insertText: () => { throw new Error('Owned text response lost'); } });try {const result = await agent.executeTool(17, 'type_text', { text: 'hello' });diff --git a/test/fixtures/rich-text-toolbar.mjs b/test/fixtures/rich-text-toolbar.mjsindex 7c5774d24..b58929875 100644--- a/test/fixtures/rich-text-toolbar.mjs+++ b/test/fixtures/rich-text-toolbar.mjs@@ -166,6 +166,8 @@ export function registerRichTextToolbarFixtures({const AgentClass = browserKind === 'chrome' ? Agent : FirefoxAgent;const agent = new AgentClass({ getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = browserKind === 'chrome' ? 1901 : 1902;const wrongTarget = {};agent._applyRichTextToolbarWrongTarget(@@ -1400,6 +1402,8 @@ export function registerRichTextToolbarFixtures({}const agent = new AgentClass({ getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 77;const focusAgent = new AgentClass({ getVisionProvider: async () => null });const extensionGlobal = AgentClass === Agent ? 'chrome' : 'browser';diff --git a/test/guard-advisory-actions.mjs b/test/guard-advisory-actions.mjsnew file mode 100644index 000000000..4e60e7493--- /dev/null+++ b/test/guard-advisory-actions.mjs@@ -0,0 +1,738 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import vm from 'node:vm';+import { test } from 'node:test';++// Quality guards on actions advise instead of refusing (PR B, guard-policy.js):+// with Settings -> General -> "Strict checks" off (the default) the action is+// dispatched and the guard's note reaches the model on the real tool result;+// with strictGuards = true the old refusal happens exactly as before. Every+// test below runs both modes for both builds.++const PAGE_URL = 'https://example.com/form';+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+const api = {+ storage: { local: area, session: area },+ runtime: { getURL: value => `extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: {+ get: async id => ({ id, url: PAGE_URL, title: 'Form' }),+ query: async () => [],+ sendMessage: async () => ({ ready: true }),+ },+ webNavigation: { getAllFrames: async () => [{ frameId: 0, parentFrameId: -1, documentId: 'document-1', url: PAGE_URL }] },+ scripting: { executeScript: async () => [{ result: null }] },+};+globalThis.chrome = api;+globalThis.browser = api;++let nextTab = 9100;+const MODES = [['default', false], ['strict', true]];++// Tool results may carry appended notes or an untrusted-data envelope.+function parse(message) {+ const text = typeof message?.content === 'string' ? message.content : '';+ for (let start = text.indexOf('{'); start >= 0; start = text.indexOf('{', start + 1)) {+ let depth = 0, quoted = false, escaped = false;+ for (let cursor = start; cursor < text.length; cursor++) {+ const char = text[cursor];+ if (quoted) { if (escaped) escaped = false; else if (char === '\\') escaped = true; else if (char === '"') quoted = false; }+ else if (char === '"') quoted = true;+ else if (char === '{') depth++;+ else if (char === '}' && --depth === 0) {+ try { return JSON.parse(text.slice(start, cursor + 1)); } catch { break; }+ }+ }+ }+ return null;+}+const resultFor = (messages, id) => parse(messages.find(message => message.role === 'tool' && message.tool_call_id === id));+const guardsOf = value => (Array.isArray(value) ? value : value?.guardAdvisories || []).map(item => item.guard);+const call = (id, name, args) => ({ id, type: 'function', function: { name, arguments: JSON.stringify(args) } });++for (const build of ['chrome', 'firefox']) {+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const { decideChatSend, WAIVABLE_CHAT_SEND_REASONS } = await import(`../src/${build}/src/agent/chat-workflow.js`);+ const { resolveAdapterWorkflowJob } = await import(`../src/${build}/src/agent/adapters.js`);++ // A batch harness that reaches the real dispatch: every pre-dispatch check+ // that is not under test is neutral, and the lifecycle wrapper that attaches+ // advisories to the result stays real (only its inner dispatch is recorded).+ function makeAgent(strict) {+ const provider = { name: 'guard advisory test', model: 'test', promptTier: 'full', contextWindow: 128000,+ supportsTools: true, supportsVision: false, chat: async () => ({ content: '' }) };+ const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent._persist = () => {};+ agent._persistNow = async () => ({ ok: true });+ agent._skipPermissionGate = true;+ agent._ensureGateSetting = async () => true;+ for (const name of ['_chromeProtectedPageFailure', '_captchaMutationPreflight', '_messageRecipientGuardBlock',+ '_detectLikelySubmitAction', '_socialPublicationPreSubmitBlock']) agent[name] = async () => null;+ agent._adoptLiveSocialPublishWorkflow = async () => false;+ agent._isFormValidationCandidate = () => false;+ agent._auditRichTextToolbarTarget = async () => {};+ agent._shouldAutoScreenshot = () => false;+ agent._currentUrl = async () => PAGE_URL;+ agent._refreshPageFeedbackForCall = async () => false;+ const dispatched = [];+ const realInner = Agent.prototype._executeToolWithLifecycleInner;+ agent._executeToolWithLifecycleInner = async function(tab, name, args, onUpdate, context) {+ dispatched.push({ name, args, context });+ // The calculator is local and side-effect free, so it really runs.+ if (name === 'calculate') return realInner.call(this, tab, name, args, onUpdate, context);+ return { success: true, dispatched: true, verified: true };+ };+ const run = async (tab, calls, allowed, runOptions = {}) => {+ const messages = [];+ const outcome = await agent._executeToolBatch(tab, calls, messages, () => {}, provider, null,+ new Set(allowed), 1, runOptions);+ return { messages, outcome };+ };+ return { agent, provider, dispatched, run };+ }++ // ── pure-calculation-tool-scope ─────────────────────────────────────────+ function arithmeticTask(agent, tab) {+ const task = 'Only calculate 12 * 7 and reply with the result.';+ const expression = '12 * 7';+ agent._planExecutionGuards.set(tab, { enabled: true, taskKey: 'arithmetic-task', readScope: 'none',+ calculationReading: { task, expression, choice: 'only_result' } });+ agent._pageFeedbackLiteralCalculationTask = () => task;+ agent._pageFeedbackCalculationResponseScope = () => ({ owner: 'owner', runToken: 'run', expression, outputRequirements: null });+ agent._pageFeedbackCalculationComplete = () => false;+ }++ for (const [mode, strict] of MODES) {+ test(`${build}: pure-calculation-tool-scope ${mode} mode ${strict ? 'refuses another expression' : 'runs another expression with a note'}`, async () => {+ const tab = nextTab++;+ const { agent, run } = makeAgent(strict);+ arithmeticTask(agent, tab);+ const { messages } = await run(tab, [call('other-expression', 'calculate', { expression: '1 + 1' })], ['calculate', 'done']);+ const result = resultFor(messages, 'other-expression');+ if (strict) {+ assert.equal(result.errorCode, 'pure_calculation_tool_denied');+ assert.equal(result.noDispatch, true);+ assert.equal(result.result, undefined);+ assert.deepEqual(guardsOf(result), []);+ } else {+ assert.equal(result.success, true);+ assert.equal(result.result, '2');+ assert.deepEqual(guardsOf(result), ['pure-calculation-tool-scope']);+ assert.match(result.guardAdvisories[0].note, /12 \* 7/);+ // A calculation does not take the task out of its arithmetic scope.+ assert.deepEqual(agent._pureCalculationToolPolicy(tab).names, ['calculate', 'done']);+ }+ });++ test(`${build}: pure-calculation-tool-scope ${mode} mode ${strict ? 'refuses a page action' : 'runs a page action and releases the arithmetic scope'}`, async () => {+ const tab = nextTab++;+ const { agent, run, dispatched } = makeAgent(strict);+ arithmeticTask(agent, tab);+ const { messages } = await run(tab, [call('page-action', 'click_ax', { ref_id: 'ref_1' })], ['click_ax', 'calculate', 'done']);+ const result = resultFor(messages, 'page-action');+ if (strict) {+ assert.equal(dispatched.length, 0);+ assert.equal(result.errorCode, 'pure_calculation_tool_denied');+ assert.ok(agent._pureCalculationToolPolicy(tab), 'Strict mode keeps the arithmetic scope');+ } else {+ assert.deepEqual(dispatched.map(item => item.name), ['click_ax']);+ assert.deepEqual(guardsOf(result), ['pure-calculation-tool-scope']);+ // Once the browser was used the captured scope could only go stale and+ // refuse every later call; the task is released instead.+ assert.equal(agent._planExecutionGuards.get(tab).pureCalculationScopeReleased, true);+ assert.equal(agent._pureCalculationToolPolicy(tab), null);+ }+ });+ }++ // ── preparation-timeout-generic (form-validation before-snapshot) ────────+ for (const [mode, strict] of MODES) {+ test(`${build}: preparation-timeout-generic ${mode} mode ${strict ? 'refuses after a snapshot timeout' : 'submits without the timed-out snapshot'}`, async () => {+ const tab = nextTab++;+ const { agent, run, dispatched } = makeAgent(strict);+ agent._isFormValidationCandidate = () => true;+ agent._detectLikelySubmitAction = async () => ({ isSubmit: true, host: 'example.com', tool: 'click', reason: 'submit control' });+ agent._waitForFormValidationFailure = async () => null;+ agent._readControlEffect = async () => null;+ let snapshots = 0;+ agent._captureFormValidationState = async () => {+ snapshots++;+ if (snapshots === 2) throw Object.assign(new Error('click did not return a page response within 1 seconds.'), { code: 'content_action_timeout' });+ return [];+ };+ const { messages } = await run(tab, [call('submit', 'click', { selector: '#submit' })], ['click']);+ const result = resultFor(messages, 'submit');+ assert.equal(snapshots >= 2, true);+ if (strict) {+ assert.equal(dispatched.length, 0);+ assert.match(result.error, /form-validation snapshot did not finish/);+ } else {+ assert.deepEqual(dispatched.map(item => item.name), ['click']);+ assert.deepEqual(guardsOf(result), ['preparation-timeout-generic']);+ }+ });+ }++ // ── media-download-target-binding ───────────────────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: media-download-target-binding ${mode} mode ${strict ? 'refuses a feed URL' : 'downloads a feed URL with a note'}`, async () => {+ const tab = nextTab++;+ const { agent, run, dispatched } = makeAgent(strict);+ const { messages } = await run(tab, [call('feed-download', 'download_public_media', { url: 'https://www.instagram.com/someuser/' })],+ ['download_public_media']);+ const result = resultFor(messages, 'feed-download');+ if (strict) {+ assert.equal(dispatched.length, 0);+ assert.equal(result.needsExplicitMediaUrl, true);+ } else {+ assert.deepEqual(dispatched.map(item => item.name), ['download_public_media']);+ assert.deepEqual(guardsOf(result), ['media-download-target-binding']);+ }+ });+ }++ // The real browser-specific download handler and its injected page wrapper,+ // as in media-download-agent-handler.mjs, on a real Agent prototype so the+ // guard policy is the production one.+ const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;+ const handlerSource = (() => {+ const source = fs.readFileSync(new URL(`../src/${build}/src/agent/agent.js`, import.meta.url), 'utf8');+ const start = source.lastIndexOf(" if (name === 'download_social_media') {");+ const end = source.indexOf(build === 'chrome' ? ' // download_file is now handled' : ' // ─── PDF reader', start);+ assert.ok(start >= 0 && end > start);+ return source.slice(start, end);+ })();+ for (const [mode, strict] of MODES) {+ test(`${build}: media-download-target-binding ${mode} mode ${strict ? 'keeps a changed media binding refused' : 'retries a changed media binding unbound, DOM only'}`, async () => {+ const handler = new AsyncFunction('tabId', 'name', 'args', 'onUpdate', 'executionContext', 'chrome', 'browser', handlerSource);+ const runs = [];+ const results = [+ { success: false, noDispatch: true, dispatched: false, pageFeedbackPending: true, errorCode: 'media_binding_changed',+ error: 'changed target', urls: [], stats: { triggered: 0, completed: 0 } },+ { urls: ['https://pbs.twimg.com/now.jpg'], stats: { triggered: 1, completed: 0, completedVideo: 0, openedInTab: 0, failed: 1, failures: [] } },+ ];+ let mseSaves = 0;+ const downloader = {+ async run(opts) { runs.push(opts); return results[runs.length - 1]; },+ _activeProfile: () => ({ name: 'twitter' }),+ getMseRecording: () => ({ orphanBuffers: [{ bytes: 100 }] }),+ async saveMse() { mseSaves++; return [{ mime: 'video/mp4' }]; },+ _buildRecommendation: () => null,+ };+ const page = { window: { SocialMediaDownloader: downloader, location: { hostname: 'x.com' } },+ location: { href: 'https://x.com/account/status/123/photo/1' } };+ const transport = {+ scripting: { async executeScript({ files, func, args }) {+ if (files) return [];+ return [{ result: await vm.runInNewContext(`(${func.toString()})(...injectedArgs)`, { ...page, injectedArgs: args }) }];+ } },+ tabs: { async executeScript(_id, { file, code }) {+ if (file) return [];+ return [await vm.runInNewContext(code, page)];+ } },+ };+ const agent = Object.create(Agent.prototype);+ Object.assign(agent, {+ strictGuards: strict,+ _activeProvider: () => ({}), providerManager: { getActive: () => ({}) },+ async _resolveVisionRoute() { assert.fail('A bound media call must not reach vision'); },+ async _saveVisibleMediaCrop() { assert.fail('A bound media call must not crop media'); },+ });+ const advisories = [];+ const binding = { schema: 1, documentToken: 'document', candidates: [{ url: 'https://pbs.twimg.com/intended.jpg' }] };+ const result = await handler.call(agent, 1, 'download_social_media', { mode: 'main', target: 'video', limit: 1 }, () => {},+ { _expectedMediaBinding: binding, guardAdvisories: advisories }, transport, transport);+ if (strict) {+ assert.equal(runs.length, 1);+ assert.equal(result.errorCode, 'media_binding_changed');+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(runs.length, 2);+ assert.equal(JSON.stringify(runs[0].expectedMediaBinding), JSON.stringify(binding));+ assert.equal(runs[1].expectedMediaBinding, undefined);+ assert.equal(runs[1].domOnly, true);+ assert.equal(mseSaves, 0, 'The unbound retry stays on the DOM item path');+ assert.notEqual(result.errorCode, 'media_binding_changed');+ assert.deepEqual(guardsOf(advisories), ['media-download-target-binding']);+ }+ });+ }++ // ── form-validation-unchanged-repeat ────────────────────────────────────+ const invalidState = [{ frameId: 0, url: PAGE_URL, activeInvalid: true,+ invalidFields: [{ label: 'Email', type: 'email', message: 'Enter an email address.' }],+ ariaInvalidFields: [], alerts: [], controlFingerprint: 'empty' }];+ for (const [mode, strict] of MODES) {+ test(`${build}: form-validation-unchanged-repeat ${mode} mode ${strict ? 'refuses the unchanged repeat' : 'sends the unchanged repeat with a note'}`, async () => {+ const tab = nextTab++;+ const { agent, run, dispatched } = makeAgent(strict);+ agent._isFormValidationCandidate = () => true;+ agent._detectLikelySubmitAction = async () => ({ isSubmit: true, host: 'example.com', tool: 'click', reason: 'submit control' });+ agent._captureFormValidationState = async () => structuredClone(invalidState);+ agent._waitForFormValidationFailure = async () => null;+ agent._readControlEffect = async () => null;+ agent._formValidationBlocks.set(tab, {+ stateKey: agent._formValidationStateKey(invalidState),+ actionKey: agent._formValidationActionKey('click', { text: 'Continue' }),+ invalidFields: invalidState[0].invalidFields,+ validationMessages: ['Enter an email address.'],+ verifyFormCount: 0,+ });+ const { messages } = await run(tab, [call('repeat', 'click', { text: 'Continue' })], ['click']);+ const result = resultFor(messages, 'repeat');+ if (strict) {+ assert.equal(dispatched.length, 0);+ assert.equal(result.blockedValidationRetry, true);+ } else {+ assert.deepEqual(dispatched.map(item => item.name), ['click']);+ assert.deepEqual(guardsOf(result), ['form-validation-unchanged-repeat']);+ assert.doesNotMatch(result.guardAdvisories[0].note, /Enter an email address/, 'Page text stays out of the note');+ }+ });++ test(`${build}: form-validation-unchanged-repeat ${mode} mode ${strict ? 'fails a repeated verify_form' : 'keeps a repeated verify_form read'}`, () => {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ const tab = nextTab++;+ const states = [{ ...invalidState[0], invalidFields: [{ label: 'Accept terms', id: 'terms', name: 'terms', type: 'checkbox', message: 'Required.' }] }];+ agent._formValidationBlocks.set(tab, { stateKey: agent._formValidationStateKey(states), actionKey: 'click|continue',+ invalidFields: states[0].invalidFields, validationMessages: ['Required.'], verifyFormCount: 0 });+ const read = () => ({ success: true, found: true, fields: [{ ref_id: 'ref_7', id: 'terms', name: 'terms', type: 'checkbox', checked: false, label: 'Accept terms' }] });+ const advisories = [];+ assert.equal(agent._applyVerifyFormRecovery(tab, read(), states, advisories).success, true);+ const repeated = agent._applyVerifyFormRecovery(tab, read(), states, advisories);+ if (strict) {+ assert.equal(repeated.success, false);+ assert.equal(repeated.blockedValidationVerifyRepeat, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(repeated.success, true);+ assert.equal(repeated.blockedValidationVerifyRepeat, undefined);+ assert.equal(repeated.formValidationRecovery.nextTool, 'set_checked');+ assert.deepEqual(guardsOf(advisories), ['form-validation-unchanged-repeat']);+ }+ });+ }++ // ── chat-send-preconditions ─────────────────────────────────────────────+ const threadKey = 'dom:telegram:k:123456:0', chatBody = 'A generated fixture reply.';+ function chatAgent(strict) {+ const harness = makeAgent(strict);+ const { agent } = harness;+ agent._currentUrl = async () => 'https://web.telegram.org/k/#123456';+ const observed = { success: true, url: 'https://web.telegram.org/k/#123456', threadKey,+ composer: { available: true, empty: false, ref: 'composer' },+ messages: [{ id: 'telegram:k:123456:0:1:rfixture', direction: 'incoming', text: 'Fixture question' }] };+ agent._readChatObservation = async () => structuredClone(observed);+ agent._messageRecipientGuardBlock = async (_tab, _name, _args, _url, value) => {+ Object.assign(value, { messageRecipientGuardRequired: true, messageRecipientBody: chatBody,+ messageRecipientDispatchBinding: { token: 'fixture-one-use-token' },+ messageRecipientNativeChatBaseline: { complete: true, threadKey, messageIds: ['telegram:k:123456:0:1'] } });+ return null;+ };+ return { ...harness, observed };+ }+ for (const [mode, strict] of MODES) {+ test(`${build}: chat-send-preconditions ${mode} mode ${strict ? 'refuses a reply after unseen incoming' : 'sends after unseen incoming with a note'}`, async () => {+ const tab = 745;+ const { agent, run, dispatched, observed } = chatAgent(strict);+ await agent._observeChatWorkflow(tab);+ observed.messages.push({ id: 'telegram:k:123456:0:2:rnext', direction: 'incoming', text: 'New fixture question' });+ const { messages } = await run(tab, [call('reply', 'click', { selector: '#send' })], ['click']);+ const result = resultFor(messages, 'reply');+ if (strict) {+ assert.equal(dispatched.length, 0);+ assert.equal(result.reason, 'chat_observe_required');+ } else {+ assert.deepEqual(dispatched.map(item => item.name), ['click']);+ assert.deepEqual(guardsOf(result), ['chat-send-preconditions']);+ assert.ok(agent.chatSessions.get(tab).pendingOutbound, 'The advised send is still tracked as pending');+ }+ });++ test(`${build}: chat-send-preconditions ${mode} mode keeps a one-time-code request blocking`, async () => {+ const tab = 745;+ const { agent, run, dispatched, observed } = chatAgent(strict);+ await agent._observeChatWorkflow(tab);+ observed.userInput = { required: true, reason: 'otp' };+ const { messages } = await run(tab, [call('reply', 'click', { selector: '#send' })], ['click']);+ assert.equal(dispatched.length, 0);+ assert.equal(resultFor(messages, 'reply').reason, 'user_input_required');+ });+ }++ test(`${build}: chat-send-preconditions waives only the quality preconditions`, () => {+ assert.deepEqual([...WAIVABLE_CHAT_SEND_REASONS], ['composer_unavailable']);+ const session = { threadKey, state: 'we_responded' };+ const snapshot = { threadKey, composer: { available: true, empty: true }, messages: [] };+ const noComposer = { ...snapshot, composer: { available: false, empty: true } };+ assert.equal(decideChatSend(session, noComposer, 'Hello').reason, 'composer_unavailable');+ assert.equal(decideChatSend(session, noComposer, 'Hello', Date.now(), { waive: new Set(['composer_unavailable']) }).ok, true);+ // A terminal session asked for no further message, and the native+ // baseline is what delivery matching and duplicate detection rely on.+ const ended = { ...session, state: 'issue_resolved' };+ assert.equal(decideChatSend(ended, snapshot, 'Hello', Date.now(), { waive: new Set(['terminal_session']) }).reason,+ 'terminal_session');+ const unverifiedBaseline = { ...snapshot, nativeChatMessageBaseline: { threadKey, coverage: 'mounted_native_id_floor',+ complete: false, messageIds: ['telegram:k:123456:0:5000'] } };+ assert.equal(decideChatSend(session, unverifiedBaseline, 'Hello', Date.now(),+ { waive: new Set(['native_baseline_unverified']) }).reason, 'native_baseline_unverified');+ for (const [label, value] of [+ ['terminal', [ended, snapshot, 'Hello']],+ ['native baseline', [session, unverifiedBaseline, 'Hello']],+ ['thread', [session, { ...snapshot, threadKey: 'dom:telegram:k:999:0' }, 'Hello']],+ ['user input', [{ ...session, userInput: { required: true, reason: 'otp' } }, snapshot, 'Hello']],+ ['draft', [session, { ...snapshot, composer: { available: true, empty: false } }, 'Hello']],+ ['empty', [session, snapshot, '']],+ ['too long', [session, snapshot, 'x'.repeat(4001)]],+ ]) {+ const decision = decideChatSend(...value, Date.now(), { waive: new Set(['terminal_session', 'native_baseline_unverified',+ 'composer_unavailable', 'composer_not_empty', 'thread_unverified', 'user_input_required', 'empty_message', 'message_too_long']) });+ assert.equal(decision.ok, false, label);+ }+ });++ // ── jev-target-changed ─────────────────────────────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: jev-target-changed ${mode} mode ${strict ? 'refuses a stale fast-path target' : 'sends a stale fast-path call unbound'}`, async () => {+ const tab = nextTab++;+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent._uncertainTextMutationBlock = async () => null;+ agent._finalizeToolResultOnce = async (_tab, _name, _args, result) => result;+ const impl = [];+ agent._executeToolImpl = async (_tab, name, _args, _onUpdate, context) => {+ impl.push({ name, jevBinding: context.jevBinding });+ return { success: true, dispatched: true };+ };+ const oldSend = api.tabs.sendMessage;+ api.tabs.sendMessage = async (_id, message) => message.action === 'jev_validate_target'+ ? { success: false, noDispatch: true, staleJevTarget: true } : { ready: true };+ try {+ const result = await agent._executeToolWithLifecycle(tab, 'click_ax', { ref_id: 'ref_3' }, null,+ { jevBinding: { ref: 'ref_3', documentToken: 'doc', structure: 's', signature: 'sig' } });+ if (strict) {+ assert.equal(impl.length, 0);+ assert.equal(result.staleJevTarget, true);+ } else {+ assert.deepEqual(impl, [{ name: 'click_ax', jevBinding: null }]);+ assert.equal(result.success, true);+ assert.deepEqual(guardsOf(result), ['jev-target-changed']);+ }+ } finally { api.tabs.sendMessage = oldSend; }+ });+ }++ test(`${build}: a note is dropped when a later check refuses the call`, async () => {+ // The jev note says the click went through unbound. When another check+ // then refuses, nothing went through and the note would mislead.+ const agent = new Agent({ getVisionProvider: async () => null });+ agent._uncertainTextMutationBlock = async () => null;+ agent._finalizeToolResultOnce = async (_tab, _name, _args, result) => result;+ const results = [{ success: false, noDispatch: true, error: 'Refused by a later check.' },+ { success: false, dispatched: false, error: 'Not dispatched.' },+ { success: false, dispatched: true, error: 'Dispatched, outcome unclear.' }];+ agent._executeToolImpl = async () => results.shift();+ const oldSend = api.tabs.sendMessage;+ api.tabs.sendMessage = async (_id, message) => message.action === 'jev_validate_target'+ ? { success: false, noDispatch: true, staleJevTarget: true } : { ready: true };+ try {+ const call = () => agent._executeToolWithLifecycle(nextTab++, 'click_ax', { ref_id: 'ref_3' }, null,+ { jevBinding: { ref: 'ref_3', documentToken: 'doc', structure: 's', signature: 'sig' } });+ assert.deepEqual(guardsOf(await call()), [], 'noDispatch: the note was kept');+ assert.deepEqual(guardsOf(await call()), [], 'dispatched:false: the note was kept');+ assert.deepEqual(guardsOf(await call()), ['jev-target-changed'], 'a dispatched call keeps its note');+ } finally { api.tabs.sendMessage = oldSend; }+ });++ // ── click-coordinate-intent ─────────────────────────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: click-coordinate-intent ${mode} mode ${strict ? 'refuses a mismatched point' : 'clicks the raw point with a note'}`, async () => {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent._resolveCoordinateVisualTarget = async () => ({ success: true, documentToken: 'doc', refScopeUrl: PAGE_URL,+ semanticTarget: { name: 'Language', role: 'button', eligibility: 'semantic-button', ref_id: 'ref_9' } });+ agent._dispatchClickAx = async () => assert.fail('A mismatched semantic target is never clicked by ref');+ const advisories = [];+ const reconciled = await agent._reconcileCoordinateClick(nextTab++, { x: 40, y: 50 },+ { expectedName: 'Send', guardAdvisories: advisories });+ if (strict) {+ assert.equal(reconciled.result.targetMismatch, true);+ assert.equal(reconciled.result.noDispatch, true);+ assert.deepEqual(advisories, []);+ } else {+ // result:null makes the click handler dispatch the raw point.+ assert.equal(reconciled.result, null);+ assert.equal(reconciled.diagnostic.clickPath, 'coordinate-fallback');+ assert.equal(reconciled.diagnostic.fallbackReason, 'intent-mismatch');+ assert.deepEqual(guardsOf(advisories), ['click-coordinate-intent']);+ }+ });+ }++ // ── carousel-traversal-guards ───────────────────────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: carousel-traversal-guards ${mode} mode ${strict ? 'refuses a revisited slide' : 'opens a revisited slide without resetting its row'}`, async () => {+ const agent = new Agent({});+ agent.strictGuards = strict;+ const tab = nextTab++;+ let currentUrl = 'https://www.instagram.com/p/ABC123/';+ const rows = [], navigations = [];+ agent._currentUrl = async () => currentUrl;+ agent._carouselPageState = async () => ({ discoveredSlideCount: 6,+ visibleMediaFingerprint: `slide-${Number(new URL(currentUrl).searchParams.get('img_index')) || 1}` });+ agent._getVisibleInteractiveElements = async () => [];+ agent.progressExpectedItems.set(tab, { count: 6, item_type: 'photo', ordered: true, required_fields: ['carousel_position'] });+ agent._currentProgressSession = () => ({ sessionId: 'carousel-session', allowedActions: ['process_item'], pageScope: currentUrl });+ agent._progressUpdate = (_tab, payload) => { rows.push(...(payload.items || [])); return { success: true }; };+ agent.executeTool = async (_tab, name, args) => {+ if (name === 'wait_for_stable') return { success: true, stable: true };+ assert.equal(name, 'navigate');+ navigations.push(args.url); currentUrl = args.url;+ return { success: true, dispatched: true, verified: true, url: currentUrl };+ };+ const navigate = index => Agent.prototype.executeTool.call(agent, tab, 'carousel_navigate', { index });+ assert.equal((await navigate(2)).success, true);+ assert.equal((await navigate(3)).success, true);+ const before = { rows: rows.length, navigations: navigations.length };+ const revisit = await navigate(2);+ if (strict) {+ assert.equal(revisit.nonMonotonic, true);+ assert.equal(navigations.length, before.navigations);+ } else {+ assert.equal(revisit.success, true);+ assert.equal(navigations.length, before.navigations + 1);+ assert.deepEqual(guardsOf(revisit), ['carousel-traversal-guards']);+ assert.equal(rows.length, before.rows, 'A revisit does not reset its processed row');+ }+ });+ }++ // ── recipient-clarify-cannot-repair-technical ───────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: recipient-clarify-cannot-repair-technical ${mode} mode ${strict ? 'refuses the recipient question' : 'asks the recipient question with a note'}`, async () => {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent.clarifyTimeoutSec = 0;+ agent._persist = () => {};+ agent._persistNow = async () => ({ ok: true });+ const tab = nextTab++;+ agent._planExecutionGuards.set(tab, { enabled: true, messageRecipientTechnicalBlock: 'recipient_identity_unavailable' });+ const updates = [];+ const result = await Agent.prototype.executeTool.call(agent, tab, 'clarify', {+ question: 'Which conversation should receive this message?', options: ['Ada', 'Grace'], purpose: 'message_recipient',+ }, (type, data) => updates.push({ type, data }));+ if (strict) {+ assert.equal(result.success, false);+ assert.equal(result.reasonCode, 'recipient_identity_unavailable');+ assert.equal(updates.some(update => update.type === 'clarify'), false);+ } else {+ assert.equal(result.success, true);+ assert.ok(updates.some(update => update.type === 'clarify'), 'The question was shown');+ assert.deepEqual(guardsOf(result), ['recipient-clarify-cannot-repair-technical']);+ // The answer still does not approve a recipient; the send stays guarded.+ assert.match(result.note || '', /recipient|answer/i);+ }+ });+ }++ // ── github-commit-split-write-required ──────────────────────────────────+ function githubCommitAgent(strict, { bound = true } = {}) {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ const tab = nextTab++;+ agent._planExecutionGuards.set(tab, { enabled: true, siteWorkflow: { adapterName: 'github', job: { id: 'edit-file-and-commit' } } });+ agent._socialPublicationPreSubmitBlock = async () => null;+ agent._captureMastodonPublicationAttempt = async () => {};+ agent._readControlEffect = async () => null;+ agent._currentUrl = async () => 'https://github.com/Example/Repo/edit/main/docs/plan.md';+ agent._refreshGithubTextReplacementProofs = async () => {};+ // The verified file and commit-message binding a commit click would use.+ agent._workflowSubmitBindingForAttempt = () => (bound+ ? { githubFileCommit: { repository: 'example/repo', branch: 'main', path: 'docs/plan.md' } }+ : { metadataRequirementsIncomplete: true });+ return { agent, tab };+ }+ for (const [mode, strict] of MODES) {+ test(`${build}: github-commit-split-write-required ${mode} mode ${strict ? 'refuses a submit that also writes' : 'lets a detected commit-with-write run with a note'}`, async () => {+ const { agent, tab } = githubCommitAgent(strict);+ const advisories = [];+ const block = await agent._workflowPreSubmitDispatchBlock(tab, 'set_field',+ { ref_id: 'ref_message', text: 'Fix typo', submit: true }, { isSubmit: true, host: 'github.com' }, null, advisories);+ if (strict) {+ assert.equal(block.splitWriteRequired, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(block, null);+ assert.deepEqual(guardsOf(advisories), ['github-commit-split-write-required']);+ }+ });++ test(`${build}: github-commit-split-write-required ${mode} mode keeps a commit-with-write refused without a verified binding`, async () => {+ // No verified file and message binding: github-commit-evidence-binding+ // keeps refusing, so there is nothing to advise.+ const { agent, tab } = githubCommitAgent(strict, { bound: false });+ const advisories = [];+ const block = await agent._workflowPreSubmitDispatchBlock(tab, 'set_field',+ { ref_id: 'ref_message', text: 'Fix typo', submit: true }, { isSubmit: true, host: 'github.com' }, null, advisories);+ assert.equal(block.splitWriteRequired, true);+ assert.deepEqual(advisories, []);+ });++ test(`${build}: github-commit-split-write-required ${mode} mode keeps an inconclusive script refused`, async () => {+ const { agent, tab } = githubCommitAgent(strict);+ assert.equal(agent._isFormValidationCandidate('execute_js', { code: 'void 0' }), true);+ const advisories = [];+ const block = await agent._workflowPreSubmitDispatchBlock(tab, 'execute_js', { code: 'void 0' }, null, null, advisories);+ assert.equal(block.splitWriteRequired, true);+ assert.deepEqual(advisories, []);+ });+ }++ // ── github-conditional-commit-rearm ─────────────────────────────────────+ for (const [mode, strict] of MODES) {+ test(`${build}: github-conditional-commit-rearm ${mode} mode ${strict ? 'defers the first editor action' : 'sends the first editor action under the armed contract'}`, async () => {+ const agent = new Agent({ getActive: () => ({ supportsVision: false }), getVisionProvider: async () => null });+ agent.strictGuards = strict;+ const tab = nextTab++;+ const runUrl = 'https://github.com/Example/Repo/actions/runs/123';+ agent.conversationModes.set(tab, 'act');+ agent.conversations.set(tab, [{ role: 'system', content: 'sys' }, { role: 'user', content: 'Check CI; if it failed, fix the workflow and commit.' }]);+ agent._persist = () => {};+ agent._currentUrl = async () => 'https://github.com/Example/Repo/edit/main/.github/workflows/main.yml';+ agent._ensureWorkflowMetadataRequirements = async () => {};+ const state = agent._startPlanExecutionGuard(tab, 'act', {+ requestKind: 'execute', requiresStateChange: false, requiresSubmission: false,+ siteWorkflowUrl: runUrl, conditionalSiteWorkflow: resolveAdapterWorkflowJob(runUrl, 'edit-file-and-commit'),+ }, { scheduledResume: true });+ const advisories = [];+ const block = await agent._conditionalGithubCommitTransition(tab, 'set_field',+ { ref_id: 'ref_editor', text: 'corrected workflow', submit: false }, { resolvedEditableTarget: true }, advisories);+ assert.equal(state.siteWorkflow?.job?.id, 'edit-file-and-commit', 'The contract is armed in both modes');+ assert.equal(state.requiresSubmission, true);+ if (strict) {+ assert.equal(block.workflowRearmed, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(block, null);+ assert.deepEqual(guardsOf(advisories), ['github-conditional-commit-rearm']);+ }+ });+ }++ // ── page-feedback-target-binding ────────────────────────────────────────+ function boundRun(agent, tab, events = []) {+ const state = { token: 'pf-run', url: PAGE_URL, frames: new Map(), steeringRevision: 0,+ actionBinding: { snapshotToken: 'snapshot-1', runToken: 'pf-run', documentToken: 'content-1' } };+ const run = { token: 'pf-run', url: PAGE_URL, documents: new Map(), frames: new Map(), revision: 0,+ events: new Map(events.map((event, index) => [index, event])), modelState: state, gestures: new Set(), gestureLeases: new Map() };+ agent._pageFeedbackRuns = new Map([[tab, run]]);+ return run;+ }+ async function bindingCall(strict, reason, events = []) {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ const tab = nextTab++;+ boundRun(agent, tab, events);+ agent._uncertainTextMutationBlock = async () => null;+ agent._finalizeToolResultOnce = async (_tab, _name, _args, result) => result;+ const impl = [];+ agent._executeToolImpl = async (_tab, name) => { impl.push(name); return { success: true, dispatched: true }; };+ const oldSend = api.tabs.sendMessage;+ api.tabs.sendMessage = async (_id, message) => message.action === 'page_monitor_validate_model'+ ? { ready: false, reason, runToken: message.params.runToken, documentToken: 'content-1', snapshotToken: message.params.snapshotToken }+ : { ready: true };+ try {+ const result = await Agent.prototype.executeTool.call(agent, tab, 'click_ax', { ref_id: 'ref_uncovered' }, null, { guardAdvisories: [] });+ return { result, impl };+ } finally { api.tabs.sendMessage = oldSend; }+ }+ for (const [mode, strict] of MODES) {+ test(`${build}: page-feedback-target-binding ${mode} mode ${strict ? 'refuses an uncovered target' : 'sends an uncovered target with a note'}`, async () => {+ const { result, impl } = await bindingCall(strict, 'target_uncovered');+ if (strict) {+ assert.deepEqual(impl, []);+ assert.equal(result.errorCode, 'action_binding_unavailable');+ } else {+ assert.deepEqual(impl, ['click_ax']);+ assert.deepEqual(guardsOf(result), ['page-feedback-target-binding']);+ }+ });++ test(`${build}: page-feedback-target-binding ${mode} mode keeps ambiguous selectors and pending page activity refused`, async () => {+ for (const [reason, events] of [['target_ambiguous', []], ['target_unresolved', []],+ ['target_uncovered', [{ kind: 'dom', source: 'unknown', frameId: 0, target: 'div#feed' }]]]) {+ const { result, impl } = await bindingCall(strict, reason, events);+ assert.deepEqual(impl, [], reason);+ assert.equal(result.errorCode, 'action_binding_unavailable', reason);+ assert.deepEqual(guardsOf(result), [], reason);+ }+ });+ }++ // ── rich-text toolbar guards ────────────────────────────────────────────+ function toolbarAgent(strict) {+ const agent = new Agent({ getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent._resolveVisionRoute = async () => ({ provider: null });+ agent._shouldAutoScreenshot = () => false;+ agent._releaseRichTextToolbarProbeTarget = async () => {};+ return { agent, tab: nextTab++ };+ }+ const toolbarCandidate = { score: 6, reasons: ['semantic_toolbar', 'numeric_preset_value'], availablePresetValues: ['10', '12', '14'] };+ const toolbarProbe = { resolved: true, rect: { x: 10, y: 10, w: 40, h: 20 }, refId: 'ref_size', documentToken: 'doc-1',+ refScopeUrl: PAGE_URL, dispatchBinding: { token: 'binding-1' },+ fieldMeta: { tag: 'input', contentEditable: false, toolbarCandidate } };+ for (const [mode, strict] of MODES) {+ test(`${build}: rich-text-toolbar-target-unresolved ${mode} mode ${strict ? 'refuses an unresolved typing target' : 'lets the tool resolve its own target'}`, async () => {+ const { agent, tab } = toolbarAgent(strict);+ agent._probeRichTextToolbarRetryTarget = async () => ({ resolved: false });+ const advisories = [];+ const preflight = await agent._preflightRichTextToolbarTarget(tab, 'type_text', { selector: '#body', text: 'Hello there' },+ null, { guardAdvisories: advisories });+ if (strict) {+ assert.equal(preflight.block.noDispatch, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(preflight.block, null);+ assert.deepEqual(guardsOf(advisories), ['rich-text-toolbar-target-unresolved']);+ }+ });++ test(`${build}: rich-text-toolbar-wrong-target ${mode} mode ${strict ? 'refuses typing into a toolbar control' : 'types with a note and keeps the recovery obligation'}`, async () => {+ const { agent, tab } = toolbarAgent(strict);+ agent._probeRichTextToolbarRetryTarget = async () => structuredClone(toolbarProbe);+ const advisories = [];+ const preflight = await agent._preflightRichTextToolbarTarget(tab, 'type_ax',+ { ref_id: 'ref_size', text: 'Dear team, the release is ready for review.' }, null, { guardAdvisories: advisories });+ assert.equal(agent._richTextToolbarGuard.hasPending(tab), true, 'The obligation is recorded in both modes');+ if (strict) {+ assert.equal(preflight.block.wrongTarget, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(preflight.block, null);+ assert.equal(preflight.probe.dispatchBinding.token, 'binding-1', 'The advised edit stays bound to the probed target');+ assert.deepEqual(guardsOf(advisories), ['rich-text-toolbar-wrong-target']);+ }+ });++ test(`${build}: rich-text-toolbar-recovery-obligation ${mode} mode ${strict ? 'refuses the recorded toolbar ref' : 'uses the recorded toolbar ref with a note'}`, async () => {+ const { agent, tab } = toolbarAgent(strict);+ agent._richTextToolbarGuard.recordWrongTarget(tab, { toolName: 'type_ax', args: { ref_id: 'ref_size', text: 'Body text' },+ candidate: toolbarCandidate, decision: { source: 'structural_fallback', targetKind: 'font_size' },+ identity: { documentToken: 'doc-1', refScopeUrl: PAGE_URL } });+ agent._lastAxScopes.set(tab, { documentToken: 'doc-1', pageUrl: PAGE_URL });+ agent._probeRichTextToolbarRetryTarget = async () => ({ resolved: false });+ const advisories = [];+ const block = await agent._richTextToolbarToolBlock(tab, 'click_ax', { ref_id: 'ref_size' }, { guardAdvisories: advisories });+ if (strict) {+ assert.equal(block.blockedToolbarRef, true);+ assert.deepEqual(advisories, []);+ } else {+ assert.equal(block, null);+ assert.deepEqual(guardsOf(advisories), ['rich-text-toolbar-recovery-obligation']);+ }+ assert.equal(agent._richTextToolbarGuard.hasPending(tab), true, 'Only a verified editor-body edit releases it');+ });+ }+}diff --git a/test/guard-advisory-completion.mjs b/test/guard-advisory-completion.mjsnew file mode 100644index 000000000..a1eb195f6--- /dev/null+++ b/test/guard-advisory-completion.mjs@@ -0,0 +1,747 @@+// Completion guards under the default policy (Settings → General → "Strict+// checks" off, see src/*/src/agent/guard-policy.js). A completion guard+// refuses a done or a plain final at most once per run: that refusal is the+// model's note. The next completion the same guard would refuse is accepted,+// and the final answer ends with one line naming what was not verified. With+// agent.strictGuards = true every old refusal, budget and forced turn stays.+// Real Agent batches and run loops (chat and stream) with mocked browser+// APIs, both builds.+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { withoutFixedChoiceAnswers } from './semantic-decision-stub.mjs';++const PAGE = 'https://owned.example.test/profile';+const TREE = 'main [ref_main]\n heading "Profile" [ref_h]\n button "Save" [ref_save]';+const area = { get: async () => ({}), set: async () => {}, remove: async () => {} };+const api = {+ storage: { local: area, session: area, onChanged: { addListener() {} } },+ runtime: { getURL: value => `extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: {+ get: async id => ({ id, url: PAGE, title: 'Profile', status: 'complete' }),+ sendMessage: async () => ({ ready: true }),+ executeScript: async () => [null],+ },+ webNavigation: { getAllFrames: async () => [{ frameId: 0, parentFrameId: -1, documentId: 'document-1', url: PAGE }] },+ scripting: { executeScript: async () => [{ result: null }] },+};+globalThis.chrome = api;+globalThis.browser = api;++const CAVEAT = 'WebBrain could not verify everything: ';+const STRICT_NOTE = 'Strict checks keep the old refusal';+let nextTab = 9300;+let nextCall = 1;++const { cdpClient } = await import('../src/chrome/src/cdp/cdp-client.js');++// A tool batch the way the run loop executes one, for a minimal Act or Ask+// agent whose done handler is stubbed unless `realDone` is set.+function batchAgent(Agent, { mode = 'act', strict = false, task = 'Update the owned profile.', realDone = false, schemas = null } = {}) {+ const tab = nextTab++;+ const agent = new Agent({ getActive: () => ({ model: 'test', supportsTools: true, supportsVision: false }), getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent.conversationIds.set(tab, `conv-${tab}`);+ agent.conversationModes.set(tab, mode);+ agent.conversations.set(tab, [{ role: 'system', content: 'sys' }, { role: 'user', content: task }]);+ agent._ensureGateSetting = async () => {};+ agent._skipPermissionGate = true;+ agent._currentUrl = async () => PAGE;+ agent._persist = () => {};+ agent._persistNow = async () => true;+ const executed = [];+ if (!realDone) {+ agent.executeTool = async (_tab, name, args) => {+ executed.push({ name, args });+ if (name === 'done') return { done: true, summary: args.summary, outcome: args.outcome };+ if (name === 'get_accessibility_tree') return { success: true, pageContent: TREE };+ return { success: true, dispatched: true };+ };+ }+ const batch = async (calls, updates = []) => {+ const toolCalls = calls.map(([name, args]) => ({ id: `${name}_${nextCall++}`, function: { name, arguments: JSON.stringify(args) } }));+ const messages = agent.conversations.get(tab);+ messages.push({ role: 'assistant', content: null, tool_calls: toolCalls });+ return agent._executeToolBatch(tab, toolCalls, messages, (type, data) => updates.push({ type, data }),+ { supportsVision: false }, null, new Set(['done', 'click_ax', 'get_accessibility_tree']), 1, {}, schemas);+ };+ return { agent, tab, batch, executed };+}++// The same done twice: by default the second is accepted with its caveat;+// under Strict checks it is refused again.+async function refusedOnceThenAccepted(Agent, setup, doneArgs, caveat, label) {+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { ...(setup.options || {}), strict });+ await setup.prepare?.(h);+ const first = await h.batch([['done', doneArgs]]);+ assert.equal(first.action, 'continue', `${label}: the first completion is refused with its note`);+ const second = await h.batch([['done', doneArgs]]);+ if (strict) {+ assert.notEqual(second.action === 'return' && !second.status, true, `${label}: ${STRICT_NOTE}`);+ if (second.action === 'return') assert.doesNotMatch(String(second.value), new RegExp(CAVEAT), `${label}: strict caveat`);+ } else {+ assert.equal(second.action, 'return', `${label}: the second completion is accepted`);+ assert.equal(second.status, undefined, `${label}: an accepted completion does not end as a guard failure`);+ assert.ok(String(second.value).startsWith(String(doneArgs.summary)), `${label}: the model's answer is kept`);+ assert.ok(String(second.value).includes(CAVEAT + caveat), `${label}: caveat missing from ${JSON.stringify(second.value)}`);+ }+ }+}++// A real run loop with a mocked model; done and page tools are stubbed at+// the lifecycle boundary, so every batch, plain-final and forced-turn path+// runs for real.+function loopAgent(Agent, next, { strict = false, realTraceStart = false } = {}) {+ const provider = {+ name: 'guard advisory test', model: 'test', promptTier: 'full', contextWindow: 128000,+ supportsTools: true, supportsVision: false,+ chat: withoutFixedChoiceAnswers((messages, options) => next(messages, options)),+ async *chatStream(messages, options) {+ const response = await next(messages, options);+ if (response.content) yield { type: 'text', content: response.content };+ if (response.toolCalls) yield { type: 'tool_call', content: response.toolCalls.map((call, index) => ({ ...call, index })) };+ yield { type: 'done' };+ },+ };+ const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ agent.strictGuards = strict;+ Object.assign(agent, {+ _hydrate: async () => {}, _persist: () => {}, _persistNow: async () => ({ ok: true }), _persistSubmittedTurn: async () => {},+ _startTraceRun: async () => null, _endTraceRun: async () => {}, _beginReadCompleteness: async () => null,+ _manageContext: async () => {}, _checkCostAllowance: async () => null, _recordCostUsage: async () => null,+ _currentUrl: async () => PAGE, _getTabUrlTitle: async () => ({ tabUrl: PAGE, tabTitle: 'Profile' }),+ _maybeEmitAskModeHandoff: async () => {}, _maybeReinjectAdapter: async () => {}, _ensureProgressSessionForCurrentTask: async () => {},+ _enrichUserMessageWithCurrentPage: async (_tab, _messages, content) => ({ role: 'user', content }),+ _plannerMode: () => 'off',+ _runPlannerIntentGate: async () => ({ proceed: true, requestKind: 'execute', requiresStateChange: false, requiresSubmission: false }),+ _skipPermissionGate: true, _ensureGateSetting: async () => true, _adoptLiveSocialPublishWorkflow: async () => false,+ _isFormValidationCandidate: () => false, _preflightRichTextToolbarTarget: async () => ({ block: null }),+ _auditRichTextToolbarTarget: async () => {}, _shouldAutoScreenshot: () => false, _pageFeedbackIdleMs: 0,+ });+ for (const name of ['_chromeProtectedPageFailure', '_captchaMutationPreflight', '_workflowPreSubmitDispatchBlock',+ '_messageRecipientGuardBlock', '_detectLikelySubmitAction', '_socialPublicationPreSubmitBlock']) agent[name] = async () => null;+ // The real run start mints the task token that bounds an untraced run.+ if (realTraceStart) delete agent._startTraceRun;+ agent.maxSteps = 8;+ agent._executeToolWithLifecycle = async (_tab, name, args) => {+ if (name === 'done') return { done: true, success: true, summary: args.summary, outcome: args.outcome };+ if (name === 'get_accessibility_tree') return { success: true, pageContent: TREE };+ return { success: true, dispatched: true };+ };+ return agent;+}+const call = (id, name, args) => ({ toolCalls: [{ id: `${id}_${nextCall++}`, function: { name, arguments: JSON.stringify(args) } }] });+const runLoop = (agent, tab, streaming, text) => streaming+ ? agent.processMessageStream(tab, text, () => {}, 'act', { detachedRequestId: `guard-${tab}` })+ : agent.processMessage(tab, text, () => {}, 'act', [], { detachedRequestId: `guard-${tab}` });++// The Act done handler with its page probe, completion judge and page checks+// running for real against a fixed page state.+function handlerAgent(Agent, build, { strict = false, page = {}, verdict = null } = {}) {+ const tab = nextTab++;+ const pageState = { url: PAGE, title: 'Profile', openDialogCount: 0, dialogTitles: [], visibleFormCount: 0,+ relevantFormCount: 0, formDescriptors: [], liveRegionMessages: [], successMessages: [], documentIdentity: 'owned-document',+ incompleteTaskControls: [], workflowStatusTexts: [], workflowResourceUrls: [], workflowResourceRecords: [], workflowPageText: 'Profile',+ ...page };+ const settings = verdict ? { decisionProvider: 'local', systemOneEnabled: true, decisionVisionMode: 'off' } : {};+ const storage = { ...area, get: async () => settings };+ globalThis.chrome = globalThis.browser = { ...api, storage: { ...api.storage, local: storage },+ tabs: { ...api.tabs, get: async id => ({ id, url: PAGE, title: 'Profile', status: 'complete' }), executeScript: async () => [pageState] } };+ cdpClient.attach = async () => {};+ cdpClient.sendCommand = async () => ({});+ cdpClient.evaluate = async () => ({ result: { value: pageState } });+ const provider = { model: 'test-model', supportsVision: false, config: { category: 'local' } };+ const agent = new Agent({ getActive: () => provider, getVisionProvider: async () => null });+ agent.strictGuards = strict;+ agent.conversationModes.set(tab, 'act');+ agent.conversations.set(tab, [{ role: 'system', content: 'sys' }, { role: 'user', content: 'Save the owned profile.' }]);+ agent.autoScreenshot = 'off';+ agent._persist = () => {};+ agent._persistNow = async () => true;+ agent.systemOneContext = () => ({ isCurrent: () => true });+ agent._latestTaskText = () => 'Save the owned profile.';+ agent._completionDocumentStamp = async () => 'owned-document';+ agent._captureViewportProbe = async () => ({ url: PAGE, title: 'Profile' });+ // The judge's own fresh page read.+ const execute = agent.executeTool.bind(agent);+ agent.executeTool = (tabId, name, args, ...rest) => name === 'get_accessibility_tree'+ ? Promise.resolve({ success: true, pageContent: 'heading "Profile"\nstatus "Saving failed"' })+ : execute(tabId, name, args, ...rest);+ if (verdict) {+ agent.evaluateSystemOne = async () => ({ model: 'judge', answers: {+ task_outcome: { type: 'choice', choice: verdict, confidence: 0.99,+ probabilities: Object.fromEntries(['succeeded', 'pending', 'failed', 'uncertain'].map(key => [key, key === verdict ? 0.97 : 0.01])) },+ later_outcome: { type: 'choice', choice: 'not_asked', confidence: 0.95, probabilities: { asked: 0.05, not_asked: 0.95 } },+ summary_kind: { type: 'choice', choice: 'result', confidence: 0.95, probabilities: { result: 0.9, meta_only: 0.05, plan_only: 0.05 } },+ } });+ }+ return { agent, tab, pageState, build };+}++const restoreGlobals = () => {+ globalThis.chrome = api;+ globalThis.browser = api;+};++for (const build of ['chrome', 'firefox']) {+ const { Agent } = await import(`../src/${build}/src/agent/agent.js`);+ const invariant = await import(`../src/${build}/src/agent/completion-invariant.js`);+ const { getToolsForMode } = await import(`../src/${build}/src/agent/tools.js`);++ // ── Forced turns, verification debt and the failure-only done ──────────+ for (const streaming of [false, true]) {+ const label = `${build} ${streaming ? 'stream' : 'chat'}`;++ test(`${label}: an unobserved action is advised once, then done is accepted with a caveat and no forced turns`, async () => {+ for (const strict of [false, true]) {+ const tab = nextTab++, requests = [];+ const agent = loopAgent(Agent, async (_messages, options) => {+ requests.push({ names: (options?.tools || []).map(tool => tool.function.name), choice: options?.toolChoice ?? null });+ const n = requests.length;+ if (n === 1) return call('save', 'click_ax', { ref_id: 'ref_save' });+ if (n === 2) return call('early-done', 'done', { summary: 'Saved the profile.', outcome: 'success' });+ if (strict && n === 3) return call('verify', 'get_accessibility_tree', { filter: 'visible' });+ return call('done', 'done', { summary: 'Saved the profile.', outcome: 'success' });+ }, { strict });+ const result = await runLoop(agent, tab, streaming, 'Save the owned profile.');+ if (!strict) {+ assert.equal(requests.length, 3, `${label}: one refusal, then the done is accepted`);+ assert.ok(requests[2].names.includes('click_ax'), `${label}: the default note leaves every tool available`);+ assert.equal(requests[2].choice, null, `${label}: no forced verification or done-only turn by default`);+ assert.equal(result, `Saved the profile.\n\n${CAVEAT}The page was not checked again after the last action.`);+ } else {+ assert.equal(requests[2].choice, 'required', `${label}: ${STRICT_NOTE} (forced read-only turn)`);+ assert.equal(requests[2].names.includes('click_ax'), false, `${label}: strict verification turn is read-only`);+ assert.deepEqual(requests[3].names, ['done'], `${label}: strict forces the done-only turn after verification`);+ assert.equal(result, 'Saved the profile.', `${label}: a verified strict completion carries no caveat`);+ }+ }+ });++ test(`${label}: a plain final after an observed action is advised once, then shown with a caveat`, async () => {+ for (const strict of [false, true]) {+ const tab = nextTab++;+ let n = 0;+ const agent = loopAgent(Agent, async () => {+ n++;+ if (n === 1) return call('save', 'click_ax', { ref_id: 'ref_save' });+ if (n === 2) return call('observe', 'get_accessibility_tree', { filter: 'visible' });+ return { content: 'Saved the profile.' };+ }, { strict });+ const result = await runLoop(agent, tab, streaming, 'Save the owned profile.');+ if (!strict) {+ assert.equal(n, 4, `${label}: one done-protocol note, then the plain final is accepted`);+ assert.equal(result, `Saved the profile.\n\n${CAVEAT}The task ended with a plain answer instead of a checked completion.`);+ } else {+ assert.equal(n, 5, `${label}: ${STRICT_NOTE} (two recovery turns)`);+ assert.match(result, /plain text repeatedly/, `${label}: strict keeps the two-strike partial`);+ }+ }+ });+ }++ test(`${build}: each untraced run gets its own one refusal per guard`, async () => {+ const tab = nextTab++;+ let requests = 0;+ const agent = loopAgent(Agent, async () => {+ requests++;+ if (requests === 1 || requests === 4) return call('save', 'click_ax', { ref_id: 'ref_save' });+ return call('done', 'done', { summary: 'Saved the profile.', outcome: 'success' });+ }, { realTraceStart: true });+ const first = await runLoop(agent, tab, false, 'Save the owned profile.');+ assert.equal(requests, 3, `${build}: run 1 refuses the unobserved done once`);+ assert.match(first, /The page was not checked again after the last action\./);+ const second = await runLoop(agent, tab, false, 'Save the owned profile again.');+ assert.equal(requests, 6, `${build}: run 2 refuses it once again instead of inheriting run 1's advice`);+ assert.match(second, /The page was not checked again after the last action\./);+ });++ test(`${build}: a new completion attempt drops stale completion caveats and keeps other guards' caveats`, async () => {+ const h = batchAgent(Agent);+ const { caveats } = h.agent._guardRunState(h.tab);+ caveats.set('done-verification-debt', 'The page was not checked again after the last action.');+ caveats.set('chat-send-preconditions', 'A caveat from another guard family.');+ await h.batch([['get_accessibility_tree', { filter: 'visible' }]]);+ assert.equal(caveats.size, 2, `${build}: a batch without done is not a completion attempt`);+ const result = await h.batch([['done', { summary: 'Saved the profile.', outcome: 'success' }]]);+ assert.equal(result.value, `Saved the profile.\n\n${CAVEAT}A caveat from another guard family.`);+ });++ test(`${build}: clearing the conversation drops its guard notes and caveats`, () => {+ const h = batchAgent(Agent);+ assert.equal(h.agent._guardRefusesOnce(h.tab, 'done-verification-debt', { decided: false, caveat: 'Not checked.' }), true);+ assert.equal(h.agent._guardRunStates.has(h.tab), true);+ h.agent.clearConversation(h.tab, { preserveStorage: true });+ assert.equal(h.agent._guardRunStates.has(h.tab), false);+ assert.equal(h.agent._guardRefusesOnce(h.tab, 'done-verification-debt', { decided: false, caveat: 'Not checked.' }), true,+ `${build}: a cleared conversation starts with a fresh note`);+ });++ test(`${build}: a scheduled resume is a pause, so its summary gets no caveat`, async () => {+ const h = batchAgent(Agent);+ h.agent._guardRunState(h.tab).caveats.set('chat-send-preconditions', 'A caveat from another guard family.');+ h.agent._isSuccessfulSchedulingEvidence = () => true;+ h.agent.executeTool = async () => ({ done: true, success: true, scheduled: true, summary: 'I will continue at 09:00.' });+ const toolCalls = [{ id: `schedule_resume_${nextCall++}`, function: { name: 'schedule_resume', arguments: JSON.stringify({+ after_seconds: 3600, reason: 'Waiting for CI.', resume_instruction: 'Check the CI result first.' }) } }];+ const messages = h.agent.conversations.get(h.tab);+ messages.push({ role: 'assistant', content: null, tool_calls: toolCalls });+ const result = await h.agent._executeToolBatch(h.tab, toolCalls, messages, () => {}, { supportsVision: false }, null,+ new Set(['done', 'schedule_resume']), 1, {}, null);+ assert.equal(result.status, 'scheduled_resume');+ assert.equal(result.value, 'I will continue at 09:00.');+ });++ test(`${build}: the forced recovery policy and failure-only done exist only under Strict checks`, () => {+ for (const strict of [false, true]) {+ const agent = new Agent({});+ agent.strictGuards = strict;+ const tab = nextTab++;+ agent.conversationModes.set(tab, 'act');+ agent.completionInvariants.set(tab, invariant.recordCompletionToolResult(+ invariant.createCompletionInvariantState(`${build}-policy`), 'download_public_media',+ { __completionDownloadAction: true }, { success: true, completedCount: 1 }));+ const policy = agent._completionRecoveryPolicy(tab, getToolsForMode('act', { compact: true }), { verification: true });+ if (strict) {+ assert.equal(policy?.kind, 'verification_unavailable', `${build}: ${STRICT_NOTE}`);+ assert.deepEqual(policy.tools[0].function.parameters.properties.outcome.enum, ['partial', 'failed']);+ } else {+ assert.equal(policy, null, `${build}: no forced turn and no failure-only done by default`);+ }+ }+ });++ // ── Completion invariant (pre-dispatch) ────────────────────────────────+ test(`${build}: unverified iframe fields, a toolbar target and a same-batch success are each advised once`, async () => {+ await refusedOnceThenAccepted(Agent, {+ prepare: h => h.agent.completionInvariants.set(h.tab, { ...invariant.createCompletionInvariantState('iframe'),+ hadAction: true, iframeFormVerificationDebt: true, iframeFormScope: 'forms.owned.example',+ iframeFormVerificationObligations: [{ scope: 'forms.owned.example', selector: '#email' }] }),+ }, { summary: 'Filled the form.', outcome: 'success' },+ 'The form fields edited inside an embedded frame were not read back.', `${build} iframe`);++ await refusedOnceThenAccepted(Agent, {+ prepare: h => { h.agent._richTextToolbarGuard.completionAction = () => ({ name: 'type_ax', ref_id: 'ref_bold' }); },+ }, { summary: 'Wrote the post.', outcome: 'success' },+ 'The last text may have gone into a formatting toolbar instead of the editor.', `${build} toolbar`);++ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict });+ h.agent.completionInvariants.set(h.tab, invariant.createCompletionInvariantState('same-batch'));+ const sameBatch = [['click_ax', { ref_id: 'ref_save' }], ['get_accessibility_tree', { filter: 'visible' }],+ ['done', { summary: 'Saved.', outcome: 'success' }]];+ assert.equal((await h.batch(sameBatch)).action, 'continue', `${build}: same-batch success is refused first`);+ const second = await h.batch(sameBatch);+ if (strict) assert.equal(second.action, 'continue', `${build}: ${STRICT_NOTE} (same batch)`);+ else assert.equal(second.value, `Saved.\n\n${CAVEAT}Success was reported in the same step as the last action, before its result was seen.`);+ }+ });++ test(`${build}: two completion invariants each get one note, and both caveats reach the answer`, async () => {+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict });+ // A toolbar obligation (decided: the text went to the wrong place) and+ // verification debt (undecided: the page was not read again).+ h.agent._richTextToolbarGuard.completionAction = () => ({ name: 'type_ax', ref_id: 'ref_bold' });+ h.agent.completionInvariants.set(h.tab, { ...invariant.createCompletionInvariantState('two'), hadAction: true,+ verificationDebt: true, sequence: 1, lastAction: { name: 'click_ax', sequence: 1 } });+ const done = ['done', { summary: 'Wrote the post.', outcome: 'success' }];+ const reasons = () => h.agent.conversations.get(h.tab).filter(message => message.role === 'tool')+ .map(message => { try { return JSON.parse(message.content).reason; } catch { return null; } }).filter(Boolean);+ assert.equal((await h.batch([done])).action, 'continue');+ assert.equal((await h.batch([done])).action, 'continue');+ if (strict) {+ assert.deepEqual(reasons(), ['rich_text_toolbar_target_unresolved', 'rich_text_toolbar_target_unresolved'],+ `${build}: ${STRICT_NOTE}`);+ assert.equal((await h.batch([done])).action, 'continue', `${build}: ${STRICT_NOTE}`);+ continue;+ }+ assert.deepEqual(reasons(), ['rich_text_toolbar_target_unresolved', 'verification_required'],+ `${build}: the second invariant was masked by the first`);+ const updates = [];+ const third = await h.batch([done], updates);+ assert.equal(third.action, 'return');+ assert.equal(third.value, `Wrote the post.\n\n${CAVEAT}The last text may have gone into a formatting toolbar instead of the editor. The page was not checked again after the last action.`);+ // Accepted over a guard that knows the claim is wrong: the run ends,+ // but not as a success.+ const doneResult = updates.filter(update => update.type === 'tool_result' && update.data.name === 'done').at(-1)?.data.result;+ assert.equal(doneResult?.outcome, 'partial', `${build}: a success over a decided guard was not downgraded`);+ }+ });++ test(`${build}: a success accepted over undecided advice keeps its outcome`, async () => {+ const h = batchAgent(Agent);+ // The debt was carried in from an earlier batch: accepting it is not a+ // second "same-batch" concern.+ h.agent.completionInvariants.set(h.tab, { ...invariant.createCompletionInvariantState('undecided'), hadAction: true,+ verificationDebt: true, sequence: 1, lastAction: { name: 'click_ax', sequence: 1 } });+ const done = ['done', { summary: 'Saved.', outcome: 'success' }];+ assert.equal((await h.batch([done])).action, 'continue');+ const updates = [];+ const second = await h.batch([done], updates);+ assert.equal(second.action, 'return');+ const doneResult = updates.filter(update => update.type === 'tool_result' && update.data.name === 'done').at(-1)?.data.result;+ assert.equal(doneResult?.outcome, 'success', `${build}: missing evidence alone must not downgrade the outcome`);+ });++ test(`${build}: a done with no outcome is advised once, then accepted as partial`, async () => {+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict });+ assert.equal((await h.batch([['done', { summary: 'Checked it.' }]])).action, 'continue');+ const second = await h.batch([['done', { summary: 'Checked it.' }]]);+ if (strict) {+ assert.equal(second.action, 'continue', `${build}: ${STRICT_NOTE}`);+ assert.equal(h.executed.length, 0);+ } else {+ assert.equal(second.action, 'return');+ assert.equal(h.executed.at(-1).args.outcome, 'partial', `${build}: an unnamed outcome claims no success`);+ assert.match(second.value, /counts as partial\.$/);+ }+ }+ });++ // ── Progress ledger ────────────────────────────────────────────────────+ test(`${build}: an honest partial over unresolved progress rows is refused once, then accepted`, async () => {+ const rows = [{ id: 'item-1', label: 'First', status: 'processed' }, { id: 'item-2', label: 'Second', status: 'pending' }];+ await refusedOnceThenAccepted(Agent, {+ prepare: h => { h.agent._currentTaskLedgerRows = () => rows; },+ }, { summary: 'One of two items is done.', outcome: 'partial' },+ '1 of 2 items in the task\'s progress list were not finished.', `${build} unresolved rows`);+ });++ test(`${build}: a success claim over skipped or failed progress rows is advised once`, async () => {+ const rows = [{ id: 'item-1', label: 'First', status: 'processed' }, { id: 'item-2', label: 'Second', status: 'skipped' }];+ await refusedOnceThenAccepted(Agent, {+ prepare: h => { h.agent._currentTaskLedgerRows = () => rows; },+ }, { summary: 'Both items are handled.', outcome: 'success' },+ 'Some items in the task\'s progress list are missing, incomplete, skipped or failed.', `${build} skipped rows`);+ });++ // ── Read coverage (Ask-mode Gmail) ─────────────────────────────────────+ test(`${build}: Ask keeps the answer and adds the Gmail expansion limitation after one note`, async () => {+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { mode: 'ask', strict });+ h.agent._runModeOverrides.set(h.tab, 'ask');+ h.agent._currentUrl = async () => 'https://mail.google.com/mail/u/0/#inbox/FMfc123';+ await h.agent._beginReadCompleteness(h.tab, 'What is going on in this conversation?', {});+ h.agent._armReadCompletenessFromPlan(h.tab, { request_kind: 'execute', read_scope: 'complete_thread' });+ const root = `ref_${build}_root`;+ h.agent._recordReadCompleteness(h.tab, 'get_accessibility_tree', { filter: 'visible', maxDepth: 12 }, {+ pageContent: 'main\n button "Expand all"', page: 1, hasMore: false, truncated: false,+ conversationRootRefId: root, conversationExpansionState: 'collapsed' });+ h.agent._recordReadCompleteness(h.tab, 'get_accessibility_tree', { filter: 'all', maxDepth: 15, ref_id: root }, {+ pageContent: 'main\n button "Expand all"\n listitem "Latest visible message"', page: 1, totalChars: 1200,+ hasMore: false, truncated: false, continuationArgs: null, conversationRootRefId: root,+ conversationExpansionState: 'collapsed', treeRevision: 'fnv1a64:4444444444444444' });+ const done = ['done', { summary: 'The visible messages discuss the launch date.' }];+ const first = await h.batch([done]);+ if (strict) {+ assert.equal(first.status, 'read_scope_limited', `${build}: ${STRICT_NOTE} (fixed limitation)`);+ assert.match(first.value, /Ask mode cannot expand/);+ continue;+ }+ assert.equal(first.action, 'continue', `${build}: the answer gets one coverage note`);+ const second = await h.batch([done]);+ assert.equal(second.action, 'return');+ assert.equal(second.value, `The visible messages discuss the launch date.\n\n${CAVEAT}Ask mode cannot expand collapsed Gmail messages, so some messages in the conversation may be missing.`);+ }+ });++ // ── Exact table export ─────────────────────────────────────────────────+ test(`${build}: table JSON without an exact extract, and an expired table reference, are advised once`, async () => {+ const json = JSON.stringify({ rowCount: 2, rows: [{ id: 'A' }, { id: 'B' }] });+ await refusedOnceThenAccepted(Agent, {+ options: { mode: 'ask', realDone: true },+ prepare: h => h.agent.readCompletenessStates.set(h.tab, { runToken: 'owned-run', tablePageObserved: true }),+ }, { summary: json, outcome: 'success' }, 'The table was not checked against the exact rows on the page.', `${build} table json`);+ const askSchemas = new Map(getToolsForMode('ask', { tier: 'full' }).map(tool => [tool.function.name, tool.function.parameters]));+ await refusedOnceThenAccepted(Agent, {+ options: { mode: 'ask', realDone: true, schemas: askSchemas },+ prepare: h => h.agent.readCompletenessStates.set(h.tab, { runToken: 'owned-run', tablePageObserved: true }),+ }, { summary: 'Full inventory.', data_ref: 'table_expired' },+ 'The table reference had expired, so the exact table could not be delivered.', `${build} table ref`);+ });++ test(`${build}: an unverifiable table snapshot is delivered over advice, but not under Strict secret mode`, async () => {+ for (const strictSecretMode of [false, true]) {+ const h = batchAgent(Agent, { mode: 'ask' });+ h.agent.strictSecretMode = strictSecretMode;+ const owner = { runToken: 'owned-run', current: () => true };+ const record = { dataRef: 'table_owned', runToken: 'owned-run', owner, args: { columns: ['id'] },+ summary: '[{"id":"A"},{"id":"B"}]' };+ h.agent.readCompletenessStates.set(h.tab, { runToken: 'owned-run', exactTableExports: new Map([['table_owned', record]]) });+ h.agent._exactTableOwner = () => owner;+ h.agent.executeTool = async () => ({ success: false, error: 'The source table changed.' });+ const args = () => ({ summary: 'Full inventory.', data_ref: 'table_owned' });+ const first = await h.agent._resolveExactTableDone(h.tab, args());+ assert.equal(first?.blockedDone, true, `${build}: the stale snapshot is refused once`);+ const accepted = args();+ assert.equal(await h.agent._resolveExactTableDone(h.tab, accepted), null);+ assert.equal(accepted.summary, strictSecretMode ? 'Full inventory.' : record.summary,+ `${build}: strictSecretMode=${strictSecretMode}`);+ assert.match(h.agent._guardCaveatLine(h.tab), /may have changed after it was extracted/);+ }+ });++ // ── Arithmetic tasks ───────────────────────────────────────────────────+ test(`${build}: an honest failure before any calculator attempt is refused once, then accepted`, async () => {+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict });+ h.agent._pureCalculationToolPolicy = () => ({ scope: { owner: 'owned', runToken: 'run', expression: '2+2' },+ stale: false, attempted: false, names: ['calculate', 'done'] });+ const done = ['done', { summary: 'The calculator was not used.', outcome: 'failed' }];+ assert.equal((await h.batch([done])).action, 'continue', `${build}: premature done gets one note`);+ const second = await h.batch([done]);+ if (strict) {+ assert.equal(second.action, 'continue', `${build}: ${STRICT_NOTE}`);+ assert.equal(h.executed.length, 0);+ } else {+ assert.equal(second.value, `The calculator was not used.\n\n${CAVEAT}The result was not computed with the calculator.`);+ }+ }+ });++ // ── Meta-only done summary (Ask) ───────────────────────────────────────+ test(`${build}: a summary that only says an answer was given is advised once`, async () => {+ await refusedOnceThenAccepted(Agent, {+ options: { mode: 'ask' },+ prepare: h => { h.agent._semanticDecision = async (_tab, kind) => ({ choice: kind === 'done_summary' ? 'meta_only' : null }); },+ }, { summary: 'Explained how it works.', outcome: 'success' },+ 'The final answer may only say that an answer was given, without the answer itself.', `${build} meta-only`);+ });++ // ── Plan-execution guard ───────────────────────────────────────────────+ const planCase = (gate, after = () => {}) => ({ prepare: h => {+ const guard = h.agent._startPlanExecutionGuard(h.tab, 'act', { requestKind: 'execute', ...gate });+ after(guard, h);+ } });++ test(`${build}: missing execution evidence is advised once, never ending the run`, async () => {+ await refusedOnceThenAccepted(Agent, planCase({ requiresStateChange: true }),+ { summary: 'Updated the profile.', outcome: 'success' }, 'I couldn\'t confirm that the requested change was made.', `${build} execution`);+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict });+ h.agent._startPlanExecutionGuard(h.tab, 'act', { requestKind: 'execute', requiresStateChange: true });+ await h.batch([['done', { summary: 'Updated.', outcome: 'success' }]]);+ const second = await h.batch([['done', { summary: 'Updated.', outcome: 'success' }]]);+ assert.equal(second.status, strict ? 'plan_only_output' : undefined, `${build}: strict alone ends the run`);+ }+ });++ test(`${build}: missing required, submission, publication and committed-file evidence are each advised once`, async () => {+ await refusedOnceThenAccepted(Agent, planCase({ requiresStateChange: false }, guard => {+ guard.requiredSchedulingTool = 'schedule_task';+ guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ }), { summary: 'Scheduled the reminder.', outcome: 'success' }, 'I couldn\'t confirm that the scheduled task was created.', `${build} scheduling`);++ await refusedOnceThenAccepted(Agent, planCase({ requiresStateChange: true, requiresSubmission: true }, guard => {+ guard.successfulConsequentialToolCalls = 1; guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ }), { summary: 'Sent the form.', outcome: 'success' }, 'I couldn\'t confirm that the submission went through.', `${build} submission`);++ await refusedOnceThenAccepted(Agent, planCase({ requiresStateChange: true, requiresSubmission: true }, guard => {+ guard.siteWorkflow = { adapterName: 'github', job: { id: 'edit-file-and-commit', template: 'publish', requiresSubmission: true } };+ guard.successfulConsequentialToolCalls = 1; guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ }), { summary: 'Committed README.md.', outcome: 'success' },+ 'I couldn\'t confirm that the committed file matches the requested text.', `${build} github commit`);++ await refusedOnceThenAccepted(Agent, planCase({ requiresStateChange: true, requiresSubmission: true }, guard => {+ guard.workflowForbiddenSubmission = true;+ guard.siteWorkflow = { adapterName: 'owned', job: { id: 'prepare-form', template: 'form', requiresSubmission: false } };+ guard.successfulConsequentialToolCalls = 1; guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ }), { summary: 'Prepared the form.', outcome: 'success' },+ 'The form was submitted even though the task was to leave it unsubmitted.', `${build} forbidden submission`);+ });++ test(`${build}: a social destination without evidence is advised once with "do not republish" intact`, async () => {+ const { normalizePublicationContract } = await import(`../src/${build}/src/agent/social-publish-contract.js`);+ for (const strict of [false, true]) {+ const h = batchAgent(Agent, { strict, task: 'Post "Hello" on X.' });+ const guard = h.agent._startPlanExecutionGuard(h.tab, 'act', { requestKind: 'execute', requiresStateChange: true, requiresSubmission: true });+ const contract = normalizePublicationContract({ version: 1, status: 'ready', actions: [{ id: 'p1', platform: 'twitter',+ account: null, posts: [{ body: { kind: 'exact', source: { source: 'request', start: 'Hello', end: 'Hello' } },+ media: { kind: 'count', type: 'any', format: null, min: 0, max: 0 }, context: { kind: 'post', target: null } }] }],+ requirements: 'p1', prohibited: [], reason: 'post' }, { request: 'Post "Hello" on X.' });+ guard.socialPublication = { key: 'contract-key', actionId: 'p1', contract, outcomes: { p1: { status: 'pending' } } };+ guard.successfulConsequentialToolCalls = 1; guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ const messages = h.agent.conversations.get(h.tab);+ assert.equal((await h.batch([['done', { summary: 'Posted.', outcome: 'success' }]])).action, 'continue');+ assert.match(String(messages.at(-1)?.content || ''), /Do not republish/, `${build}: the note keeps the republish warning`);+ const second = await h.batch([['done', { summary: 'Posted.', outcome: 'success' }]]);+ if (strict) assert.equal(second.status, 'required_evidence_missing', `${build}: ${STRICT_NOTE}`);+ else assert.equal(second.value, `Posted.\n\n${CAVEAT}I couldn't confirm the post on X.`);+ }+ });++ test(`${build}: a plain final in an execute task is advised once, then accepted instead of ending the run`, () => {+ for (const strict of [false, true]) {+ const agent = new Agent({});+ agent.strictGuards = strict;+ const tab = nextTab++;+ agent._startPlanExecutionGuard(tab, 'act', { requestKind: 'execute', requiresStateChange: false });+ const first = agent._planOnlyTerminalDecision(tab, 'The page lists three plans.');+ assert.equal(first?.retry, true, `${build}: one done-protocol note`);+ assert.match(first.nudge, /plain text cannot end it/);+ const second = agent._planOnlyTerminalDecision(tab, 'The page lists three plans.');+ if (strict) assert.equal(second?.status, 'plan_only_output', `${build}: ${STRICT_NOTE}`);+ else {+ assert.equal(second, null, `${build}: the plain final is accepted`);+ assert.equal(agent._withCompletionCaveat(tab, 'The page lists three plans.'),+ `The page lists three plans.\n\n${CAVEAT}The task ended with a plain answer instead of a checked completion. `+ + 'No successful page read or tool result backs this answer.');+ }+ }+ });++ test(`${build}: a false Ask-mode claim gets its correction once, then is shown with a caveat`, async () => {+ await refusedOnceThenAccepted(Agent, {+ prepare: h => {+ const guard = h.agent._startPlanExecutionGuard(h.tab, 'act', { requestKind: 'execute', requiresStateChange: true });+ guard.successfulTaskToolCalls = 1; guard.evidenceTaskKey = guard.taskKey;+ h.agent._semanticDecision = async (_tab, kind) => ({ choice: kind === 'done_summary' ? 'mode_claim' : null });+ },+ }, { summary: 'I cannot change pages in Ask mode.', outcome: 'failed' },+ 'The final answer blamed a read-only mode that was not in use.', `${build} mode claim`);+ });++ test(`${build}: planner JSON and a drifted task keep their strict ending by default`, () => {+ const agent = new Agent({});+ const tab = nextTab++;+ const guard = agent._startPlanExecutionGuard(tab, 'act', { requestKind: 'execute', requiresStateChange: false });+ agent._markPlanExecutionToolCall(tab, 'read_page', { success: true });+ const plan = JSON.stringify({ summary: 'Plan.', steps: [{ id: '1', action: 'Read.' }], confidence: 0.9 });+ assert.equal(agent._planOnlyTerminalDecision(tab, plan)?.retry, true, `${build}: planner JSON gets one nudge`);+ assert.match(agent._planOnlyTerminalDecision(tab, plan)?.failure || '', /./, `${build}: a planner object holds no answer to accept`);+ const drifted = new Agent({});+ const driftTab = nextTab++;+ const driftGuard = drifted._startPlanExecutionGuard(driftTab, 'act', { requestKind: 'execute', requiresStateChange: true });+ driftGuard.taskDrifted = true;+ assert.equal(drifted._planOnlyTerminalDecision(driftTab, 'Done.', { viaDone: true, outcome: 'success' })?.retry, true);+ assert.equal(drifted._planOnlyTerminalDecision(driftTab, 'Done.', { viaDone: true, outcome: 'success' })?.status,+ 'task_binding_changed', `${build}: a drifted task is a host check and still ends the run`);+ assert.ok(guard);+ });++ // ── Bot memory (managed Cloud bot runs) ────────────────────────────────+ test(`${build}: done over an uncertain bot-memory action is advised once`, async () => {+ for (const strict of [false, true]) {+ const agent = new Agent({ getActive: () => ({ model: 'test' }) });+ agent.strictGuards = strict;+ const tab = nextTab++;+ const memory = {+ prepare: async (_tab, name, args) => (name === 'done' && args.outcome === 'success'+ ? { allowed: false, reason: 'A dispatched action still has an uncertain outcome.' } : { allowed: true, readOnly: true }),+ afterTool: async () => {},+ tool: async () => ({ success: true }),+ };+ agent._botMemorySessions.set(tab, memory);+ agent._executeToolWithLifecycle = async (_tab, name, args) => ({ done: true, summary: args.summary, outcome: args.outcome });+ const first = await agent.executeTool(tab, 'done', { summary: 'Sent the reminder.', outcome: 'success' });+ assert.equal(first.blockedDone, true, `${build}: the first success claim is refused`);+ const second = await agent.executeTool(tab, 'done', { summary: 'Sent the reminder.', outcome: 'success' });+ if (strict) assert.equal(second.blockedDone, true, `${build}: ${STRICT_NOTE}`);+ else {+ assert.equal(second.done, true, `${build}: the second success claim goes through`);+ assert.match(agent._withCompletionCaveat(tab, 'x'), /An earlier action's result was still uncertain/);+ }+ }+ });++ // ── Done handler: judge, freshness, page warnings, incomplete task ─────+ test(`${build}: a failed completion verdict is advised once, then accepted with a caveat`, async () => {+ try {+ for (const strict of [false, true]) {+ const h = handlerAgent(Agent, build, { strict, verdict: 'failed' });+ const first = await h.agent.executeTool(h.tab, 'done', { summary: 'Saved.', outcome: 'success' });+ assert.equal(first.blockedDone, true, `${build}: ${JSON.stringify(first)}`);+ assert.equal(first.completionDecision?.outcome, 'failed');+ const second = await h.agent.executeTool(h.tab, 'done', { summary: 'Saved.', outcome: 'success' });+ if (strict) assert.equal(second.blockedDone, true, `${build}: ${STRICT_NOTE}`);+ else {+ assert.equal(second.done, true, `${build}: ${JSON.stringify(second)}`);+ assert.equal(second.verification?.decision?.outcome, 'failed', `${build}: the verdict stays on the result`);+ assert.match(h.agent._withCompletionCaveat(h.tab, 'x'), /suggested that the task did not succeed/);+ }+ }+ } finally { restoreGlobals(); }+ });++ test(`${build}: a submitted iframe that cannot be read again is advised once`, async () => {+ try {+ for (const strict of [false, true]) {+ const h = handlerAgent(Agent, build, { strict });+ h.agent._completionSubmitStates.set(h.tab, { dispatched: true, iframeSubmission: { frameId: 3 } });+ h.agent._completionIframeEvidence = async () => null;+ const first = await h.agent.executeTool(h.tab, 'done', { summary: 'Submitted.', outcome: 'success' });+ assert.equal(first.blockedDone, true, `${build}: ${JSON.stringify(first)}`);+ assert.equal(first.completionDecision?.engine, 'freshness');+ const second = await h.agent.executeTool(h.tab, 'done', { summary: 'Submitted.', outcome: 'success' });+ if (strict) assert.equal(second.blockedDone, true, `${build}: ${STRICT_NOTE}`);+ else {+ assert.equal(second.done, true, `${build}: ${JSON.stringify(second)}`);+ assert.match(h.agent._withCompletionCaveat(h.tab, 'x'), /embedded frame could not be read again/);+ }+ }+ } finally { restoreGlobals(); }+ });++ test(`${build}: an open dialog at done is warned about once by default, twice under Strict checks`, async () => {+ try {+ for (const strict of [false, true]) {+ const h = handlerAgent(Agent, build, { strict, page: { openDialogCount: 1, dialogTitles: ['Unsaved changes'] } });+ const first = await h.agent.executeTool(h.tab, 'done', { summary: 'Saved.', outcome: 'success' });+ assert.equal(first.completionPageBlock, true, `${build}: ${JSON.stringify(first)}`);+ assert.doesNotMatch(first.error, strict ? /^$/ : /block attempt/, `${build}: the default note names no second block`);+ const second = await h.agent.executeTool(h.tab, 'done', { summary: 'Saved.', outcome: 'success' });+ if (strict) {+ assert.equal(second.completionPageBlock, true, `${build}: ${STRICT_NOTE} (second block)`);+ const third = await h.agent.executeTool(h.tab, 'done', { summary: 'Saved.', outcome: 'success' });+ assert.equal(third.done, true, `${build}: strict lets the third done through`);+ } else {+ assert.equal(second.done, true, `${build}: ${JSON.stringify(second)}`);+ assert.match(second.verification.completionWarning, /dialog is still open/, `${build}: the warning stays on the result`);+ assert.match(h.agent._withCompletionCaveat(h.tab, 'x'), /A dialog was still open on the page at the end\./);+ }+ }+ } finally { restoreGlobals(); }+ });++ test(`${build}: the incomplete-task judge redirects an honest partial once, then is not asked again`, async () => {+ try {+ for (const strict of [false, true]) {+ const h = handlerAgent(Agent, build, { strict });+ h.agent._beginCompletionInvariant(h.tab);+ h.agent._startPlanExecutionGuard(h.tab, 'act', { requestKind: 'execute', requiresStateChange: true });+ let judged = 0;+ h.agent._semanticDecision = async (_tab, kind) => {+ if (kind === 'incomplete_task') { judged++; return { choice: 'continue_now' }; }+ return { choice: null };+ };+ const done = { summary: 'The profile still needs a photo.', outcome: 'partial' };+ const first = await h.agent.executeTool(h.tab, 'done', done);+ assert.equal(first.recoverableIncomplete, true, `${build}: ${JSON.stringify(first)}`);+ assert.match(first.error, /reasonable next step/);+ const second = await h.agent.executeTool(h.tab, 'done', done);+ if (strict) {+ assert.equal(second.recoverableIncomplete, true, `${build}: ${STRICT_NOTE} (second redirect)`);+ assert.equal(judged, 2);+ } else {+ assert.equal(second.done, true, `${build}: the honest partial ends the run`);+ assert.equal(second.outcome, 'partial');+ assert.equal(judged, 1, `${build}: the judge is not asked again`);+ }+ }+ } finally { restoreGlobals(); }+ });+}++test('chrome: an on-device answer cut off mid-sentence twice is shown with a caveat by default', async () => {+ const { Agent } = await import('../src/chrome/src/agent/agent.js');+ for (const strict of [false, true]) {+ const agent = new Agent({});+ agent.strictGuards = strict;+ const tab = nextTab++;+ assert.equal(agent._standaloneTruncationRefuses(tab), true, 'the first cut-off answer is retried');+ assert.equal(agent._standaloneTruncationRefuses(tab), strict, strict ? STRICT_NOTE : 'the second is shown');+ if (!strict) assert.match(agent._withCompletionCaveat(tab, 'Partial.'), /The on-device answer may be cut off\.$/);+ }+});diff --git a/test/guard-advisory-writes.mjs b/test/guard-advisory-writes.mjsnew file mode 100644index 000000000..92c4d71a4--- /dev/null+++ b/test/guard-advisory-writes.mjs@@ -0,0 +1,704 @@+// Text-write verification chain under the guard policy (guard-policy.js):+// by default a write whose text went out but could not be read back exactly+// is an unverified success with a note, locks nothing and is not a loop+// failure; Settings → "Strict checks" (agent.strictGuards) keeps today's+// debt, lock and failure accounting. GitHub's CodeMirror editor is the real+// case: its innerText readback doubles blank lines, so every correct write+// used to "fail", repeats were refused and the loop detector stopped the run.+import assert from 'node:assert/strict';+import { createHash, webcrypto } from 'node:crypto';+import fs from 'node:fs';+import vm from 'node:vm';+import { test } from 'node:test';++const storage = new Map();+const area = {+ async get(key) { return typeof key === 'string' ? { [key]: storage.get(key) } : Object.fromEntries(storage); },+ async set(values) { for (const [key, value] of Object.entries(values)) storage.set(key, structuredClone(value)); },+ async remove(key) { storage.delete(key); },+};+const api = {+ storage: { local: area, session: area },+ runtime: { getURL: value => `chrome-extension://test/${value}`, sendMessage: async () => ({}) },+ tabs: { get: async id => ({ id, url: scopeUrl(), title: 'Example' }), sendMessage: async () => ({}) },+ scripting: { executeScript: async () => [{ result: null }] },+};+globalThis.chrome = api;+globalThis.browser = api;++const builds = await Promise.all(['chrome', 'firefox'].map(async build => ({+ build,+ Agent: (await import(`../src/${build}/src/agent/agent.js`)).Agent,+ batch: await import(`../src/${build}/src/agent/browser-batch.js`),+})));+const { cdpClient } = await import('../src/chrome/src/cdp/cdp-client.js');+const { FirefoxBidiClient } = await import('../src/firefox/src/bidi/client.js');++const tabId = 51;+const scope = { documentToken: 'document-1', pageUrl: 'https://github.com/example/repo/edit/main/README.md' };+function scopeUrl() { return scope.pageUrl; }+const editorKey = `ax:${scope.documentToken}:ref_editor`;+const sha = text => createHash('sha256').update(text).digest('hex');+const editorMeta = { tag: 'div', contentEditable: true, codeMirror: true, ariaLabel: 'Editing README.md file contents' };+const fileText = 'line one\n\nline three\n';+// CodeMirror's innerText: every blank line reads back twice.+const renderedText = 'line one\n\n\nline three\n';+const args = { ref_id: 'ref_editor', text: fileText };+// What the content script reports when its innerText fallback cannot+// confirm a contenteditable write (content.js _insertContentEditableText).+const renderedMismatch = (extra = {}) => ({+ success: false, verified: false, dispatched: true, mutationMayHaveOccurred: true, outcomeUnknown: true,+ retryable: false, error: 'The complete settled rich-text value could not be verified exactly.',+ unverified: { reason: 'readback_mismatch', reader: 'rendered' }, readbackExact: false,+ ref_id: 'ref_editor', fieldMeta: editorMeta, ...extra,+});+const scopeReply = () => ({ documentToken: scope.documentToken, refScopeUrl: scope.pageUrl });+const advisoryOf = (result, guard) => (result.guardAdvisories || []).find(item => item.guard === guard);++function setup(Agent, { write = () => renderedMismatch(), content = null } = {}) {+ const provider = { name: 'local test', model: 'test', promptTier: 'full', contextWindow: 128000, supportsTools: true };+ const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ agent._hydrate = async () => {};+ agent._persist = () => {};+ agent._persistNow = async () => ({ ok: true });+ agent._currentUrl = async () => scope.pageUrl;+ agent._isPdfTab = async () => false;+ agent._lastAxScopes.set(tabId, { ...scope });+ agent._chromeProtectedPageFailure = async () => null;+ agent._richTextToolbarToolBlock = async () => null;+ agent._injectCoreContentScripts = async () => {};+ agent.testWrites = [];+ agent.testMessages = [];+ api.tabs.sendMessage = async (_id, message) => {+ agent.testMessages.push(message.action);+ const answer = content?.(message);+ if (answer !== undefined) return answer;+ if (message.action === 'set_field' || message.action === 'type_ax') {+ agent.testWrites.push(message.params);+ return write(message.params, agent.testWrites.length);+ }+ if (message.action === 'field_value_digest') {+ return { success: true, valueLength: renderedText.length, valueSha256: sha(renderedText), reader: 'rendered',+ readbackExact: false, fieldMeta: editorMeta, ...scopeReply() };+ }+ return { success: false, ...scopeReply() };+ };+ return agent;+}++async function withCdp(overrides, run) {+ const originals = Object.fromEntries(Object.keys(overrides).map(key => [key, cdpClient[key]]));+ Object.assign(cdpClient, overrides);+ try { return await run(); } finally { Object.assign(cdpClient, originals); }+}++for (const { build, Agent, batch } of builds) {+ test(`${build}: an unverified write succeeds with a note and arms no debt, lock or loop count`, async () => {+ const agent = setup(Agent);+ const result = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(result.success, true);+ assert.equal(result.dispatched, true);+ assert.equal(result.verified, false);+ assert.equal(result.unverifiedWrite, true);+ assert.equal(result.readbackExact, false, 'the innerText fallback is not an exact reader');+ assert.deepEqual(result.unverified, { reason: 'readback_mismatch', reader: 'rendered' });+ for (const field of ['error', 'repeatBlocked', 'recoveryRequired', 'failureScope', 'outcomeUnknown', 'mutationMayHaveOccurred', 'retryable']) {+ assert.equal(Object.hasOwn(result, field), false, `${field} belongs to the lock that default mode no longer arms`);+ }+ const note = advisoryOf(result, 'text-write-readback-unverified');+ assert.match(note?.note || '', /rendered layout[\s\S]*Do not rewrite it to match/);+ assert.ok(note.note.length <= 300, 'notes stay short');+ assert.equal(Object.keys(result)[0], 'guardAdvisories', 'notes come first so truncation keeps them');+ assert.equal(agent._uncertainTextMutations.has(tabId), false, 'no text-write debt');+ // Even a stale content failureScope does not make it a failed target.+ const scoped = { ...result, failureScope: 'field-value:ref_editor' };+ for (let attempt = 1; attempt <= 3; attempt++) {+ assert.notEqual(agent._checkLoop(tabId, 'set_field', args, scoped).kind, 'stop', `advisory write ${attempt} stopped the run`);+ }+ assert.equal(agent.failedActionLoops.get(tabId)?.get('field-value:ref_editor'), undefined);+ // A real failure on the same target still counts and stops on the third.+ const failed = { success: false, error: 'ref_id ref_editor not found.', failureScope: 'field-value:ref_editor' };+ agent._clearLoopState(tabId);+ assert.notEqual(agent._checkLoop(tabId, 'set_field', args, failed).kind, 'stop');+ assert.notEqual(agent._checkLoop(tabId, 'set_field', args, failed).kind, 'stop');+ assert.equal(agent._checkLoop(tabId, 'set_field', args, failed).kind, 'stop');+ });++ test(`${build}: a second write to the same editor is allowed, and an append is warned about duplicates`, async () => {+ const agent = setup(Agent);+ await agent.executeTool(tabId, 'set_field', args);+ const second = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(agent.testWrites.length, 2, 'the repeat reached the page');+ assert.equal(second.success, true);+ assert.equal(second.unverifiedWrite, true);+ assert.equal(Object.hasOwn(second, 'repeatBlocked'), false);+ const append = await agent.executeTool(tabId, 'set_field', { ref_id: 'ref_editor', text: 'tail\n', clear: false });+ assert.equal(agent.testWrites.length, 3, 'an append to the same editor is allowed too');+ assert.match(advisoryOf(append, 'text-write-debt-block')?.note || '', /duplicate/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ });++ test(`${build}: Strict checks keep the old text-write debt, lock and loop count`, async () => {+ const agent = setup(Agent);+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const first = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(first.success, false);+ assert.equal(first.outcomeUnknown, true);+ assert.equal(first.repeatBlocked, true);+ assert.equal(first.recoveryRequired, 'verify_or_restore_field');+ assert.equal(first.guardAdvisories, undefined);+ assert.equal(first.unverifiedWrite, undefined);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1);+ assert.equal(agent._unverifiedTextWriteRecord(tabId, { key: editorKey }), null);+ const second = await agent.executeTool(tabId, 'set_field', { ...args, text: 'changed\n' });+ assert.equal(second.noDispatch, true);+ assert.equal(second.repeatBlocked, true);+ assert.match(second.error, /Text entry is blocked/);+ assert.equal(agent.testWrites.length, 1, 'the locked editor received no second write');+ assert.equal(agent._browserActionFreshTurnReason('full', 'set_field', first), 'action_failed');+ const failed = { ...first, failureScope: 'field-value:ref_editor' };+ agent._checkLoop(tabId, 'set_field', args, failed);+ assert.equal(agent.failedActionLoops.get(tabId)?.get('field-value:ref_editor'), 1);+ });++ test(`${build}: the unverified-write record is exposed next to the proofs`, async () => {+ const agent = setup(Agent);+ await agent.executeTool(tabId, 'set_field', args);+ const record = agent._unverifiedTextWriteRecord(tabId, { key: editorKey });+ assert.equal(record.key, editorKey);+ assert.equal(record.locatorType, 'ax');+ assert.equal(record.refId, 'ref_editor');+ assert.equal(record.documentToken, scope.documentToken);+ assert.equal(record.pageUrl, scope.pageUrl);+ assert.equal(record.tool, 'set_field');+ assert.equal(record.replacesValue, true);+ assert.equal(record.expectedLength, fileText.length);+ assert.equal(record.expectedSha256, sha(fileText));+ assert.equal(record.observedLength, renderedText.length);+ assert.equal(record.observedSha256, sha(renderedText));+ assert.equal(record.readbackExact, false);+ assert.equal(record.reason, 'readback_mismatch');+ assert.equal(record.textSent, true);+ assert.equal(record.fieldMeta.codeMirror, true);+ assert.equal(typeof record.recordedAt, 'number');+ assert.equal(JSON.stringify(record).includes('line three'), false, 'the record keeps no raw text');+ const byPage = agent._unverifiedTextWriteRecord(tabId, {+ pageUrl: scope.pageUrl, match: candidate => agent._isGithubFileEditorRecord(candidate),+ });+ assert.equal(byPage?.key, editorKey, 'a commit gate can find the GitHub editor write by page');+ record.fieldMeta.codeMirror = false;+ assert.equal(agent._unverifiedTextWriteRecord(tabId, { key: editorKey }).fieldMeta.codeMirror, true, 'callers get a copy');+ // A later verified write to the same editor supersedes the record.+ const verifiedAgentWrite = { success: true, verified: true, dispatched: true, method: 'set_field', ref_id: 'ref_editor', fieldMeta: editorMeta };+ await agent._finalizeTextMutationResult(tabId, 'set_field', args, verifiedAgentWrite);+ assert.equal(agent._unverifiedTextWriteRecord(tabId, { key: editorKey }), null);+ });++ test(`${build}: proofs are invalidated by an unverified write in both modes`, async () => {+ for (const strict of [false, true]) {+ const agent = setup(Agent);+ // Strict checks: the guard's refusal itself is under test (strict pass only).+ agent.strictGuards = strict;+ agent._verifiedTextReplacements.set(tabId, new Map([[editorKey, {+ key: editorKey, fieldMeta: editorMeta, expectedSha256: sha('old'), readbackSha256: sha('old'), readbackLength: 3,+ }]]));+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(agent._verifiedTextReplacements.get(tabId)?.size ?? 0, 0,+ `${strict ? 'strict' : 'default'}: an unverified write left an editor proof that could authorize a commit`);+ }+ });++ test(`${build}: set_field submit stays withheld for an unverified value and says so`, async () => {+ const agent = setup(Agent);+ const result = await agent.executeTool(tabId, 'set_field', { ...args, submit: true });+ assert.equal(result.success, true);+ assert.equal(result.verified, false);+ assert.equal(result.submitted, false);+ assert.equal(result.submitSkipped, 'value_unverified');+ assert.match(advisoryOf(result, 'text-write-readback-unverified')?.note || '', /written but its submit was NOT sent/);+ });++ test(`${build}: a lost response after dispatch reports an unknown outcome without a lock`, async () => {+ const lost = () => { throw new Error('The message port closed before a response was received.'); };+ const agent = setup(Agent, { write: lost });+ const result = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(result.success, false);+ assert.equal(result.dispatched, true);+ assert.equal(result.outcomeUnknown, true, 'the unknown outcome is still reported');+ assert.equal(Object.hasOwn(result, 'repeatBlocked'), false);+ assert.match(advisoryOf(result, 'content-action-outcome-unknown')?.note || '', /may or may not have reached the page/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ assert.equal(agent._unverifiedTextWriteRecord(tabId, { key: editorKey })?.reason, 'outcome_unknown');+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(agent.testWrites.length, 2, 'the next write is allowed');++ const strict = setup(Agent, { write: lost });+ strict.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const locked = await strict.executeTool(tabId, 'set_field', args);+ assert.equal(locked.repeatBlocked, true);+ const blocked = await strict.executeTool(tabId, 'set_field', args);+ assert.equal(blocked.noDispatch, true);+ assert.equal(strict.testWrites.length, 1);+ });++ test(`${build}: Stop after a real content send leaves the next run free to write`, async () => {+ let release;+ // The first write never answers before Stop; later writes answer.+ const write = (_params, count) => count === 1 ? new Promise(resolve => { release = resolve; }) : renderedMismatch();+ const agent = setup(Agent, { write });+ await agent._claimRunEntry(tabId, 'interactive');+ const pending = agent.executeTool(tabId, 'set_field', args, null, { _contentActionDispatchState: { started: false } });+ while (!release) await new Promise(resolve => setTimeout(resolve, 5));+ agent.abort(tabId);+ const stopped = await pending;+ assert.equal(stopped.cancelled, true);+ assert.equal(stopped.outcomeUnknown, true, 'Stop after dispatch still reports an unknown outcome');+ assert.equal(Object.hasOwn(stopped, 'repeatBlocked'), false);+ assert.ok(advisoryOf(stopped, 'content-action-outcome-unknown'));+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ agent._releaseRunEntry(tabId);+ await agent._claimRunEntry(tabId, 'interactive');+ const next = await agent.executeTool(tabId, 'set_field', { ...args, text: 'appended\n', clear: false });+ assert.equal(agent.testWrites.length, 2, 'the next run reached the editor');+ assert.match(advisoryOf(next, 'text-write-debt-block')?.note || '', /duplicate/);+ agent._releaseRunEntry(tabId);+ release(renderedMismatch());+ });++ test(`${build}: an unproven write stays unproven, not refuted`, async () => {+ const agent = setup(Agent);+ const unproven = { success: true, method: 'cdp-insert-focused', text: 'hello' };+ const result = await agent._finalizeTextMutationResult(tabId, 'type_text', { text: 'hello' }, unproven);+ assert.equal(result.success, true);+ assert.equal(result.unverifiedWrite, true);+ assert.equal(Object.hasOwn(result, 'verified'), false, 'an unproven value is not reported as a wrong one');+ assert.match(advisoryOf(result, 'text-write-readback-unverified')?.note || '', /could not be read back exactly/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const locked = await agent._finalizeTextMutationResult(tabId, 'type_text', { text: 'hello' }, unproven);+ assert.equal(locked.success, false);+ assert.equal(locked.repeatBlocked, true);+ });++ test(`${build}: a replacement that was not inserted is reported without a lock`, async () => {+ const notInserted = () => ({ success: false, verified: false, dispatched: true, mutationMayHaveOccurred: true,+ outcomeUnknown: true, retryable: false, ref_id: 'ref_editor', fieldMeta: editorMeta,+ error: 'The editor could not be proven empty. No replacement text was inserted.' });+ const agent = setup(Agent, { write: notInserted });+ const result = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(result.success, false, 'no text went in, so this stays an honest failure');+ assert.equal(Object.hasOwn(result, 'repeatBlocked'), false);+ assert.match(advisoryOf(result, 'text-write-preinsert-unproven')?.note || '', /not inserted[\s\S]*Nothing is locked/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(agent.testWrites.length, 2);++ const strict = setup(Agent, { write: notInserted });+ strict.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ assert.equal((await strict.executeTool(tabId, 'set_field', args)).repeatBlocked, true);+ assert.equal((await strict.executeTool(tabId, 'set_field', args)).noDispatch, true);+ assert.equal(strict.testWrites.length, 1);+ });++ test(`${build}: debt left by Strict checks does not block a later write in default mode`, async () => {+ const agent = setup(Agent);+ agent.strictGuards = true; // Strict checks: arm the old debt first.+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1);+ agent.strictGuards = false;+ const result = await agent.executeTool(tabId, 'set_field', { ...args, text: 'corrected\n' });+ assert.equal(agent.testWrites.length, 2, 'the write went ahead');+ assert.equal(result.success, true);+ assert.match(advisoryOf(result, 'text-write-debt-block')?.note || '', /not verified; this replacement went ahead/);+ });++ test(`${build}: an advisory write does not stop the rest of the batch; Strict checks still do`, async () => {+ const agent = setup(Agent);+ const advisory = await agent.executeTool(tabId, 'set_field', args);+ const batchContext = { navigationChanged: false, sameNext: true, remainingObservations: false,+ hadMutation: true, hasRemaining: true, submit: false };+ assert.equal(agent._browserActionFreshTurnReason('full', 'set_field', advisory, batchContext), '');+ assert.equal(agent._browserActionFreshTurnReason('full', 'set_field', advisory), '');+ const message = { role: 'tool', content: JSON.stringify(advisory) };+ assert.equal(batch.browserBatchResultStatus(message).failed, false);+ // Real failures and unknown outcomes still interrupt.+ const unknown = { success: false, dispatched: true, outcomeUnknown: true, error: 'timed out' };+ assert.equal(agent._browserActionFreshTurnReason('full', 'set_field', unknown, batchContext), 'action_failed');+ assert.equal(batch.browserBatchResultStatus({ role: 'tool', content: JSON.stringify(unknown) }).failed, true);+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ assert.equal(agent._browserActionFreshTurnReason('full', 'set_field', advisory, batchContext), 'action_unverified');+ const strictStatus = batch.browserBatchResultStatus(message, { advisoryWritesContinue: false });+ assert.equal(strictStatus.failed, true);+ assert.equal(strictStatus.reason, 'action_unverified');+ });++ test(`${build}: content readback reports which reader produced the value`, async () => {+ const h = contentHarness(build);+ // A generic block editor reads back through innerText, the browser's+ // layout: a mismatch there cannot tell a wrong write from the reader.+ const editor = h.editor({ className: 'notes-editor', innerText: renderedText });+ const verified = await h.call('ax_verify_field_value', editor, { ref_id: 'ref_editor', expected: fileText });+ assert.equal(verified.success, true);+ assert.equal(verified.verified, false);+ assert.equal(verified.reader, 'rendered');+ assert.equal(verified.readbackExact, false);+ const digest = await h.call('field_value_digest', editor, { ref_id: 'ref_editor' });+ assert.equal(digest.valueSha256, sha(renderedText));+ assert.equal(digest.reader, 'rendered');+ assert.equal(digest.readbackExact, false);+ // GitHub's CodeMirror reads its document lines exactly.+ const codeMirror = h.codeMirror({ text: fileText, innerText: renderedText });+ const exactCm = await h.call('ax_verify_field_value', codeMirror, { ref_id: 'ref_editor', expected: fileText });+ assert.equal(exactCm.success, true);+ assert.equal(exactCm.verified, true);+ assert.equal(exactCm.reader, 'semantic');+ assert.equal(exactCm.readbackExact, true);+ const cmDigest = await h.call('field_value_digest', codeMirror, { ref_id: 'ref_editor' });+ assert.equal(cmDigest.valueSha256, sha(fileText));+ assert.equal(cmDigest.reader, 'semantic');+ // A CodeMirror view with a viewport gap cannot establish the document.+ const partial = h.codeMirror({ text: fileText, innerText: renderedText, gap: true });+ const gapResult = await h.call('ax_verify_field_value', partial, { ref_id: 'ref_editor', expected: fileText });+ assert.equal(gapResult.success, false);+ assert.match(gapResult.error, /only part of its document/);+ const input = h.input('plain value');+ const exact = await h.call('ax_verify_field_value', input, { ref_id: 'ref_input', expected: 'plain value' });+ assert.equal(exact.verified, true);+ assert.equal(exact.reader, 'exact');+ assert.equal(exact.readbackExact, true);+ });+}++test('chrome: trusted typing into GitHub CodeMirror is an unverified success, not a lock', async () => {+ const { Agent } = builds.find(item => item.build === 'chrome');+ const commands = [];+ const trustedRequired = () => ({ success: false, error: 'Contenteditable fields require trusted browser typing. Attempting one ref-bound Chrome typing pass.',+ dispatched: false, noDispatch: true, method: 'set_field_contenteditable_trusted', ref_id: 'ref_editor', verified: false,+ fieldMeta: editorMeta, fallbackAttempted: false, trustedTypeRequired: true, _expectedValue: fileText });+ const content = message => {+ if (message.action === 'ax_prepare_field_for_trusted_type') {+ return { success: true, contentEditable: true, fieldMeta: editorMeta, rect: { x: 10, y: 20, w: 600, h: 400 } };+ }+ if (message.action === 'ax_verify_field_value') {+ return { success: true, verified: false, actual: renderedText, reader: 'rendered', readbackExact: false, fieldMeta: editorMeta };+ }+ return undefined;+ };+ await withCdp({+ attach: async () => ({ attached: true }),+ sendCommand: async (_tabId, method, params) => { commands.push({ method, params }); return {}; },+ }, async () => {+ const agent = setup(Agent, { write: trustedRequired, content });+ const result = await agent.executeTool(tabId, 'set_field', { ...args, submit: true });+ assert.equal(result.success, true);+ assert.equal(result.verified, false);+ assert.equal(result.unverifiedWrite, true);+ assert.equal(result.readbackExact, false);+ assert.equal(result.trustedTypeRequired, undefined);+ assert.equal(result.submitted, false);+ assert.equal(result.submitSkipped, 'value_unverified');+ assert.ok(advisoryOf(result, 'text-write-readback-unverified'));+ assert.deepEqual(commands.filter(command => command.method === 'Input.insertText').map(command => command.params.text), [fileText]);+ assert.equal(commands.some(command => command.params?.key === 'Enter'), false, 'an unverified value is never submitted');+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ assert.equal(agent._unverifiedTextWriteRecord(tabId, { key: editorKey })?.observedSha256, sha(renderedText));+ // The repeat is allowed and goes out once more.+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 2);++ commands.length = 0;+ const strict = setup(Agent, { write: trustedRequired, content });+ strict.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const locked = await strict.executeTool(tabId, 'set_field', args);+ assert.equal(locked.success, false);+ assert.equal(locked.repeatBlocked, true);+ assert.match(locked.error, /still did not exactly match after trusted typing/);+ const blocked = await strict.executeTool(tabId, 'set_field', { ...args, text: 'changed\n' });+ assert.equal(blocked.noDispatch, true);+ assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 1);+ });+});++test('chrome: a lost trusted insertText acknowledgement is reported without a lock', async () => {+ const { Agent } = builds.find(item => item.build === 'chrome');+ const commands = [];+ const trustedRequired = () => ({ success: false, error: 'Contenteditable fields require trusted browser typing.',+ dispatched: false, noDispatch: true, ref_id: 'ref_editor', verified: false, fieldMeta: editorMeta,+ trustedTypeRequired: true, _expectedValue: fileText });+ const content = message => message.action === 'ax_prepare_field_for_trusted_type'+ ? { success: true, contentEditable: true, fieldMeta: editorMeta, rect: { x: 10, y: 20, w: 600, h: 400 } }+ : undefined;+ await withCdp({+ attach: async () => ({ attached: true }),+ sendCommand: async (_tabId, method, params) => {+ commands.push({ method, params });+ if (method === 'Input.insertText') throw new Error('Owned text response lost');+ return {};+ },+ }, async () => {+ const agent = setup(Agent, { write: trustedRequired, content });+ const result = await agent.executeTool(tabId, 'set_field', args);+ assert.equal(result.success, false, 'the outcome is unknown, so it is not reported as written');+ assert.equal(result.outcomeUnknown, true);+ assert.equal(Object.hasOwn(result, 'repeatBlocked'), false);+ assert.match(advisoryOf(result, 'trusted-field-retry-guards')?.note || '', /Nothing is locked/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ await agent.executeTool(tabId, 'set_field', args);+ assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 2, 'the model may write again');++ commands.length = 0;+ const strict = setup(Agent, { write: trustedRequired, content });+ strict.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ assert.equal((await strict.executeTool(tabId, 'set_field', args)).repeatBlocked, true);+ assert.equal((await strict.executeTool(tabId, 'set_field', args)).noDispatch, true);+ assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 1);+ });+});++test('chrome: an uncertain original write is never retyped, and only Strict checks lock it', async () => {+ const { Agent } = builds.find(item => item.build === 'chrome');+ const commands = [];+ const dispatchedMismatch = () => ({ success: false, verified: false, dispatched: true, method: 'type_ax_input', ref_id: 'ref_input',+ actual: 'reset', fieldMeta: { tag: 'input', contentEditable: false }, _expectedValue: 'gary flake',+ recoveryRequired: 'verify_or_restore_field', failureScope: 'field-value:ref_input', retryable: false,+ unverified: { reason: 'readback_mismatch', reader: 'exact' }, readbackExact: true,+ error: 'The field value did not exactly match the requested text after the page settled. Repeat the original replacement text and target for readback-only recovery, or restore the editor before another write.' });+ const inputArgs = { ref_id: 'ref_input', text: 'gary flake' };+ await withCdp({+ attach: async () => { commands.push({ method: 'attach' }); return { attached: true }; },+ sendCommand: async (_tabId, method, params) => { commands.push({ method, params }); return {}; },+ }, async () => {+ const agent = setup(Agent, { write: dispatchedMismatch });+ const branch = await agent._maybeFallbackFieldWithCdp(tabId, 'set_field', inputArgs, dispatchedMismatch());+ assert.equal(branch.repeatBlocked, undefined);+ assert.equal(branch.recoveryRequired, undefined);+ assert.equal(branch.mutationMayHaveOccurred, true, 'the possible landed write is still reported');+ assert.equal(branch.fallbackAttempted, false);+ assert.equal(commands.length, 0, 'no trusted retry is prepared or sent');+ const result = await agent.executeTool(tabId, 'set_field', inputArgs, null);+ assert.equal(result.success, true, 'by default the write is reported as an unverified success');+ assert.equal(result.readbackExact, true);+ assert.match(advisoryOf(result, 'text-write-readback-unverified')?.note || '', /reads back a different value/);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);++ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const strictBranch = await agent._maybeFallbackFieldWithCdp(tabId, 'set_field', inputArgs, dispatchedMismatch());+ assert.equal(strictBranch.repeatBlocked, true);+ assert.equal(strictBranch.recoveryRequired, 'verify_or_restore_field');+ assert.match(strictBranch.error, /No trusted retry was sent/);+ assert.equal(commands.length, 0);+ });+});++test('chrome: type_text by selector proceeds unpinned by default; Strict checks refuse', async () => {+ const { Agent } = builds.find(item => item.build === 'chrome');+ const pins = [];+ await withCdp({+ attach: async () => ({ attached: true }),+ probeRichTextToolbarSelector: async () => null,+ typeText: async (_tabId, _selector, _text, _clear, expectedNode) => {+ pins.push(expectedNode);+ return { success: true, verified: true, method: 'cdp-insert-text', tag: 'INPUT', rect: { x: 1, y: 2, w: 3, h: 4 } };+ },+ }, async () => {+ const agent = setup(Agent);+ const result = await agent.executeTool(tabId, 'type_text', { selector: '#title', text: 'Release notes' });+ assert.equal(result.success, true);+ assert.deepEqual(pins, [null], 'typed by selector without a pinned node');+ assert.match(advisoryOf(result, 'typing-target-identity')?.note || '', /could not be pinned/);++ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const refused = await agent.executeTool(tabId, 'type_text', { selector: '#title', text: 'Release notes' });+ assert.equal(refused.success, false);+ assert.equal(refused.noDispatch, true);+ assert.match(refused.error, /Could not preserve the selector target/);+ assert.deepEqual(pins, [null]);+ });+});++test('chrome: focused type_text whose bound field lost focus types into the field focused now', async () => {+ const { Agent } = builds.find(item => item.build === 'chrome');+ const commands = [];+ const content = message => {+ if (message.action === 'prepare_focused_type_dispatch') {+ return { success: false, dispatched: false, noDispatch: true, retryable: true, reasonCode: 'focused_target_changed',+ error: 'The focused target changed after the rich-text toolbar safety preflight. Focus the intended field again and retry.' };+ }+ if (message.action === 'release_dispatch_binding') return { success: true };+ return undefined;+ };+ await withCdp({+ attach: async () => ({ attached: true }),+ evaluate: async () => ({ result: { value: { focused: true, editable: true, contentEditable: false, tag: 'INPUT',+ type: 'text', name: 'q', value: '', rect: { x: 1, y: 2, w: 3, h: 4 } } } }),+ textEntrySignature: async () => 'signature',+ verifyTextEntry: async () => true,+ sendCommand: async (_tabId, method, params) => { commands.push({ method, params }); return {}; },+ }, async () => {+ const binding = { dispatchBinding: { token: 'binding-1', frameId: 0 } };+ const agent = setup(Agent, { content });+ const result = await agent.executeTool(tabId, 'type_text', { text: 'hello' }, null, binding);+ assert.equal(result.success, true);+ assert.equal(result.verified, true);+ assert.deepEqual(commands.filter(command => command.method === 'Input.insertText').map(command => command.params.text), ['hello']);+ assert.match(advisoryOf(result, 'typing-target-identity')?.note || '', /lost focus/);++ commands.length = 0;+ const strict = setup(Agent, { content });+ strict.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const refused = await strict.executeTool(tabId, 'type_text', { text: 'hello' }, null, { dispatchBinding: { token: 'binding-2', frameId: 0 } });+ assert.equal(refused.success, false);+ assert.equal(refused.reasonCode, 'focused_target_changed');+ assert.equal(commands.length, 0);+ });+});++test('chrome: a clearing focused type_text never falls back to the field focused now', async () => {+ // The truncated-preview (deletion) check runs against the bound field.+ // Select-all + delete on whichever field has focus now could erase a value+ // that check never saw, so clear:true refuses in both modes.+ const { Agent } = builds.find(item => item.build === 'chrome');+ const commands = [];+ const truncationChecks = [];+ const content = message => {+ if (message.action === 'check_truncated_replacement') {+ truncationChecks.push(message.params?.dispatchBinding?.token || 'focused-now');+ return { success: true };+ }+ if (message.action === 'prepare_focused_type_dispatch') {+ return { success: false, dispatched: false, noDispatch: true, retryable: true, reasonCode: 'focused_target_changed',+ error: 'The focused target changed after the rich-text toolbar safety preflight. Focus the intended field again and retry.' };+ }+ if (message.action === 'release_dispatch_binding') return { success: true };+ return undefined;+ };+ await withCdp({+ attach: async () => ({ attached: true }),+ evaluate: async () => ({ result: { value: { focused: true, editable: true, contentEditable: false, tag: 'TEXTAREA',+ type: '', name: 'other', value: 'A long value the preview check never saw', rect: { x: 1, y: 2, w: 3, h: 4 } } } }),+ textEntrySignature: async () => 'signature',+ captureTextClearReceipt: async () => ({ current: async () => true, verify: async () => true, dispose: async () => {} }),+ selectAllModifier: async () => 2,+ verifyTextEntry: async () => true,+ sendCommand: async (_tabId, method, params) => { commands.push({ method, params }); return {}; },+ }, async () => {+ for (const strict of [false, true]) {+ commands.length = 0;+ truncationChecks.length = 0;+ const agent = setup(Agent, { content });+ agent.strictGuards = strict;+ const result = await agent.executeTool(tabId, 'type_text', { text: 'Replacement body', clear: true }, null,+ { dispatchBinding: { token: `binding-clear-${strict}`, frameId: 0 } });+ assert.equal(result.success, false, `strict=${strict}: a clearing write fell back to another field`);+ assert.equal(result.reasonCode, 'focused_target_changed');+ assert.equal(advisoryOf(result, 'typing-target-identity'), undefined);+ assert.deepEqual(commands, [], `strict=${strict}: input was dispatched after the bound field lost focus`);+ assert.deepEqual(truncationChecks, [`binding-clear-${strict}`]);+ }+ });+});++test('firefox: type_text by selector proceeds without a binding by default; Strict checks refuse', async () => {+ const { Agent } = builds.find(item => item.build === 'firefox');+ const typed = [];+ const content = message => {+ if (message.action !== 'type') return undefined;+ typed.push(message.params);+ return { success: true, verified: true, value: message.params.text, fieldMeta: { tag: 'input' } };+ };+ const agent = setup(Agent, { content });+ agent._probeRichTextToolbarRetryTarget = async () => null;+ const result = await agent.executeTool(tabId, 'type_text', { selector: '#title', text: 'Release notes' });+ assert.equal(result.success, true);+ assert.equal(typed.length, 1);+ assert.equal(typed[0].dispatchBinding, undefined);+ assert.match(advisoryOf(result, 'typing-target-identity')?.note || '', /could not be pinned/);++ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const refused = await agent.executeTool(tabId, 'type_text', { selector: '#title', text: 'Release notes' });+ assert.equal(refused.success, false);+ assert.match(refused.error, /Could not preserve the selector target/);+ assert.equal(typed.length, 1);+});++test('firefox: a trusted BiDi readback mismatch is an unverified write, not debt', async () => {+ const { Agent } = builds.find(item => item.build === 'firefox');+ const tab = 77;+ const client = new FirefoxBidiClient({ tabs: { sendMessage: async () => ({ bidiPrepared: true, fieldMeta: editorMeta, url: scope.pageUrl }) } });+ client.runs.set(tab, { runId: 'run-1', bound: true });+ client.bindRun = async () => {};+ client.perform = async () => ({ success: false, dispatched: true, verified: false, submitted: false, outcomeUnknown: true,+ retryable: false, error: 'Trusted typing did not match the requested value; inspect before another write.' });+ const mismatch = await client.sendContent(tab, { target: 'content', action: 'set_field', params: { ...args } });+ assert.deepEqual(mismatch.unverified, { reason: 'readback_mismatch', reader: 'unknown' });+ client.perform = async () => { throw Object.assign(new Error('companion disconnected'), {}); };+ const lost = await client.sendContent(tab, { target: 'content', action: 'set_field', params: { ...args } });+ assert.equal(lost.unverified, undefined, 'a transport failure is an unknown outcome, not an unverified write');++ const agent = setup(Agent);+ const advisory = await agent._finalizeTextMutationResult(tabId, 'set_field', args, mismatch);+ assert.equal(advisory.success, true);+ assert.equal(advisory.unverifiedWrite, true);+ assert.equal(agent._uncertainTextMutations.has(tabId), false);+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.+ const locked = await agent._finalizeTextMutationResult(tabId, 'set_field', args, mismatch);+ assert.equal(locked.repeatBlocked, true);+ assert.equal(agent._uncertainTextMutations.get(tabId)?.size, 1);+});++// The real content-script readback handlers, run against a minimal DOM.+function functionSource(source, name) {+ let start = source.indexOf(`function ${name}(`);+ assert(start >= 0, name);+ if (source.slice(start - 6, start) === 'async ') start -= 6;+ const indent = source.slice(source.lastIndexOf('\n', start) + 1, start);+ const end = source.indexOf(`\n${indent}}`, start) + indent.length + 2;+ assert(end > start, name);+ return source.slice(start, end);+}+function handlerSource(source, action) {+ const start = source.indexOf(`'${action}':`);+ const end = source.indexOf('\n },', start);+ assert(start >= 0 && end > start, action);+ return source.slice(source.indexOf(':', start) + 1, end + 8).trim();+}+function contentHarness(build) {+ const source = fs.readFileSync(new URL(`../src/${build}/src/content/content.js`, import.meta.url), 'utf8');+ const names = ['_setFieldValueMatches', 'readProseMirrorText', 'readCodeMirrorText', 'readEmptyCaretText', 'isDraftJsEditor',+ 'readDraftJsText', '_nativeChatCaretContext', '_sameNativeChatCaretContext', '_singleEditableCaretBreak',+ '_nativeChatCaretValueIsEmpty', '_editableTextValue'];+ if (build === 'chrome') names.unshift('_contentEditableValueMatches');+ let target = null;+ const context = vm.createContext({ crypto: webcrypto, TextEncoder, Uint8Array, _nativeChatEmptyCaretReceipts: new WeakMap(),+ window: { __wb_ax_lookup: () => target }, msg: { params: {} }, document: {},+ _fieldMeta: () => ({ ...editorMeta }), _stableFieldSelector: () => '#editor' });+ vm.runInContext(names.map(name => functionSource(source, name)).join('\n'), context);+ const handlers = Object.fromEntries(['ax_verify_field_value', 'field_value_digest']+ .map(action => [action, vm.runInContext(`(${handlerSource(source, action)})`, context)]));+ const node = (fields) => ({ nodeType: 1, isConnected: true, childNodes: [], getAttribute: () => null,+ classList: { contains: () => false }, ...fields });+ const classes = (...names) => ({ contains: name => names.includes(name) });+ return {+ // A generic contenteditable: only innerText can be read.+ editor: ({ className, innerText }) => {+ const lines = innerText.split('\n').map(text => node({ tagName: 'DIV', textContent: text }));+ return node({ tagName: 'DIV', isContentEditable: true, innerText, textContent: innerText.replace(/\n/g, ''),+ childNodes: lines, children: lines, classList: classes(className) });+ },+ // CodeMirror 6 as GitHub renders it: one .cm-line per document line, a+ // placeholder BR in each empty line, and innerText doubling blank lines.+ codeMirror: ({ text, innerText, gap = false }) => {+ const lines = text.split('\n').map(line => node({ tagName: 'DIV', classList: classes('cm-line'),+ childNodes: line ? [{ nodeType: 3, nodeValue: line }] : [node({ tagName: 'BR' })] }));+ if (gap) lines.splice(1, 0, node({ tagName: 'DIV', classList: classes('cm-gap') }));+ return node({ tagName: 'DIV', isContentEditable: true, innerText, textContent: text.replace(/\n/g, ''),+ childNodes: lines, children: lines, classList: classes('cm-content') });+ },+ input: value => node({ tagName: 'INPUT', isContentEditable: false, value }),+ async call(action, element, params) {+ target = element;+ context.msg = { params };+ return handlers[action]();+ },+ };+}diff --git a/test/guard-policy.mjs b/test/guard-policy.mjsnew file mode 100644index 000000000..c6d622f75--- /dev/null+++ b/test/guard-policy.mjs@@ -0,0 +1,214 @@+// The rule for WebBrain's guards (docs/guards.md, AGENT.md → Safety): only+// the hard list may refuse outright; every other check leaves a note for the+// model or asks the user, and Settings → "Strict checks" restores blocking.+// A guard added after the registry was introduced names a test of a+// legitimate task it must let through (mustNotBlock). This file enforces the+// registry's shape, that the code only uses registered guard ids, and a+// ceiling on completion refusals.+import assert from 'node:assert/strict';+import fs from 'node:fs';+import { test } from 'node:test';++const BUILDS = ['chrome', 'firefox'];+const policy = await import('../src/chrome/src/agent/guard-policy.js');+const { GUARDS, HARD_GUARD_CLASSES, NON_GUARD_CLASSES, GUARD_CLASSES, GUARD_OUTCOMES, GRANDFATHERED_GUARD_COUNT, guardOutcome } = policy;+const read = path => fs.readFileSync(new URL(`../${path}`, import.meta.url), 'utf8');++// The guards that existed when the registry was introduced. This list only+// shrinks: remove an id when its guard is removed, and lower+// GRANDFATHERED_GUARD_COUNT with it. A new guard is never added here; it+// declares mustNotBlock instead.+const GRANDFATHERED = new Set([+ 'action-no-progress-classification', 'api-mutation-permission', 'auto-progress-resume', 'bot-memory-reservation',+ 'bot-memory-uncertain-done', 'browser-batch-fresh-turn-interrupt', 'browser-control-handoff-stale-batch',+ 'capability-host-permission', 'captcha-gate-action-block', 'captcha-gate-manual-required',+ 'captcha-paid-solve-protection', 'captcha-solution-binding', 'captcha-solve-detection-binding',+ 'carousel-traversal-guards', 'chat-send-evidence-unavailable', 'chat-send-preconditions',+ 'chat-send-recipient-guards', 'chat-user-input-required', 'chrome-protected-page',+ 'clarify-timeout-not-authorization', 'click-coordinate-intent', 'click-duplicate-submit', 'click-native-os-ui',+ 'click-text-ambiguous', 'clickax-native-button-preparation', 'clickax-task-click-lock',+ 'clickax-trusted-retry-vetoes', 'completion-evidence-freshness', 'completion-failure-only-done',+ 'completion-page-warning', 'completion-recovery-forced-turns', 'completion-verifier-advisory-outputs',+ 'completion-verifier-not-done', 'consequential-durability-checkpoint', 'content-action-outcome-unknown',+ 'coordinate-click-provenance', 'deletion-confirm-card', 'deletion-guard-refusal', 'delivery-observation-checkpoint',+ 'done-iframe-form-unverified', 'done-invariant-shape-checks', 'done-rich-text-toolbar-obligation',+ 'done-summary-meta-only', 'done-verification-debt', 'downloaded-file-task-changed', 'exact-table-done',+ 'form-validation-unchanged-repeat', 'generate-image-config-invalid', 'github-commit-evidence-binding',+ 'github-commit-split-write-required', 'github-committed-file-verification', 'github-conditional-commit-rearm',+ 'github-conditional-commit-unbound', 'grouped-search-card', 'iframe-target-binding', 'iframe-urlfilter-required',+ 'incomplete-task-check-stale', 'incomplete-task-redirect', 'jev-target-changed', 'loop-failed-action-target',+ 'loop-observation-stop', 'loop-repeat-stop', 'loop-unavailable-tool', 'loop-verification-dialog-reopen',+ 'media-download-target-binding', 'native-chat-receipt-not-durable', 'navigation-scheme-and-internal-pages',+ 'network-url-safety', 'otp-mailbox-scope', 'otp-open-message-gate', 'owned-native-chat-read-repair',+ 'page-blocker-wall', 'page-feedback-ask-answer-superseded', 'page-feedback-dispatch-fence',+ 'page-feedback-supersession-stop', 'page-feedback-target-binding', 'pdf-viewer-dom-tools',+ 'permission-host-unidentified', 'plain-final-done-protocol', 'plain-final-rejected-text-compaction',+ 'plain-final-two-strike-partial', 'plain-final-unusable-output', 'plan-done-summary-shape',+ 'plan-execution-evidence-missing', 'plan-plain-final-protocol', 'plan-publication-evidence-missing',+ 'plan-required-evidence-missing', 'plan-submission-evidence-missing', 'plan-task-drifted',+ 'plan-unauthorized-mutation-recorded', 'preparation-timeout-action-pipeline',+ 'preparation-timeout-captcha-preflight', 'preparation-timeout-generic', 'preparation-timeout-permission-detection',+ 'preparation-timeout-recipient-preflight', 'preparation-timeout-submit-preflight', 'progress-ledger-unresolved',+ 'progress-success-claim-checks', 'promote-iframe-ambiguous', 'pure-calculation-done-checks',+ 'pure-calculation-stale-authority', 'pure-calculation-tool-scope', 'read-coverage-ask-limitation',+ 'read-coverage-incomplete', 'recipient-active-conversation-pin', 'recipient-clarify-cannot-repair-technical',+ 'recipient-dispatch-binding-revalidate', 'recipient-draft-evidence-unavailable', 'recipient-guard-refusal',+ 'recipient-guard-target-preparation', 'recipient-guard-unrequested-send', 'recipient-mismatch-confirm-card',+ 'research-escalation-authorization', 'resource-mutation-task-authority-changed',+ 'rich-text-toolbar-recovery-obligation', 'rich-text-toolbar-target-unresolved', 'rich-text-toolbar-wrong-target',+ 'sched-reconciliation-required', 'sched-systemone-downgrade', 'schedule-owner-changed',+ 'schedule-resume-chat-state-not-durable', 'set-field-bundled-submit-outcome', 'social-api-publication-route',+ 'social-preflight-context-mismatch', 'social-publication-audit', 'social-publication-authorization-guard',+ 'social-publication-draft-quality', 'social-publication-host-checks', 'stale-ax-ref',+ 'steer-post-correction-commit-guard', 'steer-prior-submission-target-unresolved',+ 'steer-prior-submission-unreconciled', 'steering-and-page-feedback-call-fence', 'step-limit',+ 'strict-secret-credential-handling', 'structured-cloud-output-contract', 'submit-confirmation-card',+ 'terminal-recovery-no-success', 'text-write-debt-arm', 'text-write-debt-block', 'text-write-preinsert-unproven',+ 'text-write-readback-unverified', 'tool-call-malformed', 'tool-feature-availability-gates', 'tool-not-advertised',+ 'tool-routing-redirects', 'truncated-preview-replacement', 'trusted-field-retry-guards', 'typing-target-identity',+ 'unsaved-changes-data-loss', 'upload-compact-tier-sources', 'upload-selector-ambiguity', 'upload-source-validation',+ 'user-stop-or-card-cancel', 'viewport-inspection-budget', 'webmcp-frame-binding', 'webmcp-mode-and-setting-gate',+ 'webmcp-tool-id-invalid',+]);+const GRANDFATHERED_CEILING = 158;++// Completion refusals (`blockedDone: true`) per build. A new one must be a+// registered guard routed through _guardRefusesOnce (or a hard-class guard);+// raise the ceiling only in the change that registers it.+const BLOCKED_DONE_CEILING = { chrome: 18, firefox: 17 };++function walk(dir) {+ return fs.readdirSync(new URL(`../${dir}`, import.meta.url), { withFileTypes: true }).flatMap(entry => {+ const path = `${dir}/${entry.name}`;+ if (entry.isDirectory()) return entry.name === 'vendor' || entry.name === 'lib' ? [] : walk(path);+ return entry.name.endsWith('.js') ? [path] : [];+ });+}++// Guard ids the code names: the agent's guard helpers, guardAdvisory, the+// completion-invariant and plan-guard tables, and *_GUARDS id lists.+function guardIdsInSource(source) {+ const ids = new Map();+ const note = (id, where) => { if (!ids.has(id)) ids.set(id, where); };+ const kebab = /'([a-z0-9]+(?:-[a-z0-9]+)+)'/g;+ for (const match of source.matchAll(/\b_guard(?:Outcome|Advises|AdvisesFor|RefusesOnce)\(|\bguardAdvisory\(/g)) {+ // This call's arguments, up to its closing parenthesis.+ let depth = 1;+ let end = match.index + match[0].length;+ while (end < source.length && depth > 0 && end - match.index < 600) {+ const ch = source[end++];+ if (ch === '(') depth += 1;+ else if (ch === ')') depth -= 1;+ }+ for (const literal of source.slice(match.index + match[0].length, end).matchAll(kebab)) note(literal[1], match[0]);+ }+ for (const match of source.matchAll(/\bid: '([a-z0-9]+(?:-[a-z0-9]+)+)',\s*decided:/g)) note(match[1], 'completion invariant');+ const findings = source.indexOf(' _planGuardFindings(');+ if (findings >= 0) {+ const body = source.slice(findings, source.indexOf('\n }\n', findings));+ for (const match of body.matchAll(/\badd\('([a-z0-9]+(?:-[a-z0-9]+)+)'/g)) note(match[1], '_planGuardFindings');+ }+ for (const match of source.matchAll(/\b[A-Z][A-Z_]*_GUARDS\s*=\s*(?:Object\.freeze\()?(?:new Set\()?\[([^\]]*)\]/g)) {+ for (const literal of match[1].matchAll(kebab)) note(literal[1], 'id list');+ }+ return ids;+}++test('guard-policy.js is shared verbatim by both builds', () => {+ assert.equal(read('src/firefox/src/agent/guard-policy.js'), read('src/chrome/src/agent/guard-policy.js'));+});++test('every guard entry is well formed', () => {+ const families = new Set(['completion', 'content-write', 'loop', 'predispatch', 'scheduler', 'tool']);+ for (const [id, entry] of Object.entries(GUARDS)) {+ assert.match(id, /^[a-z0-9]+(?:-[a-z0-9]+)+$/, `${id}: ids are kebab-case`);+ assert.ok(GUARD_CLASSES.includes(entry.class), `${id}: unknown class ${entry.class}`);+ assert.ok(families.has(entry.family), `${id}: unknown family ${entry.family}`);+ assert.ok(['knows', 'no-evidence', 'mixed', 'protocol'].includes(entry.decides), `${id}: unknown decides ${entry.decides}`);+ assert.ok(GUARD_OUTCOMES.includes(entry.onDecided), `${id}: onDecided`);+ assert.ok(GUARD_OUTCOMES.includes(entry.onCannotDecide), `${id}: onCannotDecide must be declared`);+ assert.ok(typeof entry.summary === 'string' && entry.summary.trim().length >= 20, `${id}: summary`);+ const allowed = new Set(['class', 'family', 'decides', 'onDecided', 'onCannotDecide', 'summary', 'mustNotBlock']);+ for (const key of Object.keys(entry)) assert.ok(allowed.has(key), `${id}: unexpected field ${key}`);+ }+});++test('only the hard list refuses outright', () => {+ for (const [id, entry] of Object.entries(GUARDS)) {+ if (entry.class === 'quality') {+ assert.notEqual(entry.onDecided, 'block', `${id}: a quality guard advises or asks; it never refuses by default`);+ assert.notEqual(entry.onCannotDecide, 'block', `${id}: a quality guard that cannot decide advises or asks`);+ } else if (HARD_GUARD_CLASSES.includes(entry.class)) {+ assert.equal(entry.onDecided, 'block', `${id}: a hard guard that knows the action is wrong refuses it`);+ assert.ok(['block', 'ask'].includes(entry.onCannotDecide), `${id}: a hard guard that cannot decide asks or refuses`);+ } else {+ assert.ok(NON_GUARD_CLASSES.includes(entry.class));+ assert.equal(entry.onDecided, 'block', `${id}: ${entry.class} keeps its behavior`);+ assert.equal(entry.onCannotDecide, 'block', `${id}: ${entry.class} keeps its behavior`);+ }+ for (const decided of [true, false]) {+ const byDefault = guardOutcome(id, { decided });+ const strict = guardOutcome(id, { decided, strict: true });+ assert.equal(byDefault, decided ? entry.onDecided : entry.onCannotDecide, `${id}: default outcome`);+ assert.equal(strict, entry.class === 'quality' ? 'block' : byDefault, `${id}: Strict checks changes only quality guards`);+ }+ }+ assert.equal(guardOutcome('an-unregistered-guard'), 'block', 'an unregistered refusal is never silently relaxed');+ assert.deepEqual([...HARD_GUARD_CLASSES], ['recipient', 'deletion', 'money', 'credentials', 'unrequested_publication']);+});++for (const build of BUILDS) {+ test(`${build}: every guard id the code names is registered`, () => {+ const unknown = [];+ let seen = 0;+ for (const path of walk(`src/${build}/src`)) {+ for (const [id, where] of guardIdsInSource(read(path))) {+ seen += 1;+ if (!Object.hasOwn(GUARDS, id)) unknown.push(`${path}: ${id} (${where})`);+ }+ }+ assert.ok(seen >= 40, `${build}: the scan found only ${seen} guard ids; did the helper names change?`);+ assert.deepEqual(unknown, [], 'Register these ids in guard-policy.js (docs/guards.md, "Adding a guard")');+ });++ test(`${build}: completion refusals stay under their ceiling`, () => {+ const count = (read(`src/${build}/src/agent/agent.js`).match(/blockedDone: true/g) || []).length;+ assert.ok(count <= BLOCKED_DONE_CEILING[build],+ `${build}: ${count} completion refusals (ceiling ${BLOCKED_DONE_CEILING[build]}). A new one must be a registered guard `+ + 'routed through _guardRefusesOnce, with mustNotBlock; raise the ceiling only in that change.');+ });+}++test('guards added after the registry name a test they must not block', () => {+ assert.ok(GRANDFATHERED_GUARD_COUNT <= GRANDFATHERED_CEILING, 'the grandfathered count only shrinks');+ assert.equal(GRANDFATHERED.size, GRANDFATHERED_GUARD_COUNT, 'GRANDFATHERED_GUARD_COUNT matches the grandfathered list');+ for (const id of GRANDFATHERED) {+ assert.ok(Object.hasOwn(GUARDS, id), `${id} was removed from guard-policy.js; remove it from GRANDFATHERED and lower the count`);+ }+ for (const [id, entry] of Object.entries(GUARDS)) {+ if (GRANDFATHERED.has(id) && entry.mustNotBlock === undefined) continue;+ assert.equal(typeof entry.mustNotBlock, 'string',+ `${id}: a new guard declares mustNotBlock: 'test/<file>.mjs#<test name>', a legitimate task it must let through`);+ const [file, name, extra] = entry.mustNotBlock.split('#');+ assert.ok(file && name && extra === undefined, `${id}: mustNotBlock is 'test/<file>.mjs#<test name>'`);+ assert.match(file, /^test\/[\w./-]+\.(?:mjs|js)$/, `${id}: mustNotBlock names a file under test/`);+ assert.ok(fs.existsSync(new URL(`../${file}`, import.meta.url)), `${id}: ${file} does not exist`);+ assert.ok(read(file).includes(name.trim()), `${id}: ${file} has no test named "${name}"`);+ }+});++test('the scan recognizes each way the code names a guard', () => {+ const ids = guardIdsInSource(`+ this._guardAdvisesFor(advisories, 'alpha-guard', 'A note (with parentheses).');+ if (this._guardRefusesOnce(tabId, flag ? 'beta-guard' : 'gamma-guard', { caveat: 'x' })) {}+ this._guardOutcome('delta-guard', { decided: false });+ guardAdvisory('epsilon-guard', note);+ return { id: 'zeta-guard', decided: true, caveat: 'y' };+ const OUTCOME_DOWNGRADING_GUARDS = new Set(['eta-guard', 'theta-guard']);+ _planGuardFindings(tabId) {+ add('iota-guard', true, 'z');+ }+`);+ assert.deepEqual([...ids.keys()].sort(), ['alpha-guard', 'beta-guard', 'delta-guard', 'epsilon-guard', 'eta-guard',+ 'gamma-guard', 'iota-guard', 'theta-guard', 'zeta-guard']);+});diff --git a/test/incomplete-completion-recovery.mjs b/test/incomplete-completion-recovery.mjsindex 64a2b2767..1aa485bc8 100644--- a/test/incomplete-completion-recovery.mjs+++ b/test/incomplete-completion-recovery.mjs@@ -264,7 +264,7 @@ for (const build of ['chrome', 'firefox']) {// A full run of the real agent loop over an owned page. `script(names,// request)` plays the model; `execute(name, args)` stands in for the browser.- async function runOwnedTask({ streaming, task, url, pageState, judge, script, execute }) {+ async function runOwnedTask({ streaming, task, url, pageState, judge, script, execute, strict = false }) {const tab = nextTab++;const next = async (messages, options) => {const fixed = fixtureFixedChoiceReply(messages, { incomplete_task: judge, done_summary: 'result' });@@ -281,6 +281,7 @@ for (const build of ['chrome', 'firefox']) {if (result.toolCalls) yield { type: 'tool_call', content: result.toolCalls.map((entry, index) => ({ ...entry, index })) };yield { type: 'done' }; } };const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ agent.strictGuards = strict;Object.assign(agent, {_hydrate: async () => {}, _persist: () => {}, _persistNow: async () => ({ ok: true }), _persistSubmittedTurn: async () => {},_startTraceRun: async () => null, _endTraceRun: async () => {}, _beginReadCompleteness: async () => null,@@ -321,7 +322,8 @@ for (const build of ['chrome', 'firefox']) {test(`${build}: ${streaming ? 'stream' : 'chat'} keeps an unverified action read-only after a recoverable incomplete ending`, async () => {const actions = [];let pageText = 'Saving...\nSubmit', requests = 0, judgments = 0, reads = 0;- const result = await runOwnedTask({ streaming, task: 'Submit the owned form.', url: 'https://owned.example.test/form',+ // Strict checks: the guard's refusal itself is under test.+ const result = await runOwnedTask({ streaming, strict: true, task: 'Submit the owned form.', url: 'https://owned.example.test/form',pageState: () => ({ workflowPageText: pageText, incompleteTaskControls: [{ label: 'Submit',disabled: pageText.startsWith('Saving'), busy: pageText.startsWith('Saving') }] }),judge: () => { judgments++; return 'wait_then_check'; },@@ -363,7 +365,8 @@ for (const build of ['chrome', 'firefox']) {test(`${build}: ${streaming ? 'stream' : 'chat'} corrects an observed iframe value mismatch after a recoverable incomplete ending`, async () => {const actions = [], field = { selector: '#email', urlFilter: 'owned-frame.test', text: '[email protected]', clear: true };let requests = 0, judgments = 0, corrected = false, matched = false;- const result = await runOwnedTask({ streaming, task: 'Fill the owned email field.', url: 'https://owned.example.test/form',+ // Strict checks: the guard's refusal itself is under test.+ const result = await runOwnedTask({ streaming, strict: true, task: 'Fill the owned email field.', url: 'https://owned.example.test/form',pageState: () => ({ workflowPageText: 'Email: [email protected]', incompleteTaskControls: [] }),judge: () => { judgments++; return 'continue_now'; },script: names => {diff --git a/test/lifecycle-terminal-done.mjs b/test/lifecycle-terminal-done.mjsindex f9cc3a013..c2a37a6a5 100644--- a/test/lifecycle-terminal-done.mjs+++ b/test/lifecycle-terminal-done.mjs@@ -194,6 +194,8 @@ for (const build of ['chrome', 'firefox']) {return call('done-' + requests, 'done', { summary: 'Posted and verified.', outcome: 'success' });});agent.maxSteps = 8;+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => { send = bindMain(agent, tab); return { role: 'user', content }; };agent._completionDoneBlock = tabId => {if (blocked++) return null;diff --git a/test/media-download-agent-handler.mjs b/test/media-download-agent-handler.mjsindex 89b97e6e4..56318eb0e 100644--- a/test/media-download-agent-handler.mjs+++ b/test/media-download-agent-handler.mjs@@ -14,7 +14,7 @@ function handler(build) {return new AsyncFunction('tabId', 'name', 'args', 'onUpdate', 'executionContext', 'chrome', 'browser', source.slice(start, end));}-function setup(build, runResult, { binding = null, mseBytes = 100 } = {}) {+function setup(build, runResult, { binding = null, mseBytes = 100, strictGuards = true } = {}) {const effects = { run: 0, mseSave: 0, visionRoute: 0, visionSave: 0, opts: null };const downloader = {async run(opts) { effects.run++; effects.opts = opts; return runResult; },@@ -40,6 +40,14 @@ function setup(build, runResult, { binding = null, mseBytes = 100 } = {}) {_activeProvider: () => ({}), providerManager: { getActive: () => ({}) },async _resolveVisionRoute() { effects.visionRoute++; return { provider: {} }; },async _saveVisibleMediaCrop() { effects.visionSave++; return { success: true, completedCount: 1 }; },+ // Strict checks: the guard's refusal itself is under test. (Default+ // advice is covered with the real agent in guard-advisory-actions.mjs.)+ strictGuards,+ _guardAdvisesFor(advisories, guard, note) {+ if (this.strictGuards) return false;+ advisories?.push?.({ guard, note });+ return true;+ },};return { effects, execute: args => handler(build).call(agent, 1, 'download_social_media', args, () => {},binding ? { _expectedMediaBinding: binding } : {}, api, api) };diff --git a/test/media-download-capture-integration.mjs b/test/media-download-capture-integration.mjsindex b6b2080dc..00220b623 100644--- a/test/media-download-capture-integration.mjs+++ b/test/media-download-capture-integration.mjs@@ -75,6 +75,8 @@ for (const [build, Agent, engine] of variants) {test(`${build}: actual model capture and handler bind the intended photo across ${change}`, async () => {const { browser, page, calls } = await fixture(build, engine);const tab = nextTab++, { agent, run } = agentWithRun(Agent, tab, page.url());+ // Strict checks: the guard's refusal itself is under test.+ if (change !== 'counter') agent.strictGuards = true;try {await agent._capturePageFeedbackModelState(tab);const expected = run.modelState.mediaBindings.image;@@ -155,10 +157,12 @@ for (const change of ['counter', 'asset']) {});const ui = await context.newPage();await ui.goto(`chrome-extension://${extensionId}/src/ui/settings.html`);- const captured = await ui.evaluate(async () => {+ const captured = await ui.evaluate(async strictGuards => {const { Agent } = await import(chrome.runtime.getURL('src/agent/agent.js'));const provider = { name: 'synthetic capture test', model: 'test', supportsVision: false };const agent = new Agent({ getActive: () => provider, getProvider: () => provider, getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = strictGuards;agent._uncertainTextMutationBlock = async () => null;agent._richTextToolbarToolBlock = async () => null;agent._finalizeToolResultOnce = async (_tab, _name, _args, result) => result;@@ -172,7 +176,7 @@ for (const change of ['counter', 'asset']) {await agent._capturePageFeedbackModelState(tab.id);return { binding: run.modelState.mediaBindings.image, diagnostic: run.modelState.mediaCapture,legacyAvailable: typeof chrome.tabs.executeScript, manifest: chrome.runtime.getManifest().manifest_version };- });+ }, change !== 'counter');assert.equal(captured.manifest, 3);assert.equal(captured.legacyAvailable, 'undefined');assert.equal(captured.diagnostic.targets.image.status, 'bound');diff --git a/test/message-recipient-whatsapp.mjs b/test/message-recipient-whatsapp.mjsindex 398b595d7..14b54f7dc 100644--- a/test/message-recipient-whatsapp.mjs+++ b/test/message-recipient-whatsapp.mjs@@ -196,6 +196,10 @@ for (const [kind, engine, Agent] of [['chrome', chromium, ChromeAgent], ['firefoassert.equal(blocked?.recipientAuthorizationRequired, false);assert.equal(blocked.recipientConfirmation, undefined, 'A page without a verifiable recipient offers no card');assert.doesNotMatch(blocked.error, /clarify\(|Ask the user to authorize/);+ // The recipient refusal above ran in the default mode. Strict checks+ // only for the clarify refusal below: by default that quality check+ // advises and the question would wait for an answer.+ f.agent.strictGuards = true;const updates = [];const repeatedApproval = await f.agent._executeToolImpl(71, 'clarify', {purpose: 'message_recipient', question: 'Send to Anne instead?', options: ['Anne', 'Cancel'],@@ -257,11 +261,16 @@ for (const [kind, engine, Agent] of [['chrome', chromium, ChromeAgent], ['firefo['messageRecipientDispatchBinding', undefined, 'recipient_dispatch_binding_unavailable'],]) {f.agent._messageRecipientContentProbe = async (...args) => ({ ...await realProbe(...args), [field]: value });+ // The recipient refusal runs in the default mode; Strict checks only+ // for the clarify refusal after it (a quality check that advises by+ // default, when the question would wait for an answer).+ f.agent.strictGuards = false;const { blocked } = await f.bind();assert.equal(blocked?.reasonCode, reasonCode, JSON.stringify(blocked));assert.equal(blocked.recipientAuthorizationRequired, false);assert.deepEqual(guard.approvedRecipients, ['anne']);assert.equal(blocked.recipientConfirmation, undefined, 'Missing delivery evidence is not put to the user again');+ f.agent.strictGuards = true;const updates = [];const confirmation = await f.agent._executeToolImpl(71, 'clarify', {purpose: 'message_recipient', question: 'Send to Anne?', options: ['Anne', 'Cancel'],@@ -271,6 +280,7 @@ for (const [kind, engine, Agent] of [['chrome', chromium, ChromeAgent], ['firefoassert.deepEqual(updates, []);}f.agent._messageRecipientContentProbe = realProbe;+ f.agent.strictGuards = false;assert.equal((await f.bind()).blocked, null);assert.equal(guard.messageRecipientTechnicalBlock, undefined);assert.deepEqual(guard.approvedRecipients, ['anne']);diff --git a/test/pure-calculation-reply.mjs b/test/pure-calculation-reply.mjsindex e80217339..6319c8830 100644--- a/test/pure-calculation-reply.mjs+++ b/test/pure-calculation-reply.mjs@@ -275,6 +275,8 @@ for (const build of ['chrome', 'firefox']) {assert.equal(requests, 3);return call('honest-missing-calculation', 'done', { summary: 'The required calculation was not executed.', outcome: 'failed' });});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => {send = bind(agent, tab); return { role: 'user', content };};@@ -313,6 +315,8 @@ for (const build of ['chrome', 'firefox']) {return messages.some(m => m.role === 'tool' && String(m.content).includes(expected))? { content: answer } : call('calc-without-terminal', 'calculate', { expression });});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => {send = bind(agent, tab); return { role: 'user', content };};diff --git a/test/pure-calculation-tools.mjs b/test/pure-calculation-tools.mjsindex c3813790c..e4ec24f3b 100644--- a/test/pure-calculation-tools.mjs+++ b/test/pure-calculation-tools.mjs@@ -138,6 +138,8 @@ for(const build of ['chrome','firefox']){assert.ok(requests<=7);return call('actual-explicit-done','done',{summary:answer,outcome:'success'});});agent._skipPermissionGate=false;agent._ensureGateSetting=async()=>false;agent.maxSteps=12;+ // Strict checks: the guard's refusal itself is under test.+ if(scenario==='wrong_literal'||scenario==='same_batch_repeat')agent.strictGuards=true;agent._promptPermission=async()=>{permissions++;return 'deny';};agent._enrichUserMessageWithCurrentPage=async(_tab,_messages,content)=>{send=bind(agent,tab);return{role:'user',content};};agent._runPlannerIntentGate=async()=>({proceed:true,requestKind:'execute',requiresStateChange:false,requiresSubmission:false,...agent._plannerCompletionGateFields({read_scope:'none',deliverables:scope.deliverables})});diff --git a/test/read-continuation-browser.mjs b/test/read-continuation-browser.mjsindex 46bfcfead..10dc9e00d 100644--- a/test/read-continuation-browser.mjs+++ b/test/read-continuation-browser.mjs@@ -311,6 +311,8 @@ for (const [build, engine] of [['chrome', chromium], ['firefox', firefox]]) {try {const provider = { promptTier: 'full', contextWindow: 128000, supportsVision: false };const agent = new Agent({ getActive: () => provider });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._effectiveRunMode = () => 'ask';agent._ensureGateSetting = async () => false;agent._skipPermissionGate = true;diff --git a/test/read-continuation-schema.mjs b/test/read-continuation-schema.mjsindex 05b55ac16..71f9e132c 100644--- a/test/read-continuation-schema.mjs+++ b/test/read-continuation-schema.mjs@@ -126,6 +126,8 @@ for (const browser of ['chrome', 'firefox']) {test(`${browser}: sampled or corrupted table JSON cannot complete a literal extraction`, async () => {const agent = new Agent({ getActive: () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._effectiveRunMode = () => 'ask';const rows = Array.from({ length: 172 }, (_, index) => ({ID: `ID-${(index * 73) % 172}`, stock: index, unit_price_cents: index * 119,diff --git a/test/rich-text-frameworks.mjs b/test/rich-text-frameworks.mjsindex c1e0e8271..7bfb39b23 100644--- a/test/rich-text-frameworks.mjs+++ b/test/rich-text-frameworks.mjs@@ -272,7 +272,9 @@ test('Chrome: real trusted input updates DraftJS once through production selectoawait assertApplication(f, args.text);const retry = await agent._maybeFallbackFieldWithCdpImpl(41, 'set_field', args,{ ...unknown, _expectedValue: args.text }, {}, null, f.frameId);- assert.equal(retry.success, false); assert.equal(retry.outcomeUnknown, true); assert.equal(retry.repeatBlocked, true);+ // By default trusted-field-retry-guards advises: no repeat lock label,+ // but WebBrain still never retypes on its own (one insertion below).+ assert.equal(retry.success, false); assert.equal(retry.outcomeUnknown, true); assert.equal(retry.repeatBlocked, undefined);assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 1);await assertApplication(f, args.text);});diff --git a/test/run.js b/test/run.jsindex f9066018a..aaa0b0ac1 100644--- a/test/run.js+++ b/test/run.js@@ -9436,6 +9436,8 @@ test('carousel slide count prefers an explicit total over the current index', ()test('Instagram carousel navigation enumerates 16 slides monotonically and records 15 hotel rows', async () => {for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = label === 'chrome' ? 551 : 552;let currentUrl = 'https://www.instagram.com/p/ABC123/';const recordedRows = [];@@ -11597,6 +11599,8 @@ test('whole-thread guard blocks done before an incomplete read can become a finatest('Ask returns a fixed limitation when Gmail expansion cannot be verified', async () => {for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {const agent = new AgentClass({ getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = label === 'chrome' ? 52705 : 52706;let executed = false;agent._persist = () => { };@@ -20795,6 +20799,7 @@ async function runCoordinateSemanticCase({privateRestoreAttempt = null,privateDraftPreparationAttempt = false,privateDraftBindingAttempt = null,+ strictGuards = false,}) {const previousChrome = globalThis.chrome;const previousBrowser = globalThis.browser;@@ -20827,6 +20832,7 @@ async function runCoordinateSemanticCase({: { ...(previousBrowser || {}), tabs: { ...(previousBrowser?.tabs || {}), ...tabs } };try {const agent = new AgentClass({ getVisionProvider: async () => null });+ agent.strictGuards = strictGuards;const tabId = label === 'chrome' ? 8811 : 8812;agent._isPdfTab = async () => false;agent._richTextToolbarToolBlock = async () => null;@@ -21088,6 +21094,8 @@ test('screenshot coordinate assertions reject an unrelated language selector witglobalKey,expectedName: 'Next',expectedRole: 'button',+ // Strict checks: the guard's refusal itself is under test.+ strictGuards: true,resolverResponse: {success: true,semanticTarget: {@@ -28365,6 +28373,8 @@ test('completion recovery keeps scoped observations read-only and target-specifi['firefox', AgentFx, CompletionInvariantFx, getToolsForModeFx],]) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = label === 'chrome' ? 24852 : 24853;agent.conversationModes.set(tabId, 'act');const state = invariant.recordCompletionToolResult(@@ -28799,7 +28809,9 @@ test('field tool contracts advertise settled verification and recovery', () => {const typeText = tools.find(tool => tool.function.name === 'type_text');assert.match(typeAx.function.description, /settle[\s\S]*verified:true/i, `${label}: type_ax verification contract missing`);assert.match(setField.function.description, /verify the exact settled value/i, `${label}: set_field exact verification contract missing`);- assert.match(setField.function.description, /recoveryRequired:"verify_or_restore_field"/, `${label}: set_field recovery contract missing`);+ // Default mode reports an unconfirmed readback as verified:false with a+ // note instead of a recovery lock (Strict checks keep recoveryRequired).+ assert.match(setField.function.description, /exact readback fails, the result reports verified:false and says what to check/, `${label}: set_field recovery contract missing`);for (const tool of [typeAx, setField, typeText]) {assert.equal(tool.function.parameters.properties.lang, undefined, `${label}: ${tool.function.name} still exposes a hidden language transform`);}@@ -56230,6 +56242,8 @@ test('terminal schedule_resume settles its parent checkpoint only after durabletest('schedule_resume pauses unfinished chat work without running success completion guards', async () => {for (const [label, AgentClass, SchedulerMod] of [['chrome', AgentCh, SchedulerCh], ['firefox', AgentFx, SchedulerFx]]) {const h = makeResumeBatchHarness(AgentClass, SchedulerMod);+ // Strict checks: the guard's refusal itself is under test.+ h.agent.strictGuards = true;const guard = h.agent._startPlanExecutionGuard(77, 'act', {requestKind: 'execute', requiresStateChange: true, requiresSubmission: true,});@@ -60906,6 +60920,7 @@ test('Chrome focused replacement blocks when clear is unproven and propagates ficdpClientCh.sendCommand = async () => ({});cdpClientCh.verifyTextEntry = async () => null;const agent = new AgentCh({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const uncleared = await agent.executeTool(42, 'type_text', { text: 'hello', clear: true });assert.equal(uncleared.success, false);assert.equal(uncleared.verified, false);@@ -79708,6 +79723,8 @@ test('form validation classifier surfaces native and custom submission errors',test('unchanged failed-submit state permits one verify_form then directs checkbox recovery', () => {for (const AgentClass of [AgentCh, AgentFx]) {const agent = new AgentClass({ getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 5120;const states = [{frameId: 0,@@ -80874,6 +80891,8 @@ test('agent returns form validation messages and blocks unchanged repeat submitsfor (const AgentClass of [AgentCh, AgentFx]) {const agent = new AgentClass({ getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 5117;let executions = 0;let prompts = 0;@@ -82873,6 +82892,8 @@ test('Chrome controlled-field fallback skips retry when the original dispatch is};const agent = new AgentCh({});++ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const result = await agent._maybeFallbackFieldWithCdp(42,'set_field',@@ -82957,6 +82978,8 @@ test('Chrome controlled-field fallback recovers exactly once and never submits a};const agent = new AgentCh({});++ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const recovered = await agent._maybeFallbackFieldWithCdp(42,'set_field',@@ -83157,6 +83180,7 @@ test('uncertain text mutation debt blocks blind retries until the document changglobalThis.browser = { tabs };for (const [label, AgentClass] of [['chrome', AgentCh], ['firefox', AgentFx]]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const tabId = label === 'chrome' ? 9441 : 9442;agent._lastAxScopes.set(tabId, {documentToken: 'doc-one',@@ -83285,6 +83309,7 @@ test('an exact same-field readback resolves uncertain replacement without dispat['firefox', AgentFx, 9444],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, {documentToken: 'doc-readback',pageUrl: 'https://github.com/example/repo/edit/main/docs/plan.md',@@ -83325,6 +83350,7 @@ test('an uncertain contenteditable write invalidates stale proof across locator['firefox', AgentFx, 9448],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const pageUrl = 'https://github.com/example/repo/edit/main/docs/plan.md';agent._lastAxScopes.set(tabId, { documentToken: 'doc', pageUrl });agent._verifiedTextReplacements.set(tabId, new Map([@@ -83358,6 +83384,7 @@ test('uncertain text mutation debt survives same-document route changes and back['firefox', AgentFx, 9454],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const pageUrl = 'https://github.com/example/repo/edit/main/docs/plan.md';agent._lastAxScopes.set(tabId, { documentToken: 'doc-route', pageUrl });const uncertain = await agent._finalizeTextMutationResult(@@ -83410,6 +83437,7 @@ test('uncertain text mutation recovery requires same-field identity', async () =['firefox', AgentFx, 9456],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, {documentToken: 'doc-identity',pageUrl: 'https://github.com/example/repo/edit/main/docs/plan.md',@@ -83998,6 +84026,9 @@ test('GitHub edit-file workflow verifies the exact committed raw blob', async ()['firefox', AgentFx, resolveAdapterWorkflowJobFx, true],]) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test (the+ // conditional variants expect the re-arm to defer the editor action).+ agent.strictGuards = conditional;const tabId = label === 'chrome' ? 9445 : 9446;// Proofs bind to the active task token, minted here as _startTraceRun does.agent._taskTokens.set(tabId, `task-blob-${tabId}`);@@ -84344,6 +84375,8 @@ test('GitHub edit-file workflow blocks compound submit actions on existing bindi['firefox', AgentFx, 9462],]) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent._planExecutionGuards.set(tabId, {enabled: true,siteWorkflow: { adapterName: 'github', job: { id: 'edit-file-and-commit' } },@@ -85298,6 +85331,7 @@ test('uncertain selector writes capture live metadata for distinctness', async (['firefox', AgentFx, 9527],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-multi', pageUrl });const tabs = {captureMeta: false,@@ -85369,6 +85403,7 @@ test('selector writes to proven-distinct fields bypass unrelated debt', async ()['firefox', AgentFx, 9501, 9503],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-multi', pageUrl });const tabs = {async sendMessage(_tabId, message) {@@ -85401,6 +85436,7 @@ test('selector writes to proven-distinct fields bypass unrelated debt', async ()`${label}: distinct-field dispatch dropped the original debt`);// Shared identity field: fail-closed, still blocked.const control = new AgentClass({});+ control.strictGuards = true; // Strict checks: the guard's refusal itself is under test.control._lastAxScopes.set(controlTabId, { documentToken: 'doc-multi', pageUrl });await control._finalizeTextMutationResult(controlTabId, 'type_text', { selector: '#a', text: 'alpha', clear: true },@@ -85432,6 +85468,7 @@ test('distinctness escape covers focused and mixed-locator debts', async () => {['firefox', AgentFx, 9531, 9533],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-cross', pageUrl });const tabs = {async sendMessage(_tabId, message) {@@ -85470,6 +85507,7 @@ test('distinctness escape covers focused and mixed-locator debts', async () => {`${label}: distinct-field dispatch dropped the focused debt`);// Reverse direction: selector debt, focused retry on a distinct field.const control = new AgentClass({});+ control.strictGuards = true; // Strict checks: the guard's refusal itself is under test.control._lastAxScopes.set(controlTabId, { documentToken: 'doc-cross', pageUrl });const controlTabs = {async sendMessage(_tabId, message) {@@ -85541,6 +85579,7 @@ test('focused field_value_digest and live scope cover selectorless writes', asynliveDoc.documentToken = 'doc-old';liveDoc.refScopeUrl = 'https://example.test/form';const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-old', pageUrl: 'https://example.test/form' });await agent._finalizeTextMutationResult(tabId, 'type_text', { selector: '#field', text: 'draft', clear: true },@@ -85575,6 +85614,7 @@ test('uncertain write after navigation records live scoped debt', async () => {['firefox', AgentFx, 9491],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.// Cached scope predates a full navigation no AX read ever observed;// the live page is already the new document.agent._lastAxScopes.set(tabId, { documentToken: 'doc-old', pageUrl: 'https://example.test/form' });@@ -85624,6 +85664,7 @@ test('focused uncertain writes recover on exact same-field readback', async () =['firefox', AgentFx, 9519, 9521],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-focus', pageUrl: 'https://example.test/form' });// Commit-proof workflow so recovery mints a full readback record.agent._planExecutionGuards.set(tabId, {@@ -85671,6 +85712,7 @@ test('focused uncertain writes recover on exact same-field readback', async () =// Control: record-time focus already lost (identity capture fails), so// even a later exact readback cannot prove the same field.const control = new AgentClass({});+ control.strictGuards = true; // Strict checks: the guard's refusal itself is under test.control._lastAxScopes.set(controlTabId, { documentToken: 'doc-focus', pageUrl: 'https://example.test/form' });const controlTabs = {async sendMessage(_tabId, message) {@@ -85863,6 +85905,7 @@ test('first live token bootstraps tokenless debt by URL', async () => {globalThis.chrome = { tabs: { async sendMessage() { return { success: false }; } } };globalThis.browser = globalThis.chrome;const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._currentUrl = async () => oldUrl;await agent._finalizeTextMutationResult(tabId, 'type_text', { selector: '#field', text: 'draft', clear: true },@@ -85892,6 +85935,7 @@ test('first live token bootstraps tokenless debt by URL', async () => {globalThis.chrome = { tabs: { async sendMessage() { return { success: false }; } } };globalThis.browser = globalThis.chrome;const samePage = new AgentClass({});+ samePage.strictGuards = true; // Strict checks: the guard's refusal itself is under test.samePage._currentUrl = async () => oldUrl;await samePage._finalizeTextMutationResult(controlTabId, 'type_text', { selector: '#field', text: 'draft', clear: true },@@ -85926,6 +85970,7 @@ test('clearConversation preserves document-scoped mutation debt', async () => {['firefox', AgentFx, 9525],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-conv', pageUrl: 'https://example.test/form' });await agent._finalizeTextMutationResult(tabId, 'type_text', { selector: '#field', text: 'maybe landed', clear: true },@@ -85974,6 +86019,7 @@ test('clearConversation retains scope for first-try debt recovery', async () =>['firefox', AgentFx, 9541],]) {const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: 'doc-scope', pageUrl: 'https://example.test/form' });await agent._finalizeTextMutationResult(tabId, 'set_field', { ref_id: 'ref_a', text: 'hello' },@@ -86398,6 +86444,7 @@ test('Firefox selector debt recovers on exact digest readback', async () => {globalThis.chrome = { tabs };globalThis.browser = { tabs };const agent = new AgentFx({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const tabId = 9465;agent._lastAxScopes.set(tabId, {documentToken: 'doc-fx-selector',@@ -86495,6 +86542,7 @@ test('navigation scopes stale text-mutation debt to its document', async () => {liveDoc.documentToken = 'doc-old';liveDoc.refScopeUrl = 'https://example.test/form';const agent = new AgentClass({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, {documentToken: 'doc-old',pageUrl: 'https://example.test/form',@@ -90680,6 +90728,8 @@ test('non-stream and stream runs keep forced done active across empty and rejectgetActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = streaming ? 24812 : 24811;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -90832,6 +90882,8 @@ test('non-stream and stream runs expose failure completion after a verifier makegetActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = streaming ? 24816 : 24815;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -90985,6 +91037,8 @@ test('non-stream and stream runs release forced done when progress work remains'getActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = streaming ? 24814 : 24813;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -91108,6 +91162,8 @@ test('navigation auto-screenshot verification turns terminal prose into a forcedgetActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 24830 + browserIndex;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -91261,6 +91317,8 @@ test('repeated plain finals stop after two completion-protocol recovery turns wigetActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 24820 + (streaming ? 100 : 0) + (verified ? 10 : 0) + browserIndex;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -91384,6 +91442,8 @@ test('repeated plain finals at the step limit emit partial instead of max_steps'getActive: () => provider,getVisionProvider: async () => null,});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 24900 + (streaming ? 100 : 0) + browserIndex;agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({@@ -92138,6 +92198,8 @@ test('decision completion recognizes published Reddit content while preserving vcdpClientCh.evaluate = async () => ({ result: { value: page } });const provider = { model: 'test-model', supportsVision: false, config: { category: 'local' } };const agent = new AgentClass({ getActive: () => provider, getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent.conversationModes.set(tabId, 'act');agent.autoScreenshot = 'off';agent._persist = () => {};@@ -92307,6 +92369,8 @@ test('decision completion releases forced done into read-only recovery and then};else provider.chat = async (_messages, options) => next(options);const agent = new AgentClass({ getActive: () => provider, getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 24960 + (streaming ? 1 : 0);agent.planBeforeAct = false;agent._maybeRunPlannerGate = async () => ({ proceed: true, requestKind: 'execute', requiresStateChange: true });@@ -93317,6 +93381,8 @@ test('structured blockers may describe future requirements without becoming plantest('false Ask-mode completions receive a focused Act recovery and honest terminal evidence', () => {for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 8625 + index;agent._startPlanExecutionGuard(tabId, 'act', {requestKind: 'execute',@@ -94100,6 +94166,8 @@ test('future-promise prose is read by the completion judge, not by words', () =>test('completion words do not mask mixed progress plus plan terminals', () => {for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const tabId = 8633 + index;agent._startPlanExecutionGuard(tabId, 'act', {requestKind: 'execute',@@ -95073,6 +95141,10 @@ test('conditional resumed GitHub repair re-arms commit guards before dispatch anconst runUrl = 'https://github.com/Example/Repo/actions/runs/123';const editUrl = `https://github.com/${variant === 'other_repository' ? 'Other/Repo' : 'Example/Repo'}/${variant === 'new_file' ? 'new' : 'edit'}/main/.github/workflows/main.yml`;const agent = new AgentClass({ getActive: () => ({ supportsVision: false }), getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test. Only the+ // re-arm is a quality guard; every other variant is refused by the+ // unrequested-publication guard, which must hold with Strict checks off.+ agent.strictGuards = variant === 'authorized';configurePlanOnlyGuardAgent(agent, tabId);agent.conversations.get(tabId).push({ role: 'user', content: 'Check CI; if it failed, fix the workflow and commit.' });agent._currentUrl = async () => editUrl;@@ -95131,6 +95203,8 @@ test('conditional resumed GitHub repair re-arms commit guards before dispatch antest('planned scheduling requires successful evidence from the matching scheduling tool', () => {for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const missingTabId = 8570 + index;const missingState = agent._startPlanExecutionGuard(missingTabId, 'act', {requestKind: 'execute',@@ -95491,6 +95565,8 @@ test('only explicitly requested app-state tools count as execution evidence', ()test('repeated plan failure distinguishes read-only progress from possible side effects', () => {for (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const readTabId = 8618 + index;agent._startPlanExecutionGuard(readTabId, 'act', {requestKind: 'execute',@@ -101804,6 +101880,8 @@ test('generic submission evidence failure does not claim that a site workflow jofor (const [index, AgentClass] of [AgentCh, AgentFx].entries()) {const tabId = 8965 + index;const agent = new AgentClass({});+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;const guard = agent._startPlanExecutionGuard(tabId, 'act', {requestKind: 'execute',requiresStateChange: true,diff --git a/test/social-publish-contract.mjs b/test/social-publish-contract.mjsindex 1fa49f09e..d3ee28237 100644--- a/test/social-publish-contract.mjs+++ b/test/social-publish-contract.mjs@@ -356,6 +356,7 @@ for (const browser of ['chrome', 'firefox']) {for (const mode of ['exact','partial','wrong-document','wrong-target','append','second-debt','no-digest']) {const f = setup();const {agent,tabId} = f;+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const original = 'Original\n\nbody';const args = {ref_id:'editor',text:original,clear:true};agent._lastAxScopes.set(tabId,{documentToken:'doc',pageUrl:'https://bsky.app/'});diff --git a/test/steering-revision-recovery.mjs b/test/steering-revision-recovery.mjsindex 7372519c1..80f24b3d9 100644--- a/test/steering-revision-recovery.mjs+++ b/test/steering-revision-recovery.mjs@@ -58,7 +58,10 @@ function finish(a, tab) { a._finishSteeringRun(tab); a._releaseRunEntry(tab); }for (const build of ['chrome', 'firefox']) {const { Agent } = await import(new URL(`src/${build}/src/agent/agent.js`, ROOT));test(`${build}: missing current calculation attempts exclude premature completion`, async () => {- const tab = nextTab++, a = setup(Agent, async () => ({ content: '' })); await begin(a, tab);+ const tab = nextTab++, a = setup(Agent, async () => ({ content: '' }));+ // Strict checks: the guard's refusal itself is under test.+ a.strictGuards = true;+ await begin(a, tab);try { const policy = a._pureCalculationToolPolicy(tab); assert.deepEqual(policy.names, ['calculate', 'done']);assert.deepEqual(policy.toolChoice, { type: 'function', function: { name: 'calculate' } });for (const outcome of ['success', 'partial', 'failed']) { const blocked = a._pureCalculationToolBlock(tab, 'done', { outcome, summary: answer });@@ -133,6 +136,8 @@ for (const build of ['chrome', 'firefox']) {if (n === 7) { assert.deepEqual(opts.toolChoice, { type: 'function', function: { name: 'calculate' } }); return call('new-calculation', 'calculate', { expression }); }return call('new-done', 'done', { summary: answer, outcome: 'success' });});+ // Strict checks: the guard's refusal itself is under test.+ a.strictGuards = true;a._enrichUserMessageWithCurrentPage = async (_tab, _messages, content) => { bind(a, tab); return { role: 'user', content }; };a.executeTool = async (_tab, name, args) => {if (name === 'calculate') { calculations++; return a._executeToolImpl(_tab, name, args); }diff --git a/test/terminal-user-messages.mjs b/test/terminal-user-messages.mjsindex 027a9c7af..a8f6776b0 100644--- a/test/terminal-user-messages.mjs+++ b/test/terminal-user-messages.mjs@@ -51,6 +51,8 @@ test('terminal message module stays byte-identical across builds', () => {function batchAgent(Agent, tabId) {const agent = new Agent({ getActive: () => ({ model: 'test', supportsTools: true }), getVisionProvider: async () => null });+ // Strict checks: the guard's refusal itself is under test.+ agent.strictGuards = true;agent.conversationIds.set(tabId, 'conv-terminal');agent.conversationModes.set(tabId, 'act');agent.conversations.set(tabId, [diff --git a/test/text-write-cancellation.mjs b/test/text-write-cancellation.mjsindex 100b84dd8..b5fd9f1bd 100644--- a/test/text-write-cancellation.mjs+++ b/test/text-write-cancellation.mjs@@ -97,6 +97,7 @@ for (const [browser, Agent] of variants) {test(`${browser}: Stop after a real content send records debt and blocks the next run`, async () => {const agent = setup(Agent); const entered = deferred(); const release = deferred();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.await agent._claimRunEntry(tabId, 'interactive');agent.sendWrite = () => { entered.resolve(); return release.promise; };const dispatchState = { started: false };@@ -116,6 +117,7 @@ for (const [browser, Agent] of variants) {for (const failure of ['AbortError', 'closed channel']) {test(`${browser}: a dispatched ${failure} never reinjects or retries the text write`, async () => {const agent = setup(Agent);+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.await agent._claimRunEntry(tabId, 'interactive');agent.sendWrite = async () => { throw failure === 'AbortError' ? abortError() : new Error('The message port closed before a response was received.'); };const result = await agent.executeTool(tabId, 'set_field', args);@@ -144,6 +146,7 @@ for (const [browser, Agent] of variants) {for (const stage of ['injection', 'retry send']) {test(`${browser}: Stop during ${stage} after missing receiver preserves dispatch evidence`, async () => {const agent = setup(Agent); const entered = deferred(); const release = deferred();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.await agent._claimRunEntry(tabId, 'interactive');agent.sendWrite = () => {if (agent.writes === 1) return Promise.reject(noReceiverError());@@ -185,6 +188,7 @@ for (const [browser, Agent] of variants) {for (const stopAt of ['dispatch', 'content preparation']) {test(`${browser}: saved workflow Stop during ${stopAt} retains correct text mutation evidence`, async () => {const agent = setup(Agent); const entered = deferred(); const release = deferred();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent.ensureConversationId = async () => 'workflow-conversation';agent._startSavedWorkflowTraceRun = async () => null;agent._endSavedWorkflowTraceRun = async () => {};@@ -248,6 +252,7 @@ for (const [browser, Agent] of variants) {test(`${browser}: late lower result cannot recreate canceled debt after exact readback recovery`, async () => {const agent = setup(Agent); const entered = deferred(); const release = deferred();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const dispatchState = { started: false };agent.sendWrite = () => { entered.resolve(); return release.promise; };const pending = agent.executeTool(tabId, 'set_field', args, null, { _contentActionDispatchState: dispatchState });@@ -271,6 +276,7 @@ for (const [browser, Agent] of variants) {for (const stage of ['cancelled result', 'pending ordinary finalization']) {test(`${browser}: Stop bounds stalled scope enrichment for ${stage}`, { timeout: 2000 }, async () => {const agent = setup(Agent); const entered = deferred(); const release = deferred();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.await agent._claimRunEntry(tabId, 'interactive');agent._liveTextMutationScope = () => { entered.resolve(); return release.promise; };agent.sendWrite = async () => { throw stage === 'cancelled result'@@ -317,6 +323,7 @@ for (const [browser, Agent] of variants) {if (browser === 'chrome') {test('chrome: EARLY_CDP public wrapper shares its parent dispatch marker on cancellation', async () => {const agent = setup(Agent); const dispatchState = { started: false }; const controller = new AbortController();+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._executeToolImpl = async (_id, _name, _args, _update, context) => {assert.equal(context._contentActionDispatchState, dispatchState);context._contentActionDispatchState.started = true;diff --git a/test/trusted-field-preparation-ownership.mjs b/test/trusted-field-preparation-ownership.mjsindex 1f675033f..cd4a0cd5c 100644--- a/test/trusted-field-preparation-ownership.mjs+++ b/test/trusted-field-preparation-ownership.mjs@@ -23,6 +23,7 @@ const sha = text => createHash('sha256').update(text).digest('hex');async function runScenario(options = {}, inspect) {const savedSend = api.tabs.sendMessage, savedAttach = cdpClient.attach, savedCommand = cdpClient.sendCommand;const agent = new Agent({});+ if (options.strict) agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.const commands = [], messages = [];const abort = new AbortController();let preparations = 0, digests = 0;@@ -89,7 +90,7 @@ for (const [name, options] of [['missing initial digest', { missingBefore: true }],['Stop after focus', { abortAfterFocus: true }],]) test(`Chrome ${name} retains uncertain text debt after trusted focus`, async () => {- await runScenario(options, async ({ agent, result, commands }) => {+ await runScenario({ ...options, strict: true }, async ({ agent, result, commands }) => {assert.notEqual(result.textUnchanged, true);assert.equal(commands.some(command => command.method === 'Input.insertText'), false);const finalized = await agent._finalizeTextMutationResult(tabId, 'set_field', args, result);@@ -99,7 +100,7 @@ for (const [name, options] of [});test('Chrome a lost text-command response cannot mint unchanged preparation proof even if readback still looks unchanged', async () => {- await runScenario({ reselectionFails: false, loseTextResponse: true }, async ({ agent, result, commands, digests }) => {+ await runScenario({ reselectionFails: false, loseTextResponse: true, strict: true }, async ({ agent, result, commands, digests }) => {assert.equal(commands.filter(command => command.method === 'Input.insertText').length, 1);assert.equal(digests, 1, 'An attempted text command must not use a sample that can precede a delayed applied write.');assert.notEqual(result.textUnchanged, true);@@ -120,7 +121,7 @@ test('Chrome preparation failure before native focus preserves no-dispatch and ffor (const [name, destinationTab, destinationArgs] of [['different tab', tabId + 1, args], ['different ref', tabId, { ...args, ref_id: 'ref_8' }],]) test(`Chrome unchanged preparation attestation cannot be transferred to a ${name}`, async () => {- await runScenario({}, async ({ agent, result }) => {+ await runScenario({ strict: true }, async ({ agent, result }) => {const finalized = await agent._finalizeTextMutationResult(destinationTab, 'set_field', destinationArgs, result);assert.equal(finalized.repeatBlocked, true);assert.equal(agent._uncertainTextMutations.get(destinationTab)?.size, 1);@@ -130,6 +131,7 @@ for (const [name, destinationTab, destinationArgs] of [for (const build of ['chrome', 'firefox']) test(`${build}: page or model textUnchanged flags cannot forge native preparation authority`, async () => {const { Agent: Variant } = await import(`../src/${build}/src/agent/agent.js`);const agent = new Variant({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, { documentToken: scope.documentToken, pageUrl: scope.refScopeUrl });const saved = api.tabs.sendMessage;api.tabs.sendMessage = async () => ({ success: false, ...scope });diff --git a/test/trusted-field-preparation.mjs b/test/trusted-field-preparation.mjsindex ec07f4fde..b3166f6f8 100644--- a/test/trusted-field-preparation.mjs+++ b/test/trusted-field-preparation.mjs@@ -26,11 +26,12 @@ const digest = value => ({});const unchanged = digest('Existing draft');-async function scenario({ before = unchanged, after = unchanged, failure = 'reselect', tool = 'set_field', inputArgs = args, actualRoute = false } = {}, check) {+async function scenario({ before = unchanged, after = unchanged, failure = 'reselect', tool = 'set_field', inputArgs = args, actualRoute = false, strict = false } = {}, check) {const originalAttach = cdpClient.attach;const originalCommand = cdpClient.sendCommand;const originalMessage = api.tabs.sendMessage;const agent = new Agent({});+ if (strict) agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._hydrate = async () => {};agent._persist = () => {};agent._persistNow = async () => ({ ok: true });@@ -172,7 +173,7 @@ for (const [label, options] of [['invalid digest', { after: { ...unchanged, valueSha256: 'not-a-sha256' } }],]) {test(`Chrome: interrupted focus preserves text debt for ${label}`, async () => {- await scenario(options, async ({ agent, result, calls }) => {+ await scenario({ ...options, strict: true }, async ({ agent, result, calls }) => {assert.equal(result.success, false);assert.equal(result.dispatched, true);assert.equal(result.verified, false);@@ -212,7 +213,7 @@ for (const [label, options] of [['post-input verification mismatch', { failure: 'verification' }],]) {test(`Chrome: ${label} stays uncertain even when the editor digest is unchanged`, async () => {- await scenario(options, async ({ agent, result, calls, digests }) => {+ await scenario({ ...options, strict: true }, async ({ agent, result, calls, digests }) => {assert.equal(result.outcomeUnknown, true);assert.equal(result.mutationMayHaveOccurred, true);assert.equal(result.repeatBlocked, true);@@ -227,6 +228,7 @@ for (const [label, options] of [test('Chrome: page-supplied unchanged-text fields cannot forge the private debt exemption', async () => {const agent = new Agent({});+ agent.strictGuards = true; // Strict checks: the guard's refusal itself is under test.agent._lastAxScopes.set(tabId, scope);agent._liveTextMutationScope = async () => scope;const result = await agent._finalizeTextMutationResult(tabId, 'set_field', args, {