SWITCH CLEAN ENGINE CONTRACT - 0.10.1 / schema 1

Native Win32 UI and reusable engine; no HTTP UI or web API.
Use runtime/python.exe for CLI and runtime/pythonw.exe for explicit --gui.
Read-only CLI: -m switch_clean doctor; -m switch_clean scan --output inventory.json

Python callers use one Engine instance for preview and execution:
  import core
  engine = core.Engine()
  plan = engine.scan(workflow='cleanup')
  # Present plan.cleanup and obtain a reviewed selection.
  report = engine.execute(dict(plan_id=plan['plan_id'], action='cleanup',
                               ids=['user_temp'], confirm=True))

scan(workflow='cleanup') does not enumerate drivers. scan('prepare') performs the
conservative driver and dependency assessment without a filesystem cleanup scan.
scan() or scan('all') retains combined inventory compatibility. UI navigation
invalidates incompatible plans. Toolkit callers must handle the same distinction.

Cleanup rows contain id, title, group, detail, admin, recommended, eligible, hold,
bytes and optional files/paths. Unknown byte sizes are None. A recommended flag
never authorizes execution. Rows with eligible=False are rejected at the engine
boundary. File previews remain private; UI/API input cannot supply arbitrary
roots, commands, cleanup registry handlers or file lists. Built-in adapters are
allowlisted in cleanup_catalog.py. File bytes are logical bytes; sparse/compressed,
linked and cloud files are skipped. Windows-managed estimates are available to administrator scans; unmeasured totals
remain None. They are not independently measured deleted bytes.

Actions: cleanup, remove_devices, backup_drivers, delete_driver_packages,
prepare_reinstall, restore_drivers. IDs must come from the current plan. Missing
confirmation, expiry (30 minutes), invalid selections and insufficient privilege
raise exceptions. Plans are single-use once work starts. Serialize access to each
Engine instance; no automatic restart. Handle BOTH exceptions and report.success.
Per-item failures and partial outcomes remain in the report. Reports may contain
hardware identifiers and local paths; do not transmit them implicitly.

Driver review exposes eligible, review_status, review_reasons, reason,
vpn_or_virtual and inf_sha256. Only eligible OEM packages may be submitted for
removal. driver_review.recheck repeats full current association/dependency checks
before export and before deletion. Do not call low-level adapters to bypass these
checks. Verified export and persisted recovery manifests precede removal.
No force or uninstall flag. Candidate status is for explicit human review.

prepare_reinstall accepts checked OEM INF IDs and an existing absolute destination.
Empty IDs permit a full recovery archive with no focused packages. Every OEM
package is exported, hashed and verified; the selected subset is copied into a
separate focused archive. The inventory fingerprint must remain unchanged.
Inspect success, full_archive, focused_archive and per-package results. Backup
never implies removal. Dependencies, companion apps and Windows ranking are not
completely resolvable; surface uncertainty and preserve the full recovery archive.

reinstall.packages contains focused_recommended and focused_reason. Use these for
focused defaults instead of assuming direct present-device associations are a
complete backup. focused-selection.local.json applies only to its machine and
matching INF hashes. It affects backup defaults, never cleanup protection.
It is private local configuration and is excluded from distribution packages.

Restore: plan = engine.load_backup(absolute_folder_containing_manifest).
Present plan.restore_drivers, then execute restore_drivers with selected IDs.
The source is bound to the private plan. Every file is checked again and copied to
a private staging directory before PnPUtil /add-driver /install. Windows ranking
applies; successful import does not prove hardware operation. No forced downgrade.
Manifests use schema 1 and can be loaded from either full or focused archives.

Tests: runtime/python.exe -m unittest discover -s tests
Packaging: runtime/python.exe tests/package.py
Packaging excludes reports, caches and machine-local selection. Do not modify the
signed host/runtime binaries or use a bundler that replaces them with unsigned
executables. Review VM-VALIDATION.txt before claiming SAC compatibility.

0.8.0 TEMP EXCLUSIONS
Temporary cleanup automatically applies temp_policy at preview and execution.
Current scanner pointer targets preserve entire refresh folders. Deletion holds
the scanner refresh lock (with safe missing-file recovery during confirmed execution)
and re-reads pointers; uncertainty preserves
the cache. NVIDIA bridge, Razer and THX paths are excluded. Public cleanup rows
include protected_paths; callers must not bypass the production execute adapter.

0.8.0 CLEANUP EXTENSIONS
Engine.scan(workflow, progress=callback, cancel=threading.Event()) performs the
administrator Windows estimates and read-only component analysis automatically.
scan_scope reports administrator or standard_user. windows_volumes freezes the
fixed-drive list; changed drives stop a later Windows cleanup until reviewed again.
Rows include windows_estimate (status, bytes, per-volume results, timestamp) and
waitable. Busy servicing is waitable; pending restart and unknown state are held.
A zero estimate is distinct from an unavailable estimate (None).

