#Requires -Version 5.1 <# .SYNOPSIS Advisor Assistant native Windows 11 1-click installer. .DESCRIPTION Bootstraps Advisor Assistant natively on Windows 11 (compatible with Windows PowerShell 5.1+ and PowerShell 7+ / pwsh): 1. Resolves a real working Python 3.11+ interpreter (rejecting broken WindowsApps Store stubs and broken third-party venv shims). 2. Sets PYTHONUTF8=1 and writes advisor.cmd and advisor.ps1 launchers that always export PYTHONUTF8=1 to prevent Windows cp1252 mojibake. 3. Creates .venv via uv (fallback python -m venv) and installs the Day-1 set: cryptography, python-docx, pypdfium2 and Pillow. 4. Detects native Microsoft Edge for zero-dependency HTML-to-PDF rendering. 5. Runs 5 fail-closed acceptance self-tests (Python UTF-8 + pii/pii_gate, Ed25519 license_lease, Advisor Assistant API health, Edge headless PDF smoke render, and advisor.cmd launcher UTF-8 verification) and writes a JSON install receipt. #> [CmdletBinding()] param( [string]$InstallDir = "", [string]$ApiBaseUrl = "https://advisor-assistant-api.fly.dev", [string]$ReceiptPath = "", [switch]$NoCache ) $ErrorActionPreference = "Stop" $ProgressPreference = "SilentlyContinue" try { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13 } catch { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } $explicitInstallDir = -not [string]::IsNullOrWhiteSpace($InstallDir) if (-not $explicitInstallDir) { if (-not [string]::IsNullOrWhiteSpace($PSScriptRoot)) { $InstallDir = $PSScriptRoot } else { $InstallDir = (Get-Location).Path } } $InstallDir = [System.IO.Path]::GetFullPath($InstallDir) $ApiBaseUrl = $ApiBaseUrl.TrimEnd("/") # Resolve vault root when invoked from Site\install.ps1 without an explicit -InstallDir. if (-not $explicitInstallDir -and -not (Test-Path -LiteralPath (Join-Path $InstallDir "Backend\Scripts") -PathType Container)) { $parentDir = Split-Path -Parent $InstallDir if ($parentDir -and (Test-Path -LiteralPath (Join-Path $parentDir "Backend\Scripts\cli\advisor_cli.py") -PathType Leaf)) { $InstallDir = $parentDir } } # Pre-flight check BEFORE creating .venv, launchers, smoke dir, or install_receipt.json. $BackendScriptsDir = Join-Path $InstallDir "Backend\Scripts" if (-not (Test-Path -LiteralPath $BackendScriptsDir -PathType Container)) { Write-Host "" Write-Host "Advisor Assistant setup cannot start from this folder:" Write-Host " $InstallDir" Write-Host "" Write-Host "Expected product files (Backend\Scripts) were not found here." Write-Host "Please unzip or open the Advisor Assistant folder first, then run install.ps1 from inside it." Write-Host "Nothing was created or modified." exit 1 } if ([string]::IsNullOrWhiteSpace($ReceiptPath)) { $ReceiptPath = Join-Path $InstallDir "install_receipt.json" } $TotalSw = [System.Diagnostics.Stopwatch]::StartNew() $Timings = [ordered]@{} $Gates = [ordered]@{} $Receipt = [ordered]@{ product = "Advisor Assistant" status = "IN_PROGRESS" installed_at_utc = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") os = [System.Environment]::OSVersion.VersionString powershell_version = $PSVersionTable.PSVersion.ToString() install_dir = $InstallDir api_base_url = $ApiBaseUrl python = [ordered]@{} edge = [ordered]@{} launchers = [ordered]@{} gates = $Gates timings_seconds = $Timings error = $null } function Write-Utf8NoBom { param( [Parameter(Mandatory = $true)][string]$Path, [Parameter(Mandatory = $true)][string]$Content ) $parent = Split-Path -Parent $Path if ($parent -and -not (Test-Path -LiteralPath $parent)) { New-Item -ItemType Directory -Path $parent -Force | Out-Null } $utf8NoBom = New-Object System.Text.UTF8Encoding($false) [System.IO.File]::WriteAllText($Path, $Content, $utf8NoBom) } function Format-WinArg { param([string]$Arg) if ($null -eq $Arg -or $Arg.Length -eq 0) { return '""' } if ($Arg -notmatch '[\s"]') { return $Arg } $escaped = $Arg -replace '(\\*)"', '$1$1\"' $escaped = $escaped -replace '(\\+)$', '$1$1' return '"' + $escaped + '"' } function Invoke-ProcessCapture { param( [Parameter(Mandatory = $true)][string]$FilePath, [string[]]$Arguments = @(), [string]$RawArguments = "", [string]$WorkingDirectory = $InstallDir, [hashtable]$ExtraEnv = @{}, [int]$TimeoutMs = 120000 ) $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = $FilePath if (-not [string]::IsNullOrEmpty($RawArguments)) { $psi.Arguments = $RawArguments } elseif ($Arguments.Count -gt 0) { $quoted = @() foreach ($a in $Arguments) { $quoted += (Format-WinArg $a) } $psi.Arguments = [string]::Join(" ", $quoted) } $psi.WorkingDirectory = $WorkingDirectory $psi.UseShellExecute = $false $psi.CreateNoWindow = $true $psi.RedirectStandardOutput = $true $psi.RedirectStandardError = $true $psi.StandardOutputEncoding = [System.Text.Encoding]::UTF8 $psi.StandardErrorEncoding = [System.Text.Encoding]::UTF8 foreach ($k in $ExtraEnv.Keys) { $psi.EnvironmentVariables[$k] = [string]$ExtraEnv[$k] } $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi try { [void]$proc.Start() $outTask = $proc.StandardOutput.ReadToEndAsync() $errTask = $proc.StandardError.ReadToEndAsync() $exited = $proc.WaitForExit($TimeoutMs) if (-not $exited) { try { $proc.Kill() } catch {} return [PSCustomObject]@{ ExitCode = -1 StdOut = "" StdErr = "Timed out after $TimeoutMs ms" TimedOut = $true } } $proc.WaitForExit() return [PSCustomObject]@{ ExitCode = $proc.ExitCode StdOut = $outTask.GetAwaiter().GetResult() StdErr = $errTask.GetAwaiter().GetResult() TimedOut = $false } } catch { return [PSCustomObject]@{ ExitCode = -1 StdOut = "" StdErr = $_.Exception.Message TimedOut = $false } } finally { $proc.Dispose() } } function Test-RejectedPythonPath { param([string]$ExePath) if ([string]::IsNullOrWhiteSpace($ExePath)) { return $true } if ($ExePath -match '(?i)\\WindowsApps\\') { return $true } if ($ExePath -match '(?i)\\(\.?venv|virtualenv|hermes)\\') { return $true } return $false } function Test-RealPython { param([string]$ExePath) if (Test-RejectedPythonPath $ExePath) { return $null } if (-not (Test-Path -LiteralPath $ExePath -PathType Leaf)) { return $null } $probe = "import os, sys; " + "assert sys.version_info >= (3, 11), 'python<3.11'; " + "assert os.path.isdir(sys.base_prefix), 'missing base_prefix'; " + "assert os.path.normcase(os.path.realpath(sys.prefix)) == os.path.normcase(os.path.realpath(sys.base_prefix)), 'venv shim'; " + "print(sys.executable + '|' + sys.version.split()[0])" $res = Invoke-ProcessCapture -FilePath $ExePath -Arguments @("-I", "-c", $probe) -ExtraEnv @{ "PYTHONUTF8" = "1" "PYTHONIOENCODING" = "utf-8" } -TimeoutMs 15000 if ($res.ExitCode -ne 0) { return $null } $line = ($res.StdOut -split "`r?`n" | Where-Object { $_ -match '\|' } | Select-Object -Last 1) if ([string]::IsNullOrWhiteSpace($line)) { return $null } $parts = $line.Trim().Split("|") if ($parts.Count -lt 2) { return $null } $resolved = $parts[0].Trim() if (Test-RejectedPythonPath $resolved) { return $null } return [PSCustomObject]@{ Path = $resolved Version = $parts[1].Trim() } } function Resolve-WorkingUv { $candidates = New-Object System.Collections.Generic.List[string] if ($env:USERPROFILE) { $candidates.Add((Join-Path $env:USERPROFILE ".local\bin\uv.exe")) } if ($env:LOCALAPPDATA) { $candidates.Add((Join-Path $env:LOCALAPPDATA "uv\uv.exe")) } $cmdList = @(Get-Command uv -All -ErrorAction SilentlyContinue) foreach ($cmd in $cmdList) { if ($cmd.Source -and -not $candidates.Contains($cmd.Source)) { $candidates.Add($cmd.Source) } } foreach ($cand in $candidates) { if (-not (Test-Path -LiteralPath $cand -PathType Leaf)) { continue } $res = Invoke-ProcessCapture -FilePath $cand -Arguments @("--version") -TimeoutMs 10000 if ($res.ExitCode -eq 0 -and $res.StdOut -match 'uv\s+[0-9]') { return [PSCustomObject]@{ Path = $cand Version = $res.StdOut.Trim() } } } return $null } function Resolve-WorkingPython { param($UvInfo) $candidates = New-Object System.Collections.Generic.List[string] # 1. Windows Python Launcher (py.exe) $pyLauncher = Get-Command py -ErrorAction SilentlyContinue if ($pyLauncher -and $pyLauncher.Source) { foreach ($tag in @("-3.14", "-3.13", "-3.12", "-3.11", "-3")) { $res = Invoke-ProcessCapture -FilePath $pyLauncher.Source -Arguments @($tag, "-c", "import sys; print(sys.executable)") -TimeoutMs 10000 if ($res.ExitCode -eq 0) { $p = ($res.StdOut -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Last 1) if ($p -and -not $candidates.Contains($p.Trim())) { $candidates.Add($p.Trim()) } } } } # 2. Known native CPython install paths if ($env:LOCALAPPDATA) { $candidates.Add((Join-Path $env:LOCALAPPDATA "Python\bin\python.exe")) $localPyRoot = Join-Path $env:LOCALAPPDATA "Programs\Python" if (Test-Path -LiteralPath $localPyRoot) { $dirs = @(Get-ChildItem -LiteralPath $localPyRoot -Directory -Filter "Python3*" -ErrorAction SilentlyContinue | Sort-Object Name -Descending) foreach ($d in $dirs) { $candidates.Add((Join-Path $d.FullName "python.exe")) } } } if ($env:ProgramFiles) { $dirs = @(Get-ChildItem -LiteralPath $env:ProgramFiles -Directory -Filter "Python3*" -ErrorAction SilentlyContinue | Sort-Object Name -Descending) foreach ($d in $dirs) { $candidates.Add((Join-Path $d.FullName "python.exe")) } } # 3. uv-discovered Python interpreters if ($null -ne $UvInfo) { $res = Invoke-ProcessCapture -FilePath $UvInfo.Path -Arguments @("python", "find", ">=3.11") -TimeoutMs 15000 if ($res.ExitCode -eq 0) { $p = ($res.StdOut -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Last 1) if ($p -and -not $candidates.Contains($p.Trim())) { $candidates.Add($p.Trim()) } } } # 4. PATH python/python3 fallbacks (strictly filtered) foreach ($name in @("python", "python3")) { $found = @(Get-Command $name -All -ErrorAction SilentlyContinue) foreach ($cmd in $found) { if ($cmd.Source -and -not $candidates.Contains($cmd.Source)) { $candidates.Add($cmd.Source) } } } foreach ($cand in $candidates) { $validated = Test-RealPython $cand if ($null -ne $validated) { return $validated } } # 5. Last resort: install managed CPython via uv if ($null -ne $UvInfo) { Write-Host "[1/5] No system Python 3.11+ found; installing managed Python 3.12 via uv..." $inst = Invoke-ProcessCapture -FilePath $UvInfo.Path -Arguments @("python", "install", "3.12") -TimeoutMs 180000 if ($inst.ExitCode -eq 0) { $find = Invoke-ProcessCapture -FilePath $UvInfo.Path -Arguments @("python", "find", "3.12") -TimeoutMs 15000 if ($find.ExitCode -eq 0) { $p = ($find.StdOut -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) } | Select-Object -Last 1) if ($p) { $validated = Test-RealPython $p.Trim() if ($null -ne $validated) { return $validated } } } } } throw "No working Python 3.11+ interpreter found (WindowsApps Store stubs and third-party venv shims are rejected). Install Python 3.12+ from python.org or install uv." } function Resolve-MicrosoftEdge { $edgeCandidates = New-Object System.Collections.Generic.List[string] if (${env:ProgramFiles(x86)}) { $edgeCandidates.Add((Join-Path ${env:ProgramFiles(x86)} "Microsoft\Edge\Application\msedge.exe")) } if ($env:ProgramFiles) { $edgeCandidates.Add((Join-Path $env:ProgramFiles "Microsoft\Edge\Application\msedge.exe")) } if ($env:LOCALAPPDATA) { $edgeCandidates.Add((Join-Path $env:LOCALAPPDATA "Microsoft\Edge\Application\msedge.exe")) } foreach ($edgePath in $edgeCandidates) { if (Test-Path -LiteralPath $edgePath -PathType Leaf) { $ver = "" try { $ver = (Get-Item -LiteralPath $edgePath).VersionInfo.ProductVersion } catch { $ver = "unknown" } return [PSCustomObject]@{ Path = $edgePath Version = $ver } } } throw "Microsoft Edge (msedge.exe) not found in Program Files (x86), Program Files, or LocalAppData." } $SmokeDir = Join-Path $InstallDir ".install_smoke" try { Write-Host "=== Advisor Assistant - Windows 11 Native Installer ===" Write-Host "Install directory : $InstallDir" Write-Host "API endpoint : $ApiBaseUrl" # Step 1: Resolve real Python + uv $sw = [System.Diagnostics.Stopwatch]::StartNew() $uvInfo = Resolve-WorkingUv $pyInfo = Resolve-WorkingPython -UvInfo $uvInfo $sw.Stop() $Timings["resolve_python"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) Write-Host ("[1/5] Python resolved : {0} (v{1})" -f $pyInfo.Path, $pyInfo.Version) if ($null -ne $uvInfo) { Write-Host (" uv resolved : {0} ({1})" -f $uvInfo.Path, $uvInfo.Version) } else { Write-Host " uv resolved : not found (will use python -m venv and pip)" } # Step 2: Export PYTHONUTF8=1 and write launchers $env:PYTHONUTF8 = "1" $env:PYTHONIOENCODING = "utf-8" $cmdLauncherPath = Join-Path $InstallDir "advisor.cmd" $ps1LauncherPath = Join-Path $InstallDir "advisor.ps1" $cmdLines = @( "@echo off", "setlocal", 'set "ROOT=%~dp0"', 'if "%ROOT:~-1%"=="\" if not "%ROOT:~-2,1%"==":" set "ROOT=%ROOT:~0,-1%"', 'set "PYTHONUTF8=1"', 'set "PYTHONIOENCODING=utf-8"', 'if defined PYTHONPATH goto :append_pypath', 'set "PYTHONPATH=%ROOT%"', 'goto :after_pypath', ':append_pypath', 'set "PYTHONPATH=%ROOT%;%PYTHONPATH%"', ':after_pypath', 'if not defined VAULT_ROOT set "VAULT_ROOT=%ROOT%"', 'if not defined ADVISOR_API_URL set "ADVISOR_API_URL=https://advisor-assistant-api.fly.dev"', 'if "%~1"=="" goto :cli', 'if "%~1"=="-c" goto :py', 'if "%~1"=="-m" goto :py', 'if "%~1"=="-V" goto :py', 'if "%~1"=="--version" goto :py', 'if /i "%~x1"==".py" if exist "%~1" if not exist "%~1\*" goto :py', ":cli", '"%~dp0.venv\Scripts\python.exe" -m Backend.Scripts.cli.advisor_cli %*', "exit /b %ERRORLEVEL%", ":py", '"%~dp0.venv\Scripts\python.exe" %*', "exit /b %ERRORLEVEL%" ) Write-Utf8NoBom -Path $cmdLauncherPath -Content ([string]::Join("`r`n", $cmdLines) + "`r`n") $ps1Lines = @( '#Requires -Version 5.1', '$ErrorActionPreference = "Stop"', '$root = $PSScriptRoot', '$env:PYTHONUTF8 = "1"', '$env:PYTHONIOENCODING = "utf-8"', 'if ([string]::IsNullOrWhiteSpace($env:PYTHONPATH)) {', ' $env:PYTHONPATH = $root', '} else {', ' $env:PYTHONPATH = $root + ";" + $env:PYTHONPATH', '}', 'if ([string]::IsNullOrWhiteSpace($env:VAULT_ROOT)) {', ' $env:VAULT_ROOT = $root', '}', 'if ([string]::IsNullOrWhiteSpace($env:ADVISOR_API_URL)) {', ' $env:ADVISOR_API_URL = "https://advisor-assistant-api.fly.dev"', '}', '$venvPy = Join-Path $root ".venv\Scripts\python.exe"', 'if (-not (Test-Path -LiteralPath $venvPy -PathType Leaf)) {', ' throw "Advisor Assistant environment missing at $venvPy. Run install.ps1 first."', '}', '$passThrough = $false', 'if ($args.Count -ge 1) {', ' $firstArg = [string]$args[0]', ' if ($firstArg -ceq "-c" -or $firstArg -ceq "-m" -or $firstArg -ceq "-V" -or $firstArg -ceq "--version") {', ' $passThrough = $true', ' } elseif ($firstArg -match ''(?i)\.py$'' -and (Test-Path -LiteralPath $firstArg -PathType Leaf)) {', ' $passThrough = $true', ' }', '}', 'if ($passThrough) {', ' & $venvPy @args', '} else {', ' & $venvPy -m Backend.Scripts.cli.advisor_cli @args', '}', 'exit $LASTEXITCODE' ) Write-Utf8NoBom -Path $ps1LauncherPath -Content ([string]::Join("`n", $ps1Lines) + "`n") $Receipt.launchers["cmd"] = $cmdLauncherPath $Receipt.launchers["ps1"] = $ps1LauncherPath Write-Host "[2/5] Launchers ready : advisor.cmd, advisor.ps1 (PYTHONUTF8=1 enforced)" # Step 3: Create .venv and install the Day-1 set (secrets lock, sample letters and their PNG previews) $thinDeps = @("cryptography", "python-docx", "pypdfium2", "Pillow") $venvDir = Join-Path $InstallDir ".venv" $venvPy = Join-Path $venvDir "Scripts\python.exe" $sw = [System.Diagnostics.Stopwatch]::StartNew() if ($null -ne $uvInfo) { $venvRes = Invoke-ProcessCapture -FilePath $uvInfo.Path -Arguments @("venv", "--clear", "--python", $pyInfo.Path, $venvDir) -TimeoutMs 120000 } else { $venvRes = Invoke-ProcessCapture -FilePath $pyInfo.Path -Arguments @("-m", "venv", "--clear", $venvDir) -TimeoutMs 120000 } if ($venvRes.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $venvPy -PathType Leaf)) { throw "Failed to create .venv (exit $($venvRes.ExitCode)): $($venvRes.StdErr) $($venvRes.StdOut)" } $sw.Stop() $Timings["create_venv"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) $sw = [System.Diagnostics.Stopwatch]::StartNew() if ($null -ne $uvInfo) { $pipArgs = @("pip", "install", "--python", $venvPy) if ($NoCache) { $pipArgs += "--no-cache" } $pipArgs += $thinDeps $depRes = Invoke-ProcessCapture -FilePath $uvInfo.Path -Arguments $pipArgs -TimeoutMs 180000 } else { $pipArgs = @("-m", "pip", "install", "--disable-pip-version-check") if ($NoCache) { $pipArgs += "--no-cache-dir" } $pipArgs += $thinDeps $depRes = Invoke-ProcessCapture -FilePath $venvPy -Arguments $pipArgs -TimeoutMs 180000 } if ($depRes.ExitCode -ne 0) { throw "Failed to install dependencies (exit $($depRes.ExitCode)): $($depRes.StdErr) $($depRes.StdOut)" } $sw.Stop() $Timings["install_deps"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) $Receipt.python["resolved_path"] = $pyInfo.Path $Receipt.python["version"] = $pyInfo.Version $Receipt.python["venv_python"] = $venvPy $Receipt.python["uv_path"] = if ($null -ne $uvInfo) { $uvInfo.Path } else { $null } $Receipt.python["utf8_mode"] = $true Write-Host ("[3/5] Environment : .venv created ({0}s), deps installed ({1}s)" -f $Timings["create_venv"], $Timings["install_deps"]) # Step 4: Detect Microsoft Edge $edgeInfo = Resolve-MicrosoftEdge $Receipt.edge["path"] = $edgeInfo.Path $Receipt.edge["version"] = $edgeInfo.Version Write-Host ("[4/5] Edge detected : {0} (v{1})" -f $edgeInfo.Path, $edgeInfo.Version) # Step 5: Fail-closed acceptance self-tests (5 gates) Write-Host "[5/5] Running fail-closed acceptance self-tests..." if (Test-Path -LiteralPath $SmokeDir) { Remove-Item -LiteralPath $SmokeDir -Recurse -Force } New-Item -ItemType Directory -Path $SmokeDir -Force | Out-Null $pyEnv = @{ "PYTHONUTF8" = "1" "PYTHONIOENCODING" = "utf-8" "PYTHONPATH" = $InstallDir } # Gate 1: Python UTF-8 + file_lock + pii.py + pii_gate.py $sw = [System.Diagnostics.Stopwatch]::StartNew() $gate1Script = Join-Path $SmokeDir "gate1_pii.py" $gate1Code = @' import ast import json import locale import os import sys from pathlib import Path assert sys.flags.utf8_mode == 1, f"expected utf8_mode=1, got {sys.flags.utf8_mode}" pref_enc = locale.getpreferredencoding(False).lower() assert pref_enc == "utf-8", f"expected utf-8 preferred encoding, got {pref_enc}" from Backend.Scripts.utilities import file_lock as fl from Backend.Scripts.compliance import pii, pii_seal as ps, pii_gate as pg smoke_dir = Path(sys.argv[1]) assert fl.open_nofollow_flags() == 0 probe_file = smoke_dir / "private_probe.json" probe_file.write_text('{"ok": true}\n', encoding="utf-8") assert fl.check_private_mode(probe_file) is True # Verify exclusive_lock blocks concurrent nonblocking lock on Windows lock_path = smoke_dir / "lock_test.lock" blocked = False with fl.exclusive_lock(lock_path): try: with fl.exclusive_lock(lock_path, nonblocking=True): pass except BlockingIOError: blocked = True assert blocked, "nonblocking lock did not detect held exclusive lock" # Verify pii.py scan + Quebec UTF-8 accent preservation quebec_text = "Client SIN 046 454 286 at 123 Rue Saint-Denis, Montr\u00e9al, Qu\u00e9bec" hits = pii.check(quebec_text, "export") assert any(h.cls == "sin" and h.action == "refuse" for h in hits), f"SIN not refused: {hits}" masked, _ = pii.mask(quebec_text, "export") assert "Montr\u00e9al" in masked and "Qu\u00e9bec" in masked, f"Quebec accents mangled: {masked}" # Verify pii_gate hash-chained egress ledger + lock round-trip with UTF-8 vault_dir = smoke_dir / "vault" entry = pg.append_entry(vault_dir, { "at": "2026-11-28T12:00:00-05:00", "mode": "live", "lane": "win-selftest", "provider": "local", "model": "selftest", "decision": "held", "reasons": ["selftest: Montr\u00e9al, Qu\u00e9bec UTF-8 check"], }) ok_log, notes = pg.verify_log(vault_dir) assert ok_log, f"pii_gate verify_log failed: {notes}" entries, problems = pg.read_log(vault_dir) assert not problems and len(entries) == 1 assert "Montr\u00e9al" in entries[0]["reasons"][0] # If book_worklist.py is present, verify zero unguarded fcntl / O_NOFOLLOW wl_path = Path(os.environ["PYTHONPATH"]) / "Backend" / "Scripts" / "onboarding" / "book_worklist.py" wl_checked = False if wl_path.is_file(): tree = ast.parse(wl_path.read_text(encoding="utf-8")) for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: assert alias.name != "fcntl", "book_worklist.py still imports fcntl" if isinstance(node, ast.Attribute) and node.attr == "O_NOFOLLOW": raise AssertionError("book_worklist.py still references os.O_NOFOLLOW") wl_checked = True print(json.dumps({ "utf8_mode": sys.flags.utf8_mode, "preferred_encoding": pref_enc, "win_lock_contention_detected": blocked, "pii_sin_refused": True, "quebec_utf8_preserved": True, "pii_gate_log_verified": ok_log, "book_worklist_ast_clean": wl_checked, })) '@ Write-Utf8NoBom -Path $gate1Script -Content $gate1Code $g1Res = Invoke-ProcessCapture -FilePath $venvPy -Arguments @($gate1Script, $SmokeDir) -ExtraEnv $pyEnv -TimeoutMs 60000 $sw.Stop() $Timings["selftest_pii_gate"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) if ($g1Res.ExitCode -ne 0) { throw "Gate 1 (pii + pii_gate + file_lock) FAILED: $($g1Res.StdErr) $($g1Res.StdOut)" } $g1Data = $g1Res.StdOut.Trim() | ConvertFrom-Json $Gates["python_utf8_pii_gate"] = [ordered]@{ passed = $true details = $g1Data } Write-Host (" Gate 1 PASS : Python UTF-8 + file_lock + pii + pii_gate ({0}s)" -f $Timings["selftest_pii_gate"]) # Gate 2: Ed25519 license_lease sign/verify + tamper detection $sw = [System.Diagnostics.Stopwatch]::StartNew() $gate2Script = Join-Path $SmokeDir "gate2_license.py" $gate2Code = @' import copy import json from Backend.Scripts.licensing import license_lease as ll priv, pub = ll.generate_keypair() lease = ll.issue_lease(priv, subscriber_id="advisor-win11-selftest", tier="pro") res = ll.verify_lease(lease, pub) assert res["valid"] is True and res["status"] == "active", f"valid lease failed: {res}" tampered = copy.deepcopy(lease) tampered["payload"]["tier"] = "regulator" bad = ll.verify_lease(tampered, pub) assert bad["valid"] is False, f"tampered lease was not rejected: {bad}" fp = ll.device_fingerprint() assert len(fp) == 64 and all(c in "0123456789abcdef" for c in fp), f"bad fingerprint: {fp}" print(json.dumps({ "lease_valid": True, "tamper_rejected": True, "fingerprint_len": len(fp), "signature_len": len(lease["signature"]), })) '@ Write-Utf8NoBom -Path $gate2Script -Content $gate2Code $g2Res = Invoke-ProcessCapture -FilePath $venvPy -Arguments @($gate2Script) -ExtraEnv $pyEnv -TimeoutMs 60000 $sw.Stop() $Timings["selftest_license"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) if ($g2Res.ExitCode -ne 0) { throw "Gate 2 (Ed25519 license_lease) FAILED: $($g2Res.StdErr) $($g2Res.StdOut)" } $g2Data = $g2Res.StdOut.Trim() | ConvertFrom-Json $Gates["license_ed25519"] = [ordered]@{ passed = $true details = $g2Data } Write-Host (" Gate 2 PASS : Ed25519 license_lease sign/verify + tamper ({0}s)" -f $Timings["selftest_license"]) # Gate 3: Advisor Assistant Zero-PII Cloud API health check $sw = [System.Diagnostics.Stopwatch]::StartNew() $gate3Script = Join-Path $SmokeDir "gate3_health.py" $gate3Code = @' import json import sys import time import urllib.error import urllib.parse import urllib.request url = sys.argv[1].rstrip("/") + "/v1/health" host = urllib.parse.urlparse(url).netloc or url t0 = time.perf_counter() req = urllib.request.Request(url, headers={"User-Agent": "AdvisorAssistant-WinInstaller/1.0"}) try: with urllib.request.urlopen(req, timeout=15) as resp: status = resp.status body = json.loads(resp.read().decode("utf-8")) except (urllib.error.URLError, TimeoutError, OSError) as exc: reason = getattr(exc, "reason", exc) print(f"Cannot reach {host} ({reason}). Check your internet connection, firewall, or proxy settings, then re-run install.ps1.", file=sys.stderr) sys.exit(1) elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 1) if status != 200: print(f"Expected HTTP 200 from {host}, got {status}.", file=sys.stderr) sys.exit(1) if body.get("ok") is not True or body.get("zero_pii_enforced") is not True: print(f"Unexpected API health payload from {host}: {body}", file=sys.stderr) sys.exit(1) print(json.dumps({ "url": url, "status_code": status, "latency_ms": elapsed_ms, "service": body.get("service"), "figures_year": body.get("figures_year"), "zero_pii_enforced": body.get("zero_pii_enforced"), })) '@ Write-Utf8NoBom -Path $gate3Script -Content $gate3Code $g3Res = Invoke-ProcessCapture -FilePath $venvPy -Arguments @($gate3Script, $ApiBaseUrl) -ExtraEnv $pyEnv -TimeoutMs 30000 $sw.Stop() $Timings["selftest_api_health"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) if ($g3Res.ExitCode -ne 0) { throw "Gate 3 (API health $ApiBaseUrl/v1/health) FAILED: $($g3Res.StdErr) $($g3Res.StdOut)" } $g3Data = $g3Res.StdOut.Trim() | ConvertFrom-Json $Gates["api_health"] = [ordered]@{ passed = $true details = $g3Data } Write-Host (" Gate 3 PASS : GET {0}/v1/health -> {1} ({2}ms)" -f $ApiBaseUrl, $g3Data.status_code, $g3Data.latency_ms) # Gate 4: Native Microsoft Edge headless HTML-to-PDF smoke render $sw = [System.Diagnostics.Stopwatch]::StartNew() $smokeHtml = Join-Path $SmokeDir "smoke_report.html" $smokePdf = Join-Path $SmokeDir "smoke_report.pdf" $edgeProfile = Join-Path $SmokeDir "edge_profile" New-Item -ItemType Directory -Path $edgeProfile -Force | Out-Null $htmlContent = @' Advisor Assistant PDF Smoke Test

Advisor Assistant - Windows 11 Native PDF Smoke Test

Zero-dependency HTML-to-PDF rendering via Microsoft Edge.

Bilingual UTF-8 check: Montréal, Québec - Planification financière.

'@ Write-Utf8NoBom -Path $smokeHtml -Content $htmlContent $htmlUri = ([System.Uri]::new($smokeHtml)).AbsoluteUri $edgeArgs = @( "--headless=new", "--disable-gpu", "--no-first-run", "--user-data-dir=$edgeProfile", "--no-pdf-header-footer", "--print-to-pdf=$smokePdf", $htmlUri ) $edgeRes = Invoke-ProcessCapture -FilePath $edgeInfo.Path -Arguments $edgeArgs -TimeoutMs 45000 $sw.Stop() $Timings["selftest_edge_pdf"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) if ($edgeRes.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $smokePdf -PathType Leaf)) { throw "Gate 4 (Edge headless PDF render) FAILED (exit $($edgeRes.ExitCode)): $($edgeRes.StdErr)" } $pdfBytes = [System.IO.File]::ReadAllBytes($smokePdf) $pdfHeader = [System.Text.Encoding]::ASCII.GetString($pdfBytes, 0, [Math]::Min(5, $pdfBytes.Length)) if ($pdfBytes.Length -lt 1000 -or $pdfHeader -ne "%PDF-") { throw "Gate 4 (Edge headless PDF render) produced invalid PDF (size=$($pdfBytes.Length), header=$pdfHeader)" } $Gates["edge_pdf_render"] = [ordered]@{ passed = $true details = [ordered]@{ pdf_bytes = $pdfBytes.Length pdf_header = $pdfHeader } } Write-Host (" Gate 4 PASS : Edge headless PDF render ({0} bytes, {1}s)" -f $pdfBytes.Length, $Timings["selftest_edge_pdf"]) # Gate 5: Verify advisor.cmd launcher exports PYTHONUTF8=1 cleanly (including install paths with spaces) $sw = [System.Diagnostics.Stopwatch]::StartNew() $cmdExe = if ($env:ComSpec) { $env:ComSpec } else { "cmd.exe" } $g5PyCode = "import locale, sys; assert sys.flags.utf8_mode == 1; print(locale.getpreferredencoding(False))" # cmd.exe /c strips the outermost quote pair when both executable and arguments are quoted; double-wrap so spaced paths work. $g5RawArgs = '/d /c ""' + $cmdLauncherPath + '" -c "' + $g5PyCode + '""' $g5Res = Invoke-ProcessCapture -FilePath $cmdExe -RawArguments $g5RawArgs -ExtraEnv @{ "PYTHONUTF8" = "" "PYTHONIOENCODING" = "" } -TimeoutMs 30000 $sw.Stop() $Timings["selftest_launcher"] = [Math]::Round($sw.Elapsed.TotalSeconds, 3) $g5Out = $g5Res.StdOut.Trim().ToLowerInvariant() if ($g5Res.ExitCode -ne 0 -or $g5Out -ne "utf-8") { throw "Gate 5 (advisor.cmd launcher UTF-8) FAILED (exit $($g5Res.ExitCode), out='$g5Out'): $($g5Res.StdErr)" } $g5HelpArgs = '/d /c ""' + $cmdLauncherPath + '" "--help""' $g5HelpRes = Invoke-ProcessCapture -FilePath $cmdExe -RawArguments $g5HelpArgs -ExtraEnv @{ "PYTHONUTF8" = "" "PYTHONIOENCODING" = "" } -TimeoutMs 30000 if ($g5HelpRes.ExitCode -ne 0 -or $g5HelpRes.StdOut -notmatch "onboard") { throw "Gate 5 (advisor.cmd CLI routing --help) FAILED (exit $($g5HelpRes.ExitCode)): $($g5HelpRes.StdErr) $($g5HelpRes.StdOut)" } $Gates["launcher_utf8"] = [ordered]@{ passed = $true details = [ordered]@{ launcher = $cmdLauncherPath preferred_encoding = $g5Out cli_help = $true } } Write-Host (" Gate 5 PASS : advisor.cmd enforces PYTHONUTF8=1 and routes CLI ({0}s)" -f $Timings["selftest_launcher"]) $TotalSw.Stop() $Timings["total"] = [Math]::Round($TotalSw.Elapsed.TotalSeconds, 3) $Receipt["status"] = "PASS" $receiptJson = $Receipt | ConvertTo-Json -Depth 8 Write-Utf8NoBom -Path $ReceiptPath -Content ($receiptJson + "`n") Write-Host "" Write-Host ("Advisor Assistant install PASS in {0}s. Receipt: {1}" -f $Timings["total"], $ReceiptPath) $hasApiToken = (-not [string]::IsNullOrWhiteSpace($env:ADVISOR_API_TOKEN)) -or (-not [string]::IsNullOrWhiteSpace($env:CV_API_TOKEN)) if (-not $hasApiToken) { # The one active secrets file (secret_config.resolve_secrets_path, inline: the new name first, the legacy one kept). $newSecrets = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".advisor_assistant_secrets.json" } else { "" } $legacySecrets = if ($env:USERPROFILE) { Join-Path $env:USERPROFILE ".compliancevault_secrets.json" } else { "" } $secretsPath = if ($env:ADVISOR_ASSISTANT_SECRETS_FILE) { $env:ADVISOR_ASSISTANT_SECRETS_FILE } elseif ($env:COMPLIANCEVAULT_SECRETS_FILE) { $env:COMPLIANCEVAULT_SECRETS_FILE } elseif ($newSecrets -and (Test-Path -LiteralPath $newSecrets)) { $newSecrets } elseif ($legacySecrets -and (Test-Path -LiteralPath $legacySecrets)) { $legacySecrets } else { $newSecrets } if ($secretsPath -and (Test-Path -LiteralPath $secretsPath -PathType Leaf)) { try { $secObj = Get-Content -LiteralPath $secretsPath -Raw -Encoding UTF8 | ConvertFrom-Json # Key names are matched case-insensitively (advisor activate writes CV_API_TOKEN). foreach ($prop in $secObj.PSObject.Properties) { if (@("advisor_api_token", "cv_api_token", "api_token") -contains $prop.Name.ToLowerInvariant() -and -not [string]::IsNullOrWhiteSpace([string]$prop.Value)) { $hasApiToken = $true } } } catch {} } } if ($env:USERPROFILE) { $dropBox = Join-Path $env:USERPROFILE "Documents\Advisor Assistant Drop Box" Write-Host "" if (Test-Path -LiteralPath $dropBox -PathType Container) { Write-Host ("Your Drop Box folder: {0}" -f $dropBox) } else { try { New-Item -ItemType Directory -Path $dropBox -Force -ErrorAction Stop | Out-Null Write-Host ("Created your Drop Box folder: {0}" -f $dropBox) } catch { Write-Host ("Could not create your Drop Box folder: {0} (create it yourself before dropping files)." -f $dropBox) } } Write-Host ' After setup, put client files in that folder and the assistant files them for you.' } Write-Host "" Write-Host "Next steps:" if (-not $hasApiToken) { Write-Host ' 1. Activate your API key: .\advisor.cmd activate' Write-Host ' (or set $env:CV_API_TOKEN or save {"api_token":"..."} in ~/.advisor_assistant_secrets.json)' Write-Host ' 2. Start guided setup: .\advisor.cmd onboard' } else { Write-Host ' 1. Start guided setup: .\advisor.cmd onboard' Write-Host ' 2. Check system health: .\advisor.cmd doctor' } exit 0 } catch { $TotalSw.Stop() $Timings["total"] = [Math]::Round($TotalSw.Elapsed.TotalSeconds, 3) $Receipt["status"] = "FAIL" $Receipt["error"] = $_.Exception.Message try { $receiptJson = $Receipt | ConvertTo-Json -Depth 8 Write-Utf8NoBom -Path $ReceiptPath -Content ($receiptJson + "`n") } catch {} Write-Error ("Advisor Assistant install FAILED: " + $_.Exception.Message) exit 1 } finally { if (Test-Path -LiteralPath $SmokeDir) { for ($attempt = 0; $attempt -lt 3; $attempt++) { try { Remove-Item -LiteralPath $SmokeDir -Recurse -Force -ErrorAction Stop break } catch { Start-Sleep -Milliseconds 250 } } } }