Skip to content

fix(flow): approve Windows grid windows, and bind native fault receipts to what the detector reads - #2795

Merged
abrichr merged 15 commits into
mainfrom
fix/approval-form-state-unreadable
Nov 30, 2026
Merged

abrichr merged 15 commits into
mainfrom
fix/approval-form-state-unreadable

Conversation

@abrichr

@abrichr abrichr commented Nov 30, 2026 •

Copy link
Copy Markdown
Member

Depends on #2788. This PR is stacked on #2788's branch (fix/native-value-guard-bracket, which includes #2787, now merged); it retargets to main when #2788 merges.

Fixes the remaining failures in the windows replay (Patient Notes, WindowsBackend) job, which has failed since #2291.

1. Governed approval halted with form_state_unreadable

test_standard_run_with_approval_hold_and_resume stopped at step_006 ("click 'Save Note'") before the approval request was written. The agent's /window/form-fields refused the Patient Notes window with observation/value/bound_identity_unavailable.

A type-only census of the window from run 46355293928 shows why. Seven controls report a UI Automation value but have no window of their own (NativeWindowHandle 0): the grid's three column headers, its three data cells, and the title bar. #2291 requires every value-capable control to prove its value with two WM_GETTEXT reads on its own window that agree with two UIA reads. A windowless control has no second source, so the proof can never exist and every approval on this app refused. The synthetic approval form passed because it has no grid and no title bar, and the unit-test fake gave every control its own handle.

The change (option B, approved by the coordinator)

A control that is windowless, read-only and non-password is read through observe_uia_only_value (native_value.py):

  • The sensitivity guard runs first and is the last check before every provider access, the same as for a complete read. A password, an unsupported or missing password status, or a status that changes between reads refuses.
  • The control must have no window: the raw element's CurrentNativeWindowHandle is null or 0 (has_no_native_window). uiautomation's NativeWindowHandle property also answers 0 when the read fails, so the raw element is read instead, and a failed read is never windowless. A control that reports any handle, including its grid's, still owes a full proof and refuses without one.
  • ValuePattern.IsReadOnly must be True before and after each read, except for the narrow cell scope below. An editable control refuses (value_not_read_only).
  • The value is read twice, each read bracketed by the caller's scope (window, process, RuntimeId chain to the window, geometry, type, on screen), and the two reads must agree byte for byte. A disagreement refuses (value_observation_changed).

On hosted Windows the WinForms provider gives the grid's cells and headers an empty RuntimeId (GetRuntimeId() returns ()); the title bar has one. So there are two bindings, chosen by the control's own RuntimeId:

  • RuntimeId present (the title bar): bound by its RuntimeId chain to the window, as for a complete read. Field kind uia_only_unverified.
  • RuntimeId exactly empty (grid cells and headers): bound by its structural path. Each node from the control up to the bound window contributes its RuntimeId when it has one, otherwise its control type, bounds and its one index among its parent's children (ControlsAreSame). The path must reach an ancestor below the window that has a RuntimeId (the grid) and end at the bound window's hwnd and process; otherwise it refuses. Field kind uia_only_structural.
  • An unreadable or malformed RuntimeId refuses. It never selects the path. A control read with a RuntimeId that loses it between reads refuses.

Read-only and its one narrow exception: WinForms reports a read-only DataGridView's cells as editable (ValuePattern.IsReadOnly is False on hosted Windows). A control must say read-only, except a windowless grid or list cell or a header (DataItemControl, ListItemControl, HeaderControl, HeaderItemControl) read by its structural path, whose first ancestor with a RuntimeId is a DataGridControl, ListControl or TableControl, and the window's own title bar. For those, the flag only has to be a real boolean and stay the same at every check; a flip between the two reads refuses. An Edit, Document or ComboBox, or anything with its own window, keeps today's complete-read requirement. Digesting an editable cell's value only adds change detection: it is never complete, and read-back, not the approval digest, verifies what a save wrote.

uiautomation's HeaderControl and TitleBarControl classes have no GetValuePattern; those are read through the generic GetPattern(10002), which answers None (refused) when unsupported.

The bound scope is re-read before and after each of the two value reads, and every snapshot must be identical, so a scroll, resize or new row between the reads refuses.

The result, UnverifiedValue, has complete always False and proof always None. On the wire it is a field of kind uia_only_unverified or uia_only_structural with no proof and no identity. window_fields_state never paints it out, so OCR still reads its pixels. The form-state kind names the weakest binding in the read (window_fields_uia_only_structural, then window_fields_uia_only_unverified, then window_fields), so the three never compare equal.