Engine.execute(request, progress=callback, cancel=threading.Event()) waits for
natural servicing idle before relevant cleanup, bounded by the original plan's
30-minute deadline. Already-running Windows maintenance is never killed by Cancel.
Do not select components and windows_updates together; they overlap and are
rejected before mutation. The UI offers the latter when available.

Windows handlers execute in one isolated profile. windows_cleanup records the
command, exact handlers, verified_selection and profile_removed. Per-item
verification records before_bytes, remaining_bytes, estimate_reduction_bytes,
state=empty|remaining|unavailable and a plain-language explanation. success means
selected operations completed, not that all estimates reached zero. Also inspect
verification_warnings, cancelled, driver_records and reboot_may_be_required.
No automatic repeated cleanup is performed for a remaining estimate.

Read-only CLI: -m switch_clean scan --workflow cleanup --output inventory.json
Native startup: -m switch_clean --gui --scan-cleanup (normal UAC when required).
The standalone double-click host still opens the native interface without a console.

0.9.0 ADVICE CONTRACT (additive schema fields)
plan.recommendations contains state (recommended, nothing_worth_cleaning, or
review_needed), headline, detail, complete, suggested_ids, suggested_bytes,
small_routine_bytes, persistent_ids, unresolved_ids, threshold_bytes, history_status.
Rows expose recommendation_status and recommendation_reason. recommended now
comes from this assessment. It is advice, never execution authorization.

Engine.scan reads cleanup-history.local.json; it does not write cleanup history.
Engine.execute persists verified Windows Update remainder after a completed step.
A later failure/cancellation does not convert a completed Windows step into failure.
Unavailable measurements and failed steps do not replace known successful evidence.
report.recommendation_notice explains remaining estimates; recommendation_history_saved
reports persistence. Storage failures leave the actual cleanup result intact and
add a verification warning. API clients must show unknown and blocked states.

recommendation_context binds advice to hashed Windows installation/build and volume
identities. History expires after 30 days. The pure recommendations.apply(plan,
history) supports fixture testing and Toolkit reuse; load_history validates stored
evidence. Neither function can execute cleanup or alter driver protections.

0.9.1 SCANNER COORDINATION AUDIT
File cleanup results contain scanner_coordination, a list of per-root audit events.
status is created_and_locked, locked_existing, or blocked. Events include path,
created, and optional reason/error. Not-needed events are omitted. A blocked event
preserves scanner files and contributes per-file skips, while unrelated approved
temp files can still complete. Native results display recovery/preservation plainly.

Policy preview is read-only. execution_policy(root, running, files) is an internal
context manager used only by the confirmed file adapter; it validates selected
staging paths, current pointers and safe ancestors before opening/creating a lock.
It holds the same validated file handle and byte-range lock through deletion.
No caller should bypass the engine confirmation, expiry, snapshot or policy guards.

0.10.0 SAVED CLEANUP SNAPSHOTS
Engine.save_scan() explicitly saves the current cleanup display data under scans/.
Native UI scan completion calls it automatically; Engine.scan itself remains
read-only except for Windows analysis logs. Saving failures are disclosed without
invalidating an otherwise usable fresh plan. CLI --output exports can be reopened.

Engine.load_scan(path) first invalidates Engine.plan, including on load failure.
It returns validated display-only data with saved_scan.path and no plan_id, private
file candidates, driver/device inventory or recommendation context. It never sets
Engine.plan. Engine.execute therefore rejects requests until a fresh scan. Do not
attach loaded JSON to an executable plan. Schema/size/type validation is for robust
display, not proof that a saved file is authentic or its estimates are still valid.

Native runtime: pythonw.exe -m switch_clean --open-scan <absolute-json-path>
Cannot be combined with --scan-cleanup or a CLI command. The portable double-click
app offers More > Open saved scan... through the Windows file picker. Imported
selections are always empty; original recommendation labels are historical.
item_selectable/page_rows order available rows first, stably, without mutating
the plan, engine eligibility, recommendations, or selected IDs. Zero-byte cleanup
rows are not offered for selection. Driver-package review uses its existing guards.

0.10.1 ELEVATION DISPLAY
winapi.elevate retains the bundled pythonw.exe, runas verb, working directory and
--gui / optional --scan-cleanup arguments. ShellExecuteW now uses SW_SHOWNORMAL
(1), not SW_HIDE (0), so the child's first ShowWindow call displays the native UI.
Background measurement workers retain their existing console-free behavior.
