From 8f131f2e6ef9d2b0fce064292189b5dfe5154d8c Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:15:03 +0200 Subject: [PATCH 01/24] fix(ci): isolate account test prerequisites --- Scripts/accounts/SaiAccountsHelper.cs | 12 ++++++++--- tests/test_sai_accounts.py | 29 +++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/Scripts/accounts/SaiAccountsHelper.cs b/Scripts/accounts/SaiAccountsHelper.cs index be62a40..79ac833 100644 --- a/Scripts/accounts/SaiAccountsHelper.cs +++ b/Scripts/accounts/SaiAccountsHelper.cs @@ -922,13 +922,20 @@ private static bool IsTestMode() return Environment.GetEnvironmentVariable("SAI_HELPER_TEST_MODE") == "1"; } + private static string ResolveUserSid(string username) + { + if (IsTestMode()) + return "S-1-5-21-999999999-888888888-777777777-" + Math.Abs(username.GetHashCode() % 9000 + 1000); + return ((SecurityIdentifier)new NTAccount(username).Translate(typeof(SecurityIdentifier))).Value; + } + public static bool CreateLocalUser(string username, string password, out string sid, out string error) { sid = null; error = null; if (IsTestMode()) { // Simulated user for hermetic testing - sid = "S-1-5-21-999999999-888888888-777777777-" + Math.Abs(username.GetHashCode() % 9000 + 1000); + sid = ResolveUserSid(username); return true; } @@ -1756,8 +1763,7 @@ private static Dictionary HandleRequest(string op, Dictionary Date: Wed, 28 Oct 2026 15:21:31 +0200 Subject: [PATCH 02/24] fix(installer): normalize owned target paths --- Scripts/accounts/InstallImage.ps1 | 4 +++- tests/test_account_console_titles.py | 3 ++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Scripts/accounts/InstallImage.ps1 b/Scripts/accounts/InstallImage.ps1 index 2ec50f6..85fcd78 100644 --- a/Scripts/accounts/InstallImage.ps1 +++ b/Scripts/accounts/InstallImage.ps1 @@ -10,9 +10,11 @@ function Get-SaiExecutableHash([string]$Path) { function Install-SaiExecutableImage([string]$Source, [string]$Target, [string]$AllowedDirectory) { $directory = (Get-Item -LiteralPath $AllowedDirectory -ErrorAction Stop).FullName $destination = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Target) - if (-not [string]::Equals([IO.Path]::GetDirectoryName($destination).TrimEnd('\'), $directory.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { + $destinationDirectory = (Get-Item -LiteralPath ([IO.Path]::GetDirectoryName($destination)) -ErrorAction Stop).FullName + if (-not [string]::Equals($destinationDirectory.TrimEnd('\'), $directory.TrimEnd('\'), [StringComparison]::OrdinalIgnoreCase)) { throw "Executable replacement target is outside its owned directory: $destination" } + $destination = Join-Path $destinationDirectory ([IO.Path]::GetFileName($destination)) $sourcePath = (Get-Item -LiteralPath $Source -ErrorAction Stop).FullName $sourceHash = Get-SaiExecutableHash $sourcePath if ((Test-Path -LiteralPath $destination -PathType Leaf) -and diff --git a/tests/test_account_console_titles.py b/tests/test_account_console_titles.py index 75f7691..1eed0b9 100644 --- a/tests/test_account_console_titles.py +++ b/tests/test_account_console_titles.py @@ -126,7 +126,8 @@ def check_antigravity_result(self, launched): self.assertEqual(payload["expected_title"], title) self.assertEqual(payload["expected_account"], account) self.assertEqual(payload["arguments"], ["--dangerously-skip-permissions"]) - self.assertEqual(os.path.normcase(payload["cwd"]), os.path.normcase(workdir)) + self.assertEqual(os.path.normcase(os.path.realpath(payload["cwd"])), + os.path.normcase(os.path.realpath(workdir))) self.assertEqual(payload["console_process_count"], 2, "guard and vendor must share one console") self.assertEqual(payload["console_process_count_after"], 2, "the guard lives until its vendor exits") self.assertTrue(payload["sid"].startswith("S-1-5-21-")) From 8064c967c9aaa8fc05b8d14edcb28e21944c1d78 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:29:02 +0200 Subject: [PATCH 03/24] test(identity): report render mismatch location --- tests/account_identity_contract_test.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/account_identity_contract_test.cs b/tests/account_identity_contract_test.cs index ad3dd8c..b508c26 100644 --- a/tests/account_identity_contract_test.cs +++ b/tests/account_identity_contract_test.cs @@ -62,7 +62,11 @@ static bool Equal(Bitmap left, Bitmap right) { for (int y = 0; y < left.Height; y++) for (int x = 0; x < left.Width; x++) - if (left.GetPixel(x, y) != right.GetPixel(x, y)) return false; + if (left.GetPixel(x, y) != right.GetPixel(x, y)) + { + Console.WriteLine("PIXEL_DIFF x=" + x + " y=" + y); + return false; + } return true; } [STAThread] From 274be719374fff971054e624317ea2991cd53b75 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:32:37 +0200 Subject: [PATCH 04/24] test(identity): capture execution label context --- tests/account_identity_contract_test.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/account_identity_contract_test.cs b/tests/account_identity_contract_test.cs index b508c26..2a71869 100644 --- a/tests/account_identity_contract_test.cs +++ b/tests/account_identity_contract_test.cs @@ -48,6 +48,8 @@ static IList Rows(params object[] rows) } static Bitmap Render(Saituls.SaitulsForm form, object row, int width, int height) { + Console.WriteLine("RENDER execution=" + App.GetMethod("ExecutionLabel", Any).Invoke(form, new object[] { row }) + + " context=" + Text(row, "Context") + " runtime=" + Text(row, "RuntimeIdentityFp")); var image = new Bitmap(width, height); using (var g = Graphics.FromImage(image)) { From 69f352800a78e7c3dd9b15e4de3dba0423d1cb00 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:35:51 +0200 Subject: [PATCH 05/24] test(identity): stabilize first-paint comparisons --- tests/account_identity_contract_test.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/account_identity_contract_test.cs b/tests/account_identity_contract_test.cs index 2a71869..c05caf1 100644 --- a/tests/account_identity_contract_test.cs +++ b/tests/account_identity_contract_test.cs @@ -48,8 +48,6 @@ static IList Rows(params object[] rows) } static Bitmap Render(Saituls.SaitulsForm form, object row, int width, int height) { - Console.WriteLine("RENDER execution=" + App.GetMethod("ExecutionLabel", Any).Invoke(form, new object[] { row }) - + " context=" + Text(row, "Context") + " runtime=" + Text(row, "RuntimeIdentityFp")); var image = new Bitmap(width, height); using (var g = Graphics.FromImage(image)) { @@ -88,8 +86,14 @@ static int Main() object row = Row("AG1", "antigravity", Alice); Set(form, "_accounts", Rows(row)); Set(form, "_accountsRuntime", Rows(row)); Set(form, "_selectedAccount", "contract-AG1"); + // The invisible fixture has not had a first paint. Real GDI + // font initialization changes even the unchanged subtitle on + // hosted Windows; initialize it before comparing identities. + using (var warmup = Render(form, row, 640, 540)) { } using (var same = Render(form, row, 640, 540)) { + using (var unchanged = Render(form, row, 640, 540)) + Check(Equal(same, unchanged), "unchanged identity rendering is stable before comparisons"); Set(row, "RuntimeIdentityFp", Bob); using (var distinct = Render(form, row, 640, 540)) { From 918dda521e8d6259a00002d247ceb1d2d2a33007 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:47:41 +0200 Subject: [PATCH 06/24] fix(access): preserve unowned ACL grants Reject existing explicit allows before granting a read lease. Revoke and expiry sweep must refuse an ACL changed since the grant, because removing all allows for that SID could otherwise erase somebody else's permissions. Exercise existing FullControl and changed grants with native ACL checks. --- Scripts/accounts/sai_access.py | 44 +++++++++++++++++++++++++++---- tests/test_sai_access.py | 48 ++++++++++++++++++++++++++++++---- 2 files changed, 82 insertions(+), 10 deletions(-) diff --git a/Scripts/accounts/sai_access.py b/Scripts/accounts/sai_access.py index b1d4e47..e4267cc 100644 --- a/Scripts/accounts/sai_access.py +++ b/Scripts/accounts/sai_access.py @@ -21,9 +21,9 @@ records the exact ACL state before and after the grant so a revoke removes only what this lease demonstrably created. -stdlib only, no new dependencies. The ACL is written and read with the -platform's own tool (icacls), so every other ACE is preserved by construction -and no ownership is taken. +stdlib only, no new dependencies. ACL writes use icacls; explicit grants are +inspected through Windows security APIs in PowerShell. Existing explicit +grants and ACLs changed after a lease are refused rather than claimed. """ import json import os @@ -200,6 +200,37 @@ def icacls(path, verb, identity, rights=""): (proc.stdout + proc.stderr).strip()[:300]) +def has_explicit_allow(path, sid): + """A pre-existing allow rule cannot be owned or revoked by this lease.""" + quote = lambda value: "'" + str(value).replace("'", "''") + "'" + script = ( + "$ErrorActionPreference='Stop'; " + "$acl=Get-Acl -LiteralPath %s; " + "$rules=$acl.GetAccessRules($true,$false,[Security.Principal.SecurityIdentifier]); " + "[bool](@($rules | Where-Object { $_.IdentityReference.Value -eq %s " + "-and $_.AccessControlType -eq 'Allow' }).Count) | ConvertTo-Json -Compress" + ) % (quote(path), quote(sid)) + # A parent PowerShell 7 module path cannot be reused by Windows PowerShell. + env = {key: value for key, value in os.environ.items() if key.upper() != "PSMODULEPATH"} + proc = subprocess.run(["powershell", "-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script], + capture_output=True, text=True, timeout=60, env=env) + try: + answer = json.loads(proc.stdout) + except ValueError: + answer = None + if proc.returncode or type(answer) is not bool: + raise LeaseError("ACL_READ_FAILED", (proc.stdout + proc.stderr).strip()[:300]) + return answer + + +def remove_owned_allow(lease): + """Refuse removal when the current ACL no longer matches the lease.""" + if acl_text(lease["source"]) != lease.get("acl_after"): + raise LeaseError("ACL_CHANGED_SINCE_GRANT", + "the ACL changed since this lease; refusing to remove unowned rules") + icacls(lease["source"], "/remove:g", lease["windows_sid"]) + + def ancestors_traversable(selector, target): """A read ACE on a nested object is unreachable unless every ancestor is already traversable by that account. Opening a directory already requires @@ -287,6 +318,9 @@ def cmd_grant(argv): if "--recursive" in flags and not is_directory(target): raise LeaseError("RECURSIVE_ONLY_FOR_DIRECTORIES", target) + if has_explicit_allow(target, sid): + raise LeaseError("EQUIVALENT_ACE_ALREADY_PRESENT", + "an explicit allow rule already exists for this SID; a lease cannot own it") before = acl_text(target) if recursive: rights = "(OI)(CI)(R)" @@ -350,7 +384,7 @@ def cmd_revoke(argv): target = lease["source"] before = acl_text(target) - icacls(target, "/remove:g", lease["windows_sid"]) + remove_owned_allow(lease) after = acl_text(target) if after != lease.get("acl_before"): @@ -414,7 +448,7 @@ def cmd_sweep(argv): if lease is None or lease.get("revoked") or not lease_expired(lease): continue try: - icacls(lease["source"], "/remove:g", lease["windows_sid"]) + remove_owned_allow(lease) except LeaseError as ex: # A lease that cannot be revoked stays in the journal and is # reported. It is never silently dropped. diff --git a/tests/test_sai_access.py b/tests/test_sai_access.py index 9666451..0b32d35 100644 --- a/tests/test_sai_access.py +++ b/tests/test_sai_access.py @@ -4,8 +4,8 @@ module is allowed to use (get / probe-workdir / verify-file), and every verb it receives is recorded so the test can prove no privileged verb was ever asked for. icacls runs for real, against disposable objects in a temp directory, under -the operator's own identity: the ACE written and removed is one this lease -created, and nothing else is touched. +the operator's own identity, granting Local Service access to disposable test +objects through a fake registry. No Windows account or session is created. Run: python tests/test_sai_access.py """ @@ -137,7 +137,13 @@ def main(): capture_output=True, text=True).stdout.strip() if not identity.startswith("S-1-5-"): raise SystemExit("could not resolve an operator SID for the ACL checks: %r" % identity) - os.environ["FAKE_IDENTITY"] = identity + # Use a resolvable SID absent from the file's default ACL, so the lease + # cannot merge with (or revoke) the operator's pre-existing FullControl. + os.environ["FAKE_IDENTITY"] = 'S-1-5-19' + target_name = subprocess.run([ + "powershell", "-NoProfile", "-Command", + "([Security.Principal.SecurityIdentifier]'S-1-5-19').Translate([Security.Principal.NTAccount]).Value", + ], capture_output=True, text=True, check=True).stdout.strip() global VERB_LOG VERB_LOG = os.path.join(tmp, "verbs.log") os.environ["FAKE_VERB_LOG"] = VERB_LOG @@ -149,6 +155,9 @@ def main(): target = os.path.join(workdir, "live.log") with open(target, "w", encoding="utf-8") as handle: handle.write("hello\n") + # Freeze this disposable object's inherited baseline before exercising + # leases; hosted temp directories may materialize inherited ACEs lazily. + subprocess.run(["icacls", target, "/inheritance:d"], check=True, capture_output=True) # --- argument and selection refusals for argv, code in ( @@ -205,10 +214,11 @@ def main(): "recorded the wrong result") # icacls prints the account's SID under its resolved name, so the ACE is # identified by the read right this lease granted, not by the SID string. - check("access-grant-adds-read-ace", ":(R)" in after and ":(R)" not in before, + granted = [line for line in after.splitlines() if target_name in line] + check("access-grant-adds-read-ace", len(granted) == 1 and ":(R)" in granted[0], (before, after)) check("access-grant-is-not-modify", - ":(M)" not in after and ":(F)" not in after, after) + all(":(M)" not in line and ":(F)" not in line for line in granted), after) check("access-grant-expiry-set", doc.get("expires_at") and doc.get("expires_at_iso"), doc.get("expires_at_iso")) check("access-grant-caveats-open-handles", "already-open" in doc.get("expiry_caveat", ""), @@ -237,6 +247,34 @@ def main(): check("access-foreign-ace-untouched-by-refusal", access.acl_text(target) == before, "a refused grant still mutated the object") + # A broader existing allow is equally unowned. In particular, /grant R + # must never claim ownership of an existing F and later remove that F. + access.icacls(target, "/grant", os.environ["FAKE_IDENTITY"], "(F)") + broad_before = access.acl_text(target) + rc, doc = grant(["--account", "ag2", "--source", target, "--minutes", "15"]) + check("access-refuses-preexisting-full-control", + rc != 0 and doc.get("status") == "EQUIVALENT_ACE_ALREADY_PRESENT", (rc, doc)) + check("access-preserves-preexisting-full-control", access.acl_text(target) == broad_before, doc) + access.icacls(target, "/remove:g", os.environ["FAKE_IDENTITY"]) + + capture(["grant", "--account", "ag2", "--source", target, "--minutes", "15"]) + access.icacls(target, "/grant", os.environ["FAKE_IDENTITY"], "(F)") + changed = access.acl_text(target) + rc, doc = capture(["revoke", "--account", "ag2", "--source", target]) + check("access-revoke-refuses-concurrent-grant", + rc != 0 and doc.get("status") == "ACL_CHANGED_SINCE_GRANT", (rc, doc)) + check("access-revoke-preserves-concurrent-grant", access.acl_text(target) == changed, doc) + changed_lease = access.read_json(lease_file) + changed_lease["expires_at"] = 1 + access.write_json_atomic(lease_file, changed_lease) + rc, doc = capture(["sweep"]) + check("access-sweep-preserves-concurrent-grant", + access.acl_text(target) == changed and any( + row.get("reason") == "ACL_CHANGED_SINCE_GRANT" for row in doc.get("unrevoked", [])), doc) + # Cleanup only this fixture's rule and this disposable lease. + access.icacls(target, "/remove:g", os.environ["FAKE_IDENTITY"]) + os.remove(lease_file) + # --- rollback mismatch is preserved as evidence, never smoothed over capture(["grant", "--account", "ag2", "--source", target, "--minutes", "60"]) tampered = access.read_json(lease_file) From c081c6ea2036c72304ad97dae50b25d5474977fb Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 15:57:15 +0200 Subject: [PATCH 07/24] test(accounts): isolate credential launch checks Keep the production native credential reader as the default and inject a probe only in a separately compiled fixture entrypoint. Prove both missing authentication refusal and the complete authenticated launch argv without reading or modifying the operator's vendor credentials. Bound the consent assertion to the connect method so unrelated explanatory comments cannot satisfy its forbidden-prompt pattern. --- Scripts/accounts/SaiAccounts.cs | 9 +++++++++ tests/credential_probe_fixture.cs | 16 ++++++++++++++++ tests/test_managed_console_context.py | 27 +++++++++++++++++++++++---- tests/test_sai_accounts.py | 3 ++- 4 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 tests/credential_probe_fixture.cs diff --git a/Scripts/accounts/SaiAccounts.cs b/Scripts/accounts/SaiAccounts.cs index 45ebe81..76210f0 100644 --- a/Scripts/accounts/SaiAccounts.cs +++ b/Scripts/accounts/SaiAccounts.cs @@ -956,7 +956,16 @@ static Dictionary AntigravityLogout() return resp; } + // In-process seam for an authenticated launch fixture; the shipped CLI + // has no environment variable or command that replaces the native reader. + internal static Func> CredentialProbe = ReadCredential; + public static Dictionary CheckCredential() + { + return CredentialProbe(); + } + + static Dictionary ReadCredential() { IntPtr ptr; bool present = CredReadW("gemini:antigravity", 1, 0, out ptr); var result = Obj(); diff --git a/tests/credential_probe_fixture.cs b/tests/credential_probe_fixture.cs new file mode 100644 index 0000000..0a71ff6 --- /dev/null +++ b/tests/credential_probe_fixture.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; + +// Compiled only by the native launch harness, never by the production build. +static class CredentialProbeFixture +{ + static int Main(string[] args) + { + SaiAccounts.CredentialProbe = delegate { + return new Dictionary { + { "credential_present", Environment.GetEnvironmentVariable("SAI_FIXTURE_CREDENTIAL_PRESENT") == "1" } + }; + }; + return SaiAccounts.Main(args); + } +} diff --git a/tests/test_managed_console_context.py b/tests/test_managed_console_context.py index c153414..73a64e0 100644 --- a/tests/test_managed_console_context.py +++ b/tests/test_managed_console_context.py @@ -543,7 +543,7 @@ def test_autoconnect_lifecycle_and_scope(): def ag_account_local(plane): return {'id': 'antigravity:windows-user:' + plane.sid, 'backend': 'windows_user', 'windows_sid': plane.sid, 'provider': 'antigravity', 'label': 'Antigravity', - 'compact_label': 'AG1', 'windows_user': 'vac34', 'enabled': True} + 'compact_label': 'AG1', 'windows_user': os.environ.get('USERNAME', 'operator'), 'enabled': True} def test_launch_does_not_re_enable_disconnected(): @@ -709,16 +709,33 @@ def test_yolo_current_user_launch(): if not agy: check('yolo13-current-user-launch-carries-yolo', False, 'fake agy.exe did not build') return + fixture_exe = os.path.join(p.dir, 'credential-launch-fixture.exe') + compiled = subprocess.run([ + CSC, '/nologo', '/target:exe', '/main:CredentialProbeFixture', + '/r:System.dll', '/r:System.Core.dll', '/r:System.Web.Extensions.dll', + '/out:' + fixture_exe, ENGINE, + os.path.join(ROOT, 'tests', 'credential_probe_fixture.cs'), + ], capture_output=True, text=True) + check('yolo13-fixture-builds', compiled.returncode == 0, compiled.stdout + compiled.stderr) + if compiled.returncode: + return + p.executable = fixture_exe p.legacy('user', [ag_account_local(p)]) p.run('import') acc_id = p.registry()['accounts'][0]['account_id'] clear_agy_argv(p) + p.env['SAI_FIXTURE_CREDENTIAL_PRESENT'] = '0' + denied_code, denied, _, _ = p.run('launch', acc_id, '--workdir', p.dir) + check('yolo13-authentication-is-required', + denied_code != 0 and denied.get('status') == 'AUTH_REQUIRED' + and not os.path.exists(os.path.join(p.dir, 'bin', 'agy-argv.txt')), str(denied)) + p.env['SAI_FIXTURE_CREDENTIAL_PRESENT'] = '1' code, out, _, _ = p.run('launch', acc_id, '--workdir', p.dir) argv = read_agy_argv(p) check('yolo13-current-user-launch-carries-yolo', code == 0 and out.get('status') == 'launched' and argv is not None - and YOLO_FLAG in argv, (argv or 'no argv')[:300]) + and YOLO_FLAG in argv, (argv or json.dumps(out))[:1000]) check('yolo13b-launch-policy-reported', out.get('launch_policy') == YOLO_FLAG, str(out)[:200]) check('yolo13c-exact-workdir-survives', @@ -1203,9 +1220,11 @@ def input_policy_violations(src, extra_sources=()): # 32. No per-launch consent dialog for the broker, and no new modal in the # Accounts path. + connect_body = re.sub(r'//.*', '', method_body(gui, 'void AccountsContext(')) check('rt32-no-broker-consent-prompt', - not re.search(r'(connect|start).{0,40}(may start|allow the broker|confirm)', gui, re.I) - and 'MessageBox' not in re.sub(r'//.*', '', gui[gui.find('void AccountsContext'):gui.find('void AccountsContext') + 4000]), + bool(connect_body) + and not re.search(r'(connect|start).{0,40}(may start|allow the broker|confirm)', connect_body, re.I) + and 'MessageBox' not in connect_body, 'a consent prompt crept into the connect path') # 33. The sweep is bounded and runs off the UI thread, so startup never blocks diff --git a/tests/test_sai_accounts.py b/tests/test_sai_accounts.py index ab9c2c2..22b1311 100644 --- a/tests/test_sai_accounts.py +++ b/tests/test_sai_accounts.py @@ -75,6 +75,7 @@ class Plane: """One isolated control-plane environment (registry + broker processes).""" def __init__(self, scope='op-test'): + self.executable = EXE self.dir = tempfile.mkdtemp(prefix='sai-accounts-test-') self.scope = scope self.sid = real_sid() @@ -88,7 +89,7 @@ def __init__(self, scope='op-test'): }) def run(self, *args, timeout=90): - r = subprocess.run([EXE] + list(args), capture_output=True, text=True, + r = subprocess.run([self.executable] + list(args), capture_output=True, text=True, env=self.env, timeout=timeout, cwd=self.dir) try: payload = json.loads(r.stdout.strip().splitlines()[-1]) if r.stdout.strip() else None From 6775613f4298c2ff23f58fe14c4d9df5dbb37d1d Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:19:22 +0200 Subject: [PATCH 08/24] fix(accounts): stop stale work and scroll growth Stop the sign-in watcher when its owning window closes. Keep detail content height independent of the scroll offset so controls remain reachable. Exercise worker completion and scroll invariance, scroll visible diagnostic controls before clicking, and use the account-owned workdir setter in the readiness fixture. Preserve all launch, identity and diagnostic assertions. --- SAITULS.cs | 5 +- tests/saituls_accounts_flow_test.cs | 81 ++++++++++++++++++++++++----- 2 files changed, 72 insertions(+), 14 deletions(-) diff --git a/SAITULS.cs b/SAITULS.cs index 77ff4f9..de1efd3 100644 --- a/SAITULS.cs +++ b/SAITULS.cs @@ -7840,7 +7840,7 @@ int DrawAccountDetailPane(Graphics g, int px, int py, int pw, int ph, AccountRow oy += 22; } - return oy - startY + _acctDetailScrollY; + return oy - startY; } void DrawAccountsTab(Graphics g, int x, int y, int w, int h) @@ -8950,9 +8950,10 @@ void SignInFlow(string label, string backend, string provider, string context) // time out into a false READY, and never open a second account to // "help" if they abandon it. var sw = Stopwatch.StartNew(); - while (sw.ElapsedMilliseconds < AuthPollBudgetMs) + while (!_closing && sw.ElapsedMilliseconds < AuthPollBudgetMs) { Thread.Sleep(3000); + if (_closing) return; CliRun r = AccountsExec("status \"" + label + "\"", 20000); var o = ParseEnv(r.Stdout); if (o == null) continue; diff --git a/tests/saituls_accounts_flow_test.cs b/tests/saituls_accounts_flow_test.cs index 98473da..7b5736e 100644 --- a/tests/saituls_accounts_flow_test.cs +++ b/tests/saituls_accounts_flow_test.cs @@ -255,7 +255,8 @@ static int Main(string[] args) bool focused = args.Length == 1 && args[0] == "--offline-start-and-switch"; bool identityFocused = args.Length == 1 && args[0] == "--identity-status-and-switch"; bool catalogFocused = args.Length == 1 && args[0] == "--provider-catalog-and-layout"; - if (args.Length > 0 && !focused && !identityFocused && !catalogFocused) + bool lifetimeFocused = args.Length == 1 && args[0] == "--window-lifetime-and-scroll"; + if (args.Length > 0 && !focused && !identityFocused && !catalogFocused && !lifetimeFocused) { Console.WriteLine("FAIL unknown runtime test selection"); return 1; @@ -281,7 +282,12 @@ static int Main(string[] args) try { - if (catalogFocused) + if (lifetimeFocused) + { + TestSignInWatchStopsOnClose(); + TestAccountDetailHeightDoesNotGrowWithScroll(); + } + else if (catalogFocused) { T45ProviderCatalogIsTheDialogsSingleSource(); T46PlannedProvidersCannotNameABackend(); @@ -320,6 +326,8 @@ static int Main(string[] args) Test16FailedConnectRendersTheRealError(); Test17ConnectSuccessShowsOnline(); Test18SignInIsNotAConsoleLaunch(); + TestSignInWatchStopsOnClose(); + TestAccountDetailHeightDoesNotGrowWithScroll(); Test19SignInNeverTouchesAWorkdir(); Test20SignInStartsAnOfflineContextFirst(); Test21SignInOnAnOnlineAccountSkipsTheContextStart(); @@ -415,8 +423,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=RUNTIME_STALE"); Saituls.SaitulsForm f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("SAIPEN"), 30000); Check(LaunchCall("AG2") == null, "T288a a stale machine runtime launches no console", Show()); @@ -430,8 +438,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=READY"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); string[] launch = LaunchCall("AG2"); @@ -444,8 +452,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0", "saipen_verdict=PROJECT_LIFECYCLE_DENIED"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); Check(LaunchCall("AG2") != null, "T288c a lifecycle refusal still opens the console that repairs it", Show()); @@ -455,8 +463,8 @@ static void Test288SaipenReadinessGatesTheConsole() Arm("offline_status_calls=0"); f = MakeForm(true); - SetOf(f, "_accountsWorkdir", project); Select(f, "AG2"); + M(f, "RememberWorkdir", project); M(f, "OpenConsole"); Pump(() => !Busy(f) && Note(f).StartsWith("Launched"), 30000); Check(LaunchCall("AG2") != null && !Note(f).Contains("SAIPEN"), @@ -854,7 +862,7 @@ static void Test18SignInIsNotAConsoleLaunch() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(HasCall("auth", "AG2"), "T18a SIGN IN issues the dedicated auth operation", Show()); Check(LaunchCall("AG2") == null, "T18b SIGN IN never issues a console launch", Show()); @@ -864,6 +872,55 @@ static void Test18SignInIsNotAConsoleLaunch() } // ------------------------------------------------------------------- T19 + static void TestSignInWatchStopsOnClose() + { + Saituls.SaitulsForm f = MakeForm(true); + Select(f, "AG2"); + Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); + Exception failure = null; + var watch = new Thread(delegate() { + try { M(f, "SignInFlow", "AG2", "managed_windows_user", "antigravity", "test-secondary"); } + catch (Exception ex) { failure = ex; } + }); + watch.IsBackground = true; + watch.Start(); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 20000); + Check(HasCall("auth", "AG2"), "sign-in watch starts before testing close", Show()); + f.Dispose(); + Check(watch.Join(5000), "closing the window terminates its sign-in watch", "the owned worker remained alive"); + Check(failure == null, "closing the sign-in watch raises no worker error", Convert.ToString(failure)); + } + + static void TestAccountDetailHeightDoesNotGrowWithScroll() + { + var f = MakeForm(true); + Select(f, "AG2"); + SF(f, "_acctAdvancedExpanded", true); + using (var image = new Bitmap(900, 700)) + using (var g = Graphics.FromImage(image)) + { + SetOf(f, "_acctDetailScrollY", 0); + int first = (int)M(f, "DrawAccountDetailPane", g, 0, 0, 600, 700, Row(f, "AG2")); + SetOf(f, "_acctDetailScrollY", 100); + int scrolled = (int)M(f, "DrawAccountDetailPane", g, 0, 0, 600, 700, Row(f, "AG2")); + Check(first > 0 && scrolled == first, + "account detail scroll does not grow its own content height", first + " -> " + scrolled); + } + f.Dispose(); + } + + static void PaintAccountsAtBottom(Saituls.SaitulsForm form, Graphics graphics) + { + // The advanced controls can extend below the viewport. Emulate a + // scroll to the end and its following paint, including normal hitbox + // reset; clicking an offscreen button is not a real UI route. + SF(form, "_acctDetailScrollY", 5000); + ((IList)F(form, "Buttons")).Clear(); + M(form, "DrawAccountsTab", graphics, 0, 0, 900, 700); + ((IList)F(form, "Buttons")).Clear(); + M(form, "DrawAccountsTab", graphics, 0, 0, 900, 700); + } + // The whole point of PART 1: no workdir anywhere on the sign-in path. Not // on the command line, not in the note, and the form must not even need a // usable workdir -- so this one runs with the saved workdir cleared. @@ -873,7 +930,7 @@ static void Test19SignInNeverTouchesAWorkdir() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); bool anyFlag = false; foreach (string[] a in Calls()) @@ -898,7 +955,7 @@ static void Test20SignInStartsAnOfflineContextFirst() Select(f, "AG2"); Arm("offline_status_calls=1", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(ContextCall("start", "AG2") != null, "T20a an OFFLINE AG2 starts its own context before signing in", Show()); @@ -917,7 +974,7 @@ static void Test21SignInOnAnOnlineAccountSkipsTheContextStart() Select(f, "AG2"); Arm("offline_status_calls=0", "online_auth=AUTH_REQUIRED"); M(f, "SignInSelectedAccount"); - Pump(() => !Busy(f) && Note(f).Contains("Antigravity is open"), 40000); + Pump(() => HasCall("auth", "AG2") && Note(f).Contains("Antigravity is open"), 40000); Check(ContextCall("start", "AG2") == null, "T21a an ONLINE AG2 + SIGN IN goes straight to auth", Show()); @@ -1258,7 +1315,7 @@ static void Test29hDiagnosticsCarryTheIdentity() SF(f, "_acctAdvancedExpanded", true); var bmp = new Bitmap(900, 700); using (var g = Graphics.FromImage(bmp)) - M(f, "DrawAccountsTab", g, 0, 0, 900, 700); + PaintAccountsAtBottom(f, g); var buttons = (IList)F(f, "Buttons"); object copy = null; @@ -1746,7 +1803,7 @@ static void T40NoTokenMaterialInTheDiagnostics() SF(f, "_acctAdvancedExpanded", true); var bmp = new Bitmap(900, 700); using (var g = Graphics.FromImage(bmp)) - M(f, "DrawAccountsTab", g, 0, 0, 900, 700); + PaintAccountsAtBottom(f, g); object copy = null; foreach (object b in (IList)F(f, "Buttons")) { From 32ce4ff1a32572f74bb5e7d59b814a5e5c84d0eb Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:30:04 +0200 Subject: [PATCH 09/24] test(workers): import loader on clean Python --- tests/test_workers.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_workers.py b/tests/test_workers.py index 09b71b9..aaa3426 100644 --- a/tests/test_workers.py +++ b/tests/test_workers.py @@ -21,6 +21,7 @@ filesystem and then answers Yes. That is the real race, executed deterministically. """ import hashlib +import importlib.machinery import importlib.util import json import os From 3e313bfb0d7f40f554b2b3a61b2527c54811d5bf Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:36:50 +0200 Subject: [PATCH 10/24] Isolate console injector evidence in temp storage --- tests/saipatch_ctrlv_e2e.py | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/tests/saipatch_ctrlv_e2e.py b/tests/saipatch_ctrlv_e2e.py index 6d855ad..e91c7fc 100644 --- a/tests/saipatch_ctrlv_e2e.py +++ b/tests/saipatch_ctrlv_e2e.py @@ -7,6 +7,7 @@ import json import subprocess import sys +import tempfile import time from pathlib import Path @@ -16,15 +17,17 @@ def main() -> int: - out = Path(r"V:\_TEMP_\opencode\ctrlv-e2e.json") - out.parent.mkdir(parents=True, exist_ok=True) - for suffix in (".json", ".ready"): - p = out.with_suffix(suffix) - if p.exists(): - p.unlink() + with tempfile.TemporaryDirectory(prefix="saituls-ctrlv-") as scratch: + return run(Path(scratch) / "ctrlv-e2e.json") + + +def run(out: Path) -> int: + startup = subprocess.STARTUPINFO() + startup.dwFlags |= subprocess.STARTF_USESHOWWINDOW + startup.wShowWindow = subprocess.SW_HIDE proc = subprocess.Popen( [sys.executable, str(HERE / "saipatch_ctrlv_receiver.py"), "--out", str(out)], - creationflags=subprocess.CREATE_NEW_CONSOLE) + creationflags=subprocess.CREATE_NEW_CONSOLE, startupinfo=startup) try: ready = out.with_suffix(".ready") deadline = time.monotonic() + 30 From 0969395389f8e00cc168e8d9fa7ea77ddd36d852 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:39:23 +0200 Subject: [PATCH 11/24] ci: encode Windows Python diagnostics as UTF-8 --- .github/workflows/test.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e73aed0..b78f171 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -8,6 +8,8 @@ on: jobs: regs: runs-on: windows-latest + env: + PYTHONIOENCODING: utf-8 steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 From 98cf7edb06d30dc38d99f28ced14583e84505c14 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:47:44 +0200 Subject: [PATCH 12/24] fix: bind scenario manifest to published bytes --- .gitattributes | 4 ++++ Scripts/scenarios/MIGRATION.json | 34 ++++++++++++++++---------------- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/.gitattributes b/.gitattributes index 81c1690..5dc0efe 100644 --- a/.gitattributes +++ b/.gitattributes @@ -15,3 +15,7 @@ # SAIPEN byte-bound evidence (digest-verified; never convert line endings) -- T-1508. .saipen/recovery/board-scrub/** -text + +# The scenarios migration manifest hashes the published source bytes. +# Keep those text payloads stable even with core.autocrlf=true on Windows. +Scripts/scenarios/** text eol=lf diff --git a/Scripts/scenarios/MIGRATION.json b/Scripts/scenarios/MIGRATION.json index 57a2b12..c37a86d 100644 --- a/Scripts/scenarios/MIGRATION.json +++ b/Scripts/scenarios/MIGRATION.json @@ -76,7 +76,7 @@ "destination": "clean/office/OFFICE.cmd", "active": false, "reason": "Office scrub bundle; wrapper scenario is DISABLED pending launch-contract merge (admin, uninstall)", - "destination_sha256": "2866af22404f24941c3b66ce96ab1556a8209a45c6c0879001aa2e914aa9f73b" + "destination_sha256": "728dea69c812f9b94d74f5ddb3514c87974e2104b42eb3efca4622ea9c8b972e" }, { "source": "CLEAN/OFFICE_S/README.md", @@ -85,7 +85,7 @@ "destination": "clean/office/README.md", "active": false, "reason": "Office scrub bundle; wrapper scenario is DISABLED pending launch-contract merge (admin, uninstall)", - "destination_sha256": "42b9dbd0f8da8399bd8eb8387d2822a4e431159da98a4d0bf6248d06bb4b15f9" + "destination_sha256": "dbb6899976fe5769c89c76a1c3057e3c232adde7621e7d9d4a4e87d6f5dbcd1d" }, { "source": "CLEAN/OFFICE_S/bin/CleanOffice.txt", @@ -94,7 +94,7 @@ "destination": "clean/office/bin/CleanOffice.txt", "active": false, "reason": "Office scrub bundle; wrapper scenario is DISABLED pending launch-contract merge (admin, uninstall)", - "destination_sha256": "c0ff3e0b9cb14687e9ef6da7890941f753f6541ede627a3d14f3d43a20b1163c" + "destination_sha256": "0e8cd61f691d27d24467f844d8782da79293d4ff5176ce89b585ef8e26102259" }, { "source": "CLEAN/OFFICE_S/bin/OffScrub03.vbs", @@ -438,7 +438,7 @@ "destination": "media/audio/album_tool.py", "active": true, "reason": "Mutagen-based album/tagging tool; optional folder arg (documented convention)", - "destination_sha256": "a706aac7dfa21f3db84a4415d8800d819a8d0e7ca45352494996e01f02ad897a" + "destination_sha256": "b20c47be1ec3268695c361836bc091235242cb9b53fdd9e473c1cffae749667c" }, { "source": "MEDIA/AUDIO/MP3/INST_TAG.ps1", @@ -472,7 +472,7 @@ "destination": "media/audio/taglib_tag_from_filenames.ps1", "active": false, "reason": "Alternative tagger (TagLibSharp); active in registry but BLOCKED without bundled DLL", - "destination_sha256": "5f654ce6259cb31571515d455c2a79e3a3d3388b4b84f7ca797e4aec05fa80ca" + "destination_sha256": "619c771285846856e670cbb280ca5ddbead0c43321a62b6cf60ebf2ee18806f5" }, { "source": "MEDIA/AUDIO/MP3/MP3_WIN.py", @@ -481,7 +481,7 @@ "destination": "media/audio/mp3_win.py", "active": true, "reason": "Mutagen-based album/tagging tool; optional folder arg (documented convention)", - "destination_sha256": "6561e9571d315649c637597ba6c647b541fdcec919e469059876d90893e12b2b" + "destination_sha256": "3d7ed3988b8637b85d644e09020bc679a8604399da6922b615f1fd8d509f0e7e" }, { "source": "MEDIA/AUDIO/MP3/REM_CTX.reg", @@ -514,7 +514,7 @@ "destination": "media/audio/tag_from_list.ps1", "active": false, "reason": "ffmpeg-based tagger (re-encode path); enabled only after its output is verified", - "destination_sha256": "3954758e50fc1c5bf3dda0275f87ffef189ddeaabb5d23f84573e8246d92f360" + "destination_sha256": "e5c8e4a999e840064fd94263fd93b899e0ede595fbfb3c4de904b92eb2cd5fae" }, { "source": "MEDIA/AUDIO/MP3/TAG_MP3.py", @@ -523,7 +523,7 @@ "destination": "media/audio/tag_mp3.py", "active": true, "reason": "Mutagen-based album/tagging tool; optional folder arg (documented convention)", - "destination_sha256": "b70d73257e70b3f1c52e81e87b1fb04b1e942e1ea43ce531d4f91f9782b8369b" + "destination_sha256": "477c513dea744fe6a7fefec2441ade84990112ee648ce515c861768182232cb6" }, { "source": "MEDIA/AUDIO/MP3/TagLibSharp.dll", @@ -670,7 +670,7 @@ "destination": "media/image/compress_images_lossless.py", "active": true, "reason": "jpegoptim/oxipng lossless compressor; external bundled binaries REQUIRED", - "destination_sha256": "01ba6f5885211697a02e70f890e5427f993efee2f6a03d5d8ddbb80b693f05d7" + "destination_sha256": "03e2d85731e823e5164e727ab5b1fc185884dc70d642d367d4d310800322cdf2" }, { "source": "MEDIA/IMAGE/PIC/DDS2BW.py", @@ -679,7 +679,7 @@ "destination": "media/image/convert_dds_to_bw.py", "active": true, "reason": "In-place DDS grayscale overwrite (SUFFIX='') -> destructive badge", - "destination_sha256": "4d205270e1c725a82774da33c0206e975cc81409c1d3ceb30bb2b84fe516535b" + "destination_sha256": "e11cf70d64a2dd914fecd28e9436ea8ff567877d87c5496eb6b2a6fb3f324796" }, { "source": "MEDIA/IMAGE/PIC/DDS2PNG.py", @@ -688,7 +688,7 @@ "destination": "media/image/convert_dds_to_png.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "3a352449d29408c1295e99363cfcd4f094b864d833a152e0ecdfaef0750aeb41" + "destination_sha256": "e6cb5a2dcc5394a03c93e782629199c059972561f130cb36203d2b1ab13c6a50" }, { "source": "MEDIA/IMAGE/PIC/DDS2TGA.py", @@ -697,7 +697,7 @@ "destination": "media/image/convert_dds_to_tga.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "6552e08eaeb447ea495ba84fc5e5f523761d26fb35feb908e60bfabc0a892a88" + "destination_sha256": "2c2cbff5b8f7d3ecfbc006afecdfe72dbff3148694910b5087a1208ff428af28" }, { "source": "MEDIA/IMAGE/PIC/PNG2DDS.py", @@ -706,7 +706,7 @@ "destination": "media/image/convert_png_to_dds.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "abb46c82e9fa10e797038d11b46cb52b955d078f888071e3ec91830e4169ff6a" + "destination_sha256": "fd93efc40153bfefc75276c63dbadc6b5b86e5dd9546ea3ed3ce9e5b9350bcf9" }, { "source": "MEDIA/IMAGE/PIC/REP_DDS.ps1", @@ -723,7 +723,7 @@ "destination": "media/image/replace_dds_with_png.py", "active": false, "reason": "main1.png repack helper; registry-listed but DISABLED (replace-in-place semantics unproven)", - "destination_sha256": "de18e81fefef3478d2e439e3849e4d5bd90bfe96020294d6237dcbc036116159" + "destination_sha256": "c8ed21c56d6c914c13ba27f7675fa8c7e7b65f7a36ab31af8f52c8abf400f5b1" }, { "source": "MEDIA/IMAGE/PIC/TGA2BW.py", @@ -741,7 +741,7 @@ "destination": "media/image/convert_tga_to_dds.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "153a7e4465d19a686b9be801bc60c5923dcf75d3f155176e6cdfc919efbd19e6" + "destination_sha256": "2b0f46f5ab4ddf2a4b916f6a8ca5d468b58df6a130566ad3f9385a3df089da67" }, { "source": "MEDIA/IMAGE/PIC/TGA2DDS2.py", @@ -750,7 +750,7 @@ "destination": "media/image/convert_tga_to_dds_alt.py", "active": true, "reason": "texconv converter, creates new files alongside originals (SAFE)", - "destination_sha256": "ff64a571db68a847beb94080da67e6999450caba609703132873c85ef2010905" + "destination_sha256": "c753fa0042926b0da47d48061f65d3ef3e92f12ee6b8c8baf171b45d6e79e1cb" }, { "source": "MEDIA/IMAGE/PIC/UPS_TGA.py", @@ -1001,7 +1001,7 @@ "destination": "media/video/COMPRESS_V.sh", "active": true, "reason": "Git Bash AV1 batch compressor; source dirs moved to config; bash dependency verified on PATH", - "destination_sha256": "a5524b4589136dddb871f2051b6c52e6f064b16db15ccc1e05dbfd6ab653e220" + "destination_sha256": "a05b34317ab6f7b0b733229f63774b407f60cdb929be11a3afcfd1bd1fecfb69" }, { "source": "MEDIA/VIDEO/VID/GOV.ps1", From 908e07a59596cf6b844c11e2f010db7ab36e1900 Mon Sep 17 00:00:00 2001 From: vacterro Date: Wed, 28 Oct 2026 16:50:02 +0200 Subject: [PATCH 13/24] test: use real folders for junk policy checks --- Scripts/del_junk_policy.py | 2 +- tests/test_del_junk_all_disks.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Scripts/del_junk_policy.py b/Scripts/del_junk_policy.py index 9506cf1..09672a3 100644 --- a/Scripts/del_junk_policy.py +++ b/Scripts/del_junk_policy.py @@ -236,7 +236,7 @@ def check(name, cond): ok = ok and cond check("drive root selects SAFE_DISK", select_policy("G:\\") == "SAFE_DISK") - check("folder selects AGGRESSIVE_PROJECT", select_policy("V:\\a\\b") == "AGGRESSIVE_PROJECT") + check("folder selects AGGRESSIVE_PROJECT", select_policy(os.path.dirname(__file__)) == "AGGRESSIVE_PROJECT") p = build_policy(False, now) check("SAFE_DISK keeps build", not p["dir_junk"]("build")) check("SAFE_DISK keeps dist", not p["dir_junk"]("dist")) diff --git a/tests/test_del_junk_all_disks.py b/tests/test_del_junk_all_disks.py index d5e541c..9d91a40 100644 --- a/tests/test_del_junk_all_disks.py +++ b/tests/test_del_junk_all_disks.py @@ -185,7 +185,7 @@ def test_safe_disk_is_the_only_policy(): and '"SAFE_DISK"' in ALL_DISKS_SOURCE) check('the single-target worker still chooses its policy from the target', 'mode = select_policy(target_dir)' in SOURCE - and WORKER.select_policy('V:\\a\\b') == 'AGGRESSIVE_PROJECT') + and WORKER.select_policy(SCRIPTS) == 'AGGRESSIVE_PROJECT') check('the shell all-disks command is recognized, a path is not', WORKER.wants_all_disks(['DEL_JUNK.PYW', '--all-disks']) and not WORKER.wants_all_disks(['DEL_JUNK.PYW', 'G:\\']) From 529b89727ee4c61c480c2c95d93ff0439f0929b1 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 17:17:12 +0200 Subject: [PATCH 14/24] ci: forward to the installed Python interpreter A relocated pythonw.exe loses its runtime dependencies. Compile a CI-only windowless forwarder that keeps the interpreter in place and preserves the raw Windows argument tail and exit status. --- .github/workflows/test.yml | 5 +++ tests/ci_fixtures.ps1 | 3 +- tests/ci_python_launcher.ps1 | 44 +++++++++++++++++++++ tests/test_ci_python_launcher.ps1 | 66 +++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 tests/ci_python_launcher.ps1 create mode 100644 tests/test_ci_python_launcher.ps1 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index b78f171..ac8456d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -27,6 +27,11 @@ jobs: # stubs must break the dependent harnesses, never silently skip. powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_ci_hermetic.ps1 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Test isolated CI Python launcher and argument forwarding + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_ci_python_launcher.ps1 + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Run integrity suite shell: pwsh run: | diff --git a/tests/ci_fixtures.ps1 b/tests/ci_fixtures.ps1 index 04ea1ec..05c3b7b 100644 --- a/tests/ci_fixtures.ps1 +++ b/tests/ci_fixtures.ps1 @@ -103,7 +103,8 @@ if (-not $Verify) { } else { $pythonw = Resolve-Application 'pythonw.exe' if (-not $pythonw) { throw 'pythonw.exe is not on PATH; cannot provision the Windows Python launcher' } - Copy-Item -LiteralPath $pythonw.Source -Destination $pywExe -Force + . (Join-Path $PSScriptRoot 'ci_python_launcher.ps1') + New-SaiCiPythonLauncher $pythonw.Source $pywExe Write-Host "MAKE Windows Python launcher $pywExe (from $($pythonw.Source))" } } diff --git a/tests/ci_python_launcher.ps1 b/tests/ci_python_launcher.ps1 new file mode 100644 index 0000000..04848ed --- /dev/null +++ b/tests/ci_python_launcher.ps1 @@ -0,0 +1,44 @@ +# CI-only launcher: pythonw.exe depends on DLLs beside its installed executable. +# Copying that executable to Windows makes ShellExecute succeed while Python +# fails to load. Keep the real interpreter in place and forward the raw Windows +# argument tail, including the intentionally awkward drive-root quoting. +function New-SaiCiPythonLauncher([string]$Pythonw, [string]$Destination) { + $compiler = Join-Path $env:SystemRoot 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' + if (-not (Test-Path -LiteralPath $Pythonw -PathType Leaf)) { throw 'pythonw.exe not found' } + if (Test-Path -LiteralPath $Destination) { throw 'Refusing to replace an existing launcher' } + $encodedPath = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes([IO.Path]::GetFullPath($Pythonw))) + $source = [IO.Path]::GetTempFileName() + '.cs' + try { + @" +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +internal static class SaiCiPythonLauncher { + [DllImport("kernel32.dll", CharSet=CharSet.Unicode)] + private static extern IntPtr GetCommandLineW(); + [STAThread] + private static int Main() { + try { + string line = Marshal.PtrToStringUni(GetCommandLineW()).TrimStart(); + int end = line.StartsWith("\"") ? line.IndexOf('"', 1) + 1 : line.IndexOf(' '); + string tail = end < 0 ? "" : line.Substring(end).TrimStart(); + var start = new ProcessStartInfo { + FileName = Encoding.Unicode.GetString(Convert.FromBase64String("$encodedPath")), + Arguments = tail, UseShellExecute = false, CreateNoWindow = true + }; + using (var child = Process.Start(start)) { + child.WaitForExit(); + return child.ExitCode; + } + } catch { return 1; } + } +} +"@ | Set-Content -LiteralPath $source -Encoding UTF8 + & $compiler /nologo /target:winexe "/out:$Destination" $source + if ($LASTEXITCODE -ne 0) { throw 'CI Python launcher compilation failed' } + } finally { + Remove-Item -LiteralPath $source -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath ($source.Substring(0, $source.Length - 3)) -Force -ErrorAction SilentlyContinue + } +} diff --git a/tests/test_ci_python_launcher.ps1 b/tests/test_ci_python_launcher.ps1 new file mode 100644 index 0000000..33543f2 --- /dev/null +++ b/tests/test_ci_python_launcher.ps1 @@ -0,0 +1,66 @@ +param([string]$Implementation = (Join-Path $PSScriptRoot 'ci_python_launcher.ps1')) +$ErrorActionPreference = 'Stop' +. $Implementation +Add-Type -TypeDefinition @' +using System.Runtime.InteropServices; +public static class SaiLauncherErrorMode { + [DllImport("kernel32.dll")] public static extern uint SetErrorMode(uint mode); +} +'@ +$previousErrorMode = [SaiLauncherErrorMode]::SetErrorMode(0x8003) +$sandbox = Join-Path ([IO.Path]::GetTempPath()) ('saituls-python-launcher-' + [Guid]::NewGuid().ToString('N')) +$fails = 0 +function Check([string]$Name, [bool]$Ok) { + if ($Ok) { Write-Host "PASS $Name" } else { Write-Host "FAIL $Name"; $script:fails++ } +} +New-Item -ItemType Directory -Path $sandbox | Out-Null +try { + $launcher = Join-Path $sandbox 'isolated launcher.exe' + $recorder = Join-Path $sandbox 'argument recorder.pyw' + $result = Join-Path $sandbox 'result.json' + # The same recorder tests the real installed interpreter and isolated shim. + @' +import json, pathlib, sys +pathlib.Path(__file__).with_name('result.json').write_text(json.dumps(sys.argv[1:]), encoding='utf-8') +sys.exit(23) +'@ | Set-Content -LiteralPath $recorder -Encoding UTF8 + $pythonw = (Get-Command pythonw.exe -CommandType Application | Select-Object -First 1).Source + New-SaiCiPythonLauncher $pythonw $launcher + $psi = New-Object Diagnostics.ProcessStartInfo + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.WorkingDirectory = $sandbox + # A real installation must not be rescued by interpreter DLLs on PATH. + # The installed pythonw still finds its DLLs beside itself; a copied + # pythonw in an unrelated directory must prove independent launchability. + $psi.EnvironmentVariables['PATH'] = $env:SystemRoot + ';' + (Join-Path $env:SystemRoot 'System32') + # End with a quoted drive root exactly like the Explorer verb. The shim + # must preserve the Python parser's raw input, not repair this quoting. + $psi.Arguments = '"' + $recorder + '" "with spaces" "" "' + [char]0x00F5 + '" "C:\"' + $psi.FileName = $pythonw + $direct = [Diagnostics.Process]::Start($psi) + if (-not $direct.WaitForExit(10000)) { throw 'Direct interpreter timed out' } + Check 'known-good installed interpreter records arguments' (Test-Path -LiteralPath $result) + if (-not (Test-Path -LiteralPath $result)) { throw 'Known-good interpreter unavailable' } + $expected = [IO.File]::ReadAllText($result) + Check 'known-good interpreter returns deliberate nonzero status' ($direct.ExitCode -eq 23) + Remove-Item -LiteralPath $result -Force + $psi.FileName = $launcher + $forwarded = [Diagnostics.Process]::Start($psi) + if (-not $forwarded.WaitForExit(10000)) { throw 'Isolated launcher timed out' } + Check 'isolated launcher runs the real Python worker' (Test-Path -LiteralPath $result) + Check 'isolated launcher preserves raw Windows arguments' ((Test-Path -LiteralPath $result) -and [IO.File]::ReadAllText($result) -ceq $expected) + Check 'isolated launcher propagates child failure' ($forwarded.ExitCode -eq 23) + $direct.Dispose() + $forwarded.Dispose() +} finally { + [void][SaiLauncherErrorMode]::SetErrorMode($previousErrorMode) + $resolved = [IO.Path]::GetFullPath($sandbox) + $tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\') + '\' + if (-not $resolved.StartsWith($tempRoot, [StringComparison]::OrdinalIgnoreCase) -or + (Split-Path $resolved -Leaf) -notlike 'saituls-python-launcher-*') { throw 'Unsafe cleanup target' } + Remove-Item -LiteralPath $resolved -Recurse -Force +} +if ($fails) { Write-Host "FAILED ($fails failures)"; exit 1 } +Write-Host 'PASS (0 failures)' +exit 0 From a846addcf3bdc51225af076f621256f247fa1006 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 17:52:37 +0200 Subject: [PATCH 15/24] ci: provide a complete OpenCode test fixture SAIPATCH follows the shim to a fingerprintable executable. Compile an unsupported test host from source and verify that the target exists; retain the existing vendor-build tier and missing-fixture negative controls. --- tests/ci_fixtures.ps1 | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/ci_fixtures.ps1 b/tests/ci_fixtures.ps1 index 05c3b7b..84e14ea 100644 --- a/tests/ci_fixtures.ps1 +++ b/tests/ci_fixtures.ps1 @@ -48,6 +48,24 @@ function New-StubCommand([string]$path, [string]$name) { # A resolvable Application command is all the suite needs: the launcher and # the menu installer resolve it with Get-Command and never run it. Exiting 0 # keeps an accidental invocation from looking like an agent crash. + if ($name -eq 'opencode.cmd') { + # SAIPATCH resolves the executable behind an npm-style shim, then + # fingerprints it. An echo-only .cmd satisfies Get-Command but cannot + # satisfy that contract. Build a harmless, explicitly unsupported host + # from source; the existing build-specific tier stays separate. + $exe = Join-Path (Split-Path -Parent $path) 'opencode.exe' + if (-not (Test-Path -LiteralPath $exe)) { + $source = Join-Path $StubRoot 'opencode-fixture.cs' + 'using System; public static class Fixture { public static int Main(string[] args) { Console.WriteLine("SAITULS test fixture"); return 0; } }' | + Set-Content -LiteralPath $source -Encoding UTF8 + & $cscExe /nologo /target:exe "/out:$exe" $source + if ($LASTEXITCODE -ne 0) { throw 'OpenCode fixture compilation failed' } + } + @('@echo off', 'rem SAITULS test fixture -- not a vendor CLI.', + 'set "dp0=%~dp0"', '"%dp0%opencode.exe" %*', 'exit /b %errorlevel%') | + Set-Content -LiteralPath $path -Encoding Ascii + return + } $lines = @( '@echo off' "rem SAITULS test fixture -- a resolvable stand-in for the real $name." @@ -78,7 +96,11 @@ function Resolve-Application([string]$name) { if (-not $Verify) { New-Item -ItemType Directory -Path $binDir -Force | Out-Null foreach ($stub in $stubs) { - if (Test-Path -LiteralPath $stub.Path) { + if ((Test-Path -LiteralPath $stub.Path) -and $stub.Name -eq 'opencode.cmd' -and + (Get-Content -LiteralPath $stub.Path -Raw) -match 'SAITULS test fixture') { + New-StubCommand $stub.Path $stub.Name + Write-Host "MAKE complete owned OpenCode fixture $($stub.Path)" + } elseif (Test-Path -LiteralPath $stub.Path) { Write-Host "KEEP $($stub.Name) stub already present $($stub.Path)" } else { New-StubCommand $stub.Path $stub.Name @@ -132,6 +154,14 @@ foreach ($stub in $stubs) { Assert-Prereq "$($stub.Name) resolves as an application" ($null -ne $resolved) ` $(if ($resolved) { $resolved.Source } else { 'not on PATH -- run this script without -Verify, or install the real CLI' }) } +if (Test-Path -LiteralPath (Join-Path $binDir 'opencode.cmd')) { + $shimText = Get-Content -LiteralPath (Join-Path $binDir 'opencode.cmd') -Raw + if ($shimText -match 'SAITULS test fixture') { + Assert-Prereq 'the OpenCode fixture shim has an executable target' ( + (Test-Path -LiteralPath (Join-Path $binDir 'opencode.exe') -PathType Leaf) -and + $shimText.Contains('"%dp0%opencode.exe"')) 'source-built unsupported test host; no vendor service' + } +} Assert-Prereq 'the global Vintage skill exists' (Test-Path -LiteralPath $vintageSkill -PathType Leaf) $vintageSkill Assert-Prereq 'the Windows Python launcher exists' (Test-Path -LiteralPath $pywExe -PathType Leaf) ` "$pywExe -- a shell verb resolves pyw.exe only from the Windows directory and System32" From f9be2511fc924c98d4c04a430dbbc7cad77a4110 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 18:07:59 +0200 Subject: [PATCH 16/24] test: make scenario argv probes dependency-free The quoting oracle selected a mutagen-dependent action on a clean runner. Resolve a shipped zero-dependency Python action for both target probes; retain all 42 assertions, production dependency refusals, exact payload hashes and destructive-action protections. --- tests/test_scenarios_launcher.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/test_scenarios_launcher.py b/tests/test_scenarios_launcher.py index a567f34..fce920e 100644 --- a/tests/test_scenarios_launcher.py +++ b/tests/test_scenarios_launcher.py @@ -185,11 +185,16 @@ def probe_path(rel): check("legitimate in-root path accepted", rc == 0 and r and r["ok"]) print("== argument passing (Unicode / spaces / parens / ampersand) ==") +# Quoting is independent of optional scenario packages. Select a shipped +# Python scenario with a target and no dependencies, just as the resolution +# tests do; a clean runner must not need mutagen to inspect an argv plan. +argv_candidate = next(s for s in zds if s["interpreter"] == "python" + and s["target_mode"] in ("file", "folder")) hostile = "C:/tmp/u-ãéïöü-тест (x) & more" -rc, out = run_launcher("-Scenario", "audio.tag-mp3", "-Target", hostile) +rc, out = run_launcher("-Scenario", argv_candidate["id"], "-Target", hostile) r = parse_json_out(out) check("hostile target accepted as single argv element", rc == 0 and r and r["ok"] - and r["argv"][-1] == hostile) + and r["argv"][-1] == hostile, out) check("target arrives exactly once", r and len(r["argv"]) == 2) # CommandLineToArgvW round-trip: assert the TARGET parses back byte-identical # (the script path is re-homed when the repo moves, so compare element 1 only). @@ -197,7 +202,7 @@ def probe_path(rel): target_ok = (parsed is not None and len(parsed) == 2 and parsed[1] == hostile) check("Win32 command line round-trips hostile target", target_ok, f"parsed={parsed}") trail = "C:\\tmp\\trail test\\" -rc, out = run_launcher("-Scenario", "audio.tag-mp3", "-Target", trail) +rc, out = run_launcher("-Scenario", argv_candidate["id"], "-Target", trail) r2 = parse_json_out(out) parsed2 = win32_argv(r2["cmdline"]) check("trailing backslash survives quoting", parsed2 is not None and parsed2[1] == trail, From 4b354c1e6f9acdada40ff76d2c7bfffa25594ffa Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 18:31:09 +0200 Subject: [PATCH 17/24] test: await shell recorder completion Replace the fixed 1.2-second startup assumption with a bounded wait on the exact recorder process. Report wait and exit status on failure. The same delayed-recorder oracle fails with the old wait and passes with process synchronization; all four target assertions remain. --- tests/shell_probe_wait.ps1 | 17 ++++++++++++++++ tests/test_shell_menu.ps1 | 41 +++++++++++++++++++++++++++++--------- 2 files changed, 49 insertions(+), 9 deletions(-) create mode 100644 tests/shell_probe_wait.ps1 diff --git a/tests/shell_probe_wait.ps1 b/tests/shell_probe_wait.ps1 new file mode 100644 index 0000000..e24ec51 --- /dev/null +++ b/tests/shell_probe_wait.ps1 @@ -0,0 +1,17 @@ +# Wait on the exact hidden recorder process owned by the shell test. A fixed +# startup sleep races a cold Python/launcher; a completed process also makes +# it safe to remove the disposable script and result files. +function Wait-SaiShellProbeProcess([IntPtr]$Handle, [uint32]$TimeoutMilliseconds = 10000) { + if ($Handle -eq [IntPtr]::Zero) { + return @{ completed = $false; wait = 'NO_PROCESS_HANDLE'; exit = $null } + } + try { + $waitCode = [SaiShellExec]::WaitForSingleObject($Handle, $TimeoutMilliseconds) + $exitCode = [uint32]0 + $gotExit = [SaiShellExec]::GetExitCodeProcess($Handle, [ref]$exitCode) + return @{ completed = ($waitCode -eq 0); wait = $waitCode + exit = $(if ($gotExit) { $exitCode } else { $null }) } + } finally { + [void][SaiShellExec]::CloseHandle($Handle) + } +} diff --git a/tests/test_shell_menu.ps1 b/tests/test_shell_menu.ps1 index eff14d4..2efa279 100644 --- a/tests/test_shell_menu.ps1 +++ b/tests/test_shell_menu.ps1 @@ -2,7 +2,9 @@ param( # The tree whose Registry\*.REG and Scripts\ are under test. Defaults to the # repository this file lives in; point it at an older checkout to use this # same harness as a red control. - [string]$Repo = (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Definition)) + [string]$Repo = (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Definition)), + [string]$WaitImplementation = (Join-Path $PSScriptRoot 'shell_probe_wait.ps1'), + [ValidateRange(0,5000)][int]$RecorderDelayMilliseconds = 0 ) $ErrorActionPreference = 'Stop' @@ -46,12 +48,21 @@ public class SaiShellExec { } [DllImport("shell32.dll", SetLastError=true, CharSet=CharSet.Unicode)] public static extern bool ShellExecuteExW(ref SHELLEXECUTEINFO lpExecInfo); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern bool GetExitCodeProcess(IntPtr handle, out uint exitCode); + [DllImport("kernel32.dll", SetLastError=true)] + public static extern bool CloseHandle(IntPtr handle); } '@ +. $WaitImplementation $sandbox = Join-Path $env:TEMP ('saituls_menu_' + [Guid]::NewGuid().ToString('N')) $out = Join-Path $sandbox 'recorded.txt' $fails = 0 +$cleanupReady = $true +$ownedKeys = @() function Check([string]$name, [bool]$ok, [string]$detail = '') { if ($ok) { Write-Host "PASS $name $detail" } else { Write-Host "FAIL $name $detail"; $script:fails++ } @@ -95,7 +106,8 @@ try { # The recorder's argument handling is the workers': shell_target(argv[1]). $recorder = Join-Path $sandbox 'recorder.pyw' @" -import os, sys +import os, sys, time +time.sleep($RecorderDelayMilliseconds / 1000.0) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) try: from shell_arg import shell_target @@ -137,8 +149,9 @@ open(r'$out', 'w', encoding='utf-8').write( continue } $probe = $shipped.Replace($worker, $recorder) - $verb = "SaiMenuProbe$($case.class)" + $verb = "SaiMenuProbe$($case.class)_$([Guid]::NewGuid().ToString('N'))" $key = "HKCU:\Software\Classes\$($case.class)\shell\$verb" + $ownedKeys += $key New-Item -Path "$key\command" -Force | Out-Null Set-ItemProperty -Path "$key\command" -Name '(default)' -Value $probe @@ -150,14 +163,15 @@ open(r'$out', 'w', encoding='utf-8').write( $si.lpFile = $case.target $si.nShow = 0 $launched = [SaiShellExec]::ShellExecuteExW([ref]$si) - Start-Sleep -Milliseconds 1200 + $processResult = Wait-SaiShellProbeProcess $si.hProcess + if (-not $processResult.completed) { $cleanupReady = $false } Remove-Item $key -Recurse -Force -ErrorAction SilentlyContinue $launcher = ($probe -split ' ')[0] Check "$($case.label): the shell resolves the shipped launcher $launcher" $launched ` $(if ($launched) { '' } else { "hInstApp=$([int]$si.hInstApp) -- the menu entry cannot start" }) - if (Test-Path $out) { + if ($processResult.completed -and (Test-Path $out)) { $rec = Get-Content $out -Raw $raw = ([regex]::Match($rec, "raw='([^']*)'")).Groups[1].Value.Replace('\\', '\') $target = ([regex]::Match($rec, "target='([^']*)'")).Groups[1].Value.Replace('\\', '\') @@ -174,14 +188,23 @@ open(r'$out', 'w', encoding='utf-8').write( ($target -eq $want -and $abspath -eq $want -and $isdir -eq 'True') ` "raw='$raw' target='$target' abspath='$abspath' isdir=$isdir" } else { - Check "$($case.label): the worker receives the real target" $false 'the worker never ran' + Check "$($case.label): the worker receives the real target" $false ` + "no completed recorder: wait=$($processResult.wait) exit=$($processResult.exit)" } } } finally { - foreach ($c in 'Drive', 'Directory') { - Remove-Item "HKCU:\Software\Classes\$c\shell\SaiMenuProbe$c" -Recurse -Force -ErrorAction SilentlyContinue + foreach ($ownedKey in $ownedKeys) { + Remove-Item -LiteralPath $ownedKey -Recurse -Force -ErrorAction SilentlyContinue + } + if ($cleanupReady) { + $full = [IO.Path]::GetFullPath($sandbox) + $tempBase = [IO.Path]::GetFullPath($env:TEMP).TrimEnd('\') + '\' + if (-not $full.StartsWith($tempBase, [StringComparison]::OrdinalIgnoreCase) -or + (Split-Path $full -Leaf) -notlike 'saituls_menu_*') { throw 'Unsafe recorder cleanup target' } + Remove-Item -LiteralPath $full -Recurse -Force -ErrorAction SilentlyContinue + } else { + Write-Host "Recorder did not complete; retained its owned sandbox: $sandbox" } - Remove-Item -LiteralPath $sandbox -Recurse -Force -ErrorAction SilentlyContinue } Write-Host '---' From a4169efb323eee594d4c15f3173d141716cb743e Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 18:52:04 +0200 Subject: [PATCH 18/24] test: measure scratch containment before cleanup Record XML containment while its file handle is open. After cleanup, an existing root can expand a short alias while the missing child cannot. Keep every containment assertion and the production privilege boundary; the outside-scratch writer control still fails the updated oracle. --- tests/test_secure_apps_privtask.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_secure_apps_privtask.py b/tests/test_secure_apps_privtask.py index 584f712..65ff96b 100644 --- a/tests/test_secure_apps_privtask.py +++ b/tests/test_secure_apps_privtask.py @@ -1584,15 +1584,19 @@ def test_the_task_xml_is_written_in_protected_scratch_not_user_temp(self): real_open = builtins.open def watched(path, *args, **kwargs): + handle = real_open(path, *args, **kwargs) if isinstance(path, str) and path.lower().endswith(".xml"): - seen.append(path) - return real_open(path, *args, **kwargs) + # Measure the live file, before transaction cleanup removes it. + # An existing root can expand an 8.3 alias while a deleted XML + # retains its short spelling, making a later comparison false. + seen.append((path, sa_privtask.path_is_within(self.scratch, path))) + return handle with mock.patch.object(builtins, "open", watched): self.assertTrue(self.install()["ok"]) self.assertTrue(seen, "no task XML was written at all") - for path in seen: - self.assertTrue(sa_privtask.path_is_within(self.scratch, path), + for path, was_within in seen: + self.assertTrue(was_within, "the task XML was written outside protected " "scratch: %s" % path) # ...and in production that scratch root is under %ProgramData%, not From bdaf34bc4d25a1a51f555875a3b3072f693ec7c1 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 19:06:32 +0200 Subject: [PATCH 19/24] test: canonicalize worker launch fixtures Resolve the live temporary fixture before probing later refusal branches. A short TEMP alias otherwise fails canonical-path validation first and masks the expected non-executable refusal. All assertions stay intact. The same real dot-segment fixture fails before and passes after; a helper with broken absolute-path guards still fails two checks. All 35 hygiene tests pass. The production helper and its launch boundary are unchanged. --- tests/test_secure_apps_hygiene.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_secure_apps_hygiene.py b/tests/test_secure_apps_hygiene.py index 54896c9..4265765 100644 --- a/tests/test_secure_apps_hygiene.py +++ b/tests/test_secure_apps_hygiene.py @@ -397,7 +397,9 @@ class ElevatedWorkerLaunchTests(unittest.TestCase): HELPER = SUBSYSTEM / "sa_storage_helper.ps1" def _run_harness(self, helper=None): - scratch = Path(tempfile.mkdtemp(prefix="saituls-worker-launch-")) + # The helper deliberately refuses noncanonical paths. Resolve the live + # fixture once so a TEMP 8.3 alias does not mask later refusal branches. + scratch = Path(tempfile.mkdtemp(prefix="saituls-worker-launch-")).resolve() self.addCleanup(shutil.rmtree, scratch, ignore_errors=True) (scratch / "empty-root").mkdir() runtime = scratch / "privileged" From 0b983a863e3561c22a64f2e7487c951eec680677 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 28 Oct 2026 19:21:31 +0200 Subject: [PATCH 20/24] test: expose failing SAIPATCH unit output Hosted regs40732476949 fails the plugin unit child but discards its captured assertion output. Emit that output on nonzero exit so the exact failing assertion is visible. Keep the original child command and exit gate intact. The same198 tests pass locally; hosted cause remains unconfirmed. --- tests/test_saipatch.ps1 | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_saipatch.ps1 b/tests/test_saipatch.ps1 index be96009..dfda520 100644 --- a/tests/test_saipatch.ps1 +++ b/tests/test_saipatch.ps1 @@ -190,6 +190,7 @@ try { $unit = & node --test (Join-Path $patchSrc 'saipatch-native-queue-2x.test.mjs') (Join-Path $patchSrc 'saipatch-completion-sound.test.mjs') 2>&1 $unitOut = (($unit | ForEach-Object { "$_" }) -join "`n") $unitRc = $LASTEXITCODE + if ($unitRc -ne 0) { Write-Host $unitOut } Check '2. plugin unit tests green (projection, queue semantics, ambient, wiring, completion sound)' ($unitRc -eq 0) "exit=$unitRc" $mf = Get-Content -Raw -LiteralPath (Join-Path $patchSrc 'manifest.json') | ConvertFrom-Json From 759791f1d5b938d23779e3539344b503ac2241a4 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 29 Oct 2026 02:11:53 +0200 Subject: [PATCH 21/24] test(consoles): isolate launcher prerequisites Provision resolution-only CLI/ZCode fixtures and a synthetic account transport so hosted tests need no operator installation or registry. Canonical fixture paths retain exact WorkDir and argv assertions across Windows short/long aliases. Missing commands and engines still fail closed; console safety assertions remain enabled. --- tests/test_consoles_launcher.py | 127 +++++++++++++++++++++++++------- 1 file changed, 100 insertions(+), 27 deletions(-) diff --git a/tests/test_consoles_launcher.py b/tests/test_consoles_launcher.py index e9ba7b0..1e632bd 100644 --- a/tests/test_consoles_launcher.py +++ b/tests/test_consoles_launcher.py @@ -58,6 +58,58 @@ def strip_csharp_comments(text): LAUNCHER_CODE = strip_powershell_comments(LAUNCHER_SOURCE) +SUITE_ENV = None + + +def console_test_environment(env=None): + """Resolve only disposable CLI/account fixtures, never operator services. + + The account transport is a compiled recording stub; integration with the + real engine is covered separately by test_sai_accounts.py. + """ + global SUITE_ENV + if SUITE_ENV is None: + engine = build_stub_engine("sai-accounts", stdout_env="SAITULS_TEST_ACCOUNTS") + root = Path(engine).parent / "console-fixtures" + root.mkdir(exist_ok=True) + bindir = root / "bin" + bindir.mkdir(exist_ok=True) + for name in ("claude", "codex", "agy", "node", "cline", "opencode"): + (bindir / (name + ".cmd")).write_bytes(b"@echo off\r\nexit /b 0\r\n") + script = root / "zcode.cjs" + script.write_text("// Resolution-only test fixture; no provider code.\n", encoding="utf-8") + accounts = [] + for provider, locators in ( + ("claude", [str(Path(os.environ["USERPROFILE"]) / ".claude"), + str(Path(os.environ["USERPROFILE"]) / ".claude-account2")]), + ("codex", [str(Path(os.environ["USERPROFILE"]) / ".codex")]), + ("antigravity", [os.environ["USERNAME"], "console-fixture-ag2"]), + ): + for index, locator in enumerate(locators, 1): + prefix = {"claude": "CL", "codex": "CX", "antigravity": "AG"}[provider] + kind = "windows-user" if provider == "antigravity" else "profile-dir" + accounts.append({ + "account_id": "%s:%s:%016x" % (provider, kind, index), + "provider_id": provider, "display_name": "%s %s" % (provider.title(), index), + "compact_label": prefix + str(index), "operational_state": "ENABLED", + "hidden": False, "provider_metadata": { + "windows_user" if kind == "windows-user" else "profile_locator": locator}, + }) + SUITE_ENV = { + "PATH": str(bindir) + os.pathsep + os.environ["PATH"], + "ZCODE_CLI": str(script), "SAI_ACCOUNTS_EXE": engine, + "SAITULS_TEST_ACCOUNTS": json.dumps({"schema": "sai.accounts/list/1", "accounts": accounts}), + "STUB_EXIT": "0", "STUB_STDERR": "", "STUB_ARGV_FILE": "", + "SAITULS_CONSOLE_LOG": str(root / "launch.log"), + } + merged = dict(os.environ) + # PS7's module path can shadow the PS5 built-ins used by these children. + merged = {key: value for key, value in merged.items() if key.upper() != "PSMODULEPATH"} + merged.update(SUITE_ENV) + if env: + merged.update(env) + return merged + def run_selftest(*extra, registry_path=None, env=None, federation="off"): """Every suite here runs STANDALONE unless it says otherwise. @@ -69,16 +121,15 @@ def run_selftest(*extra, registry_path=None, env=None, federation="off"): """ cmd = ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(LAUNCHER), "-SelfTest", "-Federation", federation] + list(extra) - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(REPO), env=merged) text = (completed.stdout or "").strip() start = text.find("{") payload = json.loads(text[start:]) if start >= 0 else None - return completed.returncode, payload, completed.stderr + diagnostic = completed.stderr or (text if completed.returncode else "") + return completed.returncode, payload, diagnostic def is_template(profile): """A profile that renders one console per canonical account, not a console.""" @@ -186,7 +237,7 @@ def test_console_launcher_remains_non_elevated(self): def test_project_first_title(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "MyProject" + project = (Path(tmp) / "MyProject").resolve() project.mkdir() rc, payload, stderr = run_selftest("-Profile", "claude-1", "-WorkDir", str(project)) @@ -441,9 +492,7 @@ def test_existing_tool_entries_are_unchanged(self): INSTALLER_SOURCE = INSTALLER.read_text(encoding="utf-8") def ps(script, env=None): - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run( ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " @@ -495,6 +544,25 @@ def test_absent_engine_yields_no_accounts_and_no_exception(self): self.assertEqual(rc, 0, err) self.assertEqual(out, "0") + def test_missing_cli_still_reports_an_unresolved_profile(self): + with tempfile.TemporaryDirectory(prefix="saituls-no-cli-") as tmp: + rc, payload, stderr = run_selftest( + "-Profile", "claude-1", env={"PATH": tmp}, federation="off") + self.assertEqual(rc, 0, stderr) + self.assertFalse(payload["ok"]) + row = profile_row(payload, "claude-1") + self.assertFalse(row["Resolved"]) + self.assertEqual(row["ErrorCategory"], "EXECUTABLE_MISSING") + + def test_shared_profiles_are_bound_to_the_fixture_engine(self): + rc, payload, stderr = run_selftest(federation="on") + self.assertEqual(rc, 0, stderr) + self.assertEqual(payload["federation"]["engine"], + str(Path(console_test_environment()["SAI_ACCOUNTS_EXE"]).resolve())) + shared = [row for row in payload["profiles"] if row["Origin"] == "shared"] + self.assertTrue(shared) + self.assertTrue(all(row["Command"] == payload["federation"]["engine"] for row in shared)) + class AccountProfileShapeTests(unittest.TestCase): """The adapter's launch shape, proven on every machine. @@ -572,8 +640,7 @@ class FederationTests(unittest.TestCase): """The control plane adds accounts. It never takes any away.""" def setUp(self): - if not engine_is_installed(): - self.skipTest("SAI Accounts control plane is not installed on this machine") + self.assertTrue(engine_is_installed(), "compiled account fixture did not resolve") def federated(self): rc, payload, stderr = run_selftest(federation="on") @@ -646,7 +713,7 @@ def test_codex_shared_profiles_use_the_four_part_shape(self): def test_a_workdir_with_spaces_stays_exactly_one_argument(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "My Big Project 2" + project = (Path(tmp) / "My Big Project 2").resolve() project.mkdir() rc, payload, stderr = run_selftest("-WorkDir", str(project), federation="on") self.assertEqual(rc, 0, stderr) @@ -659,7 +726,7 @@ def test_a_workdir_with_spaces_stays_exactly_one_argument(self): def test_a_unicode_workdir_survives_intact(self): with tempfile.TemporaryDirectory(prefix="saituls-console-") as tmp: - project = Path(tmp) / "проект Ünïcødé" + project = (Path(tmp) / "проект Ünïcødé").resolve() project.mkdir() rc, payload, stderr = run_selftest("-WorkDir", str(project), federation="on") self.assertEqual(rc, 0, stderr) @@ -837,14 +904,21 @@ def test_a_local_profile_collapsed_into_a_disabled_account_leaves_the_menu(self) self.assertEqual(out, "0") def test_federation_on_without_an_engine_fails_closed(self): - rc, payload, stderr = run_selftest(federation="on", env={ - "SAI_ACCOUNTS_EXE": str(REPO / "Scripts" / "consoles" / "ACCOUNTS.ps1")}) - # The canonical install still resolves on this machine, so the honest - # assertion is the one below: 'on' never silently degrades to 'off'. - if payload: - self.assertIsNotNone(payload["federation"]["engine"]) - else: - self.assertIn("control plane is not installed", stderr) + # Inject an absent resolver into a disposable module: a developer's + # deployed/repo-built engine must not turn this negative into success. + with tempfile.TemporaryDirectory(prefix="saituls-no-engine-") as tmp: + root = Path(tmp) + (root / "CONSOLES.ps1").write_text(LAUNCHER_SOURCE, encoding="utf-8-sig") + (root / "ACCOUNTS.ps1").write_text( + ACCOUNTS_SOURCE + "\nfunction Resolve-SaiAccountsEngine { return $null }\n", + encoding="utf-8-sig") + shutil.copy(REGISTRY, root / "consoles.json") + completed = subprocess.run( + ["powershell", "-NoProfile", "-File", str(root / "CONSOLES.ps1"), + "-SelfTest", "-Federation", "on"], capture_output=True, text=True, + encoding="utf-8", errors="replace", env=console_test_environment(), timeout=30) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("control plane is not installed", completed.stdout + completed.stderr) def test_installer_and_launcher_share_one_expansion(self): self.assertIn("ACCOUNTS.ps1", INSTALLER_SOURCE) @@ -1014,9 +1088,7 @@ def ps_single(text): def psraw(script, env=None): """Plain PowerShell, without dot-sourcing the federation module.""" - merged = dict(os.environ) - if env: - merged.update(env) + merged = console_test_environment(env) completed = subprocess.run( ["powershell", "-NoLogo", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", "[Console]::OutputEncoding=[Text.Encoding]::UTF8; " + script], @@ -1029,7 +1101,7 @@ def psraw(script, env=None): STUB_DIR = [] -def build_stub_engine(name="stub-engine"): +def build_stub_engine(name="stub-engine", stdout_env="STUB_STDOUT"): """A minimal stand-in for an engine or a CLI. It records the argv it was REALLY started with and prints whatever envelope @@ -1082,7 +1154,8 @@ class StubEngine { return code; } } -''', encoding="utf-8") +'''.replace('GetEnvironmentVariable("STUB_STDOUT")', + 'GetEnvironmentVariable("%s")' % stdout_env), encoding="utf-8") built = subprocess.run([csc, "-nologo", "-target:exe", "-out:" + str(exe), str(source)], capture_output=True, text=True, timeout=180) if built.returncode != 0 or not exe.exists(): @@ -1204,7 +1277,7 @@ def setUp(self): self.windir = os.environ.get("WINDIR", r"C:\Windows") def launch(self, *extra, env=None, launcher=None): - merged = dict(os.environ) + merged = console_test_environment() merged["SAITULS_CONSOLE_LOG"] = self.log if env: merged.update(env) @@ -1274,7 +1347,7 @@ def test_a_local_console_launch_is_recorded_as_launched(self): "requires_admin": False, "title_suffix": "Stub", "description": "stub CLI"}] (Path(registry) / "consoles.json").write_text(json.dumps(doc), encoding="utf-8") - project = os.path.join(self.tmp, "project") + project = str((Path(self.tmp) / "project").resolve()) os.makedirs(project, exist_ok=True) argv_file = os.path.join(self.tmp, "argv.txt") completed = self.launch( From 96eb4702375ec519580d45068e20ab138ffebdf2 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 29 Oct 2026 04:59:48 +0200 Subject: [PATCH 22/24] test(consoles): bind physical engine identity Hosted PowerShell retains RUNNER~1 while Python resolves runneradmin. Compare the fixture file identity so both aliases bind the same engine. Different files, absent files and mismatched shared commands still fail. No production launcher or security boundary changes. --- tests/test_consoles_launcher.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test_consoles_launcher.py b/tests/test_consoles_launcher.py index 1e632bd..be8da65 100644 --- a/tests/test_consoles_launcher.py +++ b/tests/test_consoles_launcher.py @@ -557,8 +557,11 @@ def test_missing_cli_still_reports_an_unresolved_profile(self): def test_shared_profiles_are_bound_to_the_fixture_engine(self): rc, payload, stderr = run_selftest(federation="on") self.assertEqual(rc, 0, stderr) - self.assertEqual(payload["federation"]["engine"], - str(Path(console_test_environment()["SAI_ACCOUNTS_EXE"]).resolve())) + # PowerShell can preserve an 8.3 parent while Python expands it. + # Bind the actual fixture file, including rejection of other engines. + self.assertTrue(os.path.samefile( + payload["federation"]["engine"], + console_test_environment()["SAI_ACCOUNTS_EXE"])) shared = [row for row in payload["profiles"] if row["Origin"] == "shared"] self.assertTrue(shared) self.assertTrue(all(row["Command"] == payload["federation"]["engine"] for row in shared)) From 9eff11f6ab9f6aeacf98b85ca3650583485c8233 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 29 Oct 2026 10:03:49 +0200 Subject: [PATCH 23/24] fix(usn): classify native mutation failures Elevated runners reported failed native mutations as unhealthy (1), while unelevated callers masked the missing ToolFailed flag with (3). Set the existing tool-error flag so elevated failures return (2). Recording fakes exercise both admin facts without acquiring elevation. Retain no-delete after failed create and no-create after failed delete. --- Scripts/host/UsnJournalGuard.ps1 | 4 ++-- tests/test_usn_journal_guard.ps1 | 37 ++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/Scripts/host/UsnJournalGuard.ps1 b/Scripts/host/UsnJournalGuard.ps1 index e340287..d46864d 100644 --- a/Scripts/host/UsnJournalGuard.ps1 +++ b/Scripts/host/UsnJournalGuard.ps1 @@ -445,7 +445,7 @@ function Invoke-JournalResize([string]$vol, [int64]$minBytes, [int64]$targetByte } $r = Invoke-Fsutil -Arguments @('usn', 'createjournal', "m=$targetBytes", "a=$deltaBytes", $vol) if ($r.ExecutionFailed -or $r.ExitCode -ne 0) { - Add-Problem (Format-Inv '{0}: createjournal failed exit {1}: {2}' @($vol, $r.ExitCode, $r.FirstLine)) + Add-ToolProblem (Format-Inv '{0}: createjournal failed exit {1}: {2}' @($vol, $r.ExitCode, $r.FirstLine)) if (-not $script:IsAdmin) { $script:ElevationNeeded = $true } # The resize was never issued: a later delete would destroy a journal # over a permission or execution problem, so it stays forbidden. @@ -524,7 +524,7 @@ function Invoke-JournalRecreate([string]$vol, [int64]$minBytes, [int64]$targetBy Write-Log "WARNING: $vol : recreating the journal (deletejournal + createjournal) under explicit volume-scoped authorization; this forces a full volume rescan for every USN consumer" $d = Invoke-Fsutil -Arguments @('usn', 'deletejournal', '/n', $vol) if ($d.ExecutionFailed -or $d.ExitCode -ne 0) { - Add-Problem (Format-Inv '{0}: deletejournal failed exit {1}: {2}' @($vol, $d.ExitCode, $d.FirstLine)) + Add-ToolProblem (Format-Inv '{0}: deletejournal failed exit {1}: {2}' @($vol, $d.ExitCode, $d.FirstLine)) if (-not $script:IsAdmin) { $script:ElevationNeeded = $true } return $false } diff --git a/tests/test_usn_journal_guard.ps1 b/tests/test_usn_journal_guard.ps1 index 515a755..1c82f4e 100644 --- a/tests/test_usn_journal_guard.ps1 +++ b/tests/test_usn_journal_guard.ps1 @@ -132,13 +132,13 @@ function New-Mock { function Step([int]$exit, [string]$output) { return [pscustomobject]@{ exit = $exit; output = $output } } function Invoke-Guard { - param([string]$Mock, [string[]]$Extra = @(), [switch]$ExpectRaw, [string]$RegKey = '', [hashtable]$Replace = @{}, [string]$Volumes = 'C') + param([string]$Mock, [string[]]$Extra = @(), [switch]$ExpectRaw, [string]$RegKey = '', [hashtable]$Replace = @{}, [string]$Volumes = 'C', [string]$Source = $GuardSource) $stamp = [Guid]::NewGuid().ToString('N') $stdout = Join-Path $Sandbox "out_$stamp.txt" $stderr = Join-Path $Sandbox "err_$stamp.txt" $log = Join-Path $Sandbox "guard_$stamp.log" $reg = if ($RegKey) { $RegKey } else { $scratchKey } - $base = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $GuardSource, + $base = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $Source, '-Volume', $Volumes, '-FsutilPath', $Mock, '-RegistryKey', $reg, '-LogPath', $log, '-Json', '-ResizeWaitSeconds', '10', '-ResizePollSeconds', '0') foreach ($k in $Replace.Keys) { @@ -283,6 +283,39 @@ Check 'failed_createjournal_exits_nonzero' ($r.Code -eq 2 -or $r.Code -eq 3) "ex Check 'failed_createjournal_is_reported' ((Get-ProblemText $r.Report) -match 'createjournal failed') "problems=$(Get-ProblemText $r.Report)" Check 'failed_createjournal_does_not_delete' ((@($calls | Where-Object { $_ -match 'deletejournal' }).Count) -eq 0) "calls=[$($calls -join ' / ')]" +# The hosted runner can be elevated even when the local test process is not. +# Exercise both classification branches without elevation or real fsutil: +# only the admin fact in a sandbox copy changes; every operation still uses +# the recording fake and scratch registry key. Otherwise exit 3 on a local +# unelevated host can hide a missing ToolFailed flag (hosted exit 1). +$guardText = [System.IO.File]::ReadAllText($GuardSource) +$adminAssignment = '$script:IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)' +if ([regex]::Matches($guardText, [regex]::Escape($adminAssignment)).Count -ne 1) { + throw 'admin classification fixture must replace exactly one native admin fact' +} +foreach ($adminFact in @($true, $false)) { + $label = if ($adminFact) { 'elevated' } else { 'unelevated' } + $expectedCode = if ($adminFact) { 2 } else { 3 } + $factLiteral = if ($adminFact) { '$true' } else { '$false' } + $fixtureSource = Join-Path $Sandbox ("guard_$label.ps1") + [System.IO.File]::WriteAllText($fixtureSource, + $guardText.Replace($adminAssignment, ('$script:IsAdmin = ' + $factLiteral)), + (New-Object System.Text.UTF8Encoding($true))) + + $mock = New-Mock -Name ("create_fails_$label") -QuerySequence @((Step 0 $english1mb)) -Create (Step 1 'Access is denied.') + $r = Invoke-Guard -Mock $mock -Source $fixtureSource -Extra @('-RepairJournals', '-AllowJournalRecreate', '-RecreateVolume', 'C') + $calls = Get-Calls $mock + Check "failed_createjournal_${label}_exit_class" ($r.Code -eq $expectedCode -and $r.Report -and $r.Report.exitCode -eq $expectedCode -and $r.Report.elevated -eq $adminFact) "exit=$($r.Code) expected=$expectedCode" + Check "failed_createjournal_${label}_no_delete" (@($calls | Where-Object { $_ -match 'deletejournal' }).Count -eq 0 -and @($calls | Where-Object { $_ -match 'createjournal' }).Count -eq 1) "calls=[$($calls -join ' / ')]" + + $mock = New-Mock -Name ("delete_fails_$label") -QuerySequence @((Step 0 $english1mb)) -Delete (Step 1 'Access is denied.') + $r = Invoke-Guard -Mock $mock -Source $fixtureSource -Replace @{ '-ResizeWaitSeconds' = '0' } -Extra @('-RepairJournals', '-AllowJournalRecreate', '-RecreateVolume', 'C') + $calls = Get-Calls $mock + Check "failed_deletejournal_${label}_exit_class" ($r.Code -eq $expectedCode -and $r.Report -and $r.Report.exitCode -eq $expectedCode -and $r.Report.elevated -eq $adminFact) "exit=$($r.Code) expected=$expectedCode" + Check "failed_deletejournal_${label}_reported" ((Get-ProblemText $r.Report) -match 'deletejournal failed') "problems=$(Get-ProblemText $r.Report)" + Check "failed_deletejournal_${label}_no_followup_create" (@($calls | Where-Object { $_ -match 'deletejournal' }).Count -eq 1 -and @($calls | Where-Object { $_ -match 'createjournal' }).Count -eq 1) "calls=[$($calls -join ' / ')]" +} + # ---- 13. registry clamp: read-only by default, removed only on request -- Set-ItemProperty -Path $scratchKey -Name $clampName -Value 1 -Type DWord $mock = New-Mock -Name 'clamp_diagnose' -QuerySequence @((Step 0 $english1mb)) From 37183f2de3df75125ba4600722e57762aa9423bf Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 29 Oct 2026 17:32:19 +0200 Subject: [PATCH 24/24] test: await cold shell recorders safely Cold hosted launcher startup exceeds ten seconds. Wait at most sixty seconds for the exact process, retain timed-out sandboxes, and isolate each recorder output so a late process cannot satisfy a later case. Keep shipped launcher resolution and exact drive-root assertions. Exercise twelve-second recorders in CI; the old wait fails both cases. --- .github/workflows/test.yml | 4 +++- tests/shell_probe_wait.ps1 | 4 +++- tests/test_shell_menu.ps1 | 16 ++++++++++------ 3 files changed, 16 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ac8456d..104eda9 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -203,7 +203,9 @@ jobs: - name: Test Explorer menu launch and argument contract shell: pwsh run: | - powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_shell_menu.ps1 + # Exercise a recorder that is still live after the old ten-second + # bound; preserve real shell resolution and drive-root assertions. + powershell -NoProfile -ExecutionPolicy Bypass -File tests\test_shell_menu.ps1 -RecorderDelayMilliseconds 12000 if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Test single-instance activation publication shell: pwsh diff --git a/tests/shell_probe_wait.ps1 b/tests/shell_probe_wait.ps1 index e24ec51..5b5a132 100644 --- a/tests/shell_probe_wait.ps1 +++ b/tests/shell_probe_wait.ps1 @@ -1,7 +1,9 @@ # Wait on the exact hidden recorder process owned by the shell test. A fixed # startup sleep races a cold Python/launcher; a completed process also makes # it safe to remove the disposable script and result files. -function Wait-SaiShellProbeProcess([IntPtr]$Handle, [uint32]$TimeoutMilliseconds = 10000) { +# A cold system launcher on hosted Windows can take more than ten seconds. +# Keep a finite completion bound; timeout still fails and retains the sandbox. +function Wait-SaiShellProbeProcess([IntPtr]$Handle, [uint32]$TimeoutMilliseconds = 60000) { if ($Handle -eq [IntPtr]::Zero) { return @{ completed = $false; wait = 'NO_PROCESS_HANDLE'; exit = $null } } diff --git a/tests/test_shell_menu.ps1 b/tests/test_shell_menu.ps1 index 2efa279..23325ee 100644 --- a/tests/test_shell_menu.ps1 +++ b/tests/test_shell_menu.ps1 @@ -4,7 +4,7 @@ param( # same harness as a red control. [string]$Repo = (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Definition)), [string]$WaitImplementation = (Join-Path $PSScriptRoot 'shell_probe_wait.ps1'), - [ValidateRange(0,5000)][int]$RecorderDelayMilliseconds = 0 + [ValidateRange(0,60000)][int]$RecorderDelayMilliseconds = 0 ) $ErrorActionPreference = 'Stop' @@ -59,7 +59,6 @@ public class SaiShellExec { . $WaitImplementation $sandbox = Join-Path $env:TEMP ('saituls_menu_' + [Guid]::NewGuid().ToString('N')) -$out = Join-Path $sandbox 'recorded.txt' $fails = 0 $cleanupReady = $true $ownedKeys = @() @@ -103,9 +102,10 @@ try { Copy-Item $shellArg $sandbox -Force } - # The recorder's argument handling is the workers': shell_target(argv[1]). - $recorder = Join-Path $sandbox 'recorder.pyw' - @" + # Each case owns its script and output: a timed-out recorder must never + # supply a later case's evidence or lose its script while it is still live. + function New-Recorder([string]$recorder, [string]$out) { + @" import os, sys, time time.sleep($RecorderDelayMilliseconds / 1000.0) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -118,6 +118,7 @@ t = shell_target(sys.argv[1]) open(r'$out', 'w', encoding='utf-8').write( "raw=%r target=%r abspath=%r isdir=%s" % (sys.argv[1], t, os.path.abspath(t), os.path.isdir(t))) "@ | Set-Content -LiteralPath $recorder -Encoding UTF8 + } # DEL_JUNK is the only worker registered on Drive as well as Directory, so it # is the one that exposes the drive-root case. @@ -143,6 +144,9 @@ open(r'$out', 'w', encoding='utf-8').write( ) foreach ($case in $cases) { + $out = Join-Path $sandbox ("recorded-" + $case.class + '.txt') + $recorder = Join-Path $sandbox ("recorder-" + $case.class + '.pyw') + New-Recorder $recorder $out $shipped = Get-ShippedCommand (Join-Path $Repo 'Registry\DEL_JUNK.REG') $case.class $Repo if (-not $shipped) { Check "$($case.class): the .REG declares a command" $false 'no command value found' @@ -171,7 +175,7 @@ open(r'$out', 'w', encoding='utf-8').write( Check "$($case.label): the shell resolves the shipped launcher $launcher" $launched ` $(if ($launched) { '' } else { "hInstApp=$([int]$si.hInstApp) -- the menu entry cannot start" }) - if ($processResult.completed -and (Test-Path $out)) { + if ($processResult.completed -and $processResult.exit -eq 0 -and (Test-Path $out)) { $rec = Get-Content $out -Raw $raw = ([regex]::Match($rec, "raw='([^']*)'")).Groups[1].Value.Replace('\\', '\') $target = ([regex]::Match($rec, "target='([^']*)'")).Groups[1].Value.Replace('\\', '\')