From d86056304122f23f54a251a99e80964137c05647 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 01:29:21 -0500 Subject: [PATCH 1/2] test(flow): add versioned native record identity fixture --- .../native_record_identity_v2/.gitattributes | 3 + .../native_record_identity_v2/README.md | 63 ++++ .../native_record_identity_v2/RESULTS.md | 21 ++ .../build_fixture.py | 167 ++++++++++ .../check_lifecycle.ps1 | 128 ++++++++ .../native_record_identity_v2/contract.json | 90 ++++++ .../native_record_identity_v2/manifest.json | 10 + .../native_record_identity_v2/override.json | 45 +++ .../patient_notes_v2.ps1 | 297 ++++++++++++++++++ .../readback.template.json | 32 ++ .../test_native_record_identity_fixture.py | 246 +++++++++++++++ 11 files changed, 1102 insertions(+) create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/.gitattributes create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/README.md create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/build_fixture.py create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/check_lifecycle.ps1 create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/contract.json create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/manifest.json create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/override.json create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/patient_notes_v2.ps1 create mode 100644 packages/flow/tests/fixtures/native_record_identity_v2/readback.template.json create mode 100644 packages/flow/tests/test_native_record_identity_fixture.py diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/.gitattributes b/packages/flow/tests/fixtures/native_record_identity_v2/.gitattributes new file mode 100644 index 0000000000..ac7e989dd6 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/.gitattributes @@ -0,0 +1,3 @@ +# These generated bytes and override pins are identical on Windows and Unix. +*.json -text +patient_notes_v2.ps1 -text diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/README.md b/packages/flow/tests/fixtures/native_record_identity_v2/README.md new file mode 100644 index 0000000000..829f77feb5 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/README.md @@ -0,0 +1,63 @@ +# Native record identity v2 fixture + +This is a new synthetic qualification case. It exposes the loaded SQLite record +ID in a readonly standard WinForms `TextBox` named `currentRecordId`. The original +`patient_notes.ps1`, its save handler, and the older caption-based readback spec +remain unchanged. Earlier results retain their original case and denominator. + +The fixture clears the ID, note and header before loading or changing records. +It publishes an ID only after the selected grid key, the actual `pn_db.py get` +result's ID and a fresh selection read agree. Missing, malformed or mismatched +records leave the ID empty. A failed list load also clears the selection and +list. The original save handler still saves to the selected grid key; the new +fixture adds no save guard. + +`contract.json` declares the database mapping and a data-only readback template. +The generator applies exact overrides to a hash-pinned base and emits a distinct +script, pack and manifest. Run from `packages/flow`: + +```sh +python tests/fixtures/native_record_identity_v2/build_fixture.py --check +``` + +The base pin uses LF bytes; checkout CRLF is explicitly converted to LF before +comparison. No other normalization occurs. Generated files preserve their +committed bytes on either platform. The caller supplies its owned readback +session; the pack contains no endpoint or credentials. Record IDs must be +canonical signed int64 strings, including zero and the integer boundaries. +Search selects a candidate. The intended contract requires exact canonical +record-ID comparison; the existing verifier also accepts delimited caption +values. This candidate remains held for a generic exact-value consumer contract +and planted invalid-display controls. +There is no virtual-grid or complete row-count claim. + +Offline tests parse the entire generated PowerShell source and execute only its +actual database/load/selection functions, using stand-in controls and the real +SQLite CLI. They test reset, missing/ambiguous/invalid identity, wrong loaded row, +selection replacement during load, invalid list data and actual subprocess +failure. They also compare CLI IDs with independent SQLite reads and plant +incorrect mapping/schema controls. Nonempty notes prime every failure/reset +case so stale-value clearing controls are not vacuous. JSON root-shape checks +precede PowerShell pipeline enumeration. They open no GUI and send no desktop input. +These checks establish source behavior under those stand-ins, not native +WinForms behavior. + +Native qualification is **unperformed**. The intended structural read requires +the corrected known-non-password guard, mandatory `value_contract` negotiation +and `openadapt.native-value-completeness/v2` proof. Readonly identity uses +`require_editable=False`; it is not an editable-field baseline. Unsupported, +sensitive, truncated or disagreeing values must refuse, with no caption, +preview or OCR fallback. The protocol continuation was inspected at +`87d29b31b81131d591a8033ceac84e533f68264b` with shared helper +`7f65509068feb035236dd1d8a78db4daa5038e69`. Further consumer corrections +are pending; this is a source reference, not a final runtime pin or native +qualification. This fixture does not qualify an older +runtime. + +A future native case must independently compare the selected key, loaded DB +row, actual managed control value and complete native UIA/Win32 observation, +then check the target and every sibling directly in SQLite. A complete text +observation alone does not prove that the text belongs to the saved row. The +protocol/source freeze, native binding evidence, combined approval campaign and +held-out evidence remain absent in `contract.json`. No prior failed campaign is +reclassified by this new case. diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md b/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md new file mode 100644 index 0000000000..15def8fac5 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md @@ -0,0 +1,21 @@ +# Offline results + +2026-11-20, source-only candidate: + +- 21 focused pytest cases passed with no skips, using Python 3.12.13 and + PowerShell 7.5.0 on macOS. Flow and Types imports were bound to this checkout. +- One test executes 26 lifecycle cases from the generated PowerShell functions, + against stand-in controls and the real SQLite CLI. These are included in the + pytest count, not additional native trials. +- A separate planted omission of note clearing was rejected at selection reset. +- CLI IDs matched independent SQLite reads, including zero and signed int64 + boundaries. Wrong schema/mapping controls refused. All lifecycle DB rows stayed + unchanged. +- Ruff 0.17.0 checks and formatting passed. Generated output matches its pinned + base/override/manifest; the original save-handler bytes match. + +No WinForms UI, desktop input, lab, VM, cloud resource or native CI campaign was +used. Windows PowerShell 5.1 and native WinForms event/provider behavior remain +unmeasured. The shared consumer protocol, exact canonical-ID matching, live +DB-row-to-control binding, combined campaign and held-out qualification remain +held. No prior result or denominator changed. diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/build_fixture.py b/packages/flow/tests/fixtures/native_record_identity_v2/build_fixture.py new file mode 100644 index 0000000000..bccb68c364 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/build_fixture.py @@ -0,0 +1,167 @@ +"""Build a NEW synthetic fixture and pack from a pinned, unchanged base. + +This is repository-only test support. It does not qualify a native runtime. +""" + +from __future__ import annotations + +import argparse +import ast +import hashlib +import json +import sqlite3 +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +FLOW = HERE.parents[2] + + +def sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def load_contract() -> dict[str, Any]: + return json.loads((HERE / "contract.json").read_text()) + + +def canonical_source(path: Path) -> bytes: + """Windows checkout CRLF is explicit; no other byte normalization.""" + return path.read_bytes().replace(b"\r\n", b"\n") + + +def save_handler(source: str) -> str: + return source.split("$saveButton.Add_Click({", 1)[1].split("\n})", 1)[0] + + +def build(base: bytes, override: dict[str, Any]) -> bytes: + contract = load_contract() + if sha256(base) != contract["base_source"]["sha256"]: + raise ValueError("base source differs from the pinned fixture") + if override["schema"] != "openadapt.synthetic-source-override/v1": + raise ValueError("unsupported source override schema") + text = base.decode("utf-8") + original_save = save_handler(text) + for patch in override["patches"]: + if text.count(patch["before"]) != 1: + raise ValueError("source override must match exactly once") + text = text.replace(patch["before"], patch["after"], 1) + if save_handler(text) != original_save: + raise ValueError("NEW fixture changed the original save handler") + return text.encode("utf-8") + + +def readback_spec(session: dict[str, Any]) -> dict[str, Any]: + """Supply the caller's owned session; the data pack stores no endpoint.""" + return {"session": session, **load_contract()["readback_template"]} + + +def validate_database(con: sqlite3.Connection, mapping: dict[str, str]) -> None: + """Check the declared identity/value mapping against an actual SQLite DB.""" + table = mapping["table"] + if not isinstance(table, str) or not table: + raise ValueError("missing table") + kind = con.execute( + "SELECT type FROM sqlite_master WHERE name = ?", (table,) + ).fetchone() + if kind != ("table",): + raise ValueError("mapping must name an actual table") + quoted_table = '"' + table.replace('"', '""') + '"' + columns = {row[1]: row for row in con.execute(f"PRAGMA table_info({quoted_table})")} + key = columns.get(mapping["key"]) + value = columns.get(mapping["value"]) + if ( + key is None + or key[2].upper() != mapping["key_type"] + or key[2].upper() != "INTEGER" + or key[5] != 1 + or sum(bool(row[5]) for row in columns.values()) != 1 + ): + raise ValueError("identity must be the sole INTEGER primary key") + if value is None or value[2].upper() != mapping["value_type"] or value[2] != "TEXT": + raise ValueError("note mapping must name a TEXT column") + if mapping["key"] == mapping["value"]: + raise ValueError("identity and note mapping must differ") + + +def validate_source_mapping(source: bytes, contract: dict[str, Any]) -> None: + """Bind pack data to the pinned CLI's actual lookup and write statements.""" + mapping = contract["database_mapping"] + table, key, value = (mapping[name] for name in ("table", "key", "value")) + expected = { + "get": f"SELECT * FROM {table} WHERE {key} = ?", + "save": f"UPDATE {table} SET {value} = ? WHERE {key} = ?", + } + tree = ast.parse(source) + for name, sql in expected.items(): + functions = [ + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == name + ] + if len(functions) != 1: + raise ValueError("database operation is missing or ambiguous") + statements = [ + node.args[0].value + for node in ast.walk(functions[0]) + if isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "execute" + and node.args + and isinstance(node.args[0], ast.Constant) + ] + if statements != [sql]: + raise ValueError("pack mapping differs from actual CLI lookup/write SQL") + binding = contract["identity_binding"] + if any( + binding[name] != key + for name in ("selected_cell", "loaded_field", "save_target_cell") + ): + raise ValueError("selection, load and save mapping must name the same key") + template = contract["readback_template"] + if template["identity"]["field"] != key or set(template["fields"]) != {value}: + raise ValueError("readback pack differs from the database mapping") + + +def outputs() -> dict[str, bytes]: + contract = load_contract() + base = canonical_source(FLOW / contract["base_source"]["path"]) + database = canonical_source(FLOW / contract["database_source"]["path"]) + if sha256(database) != contract["database_source"]["sha256"]: + raise ValueError("database CLI differs from the pinned source") + validate_source_mapping(database, contract) + override_bytes = (HERE / "override.json").read_bytes() + fixture = build(base, json.loads(override_bytes)) + pack = (json.dumps(contract["readback_template"], indent=2) + "\n").encode() + manifest = { + "case_id": contract["case_id"], + "base_sha256": sha256(base), + "database_source_sha256": sha256(database), + "override_sha256": sha256(override_bytes), + "fixture_sha256": sha256(fixture), + "readback_template_sha256": sha256(pack), + "unchanged_save_handler_sha256": sha256(save_handler(base.decode()).encode()), + "native_validation_performed": False, + } + return { + "patient_notes_v2.ps1": fixture, + "readback.template.json": pack, + "manifest.json": (json.dumps(manifest, indent=2) + "\n").encode(), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--check", action="store_true") + args = parser.parse_args() + for name, data in outputs().items(): + path = HERE / name + if args.check: + if not path.is_file() or path.read_bytes() != data: + raise SystemExit(f"generated file differs: {name}") + else: + path.write_bytes(data) + + +if __name__ == "__main__": + main() diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/check_lifecycle.ps1 b/packages/flow/tests/fixtures/native_record_identity_v2/check_lifecycle.ps1 new file mode 100644 index 0000000000..157fa4f297 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/check_lifecycle.ps1 @@ -0,0 +1,128 @@ +# Offline control-flow proof only: no WinForms imports, windows, or input. +param([string]$Fixture, [string]$Python, [string]$DbCli, [string]$FailCli) +$ErrorActionPreference = "Stop" +$tokens = $null +$errors = $null +$ast = [System.Management.Automation.Language.Parser]::ParseFile($Fixture, [ref]$tokens, [ref]$errors) +if ($errors.Count) { throw ($errors | Out-String) } +$names = @("Invoke-Db", "ConvertTo-RecordId", "Clear-CurrentRecord", "Get-SelectedRecordId", "Update-CurrentRecord", "Load-Patients") +foreach ($name in $names) { + $fn = @($ast.FindAll({param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst]}, $true) | Where-Object Name -eq $name) + if ($fn.Count -ne 1) { throw "Missing or duplicated function $name" } + . ([scriptblock]::Create($fn[0].Extent.Text)) +} +$realInvokeDb = (Get-Command Invoke-Db).ScriptBlock +$currentRecordId = [pscustomobject]@{Text=""} +$noteBox = [pscustomobject]@{Text=""} +$patientHeader = [pscustomobject]@{Text=""} +$status = [pscustomobject]@{Text=""} +$grid = [pscustomobject]@{SelectedRows=@(); DataSource=$null; Columns=@{id=[pscustomobject]@{Visible=$false}}} +$grid | Add-Member -MemberType ScriptMethod -Name ClearSelection -Value { $this.SelectedRows = @() } +$script:recordIdentityLoading = $false +$script:mode = "normal" +$script:clearObservedBeforeList = $false +$cases = [Collections.Generic.List[string]]::new() + +function Select-Id($Id) { + $grid.SelectedRows = @([pscustomobject]@{Cells=@{id=[pscustomobject]@{Value=$Id}}}) +} +function Assert-Cleared([string]$Case) { + if ($currentRecordId.Text -cne "" -or $noteBox.Text -cne "" -or $patientHeader.Text -cne "") { + throw "Stale identity/value in $Case" + } + if ($script:recordIdentityLoading) { throw "Load guard stuck in $Case" } + $cases.Add($Case) +} +function Prime-Record { + $script:mode = "normal" + Select-Id "1" + Update-CurrentRecord + if ($currentRecordId.Text -cne "1" -or $noteBox.Text -cne "seed-note-1") { throw "Real SQLite id/note was not loaded" } +} +function Invoke-Db { + param([string[]]$DbArgs, [switch]$RequireSuccess) + if ($DbArgs[0] -eq "list") { + if ($currentRecordId.Text -cne "" -or $noteBox.Text -cne "") { throw "List saw stale identity" } + $script:clearObservedBeforeList = $true + if ($script:mode -eq "list-error") { throw "Planted list failure" } + if ($script:mode -eq "invalid-list") { return '[{"id":"01"}]' } + if ($script:mode -eq "object-list") { return '{"id":1}' } + if ($script:mode -eq "invalid-json") { return '{invalid' } + } + if ($DbArgs[0] -eq "get") { + if ($script:mode -eq "wrong-row") { return & $realInvokeDb -DbArgs @("get", "2") -RequireSuccess:$RequireSuccess } + if ($script:mode -eq "missing-row") { return "null" } + if ($script:mode -eq "ambiguous-row") { return '[{"id":1},{"id":2}]' } + if ($script:mode -eq "singleton-array-row") { return '[{"id":1}]' } + if ($script:mode -eq "invalid-loaded-id") { return '{"id":"01"}' } + if ($script:mode -eq "get-error") { throw "Planted get failure" } + if ($script:mode -eq "selection-replaced") { + $result = & $realInvokeDb -DbArgs $DbArgs -RequireSuccess:$RequireSuccess + Select-Id "2" + return $result + } + } + return & $realInvokeDb -DbArgs $DbArgs -RequireSuccess:$RequireSuccess +} + +# Canonical domain covers SQLite integer boundaries, not only the seed's id1. +foreach ($id in @("-9223372036854775808", "0", "1", "2", "9223372036854775807")) { + Select-Id $id + Update-CurrentRecord + if ($currentRecordId.Text -cne $id) { throw "Wrong canonical id $id" } + $db = (& $Python $DbCli get $id) | ConvertFrom-Json + if ((ConvertTo-RecordId $db.id) -cne $currentRecordId.Text) { throw "DB mapping mismatch" } +} +$cases.Add("actual-sqlite-get-domain") + +Prime-Record +$grid.ClearSelection() +Update-CurrentRecord +Assert-Cleared "selection-reset" +Prime-Record +$grid.SelectedRows = @($grid.SelectedRows[0], $grid.SelectedRows[0]) +Update-CurrentRecord +Assert-Cleared "ambiguous-selection" +foreach ($bad in @("01", "+1", " 1", "1.0", "9223372036854775808", $null, $true, 1.5)) { + Prime-Record + Select-Id $bad + Update-CurrentRecord + Assert-Cleared ("invalid-selected-id-" + $cases.Count) +} +foreach ($caseMode in @("wrong-row", "missing-row", "ambiguous-row", "singleton-array-row", "invalid-loaded-id", "get-error", "selection-replaced")) { + Prime-Record + $script:mode = $caseMode + Update-CurrentRecord + Assert-Cleared $caseMode +} +Prime-Record +$script:recordIdentityLoading = $true +Update-CurrentRecord +if ($currentRecordId.Text -cne "") { throw "Identity published during load" } +$script:recordIdentityLoading = $false +$cases.Add("loading-suppresses-publication") + +foreach ($caseMode in @("list-error", "invalid-list", "object-list", "invalid-json")) { + Prime-Record + $script:mode = $caseMode + Load-Patients -Filter "Neil" + Assert-Cleared $caseMode + if ($grid.SelectedRows.Count -ne 0 -or $null -ne $grid.DataSource) { throw "Failed list retained selection" } +} +Prime-Record +$script:clearObservedBeforeList = $false +Load-Patients -Filter "Neil" +if (-not $script:clearObservedBeforeList -or $currentRecordId.Text -cne "1") { throw "Reload failed" } +$cases.Add("load-clears-before-read-then-rebinds") + +# Nonzero actual child-process exits must not become cached identity. +Prime-Record +$originalCli = $DbCli +$DbCli = $FailCli +Update-CurrentRecord +Assert-Cleared "native-process-get-failure" +Load-Patients -Filter "Neil" +Assert-Cleared "native-process-list-failure" +$DbCli = $originalCli + +@{scope="offline-generated-functions-fake-controls-real-sqlite"; cases=$cases; count=$cases.Count; native_validation=$false; powershell=$PSVersionTable.PSVersion.ToString()} | ConvertTo-Json -Depth 5 diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/contract.json b/packages/flow/tests/fixtures/native_record_identity_v2/contract.json new file mode 100644 index 0000000000..917740df82 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/contract.json @@ -0,0 +1,90 @@ +{ + "schema": "openadapt.synthetic-native-record-identity/v2", + "case_id": "patient-notes-native-record-identity-v2", + "base_source": { + "path": "scripts/desktop/patient_notes.ps1", + "sha256": "0e3dcd2e8347b0f5574577c206e7c5f9c341093b3802ae45f89581fab58f1193", + "line_endings": "canonical LF" + }, + "database_source": { + "path": "scripts/desktop/pn_db.py", + "sha256": "7bc09cde1c2d4a31366e71532fffa499dc24e12a80fe03f77a6fd5964261fd0a" + }, + "database_mapping": { + "table": "patients", + "key": "id", + "key_type": "INTEGER", + "value": "note", + "value_type": "TEXT" + }, + "identity_binding": { + "control": "currentRecordId", + "control_class": "System.Windows.Forms.TextBox", + "readonly": true, + "password": false, + "selected_cell": "id", + "loaded_field": "id", + "save_target_cell": "id", + "domain": "canonical signed int64 string" + }, + "read_requirements": { + "route": "/uia/read", + "require_editable": false, + "value_contract": "openadapt.native-value-completeness/v2", + "proof_schema": "openadapt.native-value-completeness/v2", + "runtime_protocol_qualified": false, + "shared_helper_ref": "7f65509068feb035236dd1d8a78db4daa5038e69", + "identity_match": "exact canonical signed int64 string", + "identity_match_qualified": false, + "protocol_source_reference_seen": "87d29b31b81131d591a8033ceac84e533f68264b", + "protocol_source_finalized": false + }, + "readback_template": { + "search": { + "box": { + "automation_id": "searchBox" + }, + "query": { + "param": "patient_search" + }, + "submit": { + "automation_id": "searchButton" + } + }, + "ready": { + "automation_id": "currentRecordId" + }, + "identity": { + "reader": { + "automation_id": "currentRecordId" + }, + "value": { + "param": "record_id" + }, + "field": "id" + }, + "fields": { + "note": { + "control": { + "automation_id": "noteBox" + } + } + } + }, + "qualification": { + "source_only": true, + "native_value_proof": null, + "database_to_control_binding_proof": null, + "combined_campaign": null, + "held_out_case": null, + "row_count_evidence": false + }, + "native_validation_required": [ + "known-non-password readonly Edit; complete UIA/native agreement with proof v2", + "actual selected id = get.id = native observed id = independently queried SQLite id", + "no selection, list/get failure, missing/wrong row and mid-load selection replacement clear identity", + "target note and every sibling checked directly in SQLite", + "unsupported/truncated/sensitive values refuse before field verification", + "generic identity consumer rejects noncanonical/delimited display values; no caption substring matching" + ] +} diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/manifest.json b/packages/flow/tests/fixtures/native_record_identity_v2/manifest.json new file mode 100644 index 0000000000..1573831a9a --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/manifest.json @@ -0,0 +1,10 @@ +{ + "case_id": "patient-notes-native-record-identity-v2", + "base_sha256": "0e3dcd2e8347b0f5574577c206e7c5f9c341093b3802ae45f89581fab58f1193", + "database_source_sha256": "7bc09cde1c2d4a31366e71532fffa499dc24e12a80fe03f77a6fd5964261fd0a", + "override_sha256": "f367b8b931501e7a259caf42c49961f74619900e4d5e3e77f987713a222443d0", + "fixture_sha256": "976a91bc5d31fa80c76ed3af4b6a1f81d1d33d1c2eac57975e3a05f287d7ae08", + "readback_template_sha256": "d2850db8b147684cbaf2bcc6f0c84b320d8fa5c3ee6a7a96c49fa753f965c082", + "unchanged_save_handler_sha256": "78ba979a868ba4d03c44a1a884ee5efa56c476ca462eebe2e255b375076a51f9", + "native_validation_performed": false +} diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/override.json b/packages/flow/tests/fixtures/native_record_identity_v2/override.json new file mode 100644 index 0000000000..3055a06b0c --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/override.json @@ -0,0 +1,45 @@ +{ + "schema": "openadapt.synthetic-source-override/v1", + "patches": [ + { + "before": "# Patient Notes -- Benchmark Harness (WinForms).", + "after": "# Patient Notes -- Native Record Identity v2 (NEW synthetic WinForms fixture)." + }, + { + "before": "param([string[]]$DbArgs)", + "after": "param([string[]]$DbArgs, [switch]$RequireSuccess)" + }, + { + "before": " $p.WaitForExit()\n return $out", + "after": " $p.WaitForExit()\n if ($RequireSuccess -and $p.ExitCode -ne 0) { throw \"Database command failed\" }\n return $out" + }, + { + "before": "$form.Text = \"Patient Notes - Benchmark Harness\"", + "after": "$form.Text = \"Patient Notes - Native Record Identity v2\"" + }, + { + "before": "$form.Name = \"patientNotesForm\"", + "after": "$form.Name = \"patientNotesNativeIdentityV2\"" + }, + { + "before": "$form.Size = New-Object System.Drawing.Size(760, 560)", + "after": "$form.Size = New-Object System.Drawing.Size(900, 560)" + }, + { + "before": "$saveButton = New-Object System.Windows.Forms.Button", + "after": "# NEW v2 fixture identity: a readonly standard Edit value, not a caption.\n$currentRecordId = New-Object System.Windows.Forms.TextBox\n$currentRecordId.Name = \"currentRecordId\"\n$currentRecordId.AccessibleName = \"currentRecordId\"\n$currentRecordId.ReadOnly = $true\n$currentRecordId.UseSystemPasswordChar = $false\n$currentRecordId.PasswordChar = [char]0\n$currentRecordId.TabStop = $false\n$currentRecordId.Location = New-Object System.Drawing.Point(650, 320)\n$currentRecordId.Size = New-Object System.Drawing.Size(210, 28)\n$currentRecordId.Text = \"\"\n$form.Controls.Add($currentRecordId)\n\n$saveButton = New-Object System.Windows.Forms.Button" + }, + { + "before": "function Load-Patients {\n param([string]$Filter)\n $json = Invoke-Db -DbArgs @(\"list\", \"`\"$Filter`\"\")\n $rows = @()\n if ($json.Trim().Length -gt 0) { $rows = $json | ConvertFrom-Json }\n $dt = New-Object System.Data.DataTable\n [void]$dt.Columns.Add(\"id\")\n [void]$dt.Columns.Add(\"first\")\n [void]$dt.Columns.Add(\"last\")\n [void]$dt.Columns.Add(\"dob\")\n foreach ($r in $rows) {\n [void]$dt.Rows.Add($r.id, $r.first, $r.last, $r.dob)\n }\n $grid.DataSource = $dt\n if ($grid.Columns[\"id\"]) { $grid.Columns[\"id\"].Visible = $false }\n $status.Text = \"Loaded \" + $rows.Count + \" patients\"\n}\n\n$searchButton.Add_Click({ Load-Patients -Filter $searchBox.Text })\n$searchBox.Add_KeyDown({\n if ($_.KeyCode -eq \"Enter\") { Load-Patients -Filter $searchBox.Text; $_.SuppressKeyPress = $true }\n})\n\n$grid.Add_SelectionChanged({\n if ($grid.SelectedRows.Count -gt 0) {\n $row = $grid.SelectedRows[0]\n $id = $row.Cells[\"id\"].Value\n if ($id) {\n $j = Invoke-Db -DbArgs @(\"get\", \"$id\")\n $p = $j | ConvertFrom-Json\n if ($p) {\n $noteBox.Text = $p.note\n $patientHeader.Text = \"Patient: \" + $p.first + \" \" + $p.last + \" (\" + $p.dob + \")\"\n }\n }\n }\n})\n\n", + "after": "# Only the NEW fixture publishes an independently inspectable record id.\n$script:recordIdentityLoading = $false\n\nfunction ConvertTo-RecordId {\n param($Value)\n # SQLite INTEGER PRIMARY KEY is signed int64. Refuse aliases/coercions.\n if ($Value -isnot [string] -and $Value -isnot [int] -and $Value -isnot [long]) {\n throw \"Record id is not an exact integer or canonical string\"\n }\n $text = [Convert]::ToString($Value, [Globalization.CultureInfo]::InvariantCulture)\n [long]$parsed = 0\n $ok = [long]::TryParse($text, [Globalization.NumberStyles]::AllowLeadingSign,\n [Globalization.CultureInfo]::InvariantCulture, [ref]$parsed)\n if (-not $ok -or $parsed.ToString([Globalization.CultureInfo]::InvariantCulture) -cne $text) {\n throw \"Record id is not canonical signed int64\"\n }\n return $text\n}\n\nfunction Clear-CurrentRecord {\n $currentRecordId.Text = \"\"\n $noteBox.Text = \"\"\n $patientHeader.Text = \"\"\n}\n\nfunction Get-SelectedRecordId {\n if ($grid.SelectedRows.Count -ne 1) { throw \"No unique selected record\" }\n return ConvertTo-RecordId $grid.SelectedRows[0].Cells[\"id\"].Value\n}\n\nfunction Update-CurrentRecord {\n Clear-CurrentRecord\n if ($script:recordIdentityLoading) { return }\n try {\n $selectedId = Get-SelectedRecordId\n $j = Invoke-Db -DbArgs @(\"get\", \"$selectedId\") -RequireSuccess\n # Root shape is checked before PS5.1/7 pipeline enumeration.\n if (-not $j.TrimStart().StartsWith(\"{\")) { throw \"Get requires an object root\" }\n $p = $j | ConvertFrom-Json -ErrorAction Stop\n if ($null -eq $p -or $p -is [array]) { throw \"No unique loaded record\" }\n $loadedId = ConvertTo-RecordId $p.id\n if ($loadedId -cne $selectedId) { throw \"Loaded record differs from selection\" }\n $noteBox.Text = $p.note\n $patientHeader.Text = \"Patient: \" + $p.first + \" \" + $p.last + \" (\" + $p.dob + \")\"\n # A fresh selection read prevents publishing a stale in-flight load.\n if ((Get-SelectedRecordId) -cne $loadedId) { throw \"Selection changed during load\" }\n $currentRecordId.Text = $loadedId\n } catch {\n Clear-CurrentRecord\n $status.Text = \"Record identity unavailable\"\n }\n}\n\nfunction Load-Patients {\n param([string]$Filter)\n $script:recordIdentityLoading = $true\n Clear-CurrentRecord\n $loaded = $false\n try {\n $json = Invoke-Db -DbArgs @(\"list\", \"`\"$Filter`\"\") -RequireSuccess\n if (-not $json.TrimStart().StartsWith(\"[\")) { throw \"List requires an array root\" }\n $rows = @($json | ConvertFrom-Json -ErrorAction Stop)\n $dt = New-Object System.Data.DataTable\n [void]$dt.Columns.Add(\"id\")\n [void]$dt.Columns.Add(\"first\")\n [void]$dt.Columns.Add(\"last\")\n [void]$dt.Columns.Add(\"dob\")\n foreach ($r in $rows) {\n $id = ConvertTo-RecordId $r.id\n [void]$dt.Rows.Add($id, $r.first, $r.last, $r.dob)\n }\n $grid.DataSource = $dt\n if ($grid.Columns[\"id\"]) { $grid.Columns[\"id\"].Visible = $false }\n $status.Text = \"Loaded \" + $rows.Count + \" patients\"\n $loaded = $true\n } catch {\n $grid.ClearSelection()\n $grid.DataSource = $null\n Clear-CurrentRecord\n $status.Text = \"Record list unavailable\"\n } finally {\n $script:recordIdentityLoading = $false\n }\n if ($loaded) { Update-CurrentRecord }\n}\n\n$searchButton.Add_Click({ Load-Patients -Filter $searchBox.Text })\n$searchBox.Add_KeyDown({\n if ($_.KeyCode -eq \"Enter\") { Load-Patients -Filter $searchBox.Text; $_.SuppressKeyPress = $true }\n})\n\n$grid.Add_SelectionChanged({ Update-CurrentRecord })\n\n" + }, + { + "before": "foreach ($c in @($searchBox, $noteBox))", + "after": "foreach ($c in @($searchBox, $noteBox, $currentRecordId))" + }, + { + "before": "# Record header: names the open patient, the way a chart header does. The\n# separate-session read-back (desktop_readback) confirms identity here before\n# it reads the note. No AccessibleName: UI Automation then reports the label's\n# text as its Name, and Control.Name as its AutomationId.", + "after": "# Legacy display caption only. The NEW v2 pack reads currentRecordId's complete\n# native value for identity; this label's Name/preview is not identity authority." + } + ] +} diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/patient_notes_v2.ps1 b/packages/flow/tests/fixtures/native_record_identity_v2/patient_notes_v2.ps1 new file mode 100644 index 0000000000..ffddbeca33 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/patient_notes_v2.ps1 @@ -0,0 +1,297 @@ +# Patient Notes -- Native Record Identity v2 (NEW synthetic WinForms fixture). +# +# A deliberately real WinForms app standing in for OpenDental's chart+note +# workflow (list-select -> edit note -> save). It is the vision-replay TARGET +# and the UIA-arm target: real WinForms controls expose a genuine (and, for +# the DataGridView rows, deliberately partial) UIA tree -- the "WinForms a11y +# is often broken" finding the spike wants measured, not asserted. +# +# All persistence goes through pn_db.py (SQLite), so the benchmark judge reads +# ground truth from the DB, never from OCR. DPI scaling is honored +# (AutoScaleMode=Dpi) so the DPI drift condition actually moves pixels. +# +# Usage: powershell -STA -ExecutionPolicy Bypass -File patient_notes.ps1 + +param( + [string]$Python = "C:\Program Files\Python312-arm64\python.exe", + [string]$DbCli = "C:\oa\pn_db.py" +) + +Add-Type -AssemblyName System.Windows.Forms +Add-Type -AssemblyName System.Drawing +[System.Windows.Forms.Application]::EnableVisualStyles() + +# --- drift knobs (read from C:\oa\pn_env.json, written by the harness) ------ +# font_scale : render-scale proxy for DPI drift (1.0 / 1.25 / 1.5). Real +# per-monitor DPI change needs a session logoff (see LIMITS.md); scaling the +# base font reproduces the same class of rendering shift -- larger glyphs, +# moved targets -- that defeats pixel-template matching, the effect under test. +# theme : "dark" flips to a dark colour scheme. +# window : "maximized" (default) or "windowed"; size "WxH" forces windowed. +# A JSON config file is used instead of env vars because the harness launches +# the app in session 1 via CreateProcessAsUser, which does not inherit the +# caller's environment. +$cfg = @{ font_scale = 1.0; theme = ""; window = "maximized"; size = "" } +$cfgPath = "C:\oa\pn_env.json" +if (Test-Path $cfgPath) { + try { + $j = Get-Content $cfgPath -Raw | ConvertFrom-Json + foreach ($k in @("font_scale", "theme", "window", "size")) { + if ($null -ne $j.$k) { $cfg[$k] = $j.$k } + } + } catch {} +} +$fontScale = [double]$cfg["font_scale"] +$baseFont = New-Object System.Drawing.Font("Segoe UI", (9.0 * $fontScale)) +$theme = [string]$cfg["theme"] +$bgColor = [System.Drawing.Color]::White +$fgColor = [System.Drawing.Color]::Black +if ($theme -eq "dark") { + $bgColor = [System.Drawing.Color]::FromArgb(32, 32, 32) + $fgColor = [System.Drawing.Color]::FromArgb(230, 230, 230) +} + +function Invoke-Db { + param([string[]]$DbArgs, [switch]$RequireSuccess) + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $Python + $psi.Arguments = (@("`"$DbCli`"") + $DbArgs) -join ' ' + $psi.RedirectStandardOutput = $true + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $p = [System.Diagnostics.Process]::Start($psi) + $out = $p.StandardOutput.ReadToEnd() + $p.WaitForExit() + if ($RequireSuccess -and $p.ExitCode -ne 0) { throw "Database command failed" } + return $out +} + +$form = New-Object System.Windows.Forms.Form +$form.Text = "Patient Notes - Native Record Identity v2" +$form.Name = "patientNotesNativeIdentityV2" +$form.Size = New-Object System.Drawing.Size(900, 560) +$form.StartPosition = "Manual" +$form.Location = New-Object System.Drawing.Point(80, 80) +$form.AutoScaleMode = [System.Windows.Forms.AutoScaleMode]::Dpi +$form.Font = $baseFont +$form.BackColor = $bgColor +$form.ForeColor = $fgColor +# Maximize by default so the app fills the screen: the captured frame is then +# entirely app content (no background window bleed), which keeps identity +# bands and REGION_STABLE postconditions deterministic across record/replay. +# The window-resize drift condition overrides this to a fixed windowed size. +if ([string]$cfg["window"] -eq "windowed") { + $form.WindowState = "Normal" +} else { + $form.WindowState = "Maximized" +} +if ([string]$cfg["size"]) { + $wh = ([string]$cfg["size"]) -split 'x' + $form.WindowState = "Normal" + $form.Size = New-Object System.Drawing.Size([int]$wh[0], [int]$wh[1]) +} +$form.TopMost = $true + +$searchBox = New-Object System.Windows.Forms.TextBox +$searchBox.Name = "searchBox" +$searchBox.AccessibleName = "searchBox" +$searchBox.Location = New-Object System.Drawing.Point(20, 20) +$searchBox.Size = New-Object System.Drawing.Size(480, 28) +$form.Controls.Add($searchBox) + +$searchButton = New-Object System.Windows.Forms.Button +$searchButton.Name = "searchButton" +$searchButton.AccessibleName = "searchButton" +$searchButton.Text = "Search" +$searchButton.Location = New-Object System.Drawing.Point(510, 18) +$searchButton.Size = New-Object System.Drawing.Size(100, 30) +$form.Controls.Add($searchButton) + +$grid = New-Object System.Windows.Forms.DataGridView +$grid.Name = "patientGrid" +$grid.AccessibleName = "patientGrid" +$grid.Location = New-Object System.Drawing.Point(20, 60) +$grid.Size = New-Object System.Drawing.Size(590, 220) +$grid.ReadOnly = $true +$grid.AllowUserToAddRows = $false +$grid.SelectionMode = "FullRowSelect" +$grid.MultiSelect = $false +$grid.AutoSizeColumnsMode = "Fill" +$grid.RowHeadersVisible = $false +# Tall rows + header so an identity band around a row-click cleanly isolates +# that patient's values (Neil / Sorenson / dob) instead of bleeding into the +# column-header row above it. +$grid.RowTemplate.Height = [int](44 * $fontScale) +$grid.ColumnHeadersHeight = [int](40 * $fontScale) +$grid.AllowUserToResizeRows = $false +$form.Controls.Add($grid) + +$noteLabel = New-Object System.Windows.Forms.Label +$noteLabel.Text = "Clinical note:" +$noteLabel.Location = New-Object System.Drawing.Point(20, 295) +$noteLabel.Size = New-Object System.Drawing.Size(200, 22) +$form.Controls.Add($noteLabel) + +# Legacy display caption only. The NEW v2 pack reads currentRecordId's complete +# native value for identity; this label's Name/preview is not identity authority. +$patientHeader = New-Object System.Windows.Forms.Label +$patientHeader.Name = "patientHeader" +$patientHeader.Text = "" +$patientHeader.Location = New-Object System.Drawing.Point(230, 295) +$patientHeader.Size = New-Object System.Drawing.Size(380, 22) +$form.Controls.Add($patientHeader) + +$noteBox = New-Object System.Windows.Forms.TextBox +$noteBox.Name = "noteBox" +$noteBox.AccessibleName = "noteBox" +$noteBox.Multiline = $true +$noteBox.Location = New-Object System.Drawing.Point(20, 320) +$noteBox.Size = New-Object System.Drawing.Size(590, 120) +$form.Controls.Add($noteBox) + +# NEW v2 fixture identity: a readonly standard Edit value, not a caption. +$currentRecordId = New-Object System.Windows.Forms.TextBox +$currentRecordId.Name = "currentRecordId" +$currentRecordId.AccessibleName = "currentRecordId" +$currentRecordId.ReadOnly = $true +$currentRecordId.UseSystemPasswordChar = $false +$currentRecordId.PasswordChar = [char]0 +$currentRecordId.TabStop = $false +$currentRecordId.Location = New-Object System.Drawing.Point(650, 320) +$currentRecordId.Size = New-Object System.Drawing.Size(210, 28) +$currentRecordId.Text = "" +$form.Controls.Add($currentRecordId) + +$saveButton = New-Object System.Windows.Forms.Button +$saveButton.Name = "saveButton" +$saveButton.AccessibleName = "saveButton" +$saveButton.Text = "Save Note" +$saveButton.Location = New-Object System.Drawing.Point(510, 450) +$saveButton.Size = New-Object System.Drawing.Size(100, 34) +$form.Controls.Add($saveButton) + +$status = New-Object System.Windows.Forms.Label +$status.Name = "statusLabel" +$status.AccessibleName = "statusLabel" +$status.Text = "Ready" +$status.Location = New-Object System.Drawing.Point(20, 458) +$status.Size = New-Object System.Drawing.Size(470, 22) +$form.Controls.Add($status) + +# Only the NEW fixture publishes an independently inspectable record id. +$script:recordIdentityLoading = $false + +function ConvertTo-RecordId { + param($Value) + # SQLite INTEGER PRIMARY KEY is signed int64. Refuse aliases/coercions. + if ($Value -isnot [string] -and $Value -isnot [int] -and $Value -isnot [long]) { + throw "Record id is not an exact integer or canonical string" + } + $text = [Convert]::ToString($Value, [Globalization.CultureInfo]::InvariantCulture) + [long]$parsed = 0 + $ok = [long]::TryParse($text, [Globalization.NumberStyles]::AllowLeadingSign, + [Globalization.CultureInfo]::InvariantCulture, [ref]$parsed) + if (-not $ok -or $parsed.ToString([Globalization.CultureInfo]::InvariantCulture) -cne $text) { + throw "Record id is not canonical signed int64" + } + return $text +} + +function Clear-CurrentRecord { + $currentRecordId.Text = "" + $noteBox.Text = "" + $patientHeader.Text = "" +} + +function Get-SelectedRecordId { + if ($grid.SelectedRows.Count -ne 1) { throw "No unique selected record" } + return ConvertTo-RecordId $grid.SelectedRows[0].Cells["id"].Value +} + +function Update-CurrentRecord { + Clear-CurrentRecord + if ($script:recordIdentityLoading) { return } + try { + $selectedId = Get-SelectedRecordId + $j = Invoke-Db -DbArgs @("get", "$selectedId") -RequireSuccess + # Root shape is checked before PS5.1/7 pipeline enumeration. + if (-not $j.TrimStart().StartsWith("{")) { throw "Get requires an object root" } + $p = $j | ConvertFrom-Json -ErrorAction Stop + if ($null -eq $p -or $p -is [array]) { throw "No unique loaded record" } + $loadedId = ConvertTo-RecordId $p.id + if ($loadedId -cne $selectedId) { throw "Loaded record differs from selection" } + $noteBox.Text = $p.note + $patientHeader.Text = "Patient: " + $p.first + " " + $p.last + " (" + $p.dob + ")" + # A fresh selection read prevents publishing a stale in-flight load. + if ((Get-SelectedRecordId) -cne $loadedId) { throw "Selection changed during load" } + $currentRecordId.Text = $loadedId + } catch { + Clear-CurrentRecord + $status.Text = "Record identity unavailable" + } +} + +function Load-Patients { + param([string]$Filter) + $script:recordIdentityLoading = $true + Clear-CurrentRecord + $loaded = $false + try { + $json = Invoke-Db -DbArgs @("list", "`"$Filter`"") -RequireSuccess + if (-not $json.TrimStart().StartsWith("[")) { throw "List requires an array root" } + $rows = @($json | ConvertFrom-Json -ErrorAction Stop) + $dt = New-Object System.Data.DataTable + [void]$dt.Columns.Add("id") + [void]$dt.Columns.Add("first") + [void]$dt.Columns.Add("last") + [void]$dt.Columns.Add("dob") + foreach ($r in $rows) { + $id = ConvertTo-RecordId $r.id + [void]$dt.Rows.Add($id, $r.first, $r.last, $r.dob) + } + $grid.DataSource = $dt + if ($grid.Columns["id"]) { $grid.Columns["id"].Visible = $false } + $status.Text = "Loaded " + $rows.Count + " patients" + $loaded = $true + } catch { + $grid.ClearSelection() + $grid.DataSource = $null + Clear-CurrentRecord + $status.Text = "Record list unavailable" + } finally { + $script:recordIdentityLoading = $false + } + if ($loaded) { Update-CurrentRecord } +} + +$searchButton.Add_Click({ Load-Patients -Filter $searchBox.Text }) +$searchBox.Add_KeyDown({ + if ($_.KeyCode -eq "Enter") { Load-Patients -Filter $searchBox.Text; $_.SuppressKeyPress = $true } +}) + +$grid.Add_SelectionChanged({ Update-CurrentRecord }) + +$saveButton.Add_Click({ + if ($grid.SelectedRows.Count -lt 1) { $status.Text = "No patient selected"; return } + $id = $grid.SelectedRows[0].Cells["id"].Value + $bytes = [Text.Encoding]::UTF8.GetBytes($noteBox.Text) + $b64 = [Convert]::ToBase64String($bytes) + $res = Invoke-Db -DbArgs @("save", "$id", "$b64") + $status.Text = "Saved note for patient $id" +}) + +if ($theme -eq "dark") { + foreach ($c in @($searchBox, $noteBox, $currentRecordId)) { + $c.BackColor = [System.Drawing.Color]::FromArgb(50, 50, 50) + $c.ForeColor = $fgColor + } + $grid.BackgroundColor = [System.Drawing.Color]::FromArgb(45, 45, 45) + $grid.DefaultCellStyle.BackColor = [System.Drawing.Color]::FromArgb(45, 45, 45) + $grid.DefaultCellStyle.ForeColor = $fgColor + $grid.ColumnHeadersDefaultCellStyle.BackColor = [System.Drawing.Color]::FromArgb(60, 60, 60) + $grid.ColumnHeadersDefaultCellStyle.ForeColor = $fgColor + $grid.EnableHeadersVisualStyles = $false +} + +Load-Patients -Filter "" +[void]$form.ShowDialog() diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/readback.template.json b/packages/flow/tests/fixtures/native_record_identity_v2/readback.template.json new file mode 100644 index 0000000000..cd78581f62 --- /dev/null +++ b/packages/flow/tests/fixtures/native_record_identity_v2/readback.template.json @@ -0,0 +1,32 @@ +{ + "search": { + "box": { + "automation_id": "searchBox" + }, + "query": { + "param": "patient_search" + }, + "submit": { + "automation_id": "searchButton" + } + }, + "ready": { + "automation_id": "currentRecordId" + }, + "identity": { + "reader": { + "automation_id": "currentRecordId" + }, + "value": { + "param": "record_id" + }, + "field": "id" + }, + "fields": { + "note": { + "control": { + "automation_id": "noteBox" + } + } + } +} diff --git a/packages/flow/tests/test_native_record_identity_fixture.py b/packages/flow/tests/test_native_record_identity_fixture.py new file mode 100644 index 0000000000..c928cac557 --- /dev/null +++ b/packages/flow/tests/test_native_record_identity_fixture.py @@ -0,0 +1,246 @@ +"""Source/SQLite qualification of a NEW case; no native Windows claims.""" + +from __future__ import annotations + +import copy +import importlib.util +import json +import os +import shutil +import sqlite3 +import subprocess +import sys +from pathlib import Path + +import pytest + +from openadapt_flow.runtime.effects.desktop_readback import DesktopReadbackSpec + +HERE = Path(__file__).parent / "fixtures" / "native_record_identity_v2" +spec = importlib.util.spec_from_file_location( + "identity_fixture_builder", HERE / "build_fixture.py" +) +assert spec and spec.loader +builder = importlib.util.module_from_spec(spec) +spec.loader.exec_module(builder) +FLOW = HERE.parents[2] +DB_CLI = FLOW / "scripts" / "desktop" / "pn_db.py" + + +def test_generated_source_and_pack_are_reproducible() -> None: + for name, data in builder.outputs().items(): + assert (HERE / name).read_bytes() == data + contract = builder.load_contract() + base = builder.canonical_source(FLOW / contract["base_source"]["path"]) + generated = (HERE / "patient_notes_v2.ps1").read_text() + assert builder.save_handler(base.decode()) == builder.save_handler(generated) + assert "currentRecordId" not in base.decode() + assert contract["qualification"]["native_value_proof"] is None + assert contract["qualification"]["database_to_control_binding_proof"] is None + assert contract["qualification"]["combined_campaign"] is None + + +@pytest.mark.parametrize("fault", ["base", "anchor", "save"]) +def test_source_drift_and_save_changes_are_refused(fault: str) -> None: + contract = builder.load_contract() + base = builder.canonical_source(FLOW / contract["base_source"]["path"]) + override = json.loads((HERE / "override.json").read_text()) + if fault == "base": + base += b"\n# drift\n" + elif fault == "anchor": + override["patches"][0]["before"] = "missing source anchor" + else: + override["patches"].append( + {"before": '"Saved note for patient $id"', "after": '"changed"'} + ) + with pytest.raises(ValueError): + builder.build(base, override) + + +@pytest.mark.parametrize( + "fault", ["table", "key", "value", "loaded_field", "pack_identity"] +) +def test_actual_lookup_and_save_sql_reject_planted_pack_mapping(fault: str) -> None: + contract = builder.load_contract() + if fault in {"table", "key", "value"}: + contract["database_mapping"][fault] = "another_column_or_table" + elif fault == "loaded_field": + contract["identity_binding"][fault] = "first" + else: + contract["readback_template"]["identity"]["field"] = "first" + with pytest.raises(ValueError): + builder.validate_source_mapping(builder.canonical_source(DB_CLI), contract) + + +def test_pack_names_complete_value_identity_without_virtual_grid_claims() -> None: + # Validation only. This never creates a backend or opens a session. + spec = DesktopReadbackSpec.model_validate( + builder.readback_spec({"kind": "windows", "agent_url": "http://127.0.0.1:1"}) + ) + assert spec.open is None + assert spec.ready.automation_id == "currentRecordId" + assert spec.identity.reader.automation_id == "currentRecordId" + assert spec.identity.field == "id" + assert spec.identity.value.param == "record_id" + assert spec.fields["note"].control.automation_id == "noteBox" + requirements = builder.load_contract()["read_requirements"] + assert requirements["require_editable"] is False + assert requirements["value_contract"] == "openadapt.native-value-completeness/v2" + assert not requirements["runtime_protocol_qualified"] + + +@pytest.fixture +def database(tmp_path: Path) -> tuple[Path, dict[str, str]]: + path = tmp_path / "patients.db" + env = {"PN_DB": str(path), "PATH": os.defpath} + # Windows subprocesses may require these non-secret OS paths. Never pass + # the host environment wholesale or return credentials in fixture reprs. + for name in ("SystemRoot", "WINDIR", "TEMP", "TMP", "PATHEXT"): + if os.getenv(name) is not None: + env[name] = os.environ[name] + subprocess.run( + [sys.executable, str(DB_CLI), "seed", "--drift", "siblings"], + env=env, + check=True, + capture_output=True, + text=True, + ) + with sqlite3.connect(path) as con: + con.executemany( + "INSERT INTO patients VALUES (?, 'Synthetic', 'Boundary', '2000-01-01', '')", + [(-(2**63),), (0,), (2**63 - 1,)], + ) + con.execute("UPDATE patients SET note = 'seed-note-' || id") + return path, env + + +def test_real_cli_json_ids_match_independent_sqlite_rows(database: tuple) -> None: + path, env = database + mapping = builder.load_contract()["database_mapping"] + with sqlite3.connect(path) as con: + builder.validate_database(con, mapping) + rows = con.execute( + "SELECT id, first, last, dob, note FROM patients ORDER BY id" + ).fetchall() + for row in rows: + result = subprocess.run( + [sys.executable, str(DB_CLI), "get", str(row[0])], + env=env, + check=True, + capture_output=True, + text=True, + ) + assert json.loads(result.stdout) == dict( + zip(("id", "first", "last", "dob", "note"), row) + ) + + +@pytest.mark.parametrize("fault", ["table", "key", "value", "key_type", "value_type"]) +def test_planted_mapping_faults_are_refused(database: tuple, fault: str) -> None: + path, _ = database + mapping = copy.deepcopy(builder.load_contract()["database_mapping"]) + mapping[fault] = { + "table": "missing", + "key": "first", + "value": "id", + "key_type": "TEXT", + "value_type": "INTEGER", + }[fault] + with sqlite3.connect(path) as con, pytest.raises(ValueError): + builder.validate_database(con, mapping) + + +@pytest.mark.parametrize( + "schema", + [ + "id TEXT PRIMARY KEY, note TEXT", + "id INTEGER, note TEXT", + "id INTEGER, other INTEGER, note TEXT, PRIMARY KEY(id, other)", + ], +) +def test_non_integer_or_non_unique_identity_schema_is_refused(schema: str) -> None: + with sqlite3.connect(":memory:") as con: + con.execute(f"CREATE TABLE patients ({schema})") + with pytest.raises(ValueError): + builder.validate_database(con, builder.load_contract()["database_mapping"]) + + +def test_actual_generated_powershell_lifecycle_without_gui( + database: tuple, tmp_path: Path +) -> None: + pwsh = shutil.which("pwsh") + if pwsh is None: + pytest.skip("PowerShell unavailable; native qualification is still unperformed") + path, env = database + fail_cli = tmp_path / "fail_cli.py" + fail_cli.write_text("raise SystemExit(3)\n") + with sqlite3.connect(path) as con: + before = con.execute("SELECT * FROM patients ORDER BY id").fetchall() + result = subprocess.run( + [ + pwsh, + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-File", + str(HERE / "check_lifecycle.ps1"), + "-Fixture", + str(HERE / "patient_notes_v2.ps1"), + "-Python", + sys.executable, + "-DbCli", + str(DB_CLI), + "-FailCli", + str(fail_cli), + ], + env=env, + capture_output=True, + text=True, + timeout=90, + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads(result.stdout) + assert report["scope"] == "offline-generated-functions-fake-controls-real-sqlite" + assert report["native_validation"] is False + assert len(report["cases"]) == report["count"] == 26 + with sqlite3.connect(path) as con: + assert con.execute("SELECT * FROM patients ORDER BY id").fetchall() == before + + +def test_lifecycle_checker_detects_omitted_note_clear( + database: tuple, tmp_path: Path +) -> None: + pwsh = shutil.which("pwsh") + if pwsh is None: + pytest.skip("PowerShell unavailable; checker-negative cannot execute") + _, env = database + source = (HERE / "patient_notes_v2.ps1").read_text() + assert source.count(' $noteBox.Text = ""\n') == 1 + mutant = tmp_path / "planted_missing_note_clear.ps1" + mutant.write_text(source.replace(' $noteBox.Text = ""\n', "")) + fail_cli = tmp_path / "fail_cli.py" + fail_cli.write_text("raise SystemExit(3)\n") + result = subprocess.run( + [ + pwsh, + "-NoLogo", + "-NoProfile", + "-NonInteractive", + "-File", + str(HERE / "check_lifecycle.ps1"), + "-Fixture", + str(mutant), + "-Python", + sys.executable, + "-DbCli", + str(DB_CLI), + "-FailCli", + str(fail_cli), + ], + env=env, + capture_output=True, + text=True, + timeout=90, + ) + assert result.returncode != 0 + assert "Stale identity/value in selection-reset" in result.stderr From 57357add64d9c1c58ba646910b75f0e1a02f9c16 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 11:34:55 -0500 Subject: [PATCH 2/2] test(flow): align native fixture protocol references Signed-off-by: abrichr --- .../native_record_identity_v2/README.md | 27 +++++++++++-------- .../native_record_identity_v2/RESULTS.md | 17 ++++++++++++ .../native_record_identity_v2/contract.json | 10 +++---- .../test_native_record_identity_fixture.py | 2 +- 4 files changed, 39 insertions(+), 17 deletions(-) diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/README.md b/packages/flow/tests/fixtures/native_record_identity_v2/README.md index 829f77feb5..e7f0f3d912 100644 --- a/packages/flow/tests/fixtures/native_record_identity_v2/README.md +++ b/packages/flow/tests/fixtures/native_record_identity_v2/README.md @@ -12,6 +12,10 @@ records leave the ID empty. A failed list load also clears the selection and list. The original save handler still saves to the selected grid key; the new fixture adds no save guard. +This PR delivers fixture data and offline generation only. The generated +legacy-shaped readback template is nonauthoritative: it does not enforce exact +canonical-ID matching or admit a runtime. That consumer work remains separate. + `contract.json` declares the database mapping and a data-only readback template. The generator applies exact overrides to a hash-pinned base and emits a distinct script, pack and manifest. Run from `packages/flow`: @@ -42,17 +46,18 @@ precede PowerShell pipeline enumeration. They open no GUI and send no desktop in These checks establish source behavior under those stand-ins, not native WinForms behavior. -Native qualification is **unperformed**. The intended structural read requires -the corrected known-non-password guard, mandatory `value_contract` negotiation -and `openadapt.native-value-completeness/v2` proof. Readonly identity uses -`require_editable=False`; it is not an editable-field baseline. Unsupported, -sensitive, truncated or disagreeing values must refuse, with no caption, -preview or OCR fallback. The protocol continuation was inspected at -`87d29b31b81131d591a8033ceac84e533f68264b` with shared helper -`7f65509068feb035236dd1d8a78db4daa5038e69`. Further consumer corrections -are pending; this is a source reference, not a final runtime pin or native -qualification. This fixture does not qualify an older -runtime. +Native qualification is **unperformed**. The intended structural read uses +request contract `openadapt.native-value-read/v3` and the separate +`openadapt.native-value-completeness/v3` proof schema. These are source references +from frozen #2291 at `1a2503da4e240ba24620845cf85737d087c38e39`, with shared +helper commit `4be4b543da10286105090950c57a89d5e7a9a497` (Git blob +`78e47eb02e7498b5111766f25f3604e8ab78ee50`). They do not establish final protocol, +runtime or native qualification; all contract holds remain false or null. +Readonly identity uses `require_editable=False`; it is not an editable-field +baseline. Unsupported, sensitive, truncated or disagreeing values must refuse, +with no caption, preview or OCR fallback. The known-non-password guard and +mandatory `value_contract` negotiation remain prerequisites for future consumer +integration. This fixture does not qualify an older runtime. A future native case must independently compare the selected key, loaded DB row, actual managed control value and complete native UIA/Win32 observation, diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md b/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md index 15def8fac5..7196ce2a19 100644 --- a/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md +++ b/packages/flow/tests/fixtures/native_record_identity_v2/RESULTS.md @@ -19,3 +19,20 @@ used. Windows PowerShell 5.1 and native WinForms event/provider behavior remain unmeasured. The shared consumer protocol, exact canonical-ID matching, live DB-row-to-control binding, combined campaign and held-out qualification remain held. No prior result or denominator changed. + +## Protocol reference correction + +The intended request contract is `openadapt.native-value-read/v3`; the separate +proof schema is `openadapt.native-value-completeness/v3`, as defined by frozen +#2291 at `1a2503da4e240ba24620845cf85737d087c38e39` and helper commit +`4be4b543da10286105090950c57a89d5e7a9a497`. These source references replace the +historical v2 references. Every false/null qualification hold remains in place; +the legacy-shaped template remains nonauthoritative. + +The existing focused suite passed again: 21 cases, no skips (Python 3.12.13, +3.73 seconds), with Flow and Types imports verified against the correction +checkout. The existing generated-output check, changed-file Ruff lint/format +checks and repository source-boundary guard passed. All checks used the shared +CPU slot. No new test cases, native/GUI/provider execution, runtime integration +or qualification claim was added. Generated fixture, template, base and save +handler bytes are unchanged. diff --git a/packages/flow/tests/fixtures/native_record_identity_v2/contract.json b/packages/flow/tests/fixtures/native_record_identity_v2/contract.json index 917740df82..691f4c7448 100644 --- a/packages/flow/tests/fixtures/native_record_identity_v2/contract.json +++ b/packages/flow/tests/fixtures/native_record_identity_v2/contract.json @@ -30,13 +30,13 @@ "read_requirements": { "route": "/uia/read", "require_editable": false, - "value_contract": "openadapt.native-value-completeness/v2", - "proof_schema": "openadapt.native-value-completeness/v2", + "value_contract": "openadapt.native-value-read/v3", + "proof_schema": "openadapt.native-value-completeness/v3", "runtime_protocol_qualified": false, - "shared_helper_ref": "7f65509068feb035236dd1d8a78db4daa5038e69", + "shared_helper_ref": "4be4b543da10286105090950c57a89d5e7a9a497", "identity_match": "exact canonical signed int64 string", "identity_match_qualified": false, - "protocol_source_reference_seen": "87d29b31b81131d591a8033ceac84e533f68264b", + "protocol_source_reference_seen": "1a2503da4e240ba24620845cf85737d087c38e39", "protocol_source_finalized": false }, "readback_template": { @@ -80,7 +80,7 @@ "row_count_evidence": false }, "native_validation_required": [ - "known-non-password readonly Edit; complete UIA/native agreement with proof v2", + "known-non-password readonly Edit; complete UIA/native agreement with proof v3", "actual selected id = get.id = native observed id = independently queried SQLite id", "no selection, list/get failure, missing/wrong row and mid-load selection replacement clear identity", "target note and every sibling checked directly in SQLite", diff --git a/packages/flow/tests/test_native_record_identity_fixture.py b/packages/flow/tests/test_native_record_identity_fixture.py index c928cac557..70db3f7823 100644 --- a/packages/flow/tests/test_native_record_identity_fixture.py +++ b/packages/flow/tests/test_native_record_identity_fixture.py @@ -85,7 +85,7 @@ def test_pack_names_complete_value_identity_without_virtual_grid_claims() -> Non assert spec.fields["note"].control.automation_id == "noteBox" requirements = builder.load_contract()["read_requirements"] assert requirements["require_editable"] is False - assert requirements["value_contract"] == "openadapt.native-value-completeness/v2" + assert requirements["value_contract"] == "openadapt.native-value-read/v3" assert not requirements["runtime_protocol_qualified"]