Provider errors: the agent's server.py and native_value.py run as copied stdlib files, so they can't import openadapt_flow.verdict. Each has one probe (native_value.probe, server._probe) that turns any provider exception into a NOT_CHECKED sentinel, the same rule as verdict.observe. Every windowless read maps that sentinel to its refusal: not windowless, None, not in scope, or value_observation_unavailable. The replay fallback uses verdict.observe itself. check_verdict_folds.py passes with the baseline unchanged.

Why this does not weaken #2291

The approval digest answers one question: did the window change between the person's approval and the save? Before #2291, these controls reached the digest through OCR, or were masked by an unproven UIA value. #2291 made them refuse. Under this change:

  • Nothing is masked on an unproven value. The pixels OCR read before are still read.
  • The UIA value adds a second signal on top of OCR, so a change either channel sees changes the digest. Detection is a superset of the OCR-only baseline.
  • Nothing from this class is a complete value. It is never read-back evidence, an edit baseline, or the basis of VERIFIED. observe_complete_value, which read-back and edit baselines use, still refuses the same control, and the agent's read route returns incomplete for it (tested).
  • Password, unknown-status and windowed controls behave exactly as before, and so do editable controls outside the narrow cell scope.

Known limits (in code and in docs/LIMITS.md):

  • If a provider truncates a windowless value, a change in the hidden suffix that leaves the visible text unchanged is not detected.
  • A provider that swaps in another element with the same type, bounds and index reads as the same structural path. A changed value still fails the two-read check or shows in the OCR.

Things to try to break:

  • Can a control reach observe_uia_only_value with a handle, skip the password guard, or get allow_editable outside the cell scope?
  • Can a uia_only_unverified or uia_only_structural field authorize a mask, satisfy valid_value_proof/valid_value_observation, or produce a digest equal to a proved read?
  • Can the windowless scope (_form_windowless_identity, _form_windowless_path) stay equal while the control is replaced, or bind a path that never reaches a RuntimeId?
  • Can an unreadable RuntimeId, or one that disappears mid-read, end up on the structural path?

2. fault-ambiguity trial 3: qualification_fault_receipt_binding_invalid

The Windows fault driver signs a settled frame. The replayer then took one more capture and required it to be byte-identical. A caret blinking in the note box between the two captures can make identical staging read as a different frame. The replayer now captures up to 30 times at 0.1 s intervals until its own capture's digest equals the signed one. Any mismatch still refuses, and a frame the driver did not sign is never treated as staged. The refusal now names the differing receipt keys (key names only, no values).

3. fault-stale-identity: the detector never saw the fault

The stale-identity overlay covered the whole screen, including the focused note box. The consequential click's revalidation captures through the native keyboard lease, and the lease's hit test failed under the overlay. The run halted safely before delivery, but with "native keyboard lease observation unavailable", not the stale-identity detector refusal (actuation_revalidation / actuation_observation_changed). So fault_detector_contract_error rejected the case, correctly. Earlier runs never reached this case.

