diff --git a/jevdual/docs/native-row-trace.md b/jevdual/docs/native-row-trace.md new file mode 100644 index 00000000..6f267e48 --- /dev/null +++ b/jevdual/docs/native-row-trace.md @@ -0,0 +1,46 @@ +# Private row observation diagnostics + +This opt-in diagnostic observes the existing SDK row census. It adds no input route, +traversal, predicate, foreground exception or census budget. It is not a qualified +recipient and must never be used to authorize a click. + +Set `FOOTWORK_ROW_TRACE_CONFIG` to an absolute private JSON file containing exactly +`pid`, `window_id`, `url`, and `output`. The target must match the native session; +`url` must be the authorized exact ASCII HTTP numeric-loopback page, with an optional decimal port 1–65535 and no credentials, query, fragment, whitespace or backslash. The same strict authority grammar runs at typed and native SDK ingress before collection. `output` must be a new +absolute file in the private evidence directory. Run the normal public `start` +once using app/title selection and exact diagnostic PID/window configuration: start itself observes. Explicit `--pid` start currently observes twice and is unsuitable for this one-collection route. A discovery result that differs from the configuration refuses before the SDK collection; there is no fallback. Do not also call `look`. Native URL/title guards require their already-authorized durable route; `--url` is navigation and is excluded. +Configuration is checked before the SDK call; output is created exclusively with +mode 0600 after collection. An existing output refuses rather than overwriting it. + +The typed request adds `row_trace_url`; the typed reply adds `row_trace_json`. +The private artifact records the actual request, snapshot id, SDK stage, first +capture error or canonical graph/per-key results, proof attachment, typed element +proofs/token presence and projected candidate proofs. Object IDs are local census +integers. Raw AX pointers and actionable token strings are not retained. + +The graph is retained only if the existing census has exactly one web area with +the requested URL. Before scope is established, only request identity, fixed error +messages, node/role, budgets and counters survive. Unscoped page content and proofs +are withheld. `attribute_action_reads` counts the existing attribute/action reads; +it does not claim to count PID/window identity C calls. There are no extra AX calls. + +Limits: graph 2 MiB, SDK payload 3 MiB, private artifact 4 MiB; key/result lists 128, +attachment/typed elements 2048 and candidates 1000. Every exceeded bound marks +`truncated`; missing SDK data, scope mismatch and retention failures are distinct +from success. Truncation or missing evidence is not qualification. A whole SDK call +that fails before returning cannot supply the census trace; retain its public error +and treat the missing artifact as a stop, never repeat automatically. + +Bookkeeping costs CPU and memory. Existing 2-second/2048-node/4096-reference/500000- +comparison limits remain unchanged; a scheduling difference near a wall-time limit +cannot be excluded. Pure graph on/off checks compare the same decisions; no live AX +budget, latency or page topology is claimed from fixtures. Serialization and file +I/O occur after the AX collection. Callback ownership remains byte-identical. + +The authorized live use is one bound Tasks observation after reviewed delivery, +with Desktop's owner channel paused. No activation, input or functional repair is +part of this diagnostic. A start observation consumes the entire collection slot. + +Snapshot identity is compared across request, enclosing SDK response and embedded trace. A disagreement is invalid; missing/empty snapshot IDs are `snapshot_unproven`, with only explicitly unbound failure context retained and no graph or proofs. Diagnostics remain non-authoritative. + +Capture node/role fields are last-current context; a budget refusal before the next node assignment does not identify a new faulting object. Byte limits bound serialized retention, not peak process allocations. diff --git a/jevdual/docs/notebook/2026-11-17-native-row-trace.md b/jevdual/docs/notebook/2026-11-17-native-row-trace.md new file mode 100644 index 00000000..fee210e2 --- /dev/null +++ b/jevdual/docs/notebook/2026-11-17-native-row-trace.md @@ -0,0 +1,64 @@ +# Native row observation trace + +## RT1 · prediction · 2026-11-17 15:30 +Hypothesis: census002 is undecidable because the existing SDK silently drops row-capture/discovery failures and the public session retains only projected candidates. A bounded opt-in trace carried through the existing typed observation can expose the first failing stage without changing qualification, input, traversal or read budgets. +Test: commit failing offline tests before implementation for typed request/output propagation, capture/read/budget errors, per-key refusal, successful proof attachment, projection loss, missing retention and explicit truncation. Compare trace-on/off qualification results and AX read counts with identical fixtures. Preserve callback module, exact predicates and budget constants; build only the active SDK target. Independently review frozen diff, deliver exact hashes with rollback, then one authorized public start observation under serialized Desktop custody; never a second look or any action. +Predicts: diagnostic fields survive the actual ABI and private retention; generated proofs and refusal decisions agree on/off. One real trace identifies either an observed rejection or the precise missing boundary, retaining actual graph only when already collected and exact demo URL scoped. Collection emits no extra AX reads or input; serialization occurs afterward with bounded bytes and explicit truncation. +Against: tracing changes decision logic or read budgets, broadens scope, leaks pointers or unscoped content, silently truncates, fabricates graph relationships, or a failed trace is claimed as qualification. Any authority/input-semantic expansion stops the tranche. Time overhead remains measurable rather than an atomic timing guarantee. +Refs: /Volumes/External SSD/Footwork-native-row-evidence-20261117/census002-mechanism/DIAGNOSIS.md; /Volumes/External SSD/demoApps/demo/WORK_RECORD.md + +## RT2 · update · 2026-11-17 15:49 +Observed: typed contract red rejects row_trace_url; contract green69 and initial20 Python trace cases pass. Native production build and trace wheel build pass offline. Generated SDK module matches existing callback-overlay source; only contract bindings change. Source comparison preserves AX primitive call sites, reference admission and the press implementation. Public-start fixture performs one observation with zero input. +Inferred: diagnostics can expose the missing boundary without adding AX calls or changing predicates; fixed wall-time limits still make instrumentation overhead a real uncertainty. +Next: frozen-source affected checks and independent Sol review, rollback delivery, then one authorized live observation. RT1 stays open until actual trace and custody closure. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/{typed-red.txt,contract-green.txt,trace-cli-tests-rerun.txt,native-build.txt,wheel-build-resumed.txt,SOURCE-INVARIANTS.json}; failed root-directory test invocations and malformed ABI fixture retained separately, not qualification evidence. + +## RT3 · prediction · 2026-11-17 16:01 +Hypothesis: the SDK prefix check confuses userinfo with authority, while private retention does not bind an embedded trace to its enclosing snapshot. A shared strict numeric-loopback URL grammar at typed/native ingress and exact envelope matching will reject these review cases without changing valid local trace qualification or input. +Test: preserve red controls for loopback-looking remote authority, credentials, query/fragment, invalid port, and wrong/missing snapshot/PID/window; keep valid URL and matching envelope controls. Run actual Rust validation and private retention before and after, then focused ABI/integration checks and one independent correction review. +Predicts: invalid URL is refused before native preflight/collection; inconsistent envelope is invalid and missing snapshot is explicitly unproven. Valid local requests and matching traces retain unchanged discovery/input outcomes. +Against: a remote authority still enters diagnostics, genuine matching records lose classification, or the fix changes census predicates/read budgets/input. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/sol-review-b6c6163/REVIEW.md F1/F2. + +## RT4 · update · 2026-11-17 16:12 +Observed: actual typed Rust URL regression failed on the remote-authority example (1failed/1positive passed); retention regression failed6cases and kept1matching positive. Correction passes71contract tests and2macOS tests, including native ingress rejection before target validation/collection. Initial correction trace selection35passes. Source archive941c3b35 and trace2 wheel build pass offline; record ABI and callback module bytes are unchanged. Original reviewed SDK source restored to its checkpoint; correction source kept separately. +Next: final focused packaged checks and independent correction review; no installed/live change. RT3 remains open pending that review and checks; RT1 remains open pending the single real observation. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/{url-red.txt,envelope-red.txt,url-green.txt,ingress-green.txt,correction-trace-tests.txt,wheel-trace2-build.txt,sdk-correction-source}; sol-review-b6c6163/REVIEW.md. + +## RT5 · prediction · 2026-11-17 11:18 +Hypothesis: PR37 CI failed because the provenance test retains the row4 count of 15 files after diagnostics deliberately adds row_trace.rs and row_trace_probe.rs; hash-chain checks remain valid. +Test: reproduce the specific failing test on db09d2f, compare old/current manifest membership, update only its exact expected count and run the complete build/provenance test file plus notebook check. Keep the independently reviewed worktree frozen by using a separate CI worktree. +Predicts: the red failure is 17 versus 15; exactly the two diagnostic files explain the difference; all build/provenance tests pass with 17 while still checking every file hash. +Against: any unexpected added file, hash mismatch, or additional test failure means the count correction is insufficient; do not weaken provenance checks. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/CI-b6c6163-failed.txt; tests/test_cua_driver_build.py::test_local_native_patch_has_inspectable_hash_bound_provenance. + +## RT6 · update · 2026-11-17 11:18 +Resolves: RT5 = held +Observed: db09d2f reproduces the exact provenance count failure. The two added manifest members are row_trace.rs and row_trace_probe.rs. Updating only the expected count preserves all per-file/hash-chain assertions; the complete build/provenance file and notebook tests pass (see retained green log for count). Production and packaged artifact bytes remain identical to frozen db09d2f; its review worktree is untouched. +Next: await independent diagnostic correction review and fresh CI; no installation or live observation yet. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/ci-provenance-red.txt; /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/ci-provenance-green.txt. + +## RT7 · prediction · 2026-11-17 11:22 +Hypothesis: the snapshot-unproven branch loses only the producer truncation marker; carrying its strict boolean value preserves explicit diagnostic limits without retaining unbound content. +Test: reproduce the exact native sdk_trace_oversize fallback without inner snapshot ID, plus false/missing/nonboolean marker controls. Assert snapshot_unproven and no graph/proof/candidate data in every case, and strict true propagation only. Run trace, ABI, source-chain and packaging controls after the one-line correction. +Predicts: only the true-marker regression fails before correction; all cases pass afterward with unchanged binding refusals and input decisions. +Against: any unbound content becomes retained, malformed truthy values imply truncation, or other classification changes. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/sol-review-db09d2f/REVIEW.md F3. + +## RT8 · update · 2026-11-17 11:23 +Resolves: RT7 = held +Observed: actual native fallback shape fails only the true truncation case before correction (1 failed, 4 passed). One-line strict boolean propagation passes the eight-file packaged selection (199 passed); ruff and diff checks pass. Missing snapshot still withholds all graph/proof/candidate data. The initial red command used a wrong relative test path and collected no matching case; it is retained separately and is not red evidence. +Next: independent db09d2f review closes F1/F2 with no safety/input blocker. Its F3 recommendation is applied exactly here; F4 count correction is already checked. CI and rollback-preserving delivery remain, followed by one authorized observation; no input or live qualification is claimed. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/sol-review-db09d2f/REVIEW.md; /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/{truncation-red-valid.txt,truncation-green.txt,ci-provenance-green.txt}. + +## RT9 · prediction · 2026-11-17 11:45 +Hypothesis: the unrelated Linux mapping test over-specifies the final readiness reason. Session.await_probe may retain a genuine wm_not_servicing reply, then start a final probe with little shared deadline remaining and report probe_timeout. This still correctly forbids editor launch. CI observed only the final timeout; intermediate records were not uploaded, so their contents are not claimed. +Test: retain CI failure; inspect the unchanged probe loop and update only the test to require an actual retained false/wm_not_servicing reply, allow the two valid final reasons, and preserve no-editor/no-started/no-survivor assertions. Run static/notebook checks locally; Linux process-ownership execution remains CI-only on this Mac. No timeout or production behavior changes. +Predicts: Linux CI passes while still failing if every attempt times out, a ready reply is substituted, an editor starts, or children survive. The prior assertion is already disproved by the retained CI run; no aggregate Mac skip is counted as Linux verification. +Against: no retained explicit refusal exists in the failing scenario or corrected Linux CI fails again; then this hypothesis is insufficient and further probe diagnosis is required, not another permissive assertion. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/CI-186eb4c-failed.txt; python/jevdual/linux_session.py Session.await_probe and Session.run; tests/test_linux_session.py::test_editor_waits_for_window_manager_mapping_acknowledgement. + +## RT10 · update · 2026-11-17 11:46 +Observed: unchanged Linux probe source retains each attempt then reports the final reason at shared-deadline expiry. Corrected assertion requires a recorded false/wm_not_servicing reply and keeps no-editor/no-started/no-survivor checks. Ruff/diff checks pass; local notebook tests pass and the Linux case is explicitly skipped on macOS. No claim of executed Linux validation; RT9 remains open until CI. +Next: push test-only correction for actual Linux CI; no runtime/source archive/wheel change, deadline tuning or live input. +Refs: /Volumes/External SSD/Footwork-native-row-trace-evidence-20261117/linux-readiness-check.txt; CI-186eb4c-failed.txt in the same evidence directory. diff --git a/jevdual/pyproject.toml b/jevdual/pyproject.toml index ccddfde3..f7701423 100644 --- a/jevdual/pyproject.toml +++ b/jevdual/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ [project.optional-dependencies] desktop = [ - "cua-driver==0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4", # tests/contract/test_cua_driver_seams.py + "cua-driver==0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2", # tests/contract/test_cua_driver_seams.py "jeepney==0.9.0 ; sys_platform == 'linux'", # bounded AT-SPI exact-text access "pyobjc-framework-applicationservices>=12 ; sys_platform == 'darwin'", "pyobjc-framework-quartz>=12 ; sys_platform == 'darwin'", diff --git a/jevdual/python/jevdual/native.py b/jevdual/python/jevdual/native.py index 11b0ebf0..84bc39da 100644 --- a/jevdual/python/jevdual/native.py +++ b/jevdual/python/jevdual/native.py @@ -1201,6 +1201,9 @@ async def observe( # Scope must be checked before retaining pixels. This bounded route uses # AX observations only rather than capture a possibly changed page. capture_path = screenshot_path if self.observation_guard is None else None + from jevdual.row_trace import configuration, retain + + trace = configuration(self.pid, self.window_id) if self.window_controls else None snap = await self.driver.get_window_state( window_state_input( pid=self.pid, @@ -1217,6 +1220,7 @@ async def observe( # Compact SDK defaults omit the structured elements and static-text detail. full_output=True, **(row_snapshot_options() if self.window_controls else {}), + **({"row_trace_url": trace[1]} if trace else {}), ) ) self.last = None @@ -1315,6 +1319,10 @@ def qualify(element_role: str = role, element_frame: Any = frame) -> dict[str, A observed = dataclasses.replace(observed, visual_capture=capture, visual_capture_error=error) elif screenshot_path is not None: observed = dataclasses.replace(observed, visual_capture_error="scope_guard_withheld_pixels") + if trace: + retain(trace[0], {"pid": self.pid, "window_id": self.window_id, "row_trace_url": trace[1], + "qualify_rows": True, "full_output": True, "include_accessibility_tree": True, + "max_elements": max_elements, "query": query}, snap, observed.menu.candidates) self.last = observed return self.last diff --git a/jevdual/python/jevdual/row_trace.py b/jevdual/python/jevdual/row_trace.py new file mode 100644 index 00000000..0ecea453 --- /dev/null +++ b/jevdual/python/jevdual/row_trace.py @@ -0,0 +1,108 @@ +"""Private, bounded observation diagnostics. Never an input or qualification source.""" +from __future__ import annotations + +import json +import os +import re +from pathlib import Path +from urllib.parse import urlsplit + +MAX_BYTES = 4 * 1024 * 1024 + + +class _SnapshotUnproven(ValueError): + pass + + +def get(value, key): + return value.get(key) if isinstance(value, dict) else getattr(value, key, None) + + +def configuration(pid: int, window_id: int): + name = os.environ.get('FOOTWORK_ROW_TRACE_CONFIG') + if not name: + return None + path = Path(name) + if not path.is_absolute() or path.is_symlink() or path.stat().st_size > 4096: + raise ValueError('invalid row trace configuration file') + data = json.loads(path.read_text()) + if set(data) != {'pid', 'window_id', 'url', 'output'}: + raise ValueError('invalid row trace configuration fields') + if type(data['pid']) is not int or type(data['window_id']) is not int or (data['pid'], data['window_id']) != (pid, window_id): + raise ValueError('row trace target mismatch') + raw_url = data['url'] + if not isinstance(raw_url, str) or len(raw_url) > 2048 or not raw_url.isascii() or any(ord(c) <= 32 or ord(c) == 127 or c in '\\?#' for c in raw_url): + raise ValueError('invalid row trace URL') + url = urlsplit(raw_url) + if (not raw_url.startswith('http://') or url.scheme != 'http' + or not re.fullmatch(r'127\.0\.0\.1(?::[0-9]+)?', url.netloc) + or url.port == 0 or url.username or url.password or url.fragment or url.query): + raise ValueError('row trace requires an exact numeric-loopback page') + output = Path(data['output']) + if not output.is_absolute() or output.exists() or output.is_symlink() or output.parent.resolve() != output.parent: + raise ValueError('row trace requires a new regular private artifact') + return output, data['url'] + + +def retain(path, request, snapshot, candidates): + # O_EXCL/O_NOFOLLOW ensures missing evidence cannot be masked by an old file. + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) + with os.fdopen(fd, 'w') as stream: + result = {'version': 1, 'request': request, 'snapshot_id': get(snapshot, 'snapshot_id'), + 'input_performed': False, 'truncated': False, 'status': 'missing_sdk_trace'} + raw = get(snapshot, 'row_trace_json') + if isinstance(raw, str) and len(raw.encode()) > MAX_BYTES: + result.update(status='sdk_trace_oversize', truncated=True) + elif raw is not None: + try: + sdk = json.loads(raw) + if (type(sdk) is not dict or type(sdk.get('version')) is not int or sdk.get('version') != 1 + or any(type(request.get(key)) is not int for key in ('pid', 'window_id')) + or type(sdk.get('pid')) is not int or type(sdk.get('window_id')) is not int + or sdk.get('pid') != request.get('pid') or sdk.get('window_id') != request.get('window_id') + or sdk.get('scope_url') != request.get('row_trace_url')): + raise ValueError('trace binding mismatch') + if any(type(get(snapshot, key)) is not int or get(snapshot, key) != request.get(key) + for key in ('pid', 'window_id')): + raise ValueError('trace envelope identity mismatch') + snapshot_id, trace_id = get(snapshot, 'snapshot_id'), sdk.get('snapshot_id') + if not isinstance(snapshot_id, str) or not snapshot_id or not isinstance(trace_id, str) or not trace_id: + result.update(status='snapshot_unproven', sdk=None, truncated=sdk.get('truncated') is True, + unbound_summary={k: sdk[k] for k in ('status', 'error', 'node', 'role', 'budget', 'references', 'comparisons', 'reads') if k in sdk}) + raise _SnapshotUnproven('missing snapshot binding') + if snapshot_id != trace_id: + raise ValueError('trace snapshot mismatch') + result.update(status='retained', sdk=sdk, truncated=sdk.get('truncated') is True) + # Unscoped content is never retained, even if a faulty producer emits it. + if sdk.get('scope_matched') is not True: + result['sdk'] = {k: sdk[k] for k in ('version', 'pid', 'window_id', 'status', 'scope_url', 'scope_matched', 'truncated', + 'error', 'node', 'role', 'budget', 'references', 'comparisons', 'reads', 'request') if k in sdk} + result['status'] = 'scope_unproven' + else: + result['typed_elements'] = [ + {'index': get(e, 'element_index'), 'token_present': bool(get(e, 'element_token')), + 'expected_row': _proof(get(e, 'expected_row'))} + for e in (get(snapshot, 'elements') or [])[:2048] + ] + result['candidates'] = [ + {'id': get(c, 'id'), 'native_row_control': get(c, 'native_row_control')} + for c in candidates[:1000] + ] + if len(get(snapshot, 'elements') or []) > 2048 or len(candidates) > 1000: + result['truncated'] = True + except _SnapshotUnproven: + pass + except (TypeError, ValueError, AttributeError): + result.update(status='invalid_sdk_trace', sdk=None) + encoded = json.dumps(result, ensure_ascii=True) + if len(encoded.encode()) > MAX_BYTES: + encoded = json.dumps({'version': 1, 'request': request, 'snapshot_id': get(snapshot, 'snapshot_id'), + 'status': 'retention_oversize', 'truncated': True, 'input_performed': False}) + stream.write(encoded + '\n') + + +def _proof(value): + if value is None: + return None + from jevdual.native_row import FIELDS + return {k: get(value, k) for k in FIELDS} diff --git a/jevdual/tests/contract/test_cua_driver_seams.py b/jevdual/tests/contract/test_cua_driver_seams.py index a61865a4..e5553ae7 100644 --- a/jevdual/tests/contract/test_cua_driver_seams.py +++ b/jevdual/tests/contract/test_cua_driver_seams.py @@ -17,7 +17,7 @@ cd = pytest.importorskip("cua_driver") -PINNED_VERSION = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4" +PINNED_VERSION = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2" def _params(cls) -> set[str]: @@ -256,3 +256,21 @@ def test_row_recipient_records_match_native_abi(): assert "expected_row" in _params(cd.WindowElement) assert "row_receipt" in _params(cd.ActionResult) assert "qualify_rows" in _params(cd.GetWindowStateInput) + + +def test_row_trace_records_match_native_abi_without_driver(): + from cua_driver import _native_contract as native + from jevdual.effectors.cua import window_state_input + request_fields = {name: None for name, p in inspect.signature(cd.GetWindowStateInput).parameters.items() + if p.default is inspect.Parameter.empty} + request_fields.update(pid=77, window_id=9, qualify_rows=True, row_trace_url='http://127.0.0.1:5176/tasks') + request = window_state_input(**request_fields) + converter = native._UniffiFfiConverterTypeGetWindowStateInput + assert converter.lift(converter.lower(request)) == request + fields = {name: None for name, p in inspect.signature(cd.WindowStateOutput).parameters.items() + if p.default is inspect.Parameter.empty} + fields.update(pid=77, window_id=9, snapshot_id='s00000001', images=[], + row_trace_json='{"status":"capture_refused","error":"AXHeader unreadable"}') + response = cd.WindowStateOutput(**fields) + converter = native._UniffiFfiConverterTypeWindowStateOutput + assert converter.lift(converter.lower(response)) == response diff --git a/jevdual/tests/fixtures/row_trace_typed_red.rs b/jevdual/tests/fixtures/row_trace_typed_red.rs new file mode 100644 index 00000000..97bae781 --- /dev/null +++ b/jevdual/tests/fixtures/row_trace_typed_red.rs @@ -0,0 +1,13 @@ +#[cfg(test)] +mod row_trace_tests { + use super::*; + #[test] + fn row_trace_typed_fields_survive_wire() { + let request = serde_json::json!({"pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":"http://127.0.0.1:5176/tasks"}); + let typed: GetWindowStateInput = serde_json::from_value(request.clone()).unwrap(); + assert_eq!(serde_json::to_value(typed).unwrap()["row_trace_url"], request["row_trace_url"]); + let reply = serde_json::json!({"pid":77,"window_id":9,"row_trace_json":"{\"status\":\"capture_refused\"}"}); + let typed: WindowStateOutput = serde_json::from_value(reply.clone()).unwrap(); + assert_eq!(serde_json::to_value(typed).unwrap()["row_trace_json"],reply["row_trace_json"]); + } +} diff --git a/jevdual/tests/fixtures/row_trace_url_red.rs b/jevdual/tests/fixtures/row_trace_url_red.rs new file mode 100644 index 00000000..942088c5 --- /dev/null +++ b/jevdual/tests/fixtures/row_trace_url_red.rs @@ -0,0 +1,25 @@ + +#[cfg(test)] +mod row_trace_url_review_tests { + use super::*; + #[test] + fn invalid_trace_authorities_are_rejected() { + for url in ["http://127.0.0.1:5176@outside.example/tasks", "http://user@127.0.0.1:5176/tasks", + "http://127.0.0.1:5176/tasks?", "http://127.0.0.1:5176/tasks#", "http://127.0.0.1:0/tasks", + "http://127.0.0.1:65536/tasks", "http://127.0.0.1:abc/tasks", "http://127.0.0.1:/tasks", + "https://127.0.0.1:5176/tasks", "http://localhost:5176/tasks", "http://127.0.0.1.evil/tasks", + "http://127.0.0.1:5176\\@outside.example/tasks", "http://127.0.0.1:5176/ta\nks"] { + let typed: GetWindowStateInput = serde_json::from_value(serde_json::json!({ + "pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":url})).unwrap(); + assert!(typed.validate().is_err(), "admitted {url:?}"); + } + } + #[test] + fn exact_local_trace_and_no_trace_remain_valid() { + for url in [None, Some("http://127.0.0.1:5176/tasks"), Some("http://127.0.0.1/tasks")] { + let typed: GetWindowStateInput = serde_json::from_value(serde_json::json!({ + "pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":url})).unwrap(); + assert!(typed.validate().is_ok()); + } + } +} diff --git a/jevdual/tests/test_cua_driver_build.py b/jevdual/tests/test_cua_driver_build.py index a2781af3..64f1ab86 100644 --- a/jevdual/tests/test_cua_driver_build.py +++ b/jevdual/tests/test_cua_driver_build.py @@ -180,7 +180,7 @@ def test_local_native_patch_has_inspectable_hash_bound_provenance(): for name, hashes in foreground['files'].items(): assert hashlib.sha256(source.extractfile(name).read()).hexdigest() == hashes['after'] assert hashes['before'] != hashes['after'] - steps = (('ordinary-helptag', helptag, 2), ('connected-click', connected, 2), ('ref-locate', locate, 3), ('row-recipient', row, 15)) + steps = (('ordinary-helptag', helptag, 2), ('connected-click', connected, 2), ('ref-locate', locate, 3), ('row-recipient', row, 17)) for index, (step, record, count) in enumerate(steps): step_patch = (vendor / f'patches/{step}.patch').read_bytes() assert hashlib.sha256(step_patch).hexdigest() == record['patch_sha256'] diff --git a/jevdual/tests/test_linux_session.py b/jevdual/tests/test_linux_session.py index 12e4f064..b5cd3189 100644 --- a/jevdual/tests/test_linux_session.py +++ b/jevdual/tests/test_linux_session.py @@ -379,7 +379,12 @@ def test_editor_waits_for_window_manager_mapping_acknowledgement(tmp_path): assert target.run() == 1 assert 'editor' not in target.processes assert not (target.state / 'started').exists() - assert target.report['reason'] == 'wm_ready:wm_not_servicing' + # A final retry can exhaust the shared deadline after a genuine refusal. + # Require that refusal's retained reply, not a scheduler-dependent last reason. + assert target.report['reason'] in {'wm_ready:wm_not_servicing', 'wm_ready:probe_timeout'} + attempts = [json.loads(p.read_text()) for p in target.state.glob('probe-wm_ready-*.json')] + assert any(row.get('result') == {'ready': False, 'reason': 'wm_not_servicing'} + for row in attempts) assert not target.report['cleanup']['survivors'] diff --git a/jevdual/tests/test_native_row_trace.py b/jevdual/tests/test_native_row_trace.py new file mode 100644 index 00000000..e8a5c537 --- /dev/null +++ b/jevdual/tests/test_native_row_trace.py @@ -0,0 +1,232 @@ +"""Offline bounded diagnostic retention; no driver or AX calls.""" +import json +from types import SimpleNamespace + +import pytest + + +def test_trace_missing_sdk_retention_is_explicit(tmp_path): + from jevdual.row_trace import retain + path = tmp_path / 'trace.json' + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': 'http://127.0.0.1:5176/tasks'}, + SimpleNamespace(pid=77, window_id=9, snapshot_id='s1', elements=[], row_trace_json=None), []) + data = json.loads(path.read_text()) + assert data['status'] == 'missing_sdk_trace' + assert data['input_performed'] is False + assert path.stat().st_mode & 0o777 == 0o600 + + +@pytest.mark.parametrize('status', ['capture_refused', 'qualified', 'discovery_refused']) +def test_trace_preserves_actual_stage_and_projection(tmp_path, status): + from jevdual.row_trace import retain + path = tmp_path / 'trace.json' + trace = {'version': 1, 'pid': 77, 'window_id': 9, 'scope_url': 'http://127.0.0.1:5176/tasks', + 'status': status, 'truncated': False, 'scope_matched': True, 'snapshot_id': 's1', + 'graph': None, 'results': [], 'attachment': []} + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': trace['scope_url']}, + SimpleNamespace(pid=77, window_id=9, snapshot_id='s1', elements=[], row_trace_json=json.dumps(trace)), []) + data = json.loads(path.read_text()) + assert data['sdk'] == trace + assert data['snapshot_id'] == 's1' + assert data['status'] == 'retained' + + +def test_trace_oversize_and_existing_artifact_never_silently_succeed(tmp_path): + from jevdual.row_trace import MAX_BYTES, retain + path = tmp_path / 'trace.json' + snap = SimpleNamespace(pid=77, window_id=9, snapshot_id='s1', elements=[], row_trace_json='x' * (MAX_BYTES + 1)) + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': 'http://127.0.0.1:5176/tasks'}, snap, []) + data = json.loads(path.read_text()) + assert data['status'] == 'sdk_trace_oversize' and data['truncated'] + before = path.read_bytes() + with pytest.raises(FileExistsError): + retain(path, {}, snap, []) + assert path.read_bytes() == before + + +def test_unscoped_failure_keeps_reason_but_never_graph_or_proofs(tmp_path): + from jevdual.row_trace import retain + trace = {'version': 1, 'pid': 77, 'window_id': 9, 'scope_url': 'http://127.0.0.1:5176/tasks', + 'status': 'capture_refused', 'scope_matched': False, 'truncated': False, 'snapshot_id': 's1', + 'error': 'AXHeader has unsupported text type', 'node': 17, 'role': 'AXColumn', + 'reads': {'attribute_action_reads': 91, 'first_read_refusal': None}, + 'graph': {'unscoped': 'must not retain'}, 'keys': ['unscoped']} + path = tmp_path / 'trace.json' + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': trace['scope_url']}, + {'pid': 77, 'window_id': 9, 'snapshot_id': 's1', 'row_trace_json': json.dumps(trace), 'elements': ['private']}, ['private']) + data = json.loads(path.read_text()) + assert data['status'] == 'scope_unproven' + assert data['sdk']['error'] == trace['error'] and data['sdk']['reads'] == trace['reads'] + assert 'graph' not in data['sdk'] and 'keys' not in data['sdk'] + assert 'typed_elements' not in data and 'candidates' not in data + + +@pytest.mark.parametrize('field,value', [('pid', 78), ('pid', 77.0), ('window_id', 9.0), + ('scope_url', 'http://127.0.0.1:5176/other'), ('version', True)]) +def test_mismatched_sdk_scope_is_explicitly_invalid(tmp_path, field, value): + from jevdual.row_trace import retain + trace = {'version': 1, 'pid': 77, 'window_id': 9, 'scope_url': 'http://127.0.0.1:5176/tasks', + 'status': 'qualified', 'scope_matched': True, 'truncated': False} + request = {'pid': 77, 'window_id': 9, 'row_trace_url': trace['scope_url']} + trace[field] = value + path = tmp_path / 'trace.json' + retain(path, request, {'row_trace_json': json.dumps(trace)}, []) + assert json.loads(path.read_text())['status'] == 'invalid_sdk_trace' + + +def test_configuration_is_opt_in_exact_target_and_create_once(tmp_path, monkeypatch): + from jevdual.row_trace import configuration + monkeypatch.delenv('FOOTWORK_ROW_TRACE_CONFIG', raising=False) + assert configuration(77, 9) is None + path = tmp_path / 'config.json' + output = tmp_path / 'result.json' + data = {'pid': 77, 'window_id': 9, 'url': 'http://127.0.0.1:5176/tasks', 'output': str(output)} + path.write_text(json.dumps(data)) + monkeypatch.setenv('FOOTWORK_ROW_TRACE_CONFIG', str(path)) + assert configuration(77, 9) == (output, data['url']) + with pytest.raises(ValueError, match='target'): configuration(88, 9) + output.write_text('prior') + with pytest.raises(ValueError, match='new regular'): configuration(77, 9) + + +def test_projection_loss_and_count_truncation_are_visible(tmp_path): + from jevdual.row_trace import retain + trace = {'version': 1, 'pid': 77, 'window_id': 9, 'scope_url': 'http://127.0.0.1:5176/tasks', + 'status': 'qualified', 'scope_matched': True, 'truncated': False, 'snapshot_id': 's1', + 'attachment': [{'index': 3, 'generated_proof_present': True, 'proof_present': True, 'token_present': True}]} + path = tmp_path / 'trace.json' + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': trace['scope_url']}, + {'pid': 77, 'window_id': 9, 'snapshot_id': 's1', 'row_trace_json': json.dumps(trace), 'elements': [{'element_index': 3, 'element_token': 's1:3'}]}, + [{'id': 3, 'native_row_control': None}] * 1001) + data = json.loads(path.read_text()) + assert data['sdk']['attachment'][0]['proof_present'] + assert data['typed_elements'][0]['expected_row'] is None + assert data['candidates'][0]['native_row_control'] is None + assert len(data['candidates']) == 1000 and data['truncated'] + + +@pytest.mark.parametrize('fault', ['none', 'incomplete', 'read', 'header', 'duplicate']) +def test_actual_discovery_trace_preserves_result(fault): + import os + import subprocess + + from tests.test_native_row_sdk import graph_fixture, node + executable = os.environ.get('FOOTWORK_ROW_TRACE_PROBE') + if not executable: + pytest.skip('requires compiled trace adapter') + graph = graph_fixture() + if fault == 'incomplete': graph['complete'] = False + if fault == 'read': node(graph, 4)['error'] = 'AXHeader unreadable (-25212)' + if fault == 'header': node(graph, 30)['header'] = None + if fault == 'duplicate': node(graph, 21)['value'] = 'TASK-0' + result = subprocess.run([executable], input=json.dumps({'mode': 'trace', 'graph': graph, + 'pid': 77, 'window_id': 40335, 'recipient': 940}), text=True, capture_output=True, check=True) + data = json.loads(result.stdout) + assert data['on'] == data['off'] + if fault == 'none': assert 'Ok' in data['on'] and data['keys'][-1]['qualified'] + else: assert 'Err' in data['on'] + + +@pytest.mark.parametrize('enabled', [False, True]) +def test_public_start_observes_once_and_retains_only_when_enabled(world, fw, monkeypatch, tmp_path, enabled): + from tests.test_native_row_sdk import PROBE + if not PROBE: pytest.skip('requires compiled SDK row adapter') + from tests.test_native_row_sdk_cli import sdk_row_world + from tests.test_session_scenarios import _state + graph, sent = sdk_row_world(world, monkeypatch, 'complete') + url = 'http://127.0.0.1:5176/tasks' + graph['nodes'][1]['url'] = url + path = tmp_path / 'trace.json' + config = tmp_path / 'config.json' + config.write_text(json.dumps({'pid': 77, 'window_id': 40335, 'url': url, 'output': str(path)})) + if enabled: monkeypatch.setenv('FOOTWORK_ROW_TRACE_CONFIG', str(config)) + else: monkeypatch.delenv('FOOTWORK_ROW_TRACE_CONFIG', raising=False) + original = world.get_window_state + requests = [] + async def read(inp): + requests.append(inp) + snapshot = await original(inp) + if getattr(inp, 'row_trace_url', None): + snapshot['row_trace_json'] = json.dumps({'version': 1, 'pid': 77, 'window_id': 40335, + 'scope_url': url, 'scope_matched': True, 'status': 'qualified', 'truncated': False, 'snapshot_id': snapshot['snapshot_id'], + 'graph': graph, 'attachment': [{'index': 940, 'proof_present': True, 'token_present': True}]}) + return snapshot + monkeypatch.setattr(world, 'get_window_state', read) + code, out, err = fw('start', 'Observe exact row', '--app', 'Calculator', '--mode', 'exclusive_desktop') + assert code == 0, (out, err) + assert len(requests) == 1 and sent == [] + assert requests[0].qualify_rows is True and requests[0].full_output is True + offered = [c for c in _state(fw)['last_candidates'] if c['label'] == 'Open menu'] + assert len(offered) == 2 and all(c['native_row_control'] is not None for c in offered) + assert path.exists() is enabled + if enabled: + retained = json.loads(path.read_text()) + assert retained['status'] == 'retained' + assert any(e['expected_row'] for e in retained['typed_elements']) + assert any(c['native_row_control'] for c in retained['candidates']) + + +from tests import test_session_scenarios as scenarios + +fw = scenarios.fw +world = scenarios.world + + +@pytest.mark.parametrize('fault', ['sdk_id', 'envelope_id', 'pid', 'window', 'pid_float', 'window_float', 'request_float', 'missing_sdk_id', 'missing_envelope_id', 'matching']) +def test_review_trace_envelope_binding(tmp_path, fault): + from jevdual.row_trace import retain + trace = {'version': 1, 'pid': 77, 'window_id': 9, 'scope_url': 'http://127.0.0.1:5176/tasks', + 'status': 'qualified', 'scope_matched': True, 'truncated': False, 'snapshot_id': 's00000001'} + snap = {'pid': 77, 'window_id': 9, 'snapshot_id': 's00000001', 'elements': []} + if fault == 'sdk_id': trace['snapshot_id'] = 's00000002' + if fault == 'envelope_id': snap['snapshot_id'] = 's00000002' + if fault == 'pid': snap['pid'] = 88 + if fault == 'window': snap['window_id'] = 10 + if fault == 'pid_float': snap['pid'] = 77.0 + if fault == 'window_float': snap['window_id'] = 9.0 + if fault == 'missing_sdk_id': trace.pop('snapshot_id') + if fault == 'missing_envelope_id': snap['snapshot_id'] = None + snap['row_trace_json'] = json.dumps(trace) + path = tmp_path / 'trace.json' + request = {'pid': 77.0 if fault == 'request_float' else 77, 'window_id': 9, 'row_trace_url': trace['scope_url']} + retain(path, request, snap, []) + data = json.loads(path.read_text()) + expected = 'retained' if fault == 'matching' else 'snapshot_unproven' if fault.startswith('missing') else 'invalid_sdk_trace' + assert data['status'] == expected + if expected != 'retained': + assert not data.get('sdk') and 'typed_elements' not in data and 'candidates' not in data + + +@pytest.mark.parametrize('url', ['http://127.0.0.1:5176@outside.example/tasks', + 'http://user@127.0.0.1:5176/tasks', 'http://127.0.0.1:5176/tasks?', + 'http://127.0.0.1:5176/tasks#', 'http://127.0.0.1:65536/tasks', + 'http://127.0.0.1:0/tasks', 'http://127.0.0.1:/tasks', + 'http://127.0.0.1:5176\\@outside.example/tasks']) +def test_python_trace_config_matches_strict_authority(tmp_path, monkeypatch, url): + from jevdual.row_trace import configuration + path = tmp_path / 'config.json' + path.write_text(json.dumps({'pid': 77, 'window_id': 9, 'url': url, 'output': str(tmp_path / 'result.json')})) + monkeypatch.setenv('FOOTWORK_ROW_TRACE_CONFIG', str(path)) + with pytest.raises(ValueError): configuration(77, 9) + + +@pytest.mark.parametrize('marker', [True, False, None, 1, 'true']) +def test_unbound_native_oversize_fallback_preserves_strict_truncation(tmp_path, marker): + from jevdual.row_trace import retain + trace = {'version': 1, 'pid': 77, 'window_id': 9, + 'scope_url': 'http://127.0.0.1:5176/tasks', 'scope_matched': False, + 'status': 'sdk_trace_oversize', 'truncated': marker} + if marker is None: + del trace['truncated'] + path = tmp_path / 'trace.json' + retain(path, {'pid': 77, 'window_id': 9, 'row_trace_url': trace['scope_url']}, + {'pid': 77, 'window_id': 9, 'snapshot_id': 's1', + 'row_trace_json': json.dumps(trace), 'elements': ['must not retain']}, + ['must not retain']) + data = json.loads(path.read_text()) + assert data['status'] == 'snapshot_unproven' + assert data['truncated'] is (marker is True) + assert data['sdk'] is None + assert data['unbound_summary'] == {'status': 'sdk_trace_oversize'} + assert 'typed_elements' not in data and 'candidates' not in data + assert data['input_performed'] is False diff --git a/jevdual/uv.lock b/jevdual/uv.lock index dfa4288f..400d0cc3 100644 --- a/jevdual/uv.lock +++ b/jevdual/uv.lock @@ -731,7 +731,7 @@ wheels = [ [[package]] name = "cua-driver" -version = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4" +version = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2" source = { directory = "vendor/cua-driver" } [[package]] diff --git a/jevdual/vendor/cua-driver/PROVENANCE.md b/jevdual/vendor/cua-driver/PROVENANCE.md index 340fdfb1..634b4115 100644 --- a/jevdual/vendor/cua-driver/PROVENANCE.md +++ b/jevdual/vendor/cua-driver/PROVENANCE.md @@ -5,7 +5,7 @@ Reference commit: `5486b6246e4c807c0d793216e52df283671d9362` (release `cua-drive Source directory: `libs/cua-driver/python/src/cua_driver`. Python/native version: `0.46.0`. License: upstream MIT (`LICENSE.md`, copied as `LICENSE`). -Footwork distribution version: `0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4`. The published 0.46.0 wheel does not contain the required shutdown cleanup, foreground text focus, passive HelpTag, connected-node click and ref locate patches and cannot satisfy this exact dependency. The upstream Python `__version__` remains `0.46.0`. +Footwork distribution version: `0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2`. The published 0.46.0 wheel does not contain the required shutdown cleanup, foreground text focus, passive HelpTag, connected-node click and ref locate patches and cannot satisfy this exact dependency. The upstream Python `__version__` remains `0.46.0`. Three Python files remain byte-for-byte from the exact release source. The contract UniFFI module carries the row2 ABI; the SDK UniFFI module preserves exact landed fdbf48f callback ownership/drop hardening after regeneration. __init__.py additionally exports ExpectedRow and RowReceipt. The published macOS wheel has the same files except that its packaging removes the `x-release-please-version` comment from `__init__.py`. Generated records and native library must always be upgraded together. @@ -15,12 +15,12 @@ Three Python files remain byte-for-byte from the exact release source. The contr | `__main__.py` | `bcb78a6283dc6da69f3338879ae34a0f2dbeea3b444e4c3dd43f170d2922a387` | | `_daemon.py` | `f6ce97a08ab5c124ba0210b00e44bd652b41cca5a9ae20a511a6409093e8f01e` | | `_native.py` | `8bb3927dd6579d94468eb5c08b1700230359813074cd1959c2e226c318dd4828` | -| `_native_contract.py` | `2fabf55da93f67899246918e76516b8e8427340649d9fa1b6da152fc2862ec0f` | +| `_native_contract.py` | `0ab0c2376276f42ae1c7649c28a7de60c505733405f1993af1be9fe533e55cbc` | | `wrapper.py` | `cfd7abe6215aab7c1d8f66f2c15e6cd6ab7f150918de7b301b73c253e90a61d6` | ## Source archive -`native-source.tar.gz` SHA256: `c9ca9cd7d71779f33dc031f4bf38e1ad48518fce940fd1a06d79e8a7f56ae7ba` (6,444,769 bytes). It is the end of a six-step patch chain on the selected release source: cleanup2, focus1, helptag1, connected4, locate10, row4. Each step's manifest under `patches/` binds its base archive, patch, patched archive and changed files by SHA256. The focus1 archive (`804aeb8b2ba5b2b49772250a0435032bd9510835a56a33122d1cab531810cfb2`, 6,403,795 bytes) remains in Git history; `python3 scripts/cua_source_chain.py --base --output ` rebuilds this archive from it and checks every hash. +`native-source.tar.gz` SHA256: `941c3b35a6d467a14c64a4bfe5a4d6a84a67b032675b893b856cb8dcf256b52a` (6,448,145 bytes). It is the end of a six-step patch chain on the selected release source: cleanup2, focus1, helptag1, connected4, locate10, row4. Each step's manifest under `patches/` binds its base archive, patch, patched archive and changed files by SHA256. The focus1 archive (`804aeb8b2ba5b2b49772250a0435032bd9510835a56a33122d1cab531810cfb2`, 6,403,795 bytes) remains in Git history; `python3 scripts/cua_source_chain.py --base --output ` rebuilds this archive from it and checks every hash. The complete upstream release archive has SHA256 `032ce99f2e33154082cf854a1a04213e8a7b9eeae0e524564c7c6adb0ae93112`. The selected, unpatched native archive has SHA256 `257a36f5a793ad66d9c3e276709a7c81b667ed960ca5a3544e2d0ea43678fad1`. @@ -331,3 +331,8 @@ ExpectedRow version2 requires complete selected-row values aligned to explicitly Regeneration must preserve the landed fdbf48f foreign-future drop and remote-channel owning-loop implementation. `patches/python-callback-owner.patch` restores those exact bytes on the generated `_native.py`; its JSON manifest binds the generated, patch and restored hashes. From this vendor directory, after verifying the generated hash, apply `patch --batch --forward -p1 -i patches/python-callback-owner.patch` and verify the restored hash. Unexpected generator drift refuses this overlay rather than silently dropping it. `_native_contract.py` retains the independently generated row ABI. The packaged SDK module is byte-identical to fdbf48f. Tests execute the actual callback from another thread on an owned debug asyncio loop, test closed/absent loops and both remote object converters' owner-loop guard, and verify reversible overlay reconstruction against the packaged bytes. No Driver or OS input is created. + + +## Observation-only row trace + +The optional typed `row_trace_url` request and `row_trace_json` response carry bounded diagnostics through the existing observation. No new AX traversal or input endpoint is added. Existing census budget constants, recipient predicates and foreground checks remain unchanged. Diagnostic bookkeeping has CPU cost and cannot guarantee identical deadline behavior near a time limit. `_native.py` and its callback-ownership overlay are byte-identical; `_native_contract.py` is regenerated from the compiled trace ABI. See docs/native-row-trace.md for scope, retention and evidence limits. diff --git a/jevdual/vendor/cua-driver/build_support.py b/jevdual/vendor/cua-driver/build_support.py index 1361b9c9..654fb4b1 100644 --- a/jevdual/vendor/cua-driver/build_support.py +++ b/jevdual/vendor/cua-driver/build_support.py @@ -10,9 +10,9 @@ import tarfile from pathlib import Path, PurePosixPath -VERSION = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4" +VERSION = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2" SOURCE_COMMIT = "5486b6246e4c807c0d793216e52df283671d9362" -SOURCE_SHA256 = "c9ca9cd7d71779f33dc031f4bf38e1ad48518fce940fd1a06d79e8a7f56ae7ba" +SOURCE_SHA256 = "941c3b35a6d467a14c64a4bfe5a4d6a84a67b032675b893b856cb8dcf256b52a" TOOLCHAIN = "1.97.1" diff --git a/jevdual/vendor/cua-driver/native-source.tar.gz b/jevdual/vendor/cua-driver/native-source.tar.gz index bc969324..b9427cc2 100644 Binary files a/jevdual/vendor/cua-driver/native-source.tar.gz and b/jevdual/vendor/cua-driver/native-source.tar.gz differ diff --git a/jevdual/vendor/cua-driver/patches/row-recipient.json b/jevdual/vendor/cua-driver/patches/row-recipient.json index 29decc1f..5aaef5f1 100644 --- a/jevdual/vendor/cua-driver/patches/row-recipient.json +++ b/jevdual/vendor/cua-driver/patches/row-recipient.json @@ -1,6 +1,6 @@ { "base_archive_sha256": "5cf6ce6a66b06783d8798a3c90e9a82728266326c80b6beab9ff3efe0080ade9", - "patch_sha256": "cb58b96f5bae297000ab4f29f0b26cdec577fa3c4c62f8f68ea5b18e89514785", + "patch_sha256": "256bf7c6088e104badae0280945c0f8940f8c10f0223884e99166c38c022d4cf", "files": { "libs/cua-driver/rust/crates/cua-driver-contract/examples/row_guard_probe.rs": { "before": null, @@ -21,12 +21,12 @@ }, "libs/cua-driver/rust/crates/cua-driver-contract/src/row.rs": { "before": null, - "after": "c994cd1c0dbf5b33136f7f938965988180fdd0e13fecd5eb4dc82e2876bd5ec1", + "after": "035a854b7476451568990e402b6543fba01dab49dd247e2c5c4b7a2290afbc73", "mode": 420 }, "libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs": { "before": "7d119f50cfbc83d0d02d8e278835195de97694c0593e7f1fcda4d85ab0281d68", - "after": "1c457a60d6dc9146938774fa5e0ec88c5a38d3e38e8d2dc541533197fe7a0a1d" + "after": "25258c06e450d3f0116b659817d666e45d5836eec4ce1ec86a0fa3329e672548" }, "libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs": { "before": "5f39eca0bce322cf74262d6d4d36aa37402fd8d432c51ea47c377fcfe0e13686", @@ -46,11 +46,11 @@ }, "libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs": { "before": "d646cf0ff1fc6454130206484574d646205a9d9b2964416b9364d186418c381a", - "after": "05851f3175b4f1df9e3c9394196241dea8618c140965ac84dde80620b3cc068f" + "after": "41519f784cd401fb4b13b3753bf47d0b8aec6efa6c52501559a7874b650b1620" }, "libs/cua-driver/rust/crates/platform-macos/src/ax/row_guard.rs": { "before": null, - "after": "5424983d3efb02afbe5c8acf0a8726f4600c12196c76b414cc621765587e778b", + "after": "abe7100e3b9ea21f64adc3aa54008b9d110e7ae63afc2fe2ebfe50476a507f9c", "mode": 420 }, "libs/cua-driver/rust/crates/platform-macos/src/ax/snapshot.rs": { @@ -63,7 +63,17 @@ }, "libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs": { "before": "6a2659ace6595ba002a105a7a8f209221d58067b51106fa221872f64ca8c9c25", - "after": "67b74f56f30ce3dc9cacd96899fb9d1b4eef9a6ff75c5df64e8aef04b53984f7" + "after": "4b23054eb6046c7b74b1ce30f0e698b34b764a3bbbc7062de45424385d87897e" + }, + "libs/cua-driver/rust/crates/platform-macos/src/ax/row_trace.rs": { + "before": null, + "after": "ba2f072183828ed2de453048c1faa211d423fa763345409676aa2d8fc77ef704", + "mode": 420 + }, + "libs/cua-driver/rust/crates/cua-driver-contract/examples/row_trace_probe.rs": { + "before": null, + "after": "8034c5f399b687fa106a4cf8ed977c0d4ecf53236e6f2f7187a15817452b0e28", + "mode": 420 } }, "added_directories": [ @@ -71,8 +81,8 @@ ], "upstream_commit": "5486b6246e4c807c0d793216e52df283671d9362", "base_version": "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10", - "version": "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4", - "patched_archive_sha256": "c9ca9cd7d71779f33dc031f4bf38e1ad48518fce940fd1a06d79e8a7f56ae7ba", - "abi": "ExpectedRow version2 requires full row_values; held row_cells; regenerated native/Python bindings together", + "version": "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2", + "patched_archive_sha256": "941c3b35a6d467a14c64a4bfe5a4d6a84a67b032675b893b856cb8dcf256b52a", + "abi": "ExpectedRow version2 unchanged; optional row_trace_url input and row_trace_json output; callback overlay unchanged", "toolchain": "1.97.1" } diff --git a/jevdual/vendor/cua-driver/patches/row-recipient.patch b/jevdual/vendor/cua-driver/patches/row-recipient.patch index d55d44e1..add1bf97 100644 --- a/jevdual/vendor/cua-driver/patches/row-recipient.patch +++ b/jevdual/vendor/cua-driver/patches/row-recipient.patch @@ -178,7 +178,7 @@ + "row_receipt", --- /dev/null +++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/row.rs -@@ -0,0 +1,684 @@ +@@ -0,0 +1,697 @@ +//! Bounded row-recipient predicates. Graphs are SDK-owned observations, never public tool inputs. +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; @@ -760,6 +760,12 @@ + window: u64, + recipient: u64, +) -> Result { ++ discover_row_traced(graph, pid, window, recipient, None) ++} ++pub fn discover_row_traced( ++ graph: &RowGraph, pid: u32, window: u64, recipient: u64, ++ mut trace: Option<&mut Vec>, ++) -> Result { + let c = Census::new(graph, pid, window)?; + let table = c + .ancestors(recipient)? @@ -768,9 +774,16 @@ + .ok_or("not a table action")?; + for header in c.table(table)?.1 { + if !header.is_empty() { -+ if let Ok(binding) = c.qualify(recipient, &header) { -+ return Ok(binding); ++ let result = c.qualify(recipient, &header); ++ if let Some(events) = trace.as_deref_mut() { ++ if events.len() < 128 { ++ events.push(serde_json::json!({"recipient": recipient, "key": header, ++ "error": result.as_ref().err(), "qualified": result.is_ok()})); ++ } else if events.len() == 128 { ++ events.push(serde_json::json!({"truncated": true})); ++ } + } ++ if let Ok(binding) = result { return Ok(binding); } + } + } + Err("no unambiguous named key column".into()) @@ -865,16 +878,84 @@ +} --- a/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs +++ b/libs/cua-driver/rust/crates/cua-driver-contract/src/windows.rs -@@ -128,0 +129,5 @@ +@@ -128,0 +129,9 @@ + #[serde(default, skip_serializing_if = "Option::is_none")] + #[uniffi(default = None)] + /// Row predicates are enforced by foreground left AXPress click only. + /// Other token tools do not enforce this predicate; unavailable proof is omitted. + pub qualify_rows: Option, -@@ -291,0 +297,3 @@ ++ /// Private observation diagnostics, scoped to an exact numeric-loopback document. ++ #[serde(default, skip_serializing_if = "Option::is_none")] ++ #[uniffi(default = None)] ++ pub row_trace_url: Option, +@@ -147,0 +157,17 @@ ++/// Parse the closed diagnostic URL grammar without normalizing alternate hosts. ++/// Only literal HTTP numeric-loopback authority, an optional nonzero u16 port, ++/// and an ASCII path are admitted. Userinfo, query, fragment and URL backslash ++/// reinterpretation are deliberately unsupported. ++pub fn validate_row_trace_url(value: &str) -> Result<(), String> { ++ let invalid = || "row_trace_url requires exact HTTP numeric-loopback authority without credentials, query or fragment".to_owned(); ++ if value.len() > 2048 || value.bytes().any(|b| !b.is_ascii() || b.is_ascii_control() ++ || matches!(b, b' ' | b'\\' | b'?' | b'#')) { return Err(invalid()); } ++ let rest = value.strip_prefix("http://").ok_or_else(invalid)?; ++ let authority = rest.split('/').next().ok_or_else(invalid)?; ++ if authority == "127.0.0.1" { return Ok(()); } ++ let port = authority.strip_prefix("127.0.0.1:").ok_or_else(invalid)?; ++ if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) ++ || !port.parse::().is_ok_and(|p| p > 0) { return Err(invalid()); } ++ Ok(()) ++} ++ +@@ -150,0 +177 @@ ++ if let Some(url) = &self.row_trace_url { validate_row_trace_url(url)?; } +@@ -291,0 +319,3 @@ + #[serde(default, skip_serializing_if = "Option::is_none")] + #[uniffi(default = None)] + pub expected_row: Option, +@@ -301,0 +332,3 @@ ++ #[serde(default, skip_serializing_if = "Option::is_none")] ++ #[uniffi(default = None)] ++ pub row_trace_json: Option, +@@ -517,0 +551,39 @@ ++ ++#[cfg(test)] ++mod row_trace_tests { ++ use super::*; ++ #[test] ++ fn row_trace_typed_fields_survive_wire() { ++ let request = serde_json::json!({"pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":"http://127.0.0.1:5176/tasks"}); ++ let typed: GetWindowStateInput = serde_json::from_value(request.clone()).unwrap(); ++ assert_eq!(serde_json::to_value(typed).unwrap()["row_trace_url"], request["row_trace_url"]); ++ let reply = serde_json::json!({"pid":77,"window_id":9,"row_trace_json":"{\"status\":\"capture_refused\"}"}); ++ let typed: WindowStateOutput = serde_json::from_value(reply.clone()).unwrap(); ++ assert_eq!(serde_json::to_value(typed).unwrap()["row_trace_json"],reply["row_trace_json"]); ++ } ++} ++ ++#[cfg(test)] ++mod row_trace_url_review_tests { ++ use super::*; ++ #[test] ++ fn invalid_trace_authorities_are_rejected() { ++ for url in ["http://127.0.0.1:5176@outside.example/tasks", "http://user@127.0.0.1:5176/tasks", ++ "http://127.0.0.1:5176/tasks?", "http://127.0.0.1:5176/tasks#", "http://127.0.0.1:0/tasks", ++ "http://127.0.0.1:65536/tasks", "http://127.0.0.1:abc/tasks", "http://127.0.0.1:/tasks", ++ "https://127.0.0.1:5176/tasks", "http://localhost:5176/tasks", "http://127.0.0.1.evil/tasks", ++ "http://127.0.0.1:5176\\@outside.example/tasks", "http://127.0.0.1:5176/ta\nks"] { ++ let typed: GetWindowStateInput = serde_json::from_value(serde_json::json!({ ++ "pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":url})).unwrap(); ++ assert!(typed.validate().is_err(), "admitted {url:?}"); ++ } ++ } ++ #[test] ++ fn exact_local_trace_and_no_trace_remain_valid() { ++ for url in [None, Some("http://127.0.0.1:5176/tasks"), Some("http://127.0.0.1/tasks")] { ++ let typed: GetWindowStateInput = serde_json::from_value(serde_json::json!({ ++ "pid":77,"window_id":9,"qualify_rows":true,"row_trace_url":url})).unwrap(); ++ assert!(typed.validate().is_ok()); ++ } ++ } ++} --- a/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs +++ b/libs/cua-driver/rust/crates/cua-driver-core/src/action_record.rs @@ -350,0 +351 @@ @@ -936,11 +1017,12 @@ + rows: Default::default(), --- a/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs +++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/mod.rs -@@ -29,0 +30 @@ +@@ -29,0 +30,2 @@ +pub(crate) mod row_guard; ++pub(crate) mod row_trace; --- /dev/null +++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/row_guard.rs -@@ -0,0 +1,425 @@ +@@ -0,0 +1,454 @@ +//! SDK-owned row census and actual-token press. No public raw AX entry point. +use super::bindings::*; +use core_foundation::{ @@ -951,7 +1033,7 @@ + url::CFURL, +}; +use cua_driver_contract::row::{ -+ discover_row, dispatch_row, RowBinding, RowGraph, RowNode, RowReceipt, ++ discover_row_traced, dispatch_row, RowBinding, RowGraph, RowNode, RowReceipt, +}; +use cua_driver_contract::ExpectedRow; +use std::collections::{BTreeMap, BTreeSet}; @@ -988,6 +1070,8 @@ + buckets: BTreeMap>, + comparisons: usize, + deadline: Instant, ++ current_node: Option, ++ current_role: String, +} +impl Capture { + fn new(seed: &[OwnedAx]) -> Self { @@ -996,6 +1080,8 @@ + buckets: BTreeMap::new(), + comparisons: 0, + deadline: Instant::now() + Duration::from_secs(2), ++ current_node: None, ++ current_role: String::new(), + }; + for (i, el) in c.objects.iter().enumerate() { + c.buckets @@ -1093,12 +1179,15 @@ + if nodes.len() >= 2048 || Instant::now() > self.deadline { + return Err("row census incomplete".into()); + } ++ self.current_node = Some(id); ++ self.current_role.clear(); + let el = self.objects[id as usize].ptr(); + let mut owner = 0; + if unsafe { AXUIElementGetPid(el, &mut owner) } != 0 || owner as u32 != pid { + return Err("row peer PID mismatch".into()); + } + let role = text(el, "AXRole", false)?.ok_or("row peer role missing")?; ++ self.current_role = role.clone(); + let parent = if id == root { + None + } else { @@ -1188,6 +1277,7 @@ + let mut value = std::ptr::null(); + let error = + unsafe { AXUIElementCopyAttributeValue(el, key_cf.as_concrete_TypeRef(), &mut value) }; ++ super::row_trace::read(key, (error != 0 && !(optional && (error == kAXErrorNoValue || error == kAXErrorAttributeUnsupported))).then_some(error)); + if error != 0 { + if !value.is_null() { + unsafe { CFRelease(value) }; @@ -1232,6 +1322,7 @@ +fn actions(el: AXUIElementRef) -> Result, String> { + let mut names = std::ptr::null(); + let error = unsafe { AXUIElementCopyActionNames(el, &mut names) }; ++ super::row_trace::read("AXActions", (error != 0 || names.is_null()).then_some(error)); + if error != 0 || names.is_null() { + if !names.is_null() { + unsafe { CFRelease(names as _) }; @@ -1257,52 +1348,72 @@ +} + +pub fn qualify_snapshot( -+ nodes: &[super::tree::AXNode], -+ pid: u32, -+ window_id: u64, -+) -> BTreeMap> { -+ let mut qualified = BTreeMap::new(); -+ let Some(first) = nodes.iter().find(|n| { -+ n.element_index.is_some() -+ && n.in_web_content -+ && matches!(n.role.as_str(), "AXButton" | "AXPopUpButton") -+ }) else { -+ return qualified; -+ }; -+ let Ok(Some(win)) = read(first.element_ptr as AXUIElementRef, "AXWindow", false) else { -+ return qualified; -+ }; -+ if win.type_of() != unsafe { AXUIElementGetTypeID() } { -+ return qualified; -+ } -+ let mut capture = Capture::new(&[]); -+ let Ok(graph) = capture.graph(win.as_CFTypeRef() as AXUIElementRef, pid, window_id) else { -+ return qualified; -+ }; -+ let mut bindings = Vec::new(); -+ for n in nodes.iter().filter(|n| { -+ n.element_index.is_some() -+ && n.in_web_content -+ && matches!(n.role.as_str(), "AXButton" | "AXPopUpButton") -+ }) { -+ let Ok(id) = capture.intern(n.element_ptr as AXUIElementRef) else { -+ return BTreeMap::new(); ++ nodes: &[super::tree::AXNode], pid: u32, window_id: u64, trace_url: Option<&str>, ++) -> (BTreeMap>, Option) { ++ use serde_json::json; ++ let mut report = json!({"version":1,"pid":pid,"window_id":window_id,"scope_url":trace_url, ++ "scope_matched":false,"truncated":false,"status":"no_eligible_node", ++ "budget":{"seconds":2,"nodes":2048,"references":4096,"comparisons":500000}}); ++ super::row_trace::begin(trace_url.is_some()); ++ let result = (|| { ++ let mut qualified = BTreeMap::new(); ++ let Some(first) = nodes.iter().find(|n| n.element_index.is_some() && n.in_web_content ++ && matches!(n.role.as_str(), "AXButton" | "AXPopUpButton")) else { return qualified; }; ++ let win = match read(first.element_ptr as AXUIElementRef, "AXWindow", false) { ++ Ok(Some(win)) => win, ++ other => { report["status"] = json!("window_read_refused"); ++ report["error"] = json!(other.err().unwrap_or_else(|| "missing window".into())); return qualified; } + }; -+ if let Ok(binding) = discover_row(&graph, pid, window_id, id) { -+ bindings.push((n.element_index.unwrap(), binding)); ++ if win.type_of() != unsafe { AXUIElementGetTypeID() } { ++ report["status"] = json!("window_type_refused"); return qualified; + } -+ } -+ let objects = Arc::new(capture.objects); -+ for (id, binding) in bindings { -+ qualified.insert( -+ id, -+ Arc::new(QualifiedRow { -+ binding, -+ objects: objects.clone(), -+ }), -+ ); -+ } -+ qualified ++ let mut capture = Capture::new(&[]); ++ let graph = match capture.graph(win.as_CFTypeRef() as AXUIElementRef, pid, window_id) { ++ Ok(graph) => graph, ++ Err(error) => { report["status"] = json!("capture_refused"); report["error"] = json!(error); ++ report["node"] = json!(capture.current_node); report["role"] = json!(capture.current_role); ++ report["references"] = json!(capture.objects.len()); report["comparisons"] = json!(capture.comparisons); ++ return qualified; } ++ }; ++ let urls: Vec<_> = graph.nodes.iter().filter(|n| n.role == "AXWebArea").map(|n| n.url.as_deref()).collect(); ++ let scoped = trace_url.is_some() && urls.len() == 1 && urls[0] == trace_url; ++ let mut events = Vec::new(); ++ let mut results = Vec::new(); ++ let mut bindings = Vec::new(); ++ for n in nodes.iter().filter(|n| n.element_index.is_some() && n.in_web_content ++ && matches!(n.role.as_str(), "AXButton" | "AXPopUpButton")) { ++ let id = match capture.intern(n.element_ptr as AXUIElementRef) { ++ Ok(id) => id, ++ Err(error) => { report["status"] = json!("intern_refused"); report["error"] = json!(error); return BTreeMap::new(); } ++ }; ++ let result = discover_row_traced(&graph, pid, window_id, id, scoped.then_some(&mut events)); ++ if scoped { ++ if results.len() < 128 { results.push(json!({"index":n.element_index,"recipient":id,"error":result.as_ref().err(),"qualified":result.is_ok()})); } ++ else { report["truncated"] = json!(true); } ++ } ++ if let Ok(binding) = result { bindings.push((n.element_index.unwrap(), binding)); } ++ } ++ // All AX reads and reference admissions above are complete before serialization. ++ if trace_url.is_some() { ++ report["scope_matched"] = json!(scoped); ++ report["status"] = json!(if bindings.is_empty() { "discovery_refused" } else { "qualified" }); ++ report["references"] = json!(capture.objects.len()); report["comparisons"] = json!(capture.comparisons); ++ if scoped { ++ match super::row_trace::limited(&graph, 2 * 1024 * 1024) { ++ Some(graph) => report["graph"] = serde_json::from_str(&graph).unwrap(), ++ None => { report["graph"] = serde_json::Value::Null; report["truncated"] = json!(true); } ++ } ++ if events.len() > 128 { report["truncated"] = json!(true); } ++ report["keys"] = json!(events); report["results"] = json!(results); ++ } ++ } ++ let objects = Arc::new(capture.objects); ++ for (id, binding) in bindings { qualified.insert(id, Arc::new(QualifiedRow { binding, objects: objects.clone() })); } ++ qualified ++ })(); ++ let metrics = super::row_trace::finish(); ++ if trace_url.is_some() { report["reads"] = metrics; } ++ (result, trace_url.map(|_| report)) +} + +pub fn press( @@ -1456,23 +1567,56 @@ + } --- a/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs +++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/get_window_state.rs -@@ -73,0 +74 @@ +@@ -73,0 +74,2 @@ ++ "row_trace_url": { "type": "string", "description": "Bounded observation diagnostics for this exact numeric-loopback document only; no input authority." }, + "qualify_rows": { "type": "boolean", "description": "Opt in to SDK-owned row recipient predicates enforced by foreground left AXPress click only. Other token tools are not qualified by this option; unavailable proof is omitted." }, -@@ -362,0 +364 @@ +@@ -194,0 +197,11 @@ ++ // Validate before native preflight, screenshot or accessibility collection. ++ let trace_url = match args.get("row_trace_url") { ++ None | Some(Value::Null) => None, ++ Some(Value::String(url)) => { ++ if let Err(error) = cua_driver_contract::validate_row_trace_url(url) { ++ return ToolResult::error(error); ++ } ++ Some(url.clone()) ++ } ++ Some(_) => return ToolResult::error("row_trace_url must be a string"), ++ }; +@@ -363 +376,3 @@ +- let (tree_result, prepared_snapshot) = if want_tree { + let qualify_rows = args.get("qualify_rows").and_then(Value::as_bool) == Some(true); -@@ -379 +381,4 @@ ++ let collect_trace = trace_url.clone(); ++ let (tree_result, prepared_snapshot, mut row_trace) = if want_tree { +@@ -379,2 +394,6 @@ - let payload = crate::ax::snapshot::AxSnapshot::from_nodes(&tree.nodes); +- (tree, payload) + let mut payload = crate::ax::snapshot::AxSnapshot::from_nodes(&tree.nodes); ++ let mut trace = None; + if qualify_rows && !observation_only { -+ payload.rows = crate::ax::row_guard::qualify_snapshot(&tree.nodes, pid as u32, u64::from(window_id)); ++ (payload.rows, trace) = crate::ax::row_guard::qualify_snapshot(&tree.nodes, pid as u32, u64::from(window_id), collect_trace.as_deref()); + } -@@ -402,0 +408,2 @@ ++ (tree, payload, trace) +@@ -387 +406 @@ +- Ok(Ok((tree, payload))) => (Some(tree), Some(payload)), ++ Ok(Ok((tree, payload, trace))) => (Some(tree), Some(payload), trace), +@@ -400 +419 @@ +- (None, None) ++ (None, None, None) +@@ -402 +421,9 @@ +- ++ if let Some(url) = trace_url.as_ref() { ++ if row_trace.is_none() { row_trace = Some(serde_json::json!({"version":1,"pid":pid,"window_id":window_id,"scope_url":url, ++ "scope_matched":false,"truncated":false,"status":"qualification_not_run"})); } ++ if let Some(trace) = row_trace.as_mut() { trace["request"] = serde_json::json!({"qualify_rows":qualify_rows, ++ "observation_only":observation_only,"want_tree":want_tree,"max_elements":max_elements,"max_depth":max_depth,"timeout_ms":timeout_ms}); } ++ } ++ + let row_predicates: std::collections::BTreeMap = prepared_snapshot.as_ref() + .map(|p| p.rows.iter().map(|(i, q)| (*i, q.binding.predicate.clone())).collect()).unwrap_or_default(); -@@ -671 +678 @@ +@@ -671 +698 @@ - let elements_json: Vec = match (snapshot_id, tree_result.as_ref()) { + let mut elements_json: Vec = match (snapshot_id, tree_result.as_ref()) { -@@ -678,0 +686,7 @@ +@@ -678,0 +706,18 @@ + for entry in &mut elements_json { + if entry.get("element_token").and_then(Value::as_str).is_some() { + if let Some(proof) = entry.get("element_index").and_then(Value::as_u64).and_then(|i| row_predicates.get(&(i as usize))) { @@ -1480,3 +1624,179 @@ + } + } + } ++ if let Some(trace) = row_trace.as_mut() { ++ if trace["scope_matched"] == true { ++ let attachment: Vec<_> = elements_json.iter().take(2048).map(|e| serde_json::json!({ ++ "index":e.get("element_index"),"token_present":e.get("element_token").and_then(Value::as_str).is_some(), ++ "proof_present":e.get("expected_row").is_some(), ++ "generated_proof_present":e.get("element_index").and_then(Value::as_u64).is_some_and(|i|row_predicates.contains_key(&(i as usize))) ++ })).collect(); ++ if elements_json.len() > 2048 { trace["truncated"] = serde_json::json!(true); } ++ trace["attachment"] = serde_json::json!(attachment); ++ } ++ } +@@ -716,0 +762,7 @@ ++ if let Some(trace) = row_trace.as_mut() { ++ trace["snapshot_id"] = serde_json::json!(snapshot_id.map(cua_driver_core::element_token::format_snapshot_id)); ++ let encoded = crate::ax::row_trace::limited(trace, 3 * 1024 * 1024).unwrap_or_else(|| serde_json::json!({ ++ "version":1,"pid":pid,"window_id":window_id,"scope_url":trace_url,"scope_matched":false, ++ "truncated":true,"status":"sdk_trace_oversize"}).to_string()); ++ structured["row_trace_json"] = serde_json::json!(encoded); ++ } +@@ -1650,0 +1703,15 @@ ++ #[tokio::test] ++ async fn row_trace_rejects_invalid_scope_before_target_or_collection() { ++ let tool = GetWindowStateTool::new(Arc::new(ToolState::new(false, false, None))); ++ for value in [json!("http://127.0.0.1:5176@outside.example/tasks"), ++ json!("http://127.0.0.1:0/tasks"), json!("http://127.0.0.1:5176/tasks?"), json!(42)] { ++ // No PID/window: a late check would return the target-field error instead. ++ let result = tool.invoke(json!({"row_trace_url":value})).await; ++ let encoded = serde_json::to_string(&result).unwrap(); ++ assert!(encoded.contains("row_trace_url"), "{encoded}"); ++ assert!(!encoded.contains("Missing required"), "{encoded}"); ++ } ++ let result = tool.invoke(json!({"row_trace_url":"http://127.0.0.1:5176/tasks"})).await; ++ assert!(serde_json::to_string(&result).unwrap().contains("Missing required")); ++ } ++ +--- /dev/null ++++ b/libs/cua-driver/rust/crates/platform-macos/src/ax/row_trace.rs +@@ -0,0 +1,43 @@ ++//! Bounded diagnostic bookkeeping only: no AX calls, input or qualification decisions. ++use serde::Serialize; ++use serde_json::{json, Value}; ++use std::cell::RefCell; ++use std::io::{self, Write}; ++ ++thread_local! { static READS: RefCell)>> = const { RefCell::new(None) }; } ++pub fn begin(enabled: bool) { READS.with(|r| *r.borrow_mut() = enabled.then_some((0, None))); } ++pub fn read(attribute: &str, refused_status: Option) { ++ READS.with(|r| { if let Some((count, failure)) = r.borrow_mut().as_mut() { ++ *count += 1; ++ if failure.is_none() { if let Some(status) = refused_status { ++ *failure = Some(json!({"attribute": attribute, "status": status})); ++ }} ++ }}); ++} ++pub fn finish() -> Value { READS.with(|r| match r.borrow_mut().take() { ++ Some((count, failure)) => json!({"attribute_action_reads": count, "first_read_refusal": failure}), ++ None => Value::Null, ++}) } ++struct Bounded { bytes: Vec, limit: usize } ++impl Write for Bounded { ++ fn write(&mut self, bytes: &[u8]) -> io::Result { ++ if self.bytes.len() + bytes.len() > self.limit { return Err(io::Error::other("trace size limit")); } ++ self.bytes.extend_from_slice(bytes); Ok(bytes.len()) ++ } ++ fn flush(&mut self) -> io::Result<()> { Ok(()) } ++} ++pub fn limited(value: &T, limit: usize) -> Option { ++ let mut writer = Bounded { bytes: Vec::new(), limit }; ++ serde_json::to_writer(&mut writer, value).ok()?; ++ String::from_utf8(writer.bytes).ok() ++} ++#[cfg(test)] mod tests { ++ use super::*; ++ #[test] fn bookkeeping_has_explicit_failure_and_limit() { ++ begin(true); read("AXChildren", None); read("AXHeader", Some(-25212)); ++ let value = finish(); assert_eq!(value["attribute_action_reads"], 2); assert_eq!(value["first_read_refusal"]["attribute"], "AXHeader"); ++ begin(false); read("AXHeader", Some(-25212)); assert_eq!(finish(), Value::Null); ++ assert!(limited(&vec!["abcdefgh"; 100], 32).is_none()); ++ assert_eq!(limited(&true, 4).unwrap(), "true"); ++ } ++} +--- /dev/null ++++ b/libs/cua-driver/rust/crates/cua-driver-contract/examples/row_trace_probe.rs +@@ -0,0 +1,92 @@ ++//! Offline AX-provider adapter: production schema and recipient validator, no OS input. ++use cua_driver_contract::row::{discover_row, discover_row_traced, dispatch_row, RowBinding, RowGraph}; ++use cua_driver_contract::{ActionTarget, ClickInput, ToolInput}; ++use std::io::{self, Read}; ++fn main() { ++ let mut text = String::new(); ++ io::stdin().read_to_string(&mut text).unwrap(); ++ let input: serde_json::Value = serde_json::from_str(&text).unwrap(); ++ if input["mode"] == "trace" { ++ let graph: RowGraph = serde_json::from_value(input["graph"].clone()).unwrap(); ++ let pid = input["pid"].as_u64().unwrap() as u32; ++ let window = input["window_id"].as_u64().unwrap(); ++ let recipient = input["recipient"].as_u64().unwrap(); ++ let off = discover_row(&graph, pid, window, recipient); ++ let mut events = Vec::new(); ++ let on = discover_row_traced(&graph, pid, window, recipient, Some(&mut events)); ++ println!("{}", serde_json::json!({"off": off, "on": on, "keys": events})); ++ return; ++ } ++ if input["mode"] == "discover" { ++ let graph: RowGraph = serde_json::from_value(input["graph"].clone()).unwrap(); ++ let result = discover_row( ++ &graph, ++ input["pid"].as_u64().unwrap() as u32, ++ input["window_id"].as_u64().unwrap(), ++ input["recipient"].as_u64().unwrap(), ++ ); ++ println!( ++ "{}", ++ match result { ++ Ok(binding) => serde_json::json!({"binding":binding}), ++ Err(error) => serde_json::json!({"binding":null,"error":error}), ++ } ++ ); ++ return; ++ } ++ let parsed = serde_json::from_value::(input["click"].clone()) ++ .map_err(|e| e.to_string()) ++ .and_then(|i| { ++ i.validate()?; ++ Ok(i) ++ }); ++ let click = match parsed { ++ Ok(click) => click, ++ Err(error) => { ++ println!( ++ "{}", ++ serde_json::json!({"schema_valid":false,"error":error,"presses":[]}) ++ ); ++ return; ++ } ++ }; ++ if input["mode"] != "dispatch" { ++ println!("{}", serde_json::json!({"schema_valid":true})); ++ return; ++ } ++ let binding: RowBinding = serde_json::from_value(input["binding"].clone()).unwrap(); ++ let graph = ++ serde_json::from_value::(input["graph"].clone()).map_err(|e| e.to_string()); ++ let ActionTarget::Window { pid, window_id } = click.target else { ++ panic!("fixture requires window") ++ }; ++ let recipient = input["recipient"].as_u64().unwrap(); ++ let mut presses = Vec::new(); ++ let receipt = dispatch_row( ++ graph, ++ &binding, ++ click.expected_row.as_ref(), ++ pid, ++ window_id, ++ recipient, ++ || { ++ if input["admission_error"] == true { ++ Err("fixture focus lost before press".into()) ++ } else { ++ Ok(()) ++ } ++ }, ++ || { ++ presses.push(recipient); ++ if input["press_error"] == true { ++ Err("fixture AXPress response lost".into()) ++ } else { ++ Ok(()) ++ } ++ }, ++ ); ++ println!( ++ "{}", ++ serde_json::json!({"schema_valid":true,"receipt":receipt,"presses":presses}) ++ ); ++} diff --git a/jevdual/vendor/cua-driver/pyproject.toml b/jevdual/vendor/cua-driver/pyproject.toml index c8320c72..19b46258 100644 --- a/jevdual/vendor/cua-driver/pyproject.toml +++ b/jevdual/vendor/cua-driver/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "cua-driver" -version = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4" +version = "0.46.0+footwork.5486b624.cleanup2.focus1.helptag1.connected4.locate10.row4.trace2" description = "Rust-backed Cua Driver SDK and bundled executable for client applications" readme = "README.md" license = { text = "MIT" } diff --git a/jevdual/vendor/cua-driver/src/cua_driver/_native_contract.py b/jevdual/vendor/cua-driver/src/cua_driver/_native_contract.py index dde774e0..ba787304 100644 --- a/jevdual/vendor/cua-driver/src/cua_driver/_native_contract.py +++ b/jevdual/vendor/cua-driver/src/cua_driver/_native_contract.py @@ -4571,7 +4571,7 @@ def write(value, buf): @dataclass class GetWindowStateInput: - def __init__(self, *, pid:int, window_id:int, session:typing.Optional[str], query:typing.Optional[str], include_accessibility_tree:typing.Optional[bool], include_screenshot:typing.Optional[bool], screenshot_out_file:typing.Optional[str], max_elements:typing.Optional[int], max_depth:typing.Optional[int], max_dimension:typing.Optional[int], max_image_dimension:typing.Optional[int], timeout_ms:typing.Optional[int] = _DEFAULT, tree_format:typing.Optional[str] = _DEFAULT, since:typing.Optional[str] = _DEFAULT, verbose:typing.Optional[bool] = _DEFAULT, full_output:typing.Optional[bool] = _DEFAULT, qualify_rows:typing.Optional[bool] = _DEFAULT): + def __init__(self, *, pid:int, window_id:int, session:typing.Optional[str], query:typing.Optional[str], include_accessibility_tree:typing.Optional[bool], include_screenshot:typing.Optional[bool], screenshot_out_file:typing.Optional[str], max_elements:typing.Optional[int], max_depth:typing.Optional[int], max_dimension:typing.Optional[int], max_image_dimension:typing.Optional[int], timeout_ms:typing.Optional[int] = _DEFAULT, tree_format:typing.Optional[str] = _DEFAULT, since:typing.Optional[str] = _DEFAULT, verbose:typing.Optional[bool] = _DEFAULT, full_output:typing.Optional[bool] = _DEFAULT, qualify_rows:typing.Optional[bool] = _DEFAULT, row_trace_url:typing.Optional[str] = _DEFAULT): self.pid = pid self.window_id = window_id self.session = session @@ -4607,12 +4607,16 @@ def __init__(self, *, pid:int, window_id:int, session:typing.Optional[str], quer self.qualify_rows = None else: self.qualify_rows = qualify_rows + if row_trace_url is _DEFAULT: + self.row_trace_url = None + else: + self.row_trace_url = row_trace_url def __str__(self): - return "GetWindowStateInput(pid={}, window_id={}, session={}, query={}, include_accessibility_tree={}, include_screenshot={}, screenshot_out_file={}, max_elements={}, max_depth={}, max_dimension={}, max_image_dimension={}, timeout_ms={}, tree_format={}, since={}, verbose={}, full_output={}, qualify_rows={})".format(self.pid, self.window_id, self.session, self.query, self.include_accessibility_tree, self.include_screenshot, self.screenshot_out_file, self.max_elements, self.max_depth, self.max_dimension, self.max_image_dimension, self.timeout_ms, self.tree_format, self.since, self.verbose, self.full_output, self.qualify_rows) + return "GetWindowStateInput(pid={}, window_id={}, session={}, query={}, include_accessibility_tree={}, include_screenshot={}, screenshot_out_file={}, max_elements={}, max_depth={}, max_dimension={}, max_image_dimension={}, timeout_ms={}, tree_format={}, since={}, verbose={}, full_output={}, qualify_rows={}, row_trace_url={})".format(self.pid, self.window_id, self.session, self.query, self.include_accessibility_tree, self.include_screenshot, self.screenshot_out_file, self.max_elements, self.max_depth, self.max_dimension, self.max_image_dimension, self.timeout_ms, self.tree_format, self.since, self.verbose, self.full_output, self.qualify_rows, self.row_trace_url) def __eq__(self, other): if self.pid != other.pid: return False @@ -4648,6 +4652,8 @@ def __eq__(self, other): return False if self.qualify_rows != other.qualify_rows: return False + if self.row_trace_url != other.row_trace_url: + return False return True class _UniffiFfiConverterTypeGetWindowStateInput(_UniffiConverterRustBuffer): @@ -4671,6 +4677,7 @@ def read(buf): verbose=_UniffiFfiConverterOptionalBoolean.read(buf), full_output=_UniffiFfiConverterOptionalBoolean.read(buf), qualify_rows=_UniffiFfiConverterOptionalBoolean.read(buf), + row_trace_url=_UniffiFfiConverterOptionalString.read(buf), ) @staticmethod @@ -4692,6 +4699,7 @@ def check_lower(value): _UniffiFfiConverterOptionalBoolean.check_lower(value.verbose) _UniffiFfiConverterOptionalBoolean.check_lower(value.full_output) _UniffiFfiConverterOptionalBoolean.check_lower(value.qualify_rows) + _UniffiFfiConverterOptionalString.check_lower(value.row_trace_url) @staticmethod def write(value, buf): @@ -4712,6 +4720,7 @@ def write(value, buf): _UniffiFfiConverterOptionalBoolean.write(value.verbose, buf) _UniffiFfiConverterOptionalBoolean.write(value.full_output, buf) _UniffiFfiConverterOptionalBoolean.write(value.qualify_rows, buf) + _UniffiFfiConverterOptionalString.write(value.row_trace_url, buf) @dataclass class HotkeyInput: @@ -8663,7 +8672,11 @@ def read(cls, buf): @dataclass class WindowStateOutput: - def __init__(self, *, pid:int, window_id:int, snapshot_id:typing.Optional[str], app_name:typing.Optional[str], window_title:typing.Optional[str], tree_markdown:typing.Optional[str], elements:typing.Optional[typing.List[WindowElement]], element_count:typing.Optional[int], total_element_count:typing.Optional[int], returned_element_count:typing.Optional[int], filtered_element_count:typing.Optional[int], elements_complete:typing.Optional[bool], degraded:typing.Optional[bool], degraded_reason:typing.Optional[str], truncated:typing.Optional[bool], truncation_reason:typing.Optional[str], truncation_hint:typing.Optional[str], tree_format:typing.Optional[str], since:typing.Optional[str], since_status:typing.Optional[str], tree_diff:typing.Optional[str], screenshot_width:typing.Optional[int], screenshot_height:typing.Optional[int], screenshot_scale:typing.Optional[float], screenshot_mime_type:typing.Optional[str], screenshot_file_path:typing.Optional[str], screenshot_frame_valid:typing.Optional[bool], window_bounds:typing.Optional[WindowBounds], images:typing.List[SnapshotImage]): + def __init__(self, *, row_trace_json:typing.Optional[str] = _DEFAULT, pid:int, window_id:int, snapshot_id:typing.Optional[str], app_name:typing.Optional[str], window_title:typing.Optional[str], tree_markdown:typing.Optional[str], elements:typing.Optional[typing.List[WindowElement]], element_count:typing.Optional[int], total_element_count:typing.Optional[int], returned_element_count:typing.Optional[int], filtered_element_count:typing.Optional[int], elements_complete:typing.Optional[bool], degraded:typing.Optional[bool], degraded_reason:typing.Optional[str], truncated:typing.Optional[bool], truncation_reason:typing.Optional[str], truncation_hint:typing.Optional[str], tree_format:typing.Optional[str], since:typing.Optional[str], since_status:typing.Optional[str], tree_diff:typing.Optional[str], screenshot_width:typing.Optional[int], screenshot_height:typing.Optional[int], screenshot_scale:typing.Optional[float], screenshot_mime_type:typing.Optional[str], screenshot_file_path:typing.Optional[str], screenshot_frame_valid:typing.Optional[bool], window_bounds:typing.Optional[WindowBounds], images:typing.List[SnapshotImage]): + if row_trace_json is _DEFAULT: + self.row_trace_json = None + else: + self.row_trace_json = row_trace_json self.pid = pid self.window_id = window_id self.snapshot_id = snapshot_id @@ -8698,8 +8711,10 @@ def __init__(self, *, pid:int, window_id:int, snapshot_id:typing.Optional[str], def __str__(self): - return "WindowStateOutput(pid={}, window_id={}, snapshot_id={}, app_name={}, window_title={}, tree_markdown={}, elements={}, element_count={}, total_element_count={}, returned_element_count={}, filtered_element_count={}, elements_complete={}, degraded={}, degraded_reason={}, truncated={}, truncation_reason={}, truncation_hint={}, tree_format={}, since={}, since_status={}, tree_diff={}, screenshot_width={}, screenshot_height={}, screenshot_scale={}, screenshot_mime_type={}, screenshot_file_path={}, screenshot_frame_valid={}, window_bounds={}, images={})".format(self.pid, self.window_id, self.snapshot_id, self.app_name, self.window_title, self.tree_markdown, self.elements, self.element_count, self.total_element_count, self.returned_element_count, self.filtered_element_count, self.elements_complete, self.degraded, self.degraded_reason, self.truncated, self.truncation_reason, self.truncation_hint, self.tree_format, self.since, self.since_status, self.tree_diff, self.screenshot_width, self.screenshot_height, self.screenshot_scale, self.screenshot_mime_type, self.screenshot_file_path, self.screenshot_frame_valid, self.window_bounds, self.images) + return "WindowStateOutput(row_trace_json={}, pid={}, window_id={}, snapshot_id={}, app_name={}, window_title={}, tree_markdown={}, elements={}, element_count={}, total_element_count={}, returned_element_count={}, filtered_element_count={}, elements_complete={}, degraded={}, degraded_reason={}, truncated={}, truncation_reason={}, truncation_hint={}, tree_format={}, since={}, since_status={}, tree_diff={}, screenshot_width={}, screenshot_height={}, screenshot_scale={}, screenshot_mime_type={}, screenshot_file_path={}, screenshot_frame_valid={}, window_bounds={}, images={})".format(self.row_trace_json, self.pid, self.window_id, self.snapshot_id, self.app_name, self.window_title, self.tree_markdown, self.elements, self.element_count, self.total_element_count, self.returned_element_count, self.filtered_element_count, self.elements_complete, self.degraded, self.degraded_reason, self.truncated, self.truncation_reason, self.truncation_hint, self.tree_format, self.since, self.since_status, self.tree_diff, self.screenshot_width, self.screenshot_height, self.screenshot_scale, self.screenshot_mime_type, self.screenshot_file_path, self.screenshot_frame_valid, self.window_bounds, self.images) def __eq__(self, other): + if self.row_trace_json != other.row_trace_json: + return False if self.pid != other.pid: return False if self.window_id != other.window_id: @@ -8764,6 +8779,7 @@ class _UniffiFfiConverterTypeWindowStateOutput(_UniffiConverterRustBuffer): @staticmethod def read(buf): return WindowStateOutput( + row_trace_json=_UniffiFfiConverterOptionalString.read(buf), pid=_UniffiFfiConverterUInt32.read(buf), window_id=_UniffiFfiConverterUInt64.read(buf), snapshot_id=_UniffiFfiConverterOptionalString.read(buf), @@ -8797,6 +8813,7 @@ def read(buf): @staticmethod def check_lower(value): + _UniffiFfiConverterOptionalString.check_lower(value.row_trace_json) _UniffiFfiConverterUInt32.check_lower(value.pid) _UniffiFfiConverterUInt64.check_lower(value.window_id) _UniffiFfiConverterOptionalString.check_lower(value.snapshot_id) @@ -8829,6 +8846,7 @@ def check_lower(value): @staticmethod def write(value, buf): + _UniffiFfiConverterOptionalString.write(value.row_trace_json, buf) _UniffiFfiConverterUInt32.write(value.pid, buf) _UniffiFfiConverterUInt64.write(value.window_id, buf) _UniffiFfiConverterOptionalString.write(value.snapshot_id, buf)