The fixture changes; production refusal codes do not. A stale identity means the record on screen changed under the same control, so the overlay is now click-through: a layered window, transparent to hit testing, fully opaque (alpha 255, so a blinking caret under it can't change the frame). The keyboard lease and UI Automation still find the app's control, the pixels change, revalidation's identity gate refuses on the fresh frame, and the replayer records it as actuation_observation_changed with the receipt's frame digest. The agent's staging confirmation for this kind now requires the frame to change while the element at the save point stays the same. fault_detector_contract_error is unchanged.

Today's occluding overlay is kept as its own agent-only staging kind, occlusion (not a campaign fault). test_windows_qualification_campaign.py stages it before the campaign and requires the lease to refuse with "native keyboard lease observation unavailable" and the records to stay unchanged.

As a fallback, when the detector's own capture refuses after a staged fault, the replayer takes its own plain screenshot and records the receipt only if its SHA-256 equals the signed one. Otherwise nothing is recorded. The original refusal is always re-raised unchanged.

Tests

  • tests/test_approval_form_fields.py: the census window (seven windowless values unverified, edits still proved); each windowless kind unverified and unmasked; password, unsupported and missing status refuse; status turning to password between reads refuses; an editable cell refuses; disagreeing reads refuse; a cell reporting its grid's handle still needs a proof; the class never satisfies a proof check or a read-back; an unverified digest never equals a proved one; a cell with an empty RuntimeId binds by path under a grid that has one; no RuntimeId up to the window refuses; bounds changing between reads refuses; structural reads that disagree refuse; a structural password or unknown-status cell refuses; an unreadable RuntimeId never falls back to the path; a RuntimeId lost mid-read refuses; a structural value is never a proof or read-back; the three read kinds never compare equal; an editable grid cell under a grid binds as digest-only; an editable windowless Edit or Document in a grid still refuses; an editable cell outside a grid, list or table refuses; a read-only flag that flips between reads refuses; the window's editable title bar binds; header and title-bar classes read through GetPattern.
  • tests/test_windows_qualification_faults.py: a stale-identity surface stages only when the pixels change and the control under the point does not; occlusion and the other overlays need both to change.
  • tests/test_qualify_windows.py: a caret blink still binds the signed frame; an unsigned frame is never staged; a mismatched receipt names only the differing keys; a stale surface records the receipt on an exact plain-frame match and nothing otherwise, with the halt unchanged both ways; a plain-capture refusal is never rebound.
  • tests/e2e/test_windows_hosted_governed.py: when the approval halts before its request, the test prints the agent's closed refusal receipt and a type-only census of the window (no names or values).

Verification

  • Windows: desktop-replay run 46442237130 on 8b2ea9c (after fix(win_agent): recheck the bound scope around each source read, not each getter #2788's head was merged in and the probe change). test_standard_run_with_approval_hold_and_resume passed (approval, hold and resume). test_native_windows_campaign_reads_back_normal_and_all_faults passed (all 18 cases, plus the occlusion check). Every job in the run passed. The earlier run 46388088373 on 41431aa also passed.
  • Smoke checks: check_verdict_folds.py passes with the baseline unchanged. The file-size ratchet, legacy freeze and build_capabilities --check-pr pass.
  • Local: approval, native-value, Windows, qualification and import-surface suites (2161 passed on 41431aa; at 8b2ea9c, 531 passed across the approval, native-value, win-agent server, Windows qualification and fail-open suites). test_schema_surface fails the same way on the untouched base commit in this environment; this PR doesn't change those schemas.

…ned frame, and name the differing receipt keys
…approval digest as unverified, never masked or complete
…n frame when the lease refuses, on an exact digest match only
… surface, and keep occlusion as its own native refusal check
…rded identity box; report the windowless RuntimeId shape
@abrichr

abrichr commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: REQUEST CHANGES

From: Grok
Reviewed-Head: 41431aa

The safety logic holds up. One required check, smoke, fails because of this PR's own code, so I am requesting changes on that alone.

Scope

Tests run at the exact head (Linux, uv run --frozen pytest)

tests/test_approval_form_fields.py tests/test_windows_qualification_faults.py tests/test_qualify_windows.py tests/test_win_agent_server.py: 306 passed, 0 failed.

Adversarial probes (throwaway, not committed, all passed, meaning every attack was refused or behaved as intended)

  • Password flag flips to true during the Value read of a windowless cell: refused.
  • Structural cell whose child index changes between the two reads (row reordered): refused.
  • Windowless EditControl with an empty RuntimeId and an editable flag: value_not_read_only, because the cell scope excludes it.
  • Structural cell from another process id: refused.
  • Editable title bar whose parent is not the bound window: refused.
  • RuntimeId-bound (non-structural) editable grid cell: refused, because the editable exception is structural-path only.
  • Read-only windowless Edit with a RuntimeId: accepted as uia_only_unverified, never masked, never complete, no proof.
  • has_no_native_window with True, False, 0.0, "0", 5, a raising Element, or False as the raw handle: all false, so not windowless. Only None or int 0 counts.
  • observe_uia_only_value with no identity, or an identity that changes: value=None. Results always have complete=False and proof=None.
  • _observe_signed_frame: 30 mismatching captures return the last frame, whose digest never equals the signed one, so the receipt check refuses. An exact match stops early.

Findings on the key properties

  • Fail-open paths: I found none.
    • Unreadable state is never treated as approved. form_state_unreadable still stops the gate: gate.py treats a None form state as a stop.
    • An unreadable or malformed RuntimeId cannot select the structural path (_raw_runtime returns None).
    • A control with a RuntimeId never falls back to the path.
    • The password guard runs before and after each provider access.
    • The path must reach an ancestor below the window that has a RuntimeId, and the same process and window.
    • The three form-state kinds hash differently.
    • UNMASKED_KINDS keeps these fields out of masking.
    • The form_state_kind Literal is extended, and the gate compares the (kind, sha) tuple.
  • Documented limits: The structural binding is weak (same type, bounds and index reads as the same control), and a truncated provider value can hide a suffix change. Both are stated in code and in docs/LIMITS.md, and both only add detection on top of OCR.
  • Fault 2 (receipt binding): A frame the driver did not sign cannot be accepted. The loop ends early only on an exact SHA-256 match, and the receipt check still requires equality.
  • Fault 3 (stale-identity fixture and plain-frame fallback): The fallback records only on an exact digest match, swallows its own errors and always re-raises the detector's refusal. fault_detector_contract_error also requires refusal evidence at stage actuation_revalidation, code actuation_observation_changed, with detector_input_sha256 equal to the receipt's digest. A lease refusal for another reason therefore cannot pass as a detector refusal.
  • Generality gate: AGENTS.md says "Engine code stays application-agnostic: no code or tests that only work for one specific application inside packages/flow/openadapt_flow." The repo has no separate document titled "Generality gate". The added engine code keys on UIA control types, RuntimeId shape and structural scope, with no application names, strings or fixture values. A grep of the non-test additions for application names found nothing. The editable-cell exception is limited to grid, list and table cells, headers and the title bar, which is a general WinForms provider quirk. WPF-style grids with a RuntimeId and an editable flag still refuse, which fails closed.

Blocker: smoke fails on a PR-introduced fold-count rise

  • python3 packages/flow/scripts/check_verdict_folds.py passes at fix(win_agent): recheck the bound scope around each source read, not each getter #2788's head (141e3cef7): "Verdict folds OK".
  • At this head it fails on swallow (except Exception that returns or continues):
    • packages/flow/openadapt_flow/backends/win_agent/native_value.py has 6 against a baseline of 4.
    • packages/flow/openadapt_flow/backends/win_agent/server.py has 55 against a baseline of 49.
    • The new swallow sites are has_no_native_window, observe_uia_only_value, _raw_runtime, _child_index, _form_windowless_path, _windowless_cell_in_scope, _form_windowless_identity and _record_fault_on_plain_frame. The script also lists a few other files that rose, from the stale base.
  • Repro: check out the head, then run python3 packages/flow/scripts/check_verdict_folds.py from the repo root.
  • AGENTS.md says a PR whose CI fails is not done, and the baseline may only be lowered. Fix the swallow sites so they do not count, for example by using the verdict.settle or @verdict_site pattern the script asks for. Do not raise the baseline.

CI at this head (gh pr checks 2795)

  • Fail: smoke (above), review-verdict and Evaluate review verdict. The last two say "protected paths changed and there is no Grok or Codex review", and this review is the missing input.
  • Pass: flow core lint (ruff, mypy), gitleaks, dependency-review, the GTK save check, the freerdp round trip and the other lint, link and manifest jobs.
  • Still pending at last look: windows replay (Patient Notes, WindowsBackend), flow core unit shards 1 to 4, default-at-rest shards 1 to 4, critical, agent frameworks, verify facade, on-prem offline install.

Not run

  • The hosted Windows job and anything needing real UIA.
  • The pending CI jobs above.
  • The full flow unit suite (I ran only the four relevant files).

Non-blocking: re-review after the smoke fix and a rebase onto #2788's current head, if the fix touches the guarded files.

…ecked value, not an except-return

The verdict-fold check counted eight new except-Exception handlers that return
a default. The agent's server.py and native_value.py run as copied stdlib files
and cannot import openadapt_flow.verdict, so each now goes through one probe
that maps any provider exception to NOT_CHECKED, the same rule as
verdict.observe; every caller maps it to the refusal it returned before. The
replay fallback uses verdict.observe itself. Behaviour is unchanged.
@abrichr

abrichr commented Nov 30, 2026

Copy link
Copy Markdown
Member Author

Independent adversarial review: APPROVE

From: Grok
Reviewed-Head: 8b2ea9c

The previous REQUEST CHANGES at 41431aad9 was only for the smoke fold-count rise. That blocker is fixed at this head.

Scope

  • Re-review of the delta after 41431aad9: merge of fix(win_agent): recheck the bound scope around each source read, not each getter #2788's head 141e3cef7 (now an ancestor), plus a2047e691 (probe/sentinel) and 8b2ea9cfe (mapping test). git diff 141e3cef7..8b2ea9cfe is 16 files, +1942/-47, this PR's change only.
  • Read the PR body, AGENTS.md and packages/flow/AGENTS.md. The repo has no separate document titled "Generality gate"; the engine-generality script and packages/flow/CONTRIBUTING.md are the check.
  • Windows-only paths were reviewed by reading and by fakes only.

Tests run at the exact head (Linux)

  • python3 packages/flow/scripts/check_verdict_folds.py: Verdict folds OK (2615 baseline folds left).
  • python3 packages/flow/scripts/check_engine_generality.py: Engine generality OK (7 baseline hits left).
  • uv run --frozen pytest on tests/test_approval_form_fields.py tests/test_windows_qualification_faults.py tests/test_qualify_windows.py tests/test_win_agent_server.py tests/test_native_value_completeness.py tests/test_native_value_deployment.py: 410 passed, 0 failed.
  • ruff check on the three production files and the new test: pass.
  • CI packages / flow core lint (ruff, mypy) also passed at this head.

Adversarial probes (throwaway, not committed, all passed)

Previous probes still hold. New ones for the swallow fix:

  • probe / _probe turn a raising provider into NOT_CHECKED, and a successful read through unchanged.
  • has_no_native_window is True only for a COM null or integer 0. A raising Element, a raising handle, True, False, 0.0, "0" or 5 is not windowless.
  • _raw_runtime on a raising GetRuntimeId is None, not an empty RuntimeId, so a failure cannot select the structural path. A successful empty tuple still is empty.
  • _child_index on a raising parent or ControlsAreSame is None.
  • verdict.observe turns a record-path Exception (including a StructuralResolutionRefused) into Errored and does not raise; FailClosed still re-raises. _observe_signed_frame and _validate_fault_mutation raise RuntimeError or StructuralResolutionRefused, not FailClosed, so the caller still re-raises the detector's refusal.
  • Callers use is True or isinstance(..., _NotChecked) / isinstance(..., UnverifiedValue). They do not treat the truthy NOT_CHECKED sentinel as success.

The official test test_every_windowless_probe_maps_a_provider_error_to_its_refusal also passed.

Findings

  • The smoke blocker is gone. The eight new except Exception: return <default> sites are gone. server.py and native_value.py cannot import openadapt_flow.verdict, so each has one probe that maps any Exception to NOT_CHECKED. Every caller maps that to the same refusal as before (not windowless, None, False, or value_observation_unavailable). ValueUnavailable reasons still pass through _read_uia_only_value. The replay fallback uses verdict.observe and records nothing on Errored.
  • Fail-open paths: I found none in this delta. The earlier properties still hold: an unreadable RuntimeId cannot select the structural path; a control with a RuntimeId never falls back to the path; the password guard still runs first; unreadable form state still stops the gate; the plain-frame fallback still records only on an exact digest match and always leaves the original refusal in place.
  • Generality gate: Engine additions key on UIA control types, RuntimeId shape and structural scope. Comments mention the WinForms provider quirk, not an application. The generality script passes at this head.
  • Documented limits: Unchanged from the last review (structural binding is weak; a truncated provider value can hide a suffix change). Both are stated in docs/LIMITS.md and only add detection on top of OCR.

CI at this head (gh pr checks 2795)

  • The previous smoke failure is now a pass.
  • Fail: review-verdict and Evaluate review verdict, because the newest Grok review is still REQUEST CHANGES at 41431aad. This comment is the review of the current head.
  • Pass: smoke, flow core lint (ruff, mypy), flow core critical, gitleaks, dependency-review, the GTK save check, the freerdp round trip, verify facade, on-prem offline install, clean install/quickstart, and the other lint, link and manifest jobs.
  • Still pending at last look: the hosted windows replay job, flow core unit shards 1-4, and default-at-rest shards 1-4.

Not run

  • The hosted Windows job and anything needing real UIA.
  • The pending CI jobs above.
  • The full flow unit suite (I ran the six relevant files).

This PR is still based on #2788, not main. #2788 must merge first; I cannot merge either. A later head change should be re-reviewed.

Base automatically changed from fix/native-value-guard-bracket to main November 30, 2026 16:19
@abrichr
abrichr added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit fda882a Nov 30, 2026
57 of 58 checks passed
@abrichr
abrichr deleted the fix/approval-form-state-unreadable branch November 30, 2026 18:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant