diff --git a/.github/workflows/migration-fixture-bootstrap.yml b/.github/workflows/migration-fixture-bootstrap.yml new file mode 100644 index 000000000..8e4e0394f --- /dev/null +++ b/.github/workflows/migration-fixture-bootstrap.yml @@ -0,0 +1,295 @@ +name: Migration Fixture Bootstrap + +# Manual upload path for a migration fixture archive captured OUTSIDE CI — the +# v0.9.3 baseline needs a GUI capture against a released binary, see +# tests/migration-fixtures/README.md. It turns local bytes into a GitHub +# Actions build artifact without them ever entering the git tree: git history +# is permanent, while an artifact can be deleted or left to expire. +# +# The archive reaches the runner in one of two ways. Everything else — artifact +# name, file name, size, sha256 — comes from the COMMITTED manifest entry named +# by `fixture_id`, so a dispatch can only publish bytes a reviewed manifest +# already describes. +# +# - `archive_b64`: the archive base64-encoded in a workflow_dispatch input. The +# inputs payload limit is 65,535 characters, so archives up to ~48 KB fit; +# the v0.9.3 baseline is 6 KB. +# - `release_tag`: the archive attached to a temporary DRAFT release under that +# tag, for anything larger (a current-era profile carries its SQLite WAL). +# Draft releases are listed only to tokens with push access, so the one job +# that fetches the archive holds `contents: write` and nothing else. It runs +# nothing but jq and the GitHub API, and hands the bytes to the verifying job +# as a same-run artifact. Delete the draft once the run has succeeded. +# +# This is not capture automation: it captures nothing, runs on no schedule and +# opens no PR. A human dispatches it and records the run id in the manifest. +# +# USAGE, small archive: +# gh workflow run migration-fixture-bootstrap.yml \ +# --repo dashpay/dash-evo-tool --ref \ +# -f fixture_id=v0.9.3-wallet-only \ +# -f archive_b64="$(base64 -w0 dash-evo-tool-v093-fixture.tar.zst)" +# +# USAGE, large archive (draft-release relay): +# gh release create fixture-relay- \ +# --repo dashpay/dash-evo-tool --draft --title "Fixture relay (temporary)" \ +# --notes "Temporary: deleted once migration-fixture-bootstrap.yml has uploaded it." +# gh workflow run migration-fixture-bootstrap.yml \ +# --repo dashpay/dash-evo-tool --ref \ +# -f fixture_id= -f release_tag=fixture-relay- +# # once the run has succeeded: +# gh release delete fixture-relay- --repo dashpay/dash-evo-tool \ +# --cleanup-tag --yes +# +# Either way, copy the values from the run's step summary into the entry's +# `artifact` block in tests/migration-fixtures/manifest.json. +# +# RETENTION HAZARD: artifacts expire, and 90 days is the ceiling for a public +# repository. Before the manifest's `expires_at`, re-dispatch with the same +# bytes and record the new `workflow_run_id`/`expires_at`. Once the artifact +# has expired, the migration matrix fails (download-fixtures.sh --strict) +# until that is done. +# +# REVOCATION: `gh run delete ` removes the artifact together with the +# run's inputs payload. + +on: + workflow_dispatch: + inputs: + fixture_id: + description: "Manifest entry id (tests/migration-fixtures/manifest.json .fixtures[].id)" + required: true + type: string + archive_b64: + description: "The fixture archive, base64-encoded without line wraps (base64 -w0). Leave empty when using release_tag." + required: false + type: string + release_tag: + description: "Tag of a temporary draft release carrying the archive, for archives over ~48 KB. Leave empty when using archive_b64." + required: false + type: string + # Registration only. GitHub dispatches a workflow only once it exists on the + # default branch or has already run; this trigger makes the pull request that + # adds or edits this file register it, so it can be dispatched with `--ref` + # against that PR's branch before it reaches the default branch. The jobs + # below never run for it. + pull_request: + paths: + - ".github/workflows/migration-fixture-bootstrap.yml" + +concurrency: + group: ${{ github.workflow }}-${{ inputs.fixture_id || github.ref }} + cancel-in-progress: false + +permissions: {} + +jobs: + fetch-draft-release: + name: Fetch archive from draft release + if: github.event_name == 'workflow_dispatch' && inputs.release_tag != '' + runs-on: ubuntu-latest + permissions: + # Draft releases are listed only to tokens with push access. This job + # holds nothing else, and it only reads the manifest and the API. + contents: write + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + # The write-scoped token must not linger in .git/config. + persist-credentials: false + + - name: Download the draft release asset + env: + GH_TOKEN: ${{ github.token }} + FIXTURE_ID: ${{ inputs.fixture_id }} + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + set -euo pipefail + manifest=tests/migration-fixtures/manifest.json + archive_filename="$(jq -r --arg id "$FIXTURE_ID" \ + '[.fixtures[] | select(.id == $id)] | if length == 1 then (.[0].artifact.archive_filename // empty) else empty end' "$manifest")" + if ! [[ "$archive_filename" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*\.tar\.(zst|gz)$ ]]; then + echo "::error::$manifest has no single entry '$FIXTURE_ID' with a well-formed artifact.archive_filename." + exit 1 + fi + # A draft has no published tag, so it is found by listing. Only a + # draft qualifies: a published release is not this relay. + releases="$(gh api --paginate "repos/$GITHUB_REPOSITORY/releases?per_page=100" | + jq -c --arg tag "$RELEASE_TAG" '.[] | select(.draft and .tag_name == $tag)')" + if [ "$(jq -s 'length' <<<"$releases")" != "1" ]; then + echo "::error::Expected exactly one draft release tagged '$RELEASE_TAG'." + exit 1 + fi + asset_id="$(jq -r --arg name "$archive_filename" \ + '[.assets[] | select(.name == $name)] | if length == 1 then .[0].id else empty end' <<<"$releases")" + if [ -z "$asset_id" ]; then + echo "::error::The draft release '$RELEASE_TAG' has no single asset named $archive_filename." + exit 1 + fi + dir="$RUNNER_TEMP/relay" + mkdir -p "$dir" + gh api -H 'Accept: application/octet-stream' \ + "repos/$GITHUB_REPOSITORY/releases/assets/$asset_id" >"$dir/$archive_filename" + echo "Fetched $archive_filename ($(stat -c %s "$dir/$archive_filename") bytes); the upload job verifies it against the manifest." + + - name: Hand the archive to the upload job + uses: actions/upload-artifact@v4 + with: + name: fixture-relay + path: ${{ runner.temp }}/relay + retention-days: 1 + if-no-files-found: error + compression-level: 0 + + upload: + name: Upload fixture artifact + needs: fetch-draft-release + # `always()` lets the archive_b64 path run although the relay job was + # skipped. The relay path needs that job to have succeeded; the input check + # below rejects a dispatch that gives neither or both inputs. + if: >- + always() && github.event_name == 'workflow_dispatch' && + needs.fetch-draft-release.result != 'failure' && + needs.fetch-draft-release.result != 'cancelled' + runs-on: ubuntu-latest + permissions: + contents: read + # Reads back the uploaded artifact's expiry for the step summary. + actions: read + env: + # Platform ceiling for a public repository; see RETENTION HAZARD above. + RETENTION_DAYS: 90 + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Resolve manifest entry + id: entry + env: + FIXTURE_ID: ${{ inputs.fixture_id }} + HAS_ARCHIVE_B64: ${{ inputs.archive_b64 != '' }} + HAS_RELEASE_TAG: ${{ inputs.release_tag != '' }} + run: | + set -euo pipefail + if [ "$HAS_ARCHIVE_B64" = "$HAS_RELEASE_TAG" ]; then + echo "::error::Give exactly one of archive_b64 (archives up to ~48 KB) or release_tag (a draft release carrying the archive)." + exit 1 + fi + manifest=tests/migration-fixtures/manifest.json + entry="$(jq -c --arg id "$FIXTURE_ID" \ + '[.fixtures[] | select(.id == $id)] | if length == 1 then .[0] else empty end' "$manifest")" + if [ -z "$entry" ]; then + echo "::error::$manifest has no single fixture entry with id '$FIXTURE_ID'." + exit 1 + fi + # Each value lands in $GITHUB_OUTPUT and later in a file path, so it + # is held to a strict shape rather than trusted as free text. + check() { + local key="$1" pattern="$2" value + value="$(jq -r --arg k "$key" '.artifact[$k] // empty' <<<"$entry")" + if ! [[ "$value" =~ $pattern ]]; then + echo "::error::Manifest entry '$FIXTURE_ID' has a missing or malformed artifact.$key." + exit 1 + fi + echo "$key=$value" >>"$GITHUB_OUTPUT" + } + check artifact_name '^[A-Za-z0-9][A-Za-z0-9._-]*$' + check archive_filename '^[A-Za-z0-9][A-Za-z0-9._-]*\.tar\.(zst|gz)$' + check sha256 '^[0-9a-f]{64}$' + check bytes '^[1-9][0-9]*$' + + - name: Download relayed archive + if: inputs.release_tag != '' + uses: actions/download-artifact@v4 + with: + name: fixture-relay + path: ${{ runner.temp }}/relay + + - name: Decode and verify archive + id: archive + env: + # Passed through the environment, never interpolated into the + # script, and never echoed: it is dispatch input. + ARCHIVE_B64: ${{ inputs.archive_b64 }} + RELEASE_TAG: ${{ inputs.release_tag }} + ARCHIVE_FILENAME: ${{ steps.entry.outputs.archive_filename }} + EXPECTED_SHA256: ${{ steps.entry.outputs.sha256 }} + EXPECTED_BYTES: ${{ steps.entry.outputs.bytes }} + run: | + set -euo pipefail + dir="$RUNNER_TEMP/fixture" + mkdir -p "$dir" + archive="$dir/$ARCHIVE_FILENAME" + if [ -n "$RELEASE_TAG" ]; then + # Fetched from the draft release by the job above. + relayed="$RUNNER_TEMP/relay/$ARCHIVE_FILENAME" + if [ ! -f "$relayed" ]; then + echo "::error::The relay job handed over no $ARCHIVE_FILENAME." + exit 1 + fi + mv "$relayed" "$archive" + elif ! printf '%s' "$ARCHIVE_B64" | base64 --decode >"$archive"; then + echo "::error::archive_b64 is not valid base64." + exit 1 + fi + actual_bytes="$(stat -c %s "$archive")" + actual_sha="$(sha256sum "$archive" | cut -d' ' -f1)" + if [ "$actual_bytes" != "$EXPECTED_BYTES" ] || [ "$actual_sha" != "$EXPECTED_SHA256" ]; then + echo "::error::The dispatched archive does not match the manifest entry (manifest: $EXPECTED_BYTES bytes, sha256 $EXPECTED_SHA256; received: $actual_bytes bytes, sha256 $actual_sha). Nothing was uploaded." + exit 1 + fi + # The checksum proves these are the bytes the manifest describes; this + # proves the manifest describes a readable archive. + tar -tf "$archive" >/dev/null + # Same sidecar format pack.sh writes, so the artifact matches what a + # CI capture would have uploaded. + printf '%s %s\n' "$actual_sha" "$ARCHIVE_FILENAME" >"$archive.sha256" + echo "dir=$dir" >>"$GITHUB_OUTPUT" + echo "Verified $ARCHIVE_FILENAME: $actual_bytes bytes, sha256 $actual_sha." + + - name: Upload fixture artifact + id: upload + uses: actions/upload-artifact@v4 + with: + name: ${{ steps.entry.outputs.artifact_name }} + path: ${{ steps.archive.outputs.dir }} + retention-days: ${{ env.RETENTION_DAYS }} + if-no-files-found: error + # A name clash inside one run is a mis-dispatch, not a refresh. + overwrite: false + # Already zstd/gzip-compressed; zipping it again gains nothing. + compression-level: 0 + + - name: Record manifest values + env: + GH_TOKEN: ${{ github.token }} + ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }} + FIXTURE_ID: ${{ inputs.fixture_id }} + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + set -euo pipefail + # The expiry actually granted: a repository-level retention setting + # can cap what RETENTION_DAYS asked for. + expires_at="$(gh api "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" --jq .expires_at)" + workflow="${GITHUB_WORKFLOW_REF%@*}" + workflow="${workflow##*/}" + { + echo "### Fixture \`$FIXTURE_ID\` uploaded" + echo + echo "Set these in the fixture's \`artifact\` block of \`tests/migration-fixtures/manifest.json\` and drop \`staging_note\`:" + echo + echo '```json' + jq -n --arg workflow "$workflow" --argjson run "$GITHUB_RUN_ID" \ + --argjson days "$RETENTION_DAYS" --arg expires "$expires_at" \ + '{workflow_name: $workflow, workflow_run_id: $run, retention_days: $days, expires_at: $expires}' + echo '```' + if [ -n "$RELEASE_TAG" ]; then + echo + echo "The archive came through the draft release \`$RELEASE_TAG\`. Delete it now:" + echo + echo '```sh' + echo "gh release delete '$RELEASE_TAG' --repo $GITHUB_REPOSITORY --cleanup-tag --yes" + echo '```' + fi + } >>"$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/migration-matrix.yml b/.github/workflows/migration-matrix.yml new file mode 100644 index 000000000..831037305 --- /dev/null +++ b/.github/workflows/migration-matrix.yml @@ -0,0 +1,307 @@ +name: Migration Matrix + +# Boots real, previously-captured DET data directories against the current build +# and asserts they migrate cleanly. Complements the unit-level migration tests: +# those use synthetic SQL fixtures, this one uses profiles captured from actual +# released binaries. +# +# Path filters cover every layer a data directory passes through on the way up: +# the platform pin (whose migrations run inside the wallet storage), DET's own +# schema ladder and unwire step, the wallet-backend seam, app boot, and the +# fixture tooling itself. +# +# MERGE ORDER: the `matrix` job runs `cargo test --test migration-matrix`, which +# needs both tests/migration-matrix/main.rs and its [[test]] entry in Cargo.toml. +# Landing this workflow before those exist makes the job fail on a missing test +# target, which looks like a migration regression and is not one. +on: + push: + branches: + - "v*-dev" + paths: &migration_paths + - "Cargo.toml" + - "Cargo.lock" + - "rust-toolchain.toml" + - ".cargo/config.toml" + - "build.rs" + - "src/bin/det_cli/**" + - "src/mcp/**" + - "src/logging.rs" + - "src/database/**" + - "src/backend_task/migration/**" + - "src/model/data_migration.rs" + - "src/wallet_backend/**" + - "src/context/**" + - "src/app/**" + # src/app.rs is listed alongside src/app/** deliberately: both exist, and + # app.rs owns the startup and task-polling loop the migration runs under. + - "src/app.rs" + - "src/app_dir.rs" + - "src/boot.rs" + - "tests/migration-matrix/**" + - "tests/migration-fixtures/**" + - "scripts/migration-fixtures/**" + - ".github/workflows/migration-matrix.yml" + pull_request: + types: [opened, synchronize, reopened, ready_for_review] + paths: *migration_paths + # Weekly, independent of any code change: the pin guard compares against a + # MOVING upstream branch and the coverage check against releases cut since the + # last run, so both can start failing with nothing in this repo having changed. + schedule: + - cron: "0 4 * * 1" # Every Monday at 04:00 UTC + # Draft PRs are suppressed by the `draft != true` guards below and otherwise + # have no way to run CI at all; a manual run covers them. + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: {} + +env: + CARGO_TERM_COLOR: always + +jobs: + pin-ancestry: + name: Platform pin guard + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Check fixture scripts + env: + TMPDIR: ${{ runner.temp }} + run: bash scripts/migration-fixtures/test-scripts.sh + + # Fetches only the upstream commit graph plus the pinned rev's migration + # sources — seconds, not a full platform clone. See the script header for + # why ancestry alone is not sufficient. + - name: Check platform pin ancestry and migration fingerprint + run: scripts/migration-fixtures/check-pin-ancestry.sh + + build: + name: Build det-cli + needs: pin-ancestry + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Cache Cargo registry + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-registry- + + # No `toolchain` input: the action installs what rust-toolchain.toml pins, + # so this job runs the same compiler the project builds with. + - name: Install Rust toolchain + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + # Matches tests.yml: Clippy owns the warnings gate, not this workflow. + rustflags: "" + # Cargo caching is handled by the actions/cache step above. + cache: false + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y build-essential pkg-config clang cmake libsqlite3-dev + + - name: Install protoc + run: | + curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v25.2/protoc-25.2-linux-x86_64.zip + sudo unzip -o protoc-25.2-linux-x86_64.zip -d /usr/local bin/protoc + sudo unzip -o protoc-25.2-linux-x86_64.zip -d /usr/local 'include/*' + rm -f protoc-25.2-linux-x86_64.zip + env: + PROTOC: /usr/local/bin/protoc + + # The harness drives a real compiled binary rather than booting in-process, + # because an in-process boot does not reproduce the production startup path + # that migrations actually run on. + - name: Build det-cli + run: cargo build --locked --bin det-cli --features cli + + - name: Locate det-cli + id: locate + run: | + set -euo pipefail + # Never assume ./target: CARGO_TARGET_DIR or build.target-dir in + # .cargo/config.toml can redirect it. Ask cargo. + target_dir="$(cargo metadata --format-version 1 --no-deps | jq -r .target_directory)" + echo "path=$target_dir/debug/det-cli" >>"$GITHUB_OUTPUT" + + - name: Upload det-cli + uses: actions/upload-artifact@v4 + with: + name: migration-matrix-det-cli + path: ${{ steps.locate.outputs.path }} + retention-days: 7 + if-no-files-found: error + + matrix: + name: Migration matrix + needs: build + if: github.event.pull_request.draft != true + runs-on: ubuntu-latest + permissions: + contents: read + # Fixture archives are Actions build artifacts, usually from an EARLIER + # run of this or the capture workflow, so the job needs to read runs and + # artifacts across the repository — not just its own. + actions: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Cache Cargo registry + uses: actions/cache@v4 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }} + restore-keys: | + ${{ runner.os }}-cargo-registry- + + - name: Install Rust toolchain + uses: actions-rust-lang/setup-rust-toolchain@v1 + with: + rustflags: "" + cache: false + + - name: Install system dependencies + run: | + sudo apt-get update + sudo apt-get install -y build-essential pkg-config clang cmake libsqlite3-dev zstd + + - name: Install protoc + run: | + curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v25.2/protoc-25.2-linux-x86_64.zip + sudo unzip -o protoc-25.2-linux-x86_64.zip -d /usr/local bin/protoc + sudo unzip -o protoc-25.2-linux-x86_64.zip -d /usr/local 'include/*' + rm -f protoc-25.2-linux-x86_64.zip + env: + PROTOC: /usr/local/bin/protoc + + - name: Download det-cli + uses: actions/download-artifact@v4 + with: + name: migration-matrix-det-cli + path: ${{ runner.temp }}/bin + + - name: Make det-cli executable + run: chmod +x "$RUNNER_TEMP/bin/det-cli" + + # THE AWKWARD PART, in full: the fixture this run needs was almost never + # produced by this run. The v0.9.3 baseline is captured once and consumed + # by every run afterwards; each later release's fixture comes from the + # capture run that followed that release. `actions/download-artifact` + # (used above for det-cli, which IS same-run) only sees the current run's + # artifacts unless given an explicit `run-id`, and the run id here is not + # known when this file is written — it lives in the committed manifest, + # which is the durable pointer from "fixture" to "artifact". + # + # download-fixtures.sh resolves each manifest entry through `gh`: by exact + # run id when the entry records one, otherwise by searching the newest + # successful run of the named workflow for the named artifact. See its + # header for why this is preferred over dawidd6/action-download-artifact, + # which is the drop-in third-party alternative for the fallback branch. + # + # --strict: an empty manifest, an entry that cannot be resolved (no run + # pointer, a deleted or EXPIRED artifact) or a checksum mismatch fails the + # job. A matrix run over an empty fixture set proves nothing, so it must + # never pass. Hand-captured fixtures (the v0.9.3 baseline) are uploaded by + # migration-fixture-bootstrap.yml with a finite retention; an expiry + # failure here means: re-dispatch that workflow with the same archive and + # record the new run id in tests/migration-fixtures/manifest.json. + - name: Download migration fixtures + id: fixtures + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + dest="$RUNNER_TEMP/migration-fixtures" + mkdir -p "$dest" + scripts/migration-fixtures/download-fixtures.sh --strict --dest "$dest" + count="$(find "$dest" -maxdepth 1 \( -name '*.tar.zst' -o -name '*.tar.gz' \) | wc -l)" + # --strict already fails on any unresolved entry. This covers what it + # cannot see: a run that reported success yet left no archive here. + if [ "$count" -eq 0 ]; then + echo "::error::No migration fixture archives were resolved into $dest. The matrix refuses to run over an empty fixture set." + exit 1 + fi + echo "Resolved $count fixture archive(s)." + echo "count=$count" >>"$GITHUB_OUTPUT" + echo "dir=$dest" >>"$GITHUB_OUTPUT" + + - name: Run migration matrix + env: + # Directory of fixture archives (.tar.zst / .tar.gz plus .sha256), + # exactly as pack.sh produced them. + MIGRATION_FIXTURES_DIR: ${{ steps.fixtures.outputs.dir }} + # download-fixtures.sh places only archives in the fixtures directory; + # the harness reads manifest.json from there unless pointed at it. + MIGRATION_FIXTURES_MANIFEST: ${{ github.workspace }}/tests/migration-fixtures/manifest.json + # The binary under test, from the build job. Required, not optional: + # det-cli needs the `cli` feature, which `--features testing` below + # does not enable, so Cargo builds no det-cli for the harness to find. + DET_CLI_BIN: ${{ runner.temp }}/bin/det-cli + MIGRATION_V093_WALLET_PASSWORD: ${{ secrets.MIGRATION_V093_WALLET_PASSWORD }} + MIGRATION_MATRIX_SKIP_PASSWORDS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository }} + run: | + if [ "$MIGRATION_MATRIX_SKIP_PASSWORDS" = "true" ]; then + echo "::notice::Fork PR: password scenarios are skipped because repository secrets are unavailable. Password-free migration scenarios still run." + echo "Migration coverage: password-free scenarios only (fork PR)." >>"$GITHUB_STEP_SUMMARY" + fi + cargo test --locked --test migration-matrix --features testing -- --nocapture + + # The weekly profile once more, opened directly through the + # platform_compatibility bridge instead of through a det-cli boot: the + # bridge's own contract (typed load, row counts, retained backup, + # idempotent re-open) on bytes a released build wrote. The test is + # env-gated, so tests.yml's plain `cargo test` only skips it; this step + # therefore checks that it really ran against the downloaded fixture. + - name: Run platform_compatibility real-data test + env: + MIGRATION_FIXTURES_DIR: ${{ steps.fixtures.outputs.dir }} + run: | + set -euo pipefail + log="$RUNNER_TEMP/platform-compatibility-real-data.log" + cargo test --locked --features testing --lib platform_compatibility_upgrades_the_real -- --nocapture 2>&1 | tee "$log" + if ! grep -q 'test result: ok. 1 passed' "$log" || grep -q '^skipped:' "$log"; then + echo "::error::The platform_compatibility real-data test did not run against the downloaded fixture." + exit 1 + fi + + coverage: + name: Fixture coverage + # Schedule only: a coverage gap is created by cutting a release, never by + # editing code, so running this per-PR would fail pull requests for + # something no contributor did or can fix. + if: github.event_name == 'schedule' + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Check fixture coverage against published releases + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: scripts/migration-fixtures/check-coverage.sh diff --git a/.github/workflows/weekly-build.yml b/.github/workflows/weekly-build.yml index 16c42b829..17cefb2e9 100644 --- a/.github/workflows/weekly-build.yml +++ b/.github/workflows/weekly-build.yml @@ -75,7 +75,7 @@ jobs: # as falsely green. A workflow that has never run is treated as # absent, not red. red=false - for wf in tests.yml clippy.yml; do + for wf in tests.yml clippy.yml migration-matrix.yml; do concl=$(gh run list --workflow "$wf" --branch "$REF_NAME" --status completed \ --limit 1 --json conclusion --jq '.[0].conclusion // ""') case "$concl" in diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a9e232bd..2896f1160 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Security +- The CLI keeps MCP requests at the selected endpoint without following HTTP + redirects or using system/environment proxies. Migration fixture packaging rejects configured credentials, and + CI requires verified archive checksums and a runtime fixture password. + - **Dependency advisory GHSA-4w2j-m93h-cj5j cleared**: the `quinn-proto` entry in the lock file moves from 0.11.14 to 0.11.15, which fixes a remote memory-exhaustion issue in out-of-order stream reassembly. The crate is an @@ -25,6 +29,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Added +- Migration tests also replay public user/DPNS and Evonode identities serialized + by v0.9.3, checking their metadata and every public key after repeated startup. + +- Historical-profile migration tests cover v0.9.3 and the September 8 weekly + release, including protected wallets and repeat startup. CLI tools expose + saved identity bindings, inspect storage without starting an upgrade, and + complete protected storage updates using password files or standard input. + - **Keys saved on this device but not on the identity's key lists are now listed**: a key can be saved here while appearing on none of the identity's key lists — for example when adding it to the network did not finish. The @@ -101,6 +113,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ### Fixed +- CLI builds no longer warn about an unused passphrase-limit import. + +- Migration tests compile with the current rand dependency. + +- Migration CI runs for PR #983 through the regular pull-request workflow. + +- CLI network switches persist across restarts, including headless fixture capture. + Migration checks reject undeclared legacy wallets, changed captured completion + markers, and legacy row changes committed only to the SQLite WAL. + +- Storage preparation retries incomplete app-data imports when unreadable + identities are also present, and concurrent callers receive the migration error. + - Cancelling a network switch takes priority over simultaneous startup and reports chain sync as stopped after shutting down the new backend. diff --git a/Cargo.toml b/Cargo.toml index 1c65fcb98..bd20c9353 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,8 +65,8 @@ tokio = { version = "1.46.1", features = ["full"] } # (non-`*_untrusted`) paths DET uses — native, `bincode::serde` and the derive macros — # its wire format is identical to bincode 2.0.1, per source-level analysis of hash-identical # function bodies and derive-codegen substitution (docs/ai-design/2026-09-14-platform-4.2-dev-bump/); -# no executable fixture pins it. This switch therefore needs no read-old/write-new -# migration. Any other encoder change still does: +# Historical-profile migration tests verify the old encodings remain readable. +# Any encoder change that breaks that compatibility needs a read-old/write-new migration: # this crate encodes the on-disk wallet-secret envelopes and QualifiedIdentity blobs. bincode = { package = "grovedb-bincode", version = "=2.1.0", features = ["serde"] } hex = { version = "0.4.3" } @@ -157,6 +157,11 @@ name = "backend-e2e" path = "tests/backend-e2e/main.rs" required-features = ["testing"] +[[test]] +name = "migration-matrix" +path = "tests/migration-matrix/main.rs" +required-features = ["testing"] + [[test]] name = "mcp_http_auth" path = "tests/mcp_http_auth.rs" diff --git a/docs/CLI.md b/docs/CLI.md index 5e53d7e31..7c55f6571 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -44,6 +44,8 @@ Saved wallets are hydrated from the shared data directory on demand, so one-shot Set `MCP_API_KEY` (in `.env` or shell) to connect to a running Dash Evo Tool instance instead. This shares the app's live state — wallets, network, database. +HTTP connections bypass system and environment proxies, keeping loopback calls on this machine. + The GUI address defaults to `http://127.0.0.1:9527/mcp`. Override with `--addr`: ```bash @@ -65,11 +67,49 @@ return `SecretPromptUnavailable` when a protected wallet needs to authorize a shielded operation. There is currently no environment-variable or CLI-passphrase workaround, so unattended shielded operations from a protected wallet are not supported. Use an unprotected wallet for that automation. +The storage update is the one exception; see the next section. This limitation does not apply in the same way when `det-cli` connects to MCP embedded in a running GUI. The embedded server can use the GUI's existing interactive prompt and authorized secret session. +## Finishing the storage update of password-protected wallets + +After an upgrade from an older version, an installation with password-protected +wallets stops every wallet command with *"Open the Dash Evo Tool desktop app +once to finish the storage update, then try again."* To finish the update +without the desktop app, supply the wallet password to `app-storage-update`: + +```bash +# From a file only you can read (refused if the group or others have any access) +chmod 600 ~/det-wallet-password +det-cli app-storage-update --password-file ~/det-wallet-password + +# From a pipe, e.g. a password manager (refused when stdin is a terminal) +pass show dash/det-wallets | det-cli app-storage-update --password-stdin +``` + +- The password is tried on every protected wallet, so they must all share it. + If it does not open one of them, the command fails, no wallet is skipped, and + you can run it again with the right password. Wallets with different + passwords need the desktop app. +- The input must be exactly one line. One trailing line ending is removed; + every other character, spaces included, is part of the password. +- `--password-file` refuses a file with any group or other permission (like SSH + does for private keys), a directory, and — on platforms other than Linux and + macOS — every file, because the permissions cannot be checked there. Use + `--password-stdin` instead. +- A password given as `password=...` is refused: command-line arguments are + visible to other users and saved in shell history. There is no environment + variable for it either. +- The command is refused while the desktop app is running (`--addr` / HTTP + mode against the GUI): the app asks for the password in its own window. +- In HTTP mode, a password is sent only to this computer (`127.0.0.1`, `::1` + or `localhost`) or to an `https` address. Any other `--addr` or `MCP_LISTEN` + is refused before the password is read, `0.0.0.0` included. Use + `--addr http://127.0.0.1:/mcp` instead. +- Once the update has finished, other commands need no password. + ## Usage Commands use hyphens (`core-wallets-list`, not `core_wallets_list`). Parameters are passed as `key=value` pairs: @@ -130,9 +170,18 @@ det-cli core-wallets-list # Generate a receive address det-cli core-address-create wallet-id=savings +# List locally saved identities with their DPNS names (no identity refresh) +det-cli identity-list + # Show active network and available networks det-cli network-info +# Report schema versions, migration state and upgrade markers on disk +det-cli app-storage-status + +# Finish the storage update of password-protected wallets without the desktop app +det-cli app-storage-update --password-file ~/det-wallet-password + # Check wallet balance det-cli core-balances-get wallet-id=savings diff --git a/docs/MCP.md b/docs/MCP.md index 3bb9a0446..0d58e47ae 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -67,11 +67,45 @@ they have no authorized GUI session. These transports return shielded operation. There is currently no environment-variable or CLI-passphrase workaround, so unattended shielded operations from a protected wallet are not supported. Use an unprotected wallet for that automation. +The storage update is the one operation that accepts a password +non-interactively; see the next section. MCP embedded in a running GUI is not affected in the same way: it can use the GUI's existing interactive prompt and authorized secret session. This caveat applies only to standalone and headless transports. +## Protected wallets and the storage update + +When an older installation holds password-protected wallets, standalone and +headless transports stop the storage update with `StorageUpdateNeedsDesktop` +(code `-32004`): there is no window to ask for the password. Every wallet tool +returns that error until the update finishes. + +`app_storage_update` finishes the update without the desktop app: + +- The `password` is tried on every wallet still locked after the copy, through + the same verification the desktop prompt uses. All protected wallets must + share it. +- When it opens every wallet, each one is registered, keeps its password + protection, and the update completes. Later tool calls need no password. +- When it does not open a wallet, the call fails with + `StorageUpdatePasswordRejected` (code `-32004`). No wallet is skipped and + the update stays unfinished, so it can be retried with the right password. +- An installation whose wallets have different passwords must finish the update + in the desktop app. +- It is refused with code `-32006` while the desktop app is running (MCP + embedded in the GUI): the app asks for the password in its own window. +- It is a no-op once the update has finished. An empty password is refused with + code `-32602`. + +The password is typed as `SecretString`: it deserializes straight into guarded, +zeroizing memory, its `Debug` is redacted, the schema carries no default or +example, and it is never stored or echoed in results or errors. Over the HTTP +transport it travels in the request body, so send it only to a loopback or +`https` endpoint; det-cli refuses any other address. From det-cli, supply it +with `--password-stdin` or `--password-file` (see `docs/CLI.md`), never as +`password=...`. + ## Environment variables | Variable | Default | Description | @@ -95,6 +129,7 @@ Set these in the app's `.env` file (see `.env.example`) or as environment variab | `platform_addresses_list` | `wallet_id`, `network`? | `det-cli platform-addresses-list` | Fetch platform address balances (credits and nonces) | | `core_funds_send` | `wallet_id`, `address`, `amount_duffs`, `network` | `det-cli core-funds-send` | Send DASH from a wallet to an address (amount in duffs) | | `platform_withdrawals_get` | `status`?, `limit`?, `start_after`?, `network`? | `det-cli platform-withdrawals-get` | Query Platform withdrawal documents (`"queued"` or `"completed"`); returns structured entries with a `next_cursor` for pagination | +| `identity_list` | `network`? | `det-cli identity-list` | List identities saved for the active network (id, alias, type, status, balance, DPNS names, wallet binding). Prepares local storage as needed, then reads saved identities without refreshing them from Platform | | `identity_credits_topup` | `wallet_id`, `identity_id`, `amount_duffs`, `network` | `det-cli identity-credits-topup` | Top up an identity with DASH from wallet (via asset lock) | | `identity_credits_topup_from_platform` | `wallet_id`, `identity_id`, `amount_credits`, `network` | `det-cli identity-credits-topup-from-platform` | Top up an identity from Platform address balances | | `identity_credits_transfer` | `wallet_id`, `from_identity_id`, `to_identity_id`, `amount_credits`, `network` | `det-cli identity-credits-transfer` | Transfer credits between identities | @@ -112,14 +147,22 @@ Set these in the app's `.env` file (see `.env.example`) or as environment variab | `shielded_balance_get` | `wallet_id`, `network`? | `det-cli shielded-balance-get` | Read the shielded balance from the last synced snapshot (credits + duffs); no sync | | `shielded_address_get` | `wallet_id`, `network`? | `det-cli shielded-address-get` | Return the wallet's default shielded (Orchard) receive address (bech32m) | | `tool_describe` | `name` | `det-cli tool-describe` | Return the full MCP tool definition for a given tool name | +| `app_storage_status` | `network`? | `det-cli app-storage-status` | Report local storage state: `data.db` schema version vs the version this build expects, upstream wallet-storage schema lineage, live migration state, and each network's upgrade completion markers. Observes without starting or advancing an upgrade | +| `app_storage_update` | `password`, `network`? | `det-cli app-storage-update --password-file ` | Finish the storage update of an upgraded installation whose wallets were password-protected, without the desktop app. One password for every protected wallet; a wallet it does not open fails the update and nothing is skipped. Refused while the desktop app is running. See [Protected wallets and the storage update](#protected-wallets-and-the-storage-update) | Parameters marked `?` are optional. The `det-cli` column shows the equivalent CLI command (underscores become hyphens). +`app_storage_status` opens existing databases read-only when used standalone. It +does not create a profile, open the secret vault, or apply storage migrations. +Missing databases or migration history are reported as `null`; unreadable or +corrupt storage returns an error. `identity_list` reports the persisted owning +wallet only, or an empty wallet list for an identity with no saved wallet link. + ### SPV requirements Wallet-facing tools that need chain or proof state wait for SPV to fully sync before executing. This includes both core-chain tools (`core_address_create`, `core_balances_get`, `core_funds_send`) and proof-verifying platform tools (`platform_addresses_list`, `identity_credits_topup`, `shielded_shield_from_core`). These Platform operations need SPV because the SDK verifies DAPI proofs against quorum and masternode list data from the synced chain. When another DET instance is already running, SPV falls back to a temporary directory and must sync from scratch. -Tools that make no network calls skip the SPV gate: the metadata tools (`core_wallets_list`, `network_info`, `tool_describe`), the local wallet import (`core_wallet_import`), and the shielded snapshot read `shielded_balance_get` (a pure in-memory read of the last synced balance). Wallet-reading tools hydrate saved wallets from local storage without starting SPV. `shielded_address_get` also skips the SPV gate and wires the wallet backend automatically, but `shielded_init` is still required before it can return an address for a wallet whose shielded keys have not been bound. `shielded_init` and `shielded_sync` still wait for SPV and drive a coordinator sync. +Tools that make no network calls skip the SPV gate: the metadata tools (`core_wallets_list`, `identity_list`, `network_info`, `tool_describe`, `app_storage_status`), the storage update (`app_storage_update`), the local wallet import (`core_wallet_import`), and the shielded snapshot read `shielded_balance_get` (a pure in-memory read of the last synced balance). Wallet-reading tools hydrate saved wallets from local storage without starting SPV. `shielded_address_get` also skips the SPV gate and wires the wallet backend automatically, but `shielded_init` is still required before it can return an address for a wallet whose shielded keys have not been bound. `shielded_init` and `shielded_sync` still wait for SPV and drive a coordinator sync. `masternode_credits_withdraw` waits for SPV before dispatching: a withdrawal does proof-verified Platform reads, so it gates like every other proof-verifying tool. (`identity_credits_withdraw` historically skipped this gate; the masternode tool deliberately adds it.) @@ -165,7 +208,7 @@ Tools accept a `network` parameter (e.g. `"mainnet"`, `"testnet"`, `"devnet"`, ` For **destructive tools** (those that spend funds or modify state — the fund-moving identity tools `identity_credits_topup`, `identity_credits_topup_from_platform`, `identity_credits_transfer`, `identity_credits_withdraw`, `identity_credits_to_address`, `masternode_credits_withdraw`, plus `core_funds_send`, `core_wallet_import`, and the fund-moving shielded tools `shielded_shield_from_core`, `shielded_shield_from_platform`, `shielded_transfer`, `shielded_unshield`, `shielded_withdraw`), `network` is **required**. The tool will reject the request if `network` is omitted or does not match the active network. This is a safety measure to prevent accidentally spending funds on the wrong network. Note: `masternode_identity_load` is non-destructive (it does not move funds) but also requires `network`, because the private keys it binds are chain-scoped. -For **read-only tools** (e.g. `core_wallets_list`, `core_balances_get`) and the shielded control/read tools (`shielded_init`, `shielded_sync`, `shielded_balance_get`, `shielded_address_get`), `network` is optional. When omitted, the tool operates on whatever network is currently active. +For **read-only tools** (e.g. `core_wallets_list`, `identity_list`, `core_balances_get`, `app_storage_status`) and the shielded control/read tools (`shielded_init`, `shielded_sync`, `shielded_balance_get`, `shielded_address_get`), `network` is optional. When omitted, the tool operates on whatever network is currently active. The `network_info` and `tool_describe` tools do not perform this check. @@ -266,3 +309,4 @@ The HTTP MCP server uses bearer token authentication via the `MCP_API_KEY` envir - The HTTP server is disabled when `MCP_API_KEY` is empty or unset. - Stdio mode has no authentication — the caller controls which process connects. - Headless mode requires `MCP_API_KEY`; it will refuse to start without it. +- rmcp logs raw requests (tool arguments, secrets included) at `debug` and `trace`. Every log subscriber DET installs caps the `rmcp` target at `info`, whatever `RUST_LOG` says, so those lines are never written. diff --git a/docs/ai-design/2026-06-02-jit-secret-access/design.md b/docs/ai-design/2026-06-02-jit-secret-access/design.md index a4e9497fb..426038e54 100644 --- a/docs/ai-design/2026-06-02-jit-secret-access/design.md +++ b/docs/ai-design/2026-06-02-jit-secret-access/design.md @@ -774,6 +774,9 @@ Smythe review: T1, T2, T3, T4, T5, T6, T7, T8, T9 (all touch secret handling). must fail with a typed "secret required, no interactive prompt available" error rather than hang. Recommend: a `NullSecretPrompt` that immediately cancels, surfacing `SecretPromptCancelled` (or a dedicated `SecretPromptUnavailable`) to the MCP error envelope. **User confirm** the headless UX. + *2026-09-11:* the storage update gained an explicit, non-interactive password path + (`app_storage_update`, det-cli `--password-stdin` / `--password-file`). Signing operations keep + this ruling. See `docs/ai-design/2026-07-14-migration-password-prompt/design.md`. 6. **Q-RETRYCAP — Wrong-passphrase soft cap?** Default: none (local AES-GCM, no remote attacker). Smythe may want a soft cap. **Security decision.** 7. **Q-MIDSTREAM — Any operation that must prompt mid-stream after partial broadcast?** None today diff --git a/docs/ai-design/2026-07-14-migration-password-prompt/design.md b/docs/ai-design/2026-07-14-migration-password-prompt/design.md index afa026c75..237574549 100644 --- a/docs/ai-design/2026-07-14-migration-password-prompt/design.md +++ b/docs/ai-design/2026-07-14-migration-password-prompt/design.md @@ -29,3 +29,66 @@ The current vault may contain both the copied recovery envelope and its current ## Registration concurrency Upstream wallet registration is single-flight per wallet seed hash. Concurrent callers share a keyed one-shot outcome cell, so one leader reaches upstream and every follower receives the same success or typed error. Completed flights are removed so a later, non-concurrent user retry can try again. Different wallets can register concurrently. + +## Decision 2026-09-11: added a safe non-interactive path + +**Decided by:** the project owner (Lukasz Klimek), on 2026-09-11. This deliberately reverses the headless restriction above, for the storage update only. + +### Why + +Under the rule above, every standalone upgrade of an installation holding a password-protected wallet ends at `StorageUpdateNeedsDesktop`. An operator who runs DET only headless — a server, CI, the migration matrix — had no way to finish that upgrade at all. The rule is a capability decision: never wait for a prompt nobody can render. Nothing on record weighed an explicit, non-interactive password channel against it. Q-HEADLESS in `docs/ai-design/2026-06-02-jit-secret-access/design.md` asked only how a headless caller should *fail*, and the "no environment variable or flag" wording was added later without a recorded rationale. + +### What changed + +- **MCP tool `app_storage_update`.** It takes one secret parameter, `password: SecretString`, plus the usual optional `network`. The password deserializes straight into guarded, zeroizing memory. Its `Debug` is redacted, and its schema is a plain string with no default or example. It is borrowed down the call chain (`prepare_storage_with_wallet_password` → `run_gated` → `register_migrated_wallets`) for the one call and is never kept in shared state. +- **Drain.** Before the interactive-capability check, a supplied password is tried on every wallet that is still locked. It goes through `AppContext::handle_wallet_unlocked` with `WalletUnlockRetention::UntilStorageUpdateComplete`, the same boundary the desktop prompt submits to. + - When the password is right, the wallet is registered and keeps its protection: the legacy envelope is re-sealed as Tier-2 under the same password. Its seed is forgotten when the update ends. + - When the password doesn't open a wallet, the update fails with `MigrationError::WalletPasswordRejected`, surfaced as `TaskError::StorageUpdatePasswordRejected`. Nothing is skipped, and the completion sentinel is withheld. +- **Without a password, nothing changes.** The update still fails at once with `InteractivePromptUnavailable` → `StorageUpdateNeedsDesktop`. +- **det-cli `--password-stdin` / `--password-file `.** These are client-side conveniences only. det-cli reads the password and passes it as the tool's `password` parameter, and the tool never learns where it came from, so the path works the same in-process and over HTTP. +- **Desktop sessions refuse the tool** (`McpToolError::DesktopOwnsPasswordPrompt`). See below. + +### Why stdin or a file, and never an environment variable or an argument + +| Channel | Exposure | Decision | +|---|---|---| +| Argument (`password=...`) | Every local user can see it through `ps` or `/proc//cmdline`, and the shell saves it in history. | Refused by det-cli. | +| Environment variable | Same-user processes can read it through `/proc//environ`. Every child process inherits it, and crash reporters, `env` dumps and CI logs capture it. It lives as long as the process does. | Not offered. | +| stdin | The reading process consumes it once. It never appears in the process table or in history. | Accepted, except from a terminal, where it would echo. | +| File | Owner-only files only: refused when any group or other permission bit is set (`mode & 0o077`, the OpenSSH private-key rule). The mode is checked on the opened descriptor, so the file can't be swapped between the check and the read. | Accepted on Unix. Refused elsewhere until an ACL check exists. | + +Both accepted sources must hold exactly one line. A single trailing line ending is stripped. Empty, multi-line, over-long (`MAX_PASSPHRASE_LEN`) or non-UTF-8 input is refused. The input is read into one pre-allocated zeroizing buffer, so no reallocation leaves an unwiped copy. + +### Why this does not weaken the fail-fast rule + +The rule exists so that a headless caller never waits for a person. This path never waits either. The password is supplied before the run starts; a missing one fails at once with the same error as before, and a wrong one fails at once with its own typed error. `NullSecretPrompt` stays non-interactive, and no prompt is added. Signing operations (`SecretPromptUnavailable`) keep the Q-HEADLESS ruling. + +### One password, no inferred skip + +One password is tried on every locked wallet, so all protected wallets must share it. A wallet it does not open fails the whole update rather than being skipped. Skipping is the user's decision in the desktop prompt, and a mistyped password must not make it for them. Wallets opened before the rejection stay registered and protected. The sentinel is withheld, so a re-run revisits them. The limitation: each headless process starts with every protected wallet locked again, so an installation whose wallets have different passwords must finish its update in the desktop app. + +### Desktop sessions refuse + +In a desktop session the storage update collects passwords in its own window, and it may be parked on that prompt while holding the preparation gate. The tool therefore refuses instead of opening a second, remote channel into that session, or blocking on the gate until someone answers the window. + +### Logging + +rmcp logs every inbound request, raw tool arguments included, at DEBUG, and every streamable-HTTP response at TRACE. `logging::sensitive_target_cap()` layers a separate global filter over `RUST_LOG` in every subscriber DET installs. It pins the `rmcp` target at INFO, and because it is ANDed with `RUST_LOG`, no directive can lift it. The same fix closes the equivalent, pre-existing exposure of `core_wallet_import`'s recovery phrase and the masternode keys. + +### Residuals + +- The JSON-RPC request that carries the password is an ordinary buffer in the transport, which `SecretString` cannot wipe. That buffer is the in-process pipe for standalone det-cli, or the bearer-authenticated HTTP body. Every secret tool parameter shares this residual. det-cli refuses to send a password over HTTP unless the address is loopback (`127.0.0.0/8`, `::1`, `localhost`) or `https`, and its HTTP client does not follow redirects. Other MCP clients must hold themselves to the same rule. +- det-cli reads `--password-stdin` through a duplicated, unbuffered descriptor rather than `std::io::stdin()`, whose process-wide 8 KiB buffer is never wiped. The zeroizing read buffer is the only user-space copy until the transport one above. +- `--password-file` is unavailable on non-Unix platforms until the file's ACL can be checked (TODO in `src/bin/det_cli/password.rs`). + +### Known, accepted limitations + +Two limitations need architectural work beyond this change. + +- **The desktop check covers only the current process.** `has_interactive_secret_prompt()` recognizes a desktop app embedded in the same process, which is how MCP-over-HTTP reaches a running GUI. A standalone det-cli or `det-cli headless` that shares the data directory with a desktop app in another process is not refused. Both processes can then drive the storage update at the same time. The update's idempotent, sentinel-gated drain bounds the damage, but a proper fix needs a cross-process lock on the data directory. +- **Password attempts are not throttled.** Every `app_storage_update` call costs one Argon2id derivation per locked wallet and nothing more. A caller can therefore guess repeatedly, limited only by Argon2id's cost. Reaching the tool already requires the stdio pipe or the HTTP bearer token, so the attacker is local or trusted. Attempt throttling with backoff is the fix. + +### Verification + +- Unit tests cover the drain (right password, shared password, rejection), the tool (desktop refusal, empty password, redacted `Debug`, plain schema), and det-cli (flags, permissions, the one-line rule, no password in any error). +- The migration matrix boots the real v0.9.3 archive twice. The unchanged no-password scenario must stop at `StorageUpdateNeedsDesktop`. The `password_runs` scenario runs `app-storage-update --password-file` and must migrate both wallets. It logs DET, det-cli and rmcp at `trace`, and fails if any command's output contains the password. diff --git a/docs/ai-design/2026-09-10-migration-matrix/design.md b/docs/ai-design/2026-09-10-migration-matrix/design.md new file mode 100644 index 000000000..ae251d7f7 --- /dev/null +++ b/docs/ai-design/2026-09-10-migration-matrix/design.md @@ -0,0 +1,184 @@ +# Migration matrix: proving DET data survives an upgrade + +A CI matrix that upgrades a data directory written by a **released** DET build +with the current build and asserts nothing was lost. The required baseline +today is `v0.9.3 → current`; from the next release forward, every new release +adds the pair `previous → next` on its own. + +Companion to `docs/user-stories.md` WAL-033, to the capture recipe in +`docs/gui-testing/scenarios/migration-fixture-capture.md`, and to the fixture +contract in `tests/migration-fixtures/`. Complementary to — not a replacement +for — the compatibility bridge documented in +`docs/ai-design/2026-09-10-platform-pin/upgrade-notes.md`. + +## 1. Context + +DET's local state is the user's wallet: seeds, derived addresses, identities +and their keys, aliases, settings. Every release moves that state through +several independent migration mechanisms, and no test today runs a *real* +released binary's on-disk output through a *real* current binary. The nearest +coverage is unit-level and synthetic on both ends. + +Two additional facts shaped this design: + +- **`platform-wallet-storage` was pinned to a commit outside `v4.2-dev`.** The + two lineages materialize genuinely different schemas — not merely different + migration numbering — so rewriting checksums upstream would not have fixed + it. This is already solved; see §3. +- **Only `v0.9.3` is a required baseline today.** The obligation "every new + version gets tested" starts with the next release. `v1.0.0-weekly.20260908` + is deliberately out of scope. + +Standing assumption for everything below: **only migrations that work +correctly and unattended are supported.** A migration that cannot complete +safely is a defect to fix, not a case to document a manual recovery procedure +around. A harness assertion therefore fails; it never falls back. + +## 2. The three migration systems + +| # | System | Where | Notes | +|---|---|---|---| +| 1 | `data.db` schema ladder | `src/database/initialization.rs` | Legacy DET SQLite; `DEFAULT_DB_VERSION` is 11 at v0.9.3. Since the platform-wallet rewrite (#860) it only builds a fresh file: every boot path opens an existing `data.db` read-only | +| 2 | The "unwire" drain | `src/backend_task/migration/`, gated by `MIN_DIRECT_MIGRATION_VERSION` (11) / `MAX_DIRECT_MIGRATION_VERSION` (40) in `src/model/data_migration.rs` | One-shot move of legacy `data.db` rows into the `platform-wallet-storage` k/v store; idempotent through sentinels | +| 3 | `refinery` migrations inside `platform-wallet-storage` | upstream, applied to both `det-app.sqlite` and `det-.sqlite` | The layer the lineage divergence hit | + +A fixture drives all three in the order a user meets them, which is the point: +each system is individually tested, their composition is not. + +## 3. PR #981's bridge, and the gap it names + +[PR #981](https://github.com/dashpay/dash-evo-tool/pull/981) repins the four +Platform dependencies onto `v4.2-dev` and adds a DET-side compatibility bridge, +`src/wallet_backend/platform_compatibility/`. Its behaviour: + +- Recognises the exact old migration history *and* materialized schema before + translating anything. +- Keeps a backup beside the original + (`.platform-67d4ef3-backup-*.sqlite`), validates the converted + data with the new reader, and rebuilds the original in one transaction. +- **Stops the upgrade** on unknown history, unexpected schema, or unreadable + data, rather than guessing a conversion. +- Copies DET blobs and shared wallet columns byte for byte, so it never has to + understand a bincode payload's internals. +- Covers both `det-app.sqlite` and the per-network database with the same + mechanism. + +Its own stated limits are exactly this design's mandate: *"Validation uses +synthetic upstream fixtures, not a user's real profile"* and *"Network-dependent +backend E2E and GUI tests were not run."* The matrix supplies real captured +profiles and a real process boot; it does not re-test what the bridge's unit +tests already cover. + +One consequence to accept: the bridge is specific to one recognised old history +(`67d4ef3`). A future divergence needs another dedicated bridge — that is +inherent to "stop rather than guess", and the guard in D0.2 exists to catch the +next one early rather than to make bridges unnecessary. + +**v0.9.3 is structurally immune to all of this.** That build predates the +`platform-wallet` rewrite: it has no `det-.sqlite` at all, so its +upgrade always runs path (2) and creates the persister from scratch. That is +why the single required baseline is also the safest one. + +## 4. Fixtures + +A fixture is a data directory captured from a released binary, packed, and +replayed later. The contract lives in `tests/migration-fixtures/README.md`; the +summary: + +- **Capture with the old binary, never regenerate with the current one.** + Regenerating would test nothing. +- **v0.9.3 needs the GUI.** No det-cli, no MCP, no SPV at that tag; isolation is + via `XDG_CONFIG_HOME` (no `DASH_EVO_DATA_DIR` yet) and the era's own + `.env.example`. Its identity is registered beforehand by the current build + and only loaded by ID during capture, because without SPV that binary can see + funds only through a local Dash Core node over RPC/ZMQ. +- **From the next release forward, capture headless** through det-cli; the GUI + stays required only for a password-protected wallet import (no password + parameter on `core_wallet_import`) and for reacting to a testnet reset. +- **Storage: GitHub Actions build artifacts**, not Releases. Artifacts expire, + so a baseline needs explicit long retention and/or a refresh job; + `manifest.json` in the repo is the only durable index, and a missing or + expired artifact fails the job loudly. +- **The fixture wallet is public by design**: dedicated, testnet-only, + dust-only, never the backend-E2E framework wallet. The protected wallet's + password is supplied through `MIGRATION_V093_WALLET_PASSWORD` at runtime. + Neither the password nor the recovery phrase enters the repository. + +## 5. Verification harness + +The harness runs a **real compiled binary as a subprocess** against the +extracted fixture directory — det-cli headless where the version supports it, +the GUI under Xvfb for v0.9.3. An in-process `egui_kittest` boot is explicitly +rejected: it does not reproduce the production startup path, which is a large +part of what migration correctness means here. The environment is fully reset +between fixtures. + +Assertions are **conditional, never unconditional** — "the migration ran" and +"the data was already current" are different passes, and a test that cannot +tell them apart contradicts existing coverage: + +| Property | Assertion | +|---|---| +| Boot | No panic, no `WalletDataIncompatible`. A migration that cannot complete is a failure, never a fallback | +| `data.db` | Never written: every boot path opens an existing file read-only (#860), so it stays byte-identical whatever its version. A fixture without one gets a fresh file at `DEFAULT_DB_VERSION` | +| Sentinels | An already-completed import keeps its original marker | +| Wallets | Aliases, addresses and wallet count preserved | +| Protected wallet | Right password opens it, wrong password is rejected, at-rest protection survived | +| Identity | Same ID, alias, type and wallet link; DPNS name still shown without a manual re-fetch | +| Idempotence | A second boot changes nothing further | + +Read-only MCP tools (`identity_list`, `app_storage_status`) provide the +post-upgrade view without a GUI. + +## 6. Phases + +- **Phase 0 — validate the bridge on real data, and prevent a repeat.** + (D0.1) Feed a captured fixture to `platform_compatibility` as an extra case, + closing the "synthetic fixtures only" gap. (D0.2) A CI guard that flags a new + `platform-wallet-storage` pin whose migration history diverges from the + previous pin — ancestry *and* a fingerprint of the rendered migrations, since + ancestry alone misses an SQL change under an unchanged version number. + (D0.3) Document `platform_compatibility` as the established pattern for the + next divergence. Phase 0 blocks nothing: the required baseline is v0.9.3, + which is immune by construction. +- **Phase 1 — capture.** v0.9.3 first (GUI); tooling and manifest under + `tests/migration-fixtures/`. Optionally capture one of the diverged weeklies + (`20260818` / `20260825`) as real regression material for D0.1. +- **Phase 2 — harness.** As in §5. +- **Phase 3 — CI (`migration-matrix.yml`).** Gate matched to the release + candidate's exact commit; matrix-pruning policy sized after the first real + timing measurement; explicit failure on missing or expired inputs. +- **Phase 4 — automation, from the next release forward.** Triggered by + chaining from the weekly publish run itself, not the `release: published` + event (which a `GITHUB_TOKEN` normally will not fan out from). Headless + capture → artifact upload → manifest PR. Steps that cannot be automated + (re-registration after a testnet reset, the protected wallet, milestone + promotion) stay documented as manual. +- **Phase 5 — documentation.** This directory, the capture scenario, + `docs/user-stories.md` WAL-033, the `docs/kv-keys.md` filename correction + (`platform-wallet.sqlite` → `det-.sqlite`), and `CHANGELOG.md`. + +## 7. Sequencing + +1. PR #981 — independent; merges on its own track. +2. **PR-A**: fixture tooling, storage/retention, and the v0.9.3 capture. + Independent of #981, may run in parallel. +3. **PR-B**: real-binary harness, read-only MCP tools, `migration-matrix.yml`, + and the weekly-build gate. Requires only `v0.9.3 → current`. +4. **PR-C** (after #981 merges): D0.1, D0.2, D0.3. +5. **PR-D**: capture automation for future releases. + +After the first release cut following PR-B, that release becomes baseline #2 +and the `N → N+1` chain extends by itself. + +## 8. Accepted risks + +- The bridge covers exactly one recognised old history; a future divergence + needs another one. D0.2 detects, it does not prevent. +- Artifact retention is a configuration decision, not a property — unlike a + Release, an artifact disappears if nobody keeps it alive. +- Capture jobs need runner egress to testnet P2P/DAPI, with the same + flakiness class that keeps `backend-e2e` out of `tests.yml`. +- Phase 4's automatic PRs depend on a GitHub App token; the fallback is a human + opening the PR after a notification. +- Linux-only in v1. Windows and macOS are an open decision, not an oversight. diff --git a/docs/ai-design/2026-09-11-platform-compatibility-bridge-pattern/design.md b/docs/ai-design/2026-09-11-platform-compatibility-bridge-pattern/design.md new file mode 100644 index 000000000..cdd839be2 --- /dev/null +++ b/docs/ai-design/2026-09-11-platform-compatibility-bridge-pattern/design.md @@ -0,0 +1,107 @@ +# Compatibility bridges for a diverged `platform-wallet-storage` pin + +Reusable pattern, not a point-in-time record. For the specific incident that +established it, see `docs/ai-design/2026-09-10-platform-pin/upgrade-notes.md` +(PR #981) and `docs/ai-design/2026-09-10-migration-matrix/design.md` §3. +Reference implementation: `src/wallet_backend/platform_compatibility/`. + +## 1. When this pattern applies + +`scripts/migration-fixtures/check-pin-ancestry.sh` fails one of its two +checks on a `platform-wallet` / `platform-wallet-storage` repin: + +- **Ancestry** — the new pin is not an ancestor of the target release branch + (taken from a side branch, like `67d4ef3`). +- **Fingerprint** — the pin is on the target branch, but the hash over its + rendered migration sources changed without the pin moving. Upstream edited + an already-released migration's SQL in place. + +Either failure means migration history has forked or been rewritten: +databases already written by the old pin and databases written by the new +code no longer share one linear `refinery` history. `SqlitePersister::open` +on an old database then fails with `WalletStorageError::Migration(_)` +instead of applying new migrations on top. That failure is the trigger to +build a new bridge module — do not silence the guard or force a checksum +match instead. + +## 2. Why reconciling checksums/numbering is not a fix + +The intuitive fix — renumber or re-hash the old migrations to line up with +the new history — only works if the *materialized schemas* are actually the +same. They may not be. In the incident that motivated this pattern (#981): + +- The old pin's `V001` migration checksum differed from the new pin's `V001`. +- The old pin's `V003` was already a "unified" schema that the new pin only + reaches at `V009`. + +That is real schema divergence, not just a version-numbering mismatch. +Rewriting checksums would make refinery *believe* the histories match while +leaving column sets, tables, and constraints genuinely different — silent +data corruption on the next write, not a fixed migration. Before writing a +bridge, confirm by diffing rendered schemas (`sqlite_master`, as captured in +`engine.rs`'s `OLD_SCHEMA`/`TARGET_SCHEMA` fixtures) — never assume checksum +repair is sufficient without checking. + +## 3. The bridge mechanism (design level) + +A bridge (`engine.rs`) is deliberately narrow and fails closed at every step: + +1. **Recognize the exact old shape.** Compare the source database's + `sqlite_master` objects and `refinery_schema_history` byte-for-byte + against a known old schema/history baked in as a fixture. Any deviation + (including `PRAGMA application_id`) aborts with `Unrecognized` — no + partial or fuzzy matching. +2. **Back up the original file first**, verified with `PRAGMA + integrity_check` before anything is touched, kept beside the original + regardless of outcome. +3. **Convert and validate against the new reader**, not just the new schema. + Data is copied column-by-column into a fresh database built by the + current `SqlitePersister::open`, verified row-for-row against the source + (`equal_rows`), then opened and loaded through the real public API + (`SqlitePersister::load()` and friends) before it is trusted. +4. **Rebuild the original file atomically, in one SQLite transaction.** A + crash or power loss during rebuild leaves either the complete old schema + or the complete new schema — never a half-migrated file. +5. **Unknown or unreadable data stops the upgrade.** Every ambiguous case + (unexpected added/removed columns, non-empty tables that should be new, + a malformed identity roster) returns a typed `UpgradeError` variant and + leaves the original file untouched, rather than guessing at a conversion. + `open()` in `mod.rs` falls back to surfacing the *original* open error + when the bridge declines to act — it never masks a real incompatibility. + +## 4. Building the test fixture for a new bridge + +Synthetic SQL fixtures (empty schemas rendered from the old and new +migration sources, per `fixtures/README.md`) are the starting point, but +PR #981 explicitly flagged them as insufficient alone: they only prove the +bridge handles an *empty* database of the recognized shape, not the byte +encodings, blob payloads, and edge-case rows a real released binary +actually produced. + +Prefer a real captured profile from an affected release, per D0.1 in +`docs/ai-design/2026-09-10-migration-matrix/design.md`: + +- Capture with the affected binary itself — `tests/migration-fixtures/` + documents the capture contract; use det-cli headless where the affected + release supports it, GUI capture otherwise. +- Treat the captured fixture as an additional test case fed through the new + bridge, alongside (not instead of) the synthetic empty-schema tests. +- Never regenerate a fixture with the current build — that tests nothing + about the old shape. + +## 5. Non-goals and limits + +- **One bridge per divergence, not a general translator.** This is a + per-incident bridge, not an N-way schema migration engine. It recognizes + one exact old history and one exact new target; it does not attempt to + cover multiple old lineages or guess at partial matches. +- **Do not extend an existing bridge module to "handle more cases."** A new + divergence gets its own dedicated module (own fixtures, own recognition + check, own `UpgradeError` review) rather than branching inside + `platform_compatibility/` to recognize a second old shape. Keeping + recognition exact and single-purpose is what makes "stop rather than + guess" trustworthy. +- **The CI guard detects divergence; it does not prevent or fix it.** + `check-pin-ancestry.sh` (D0.2) is the early-warning signal that a new + bridge is needed. Passing the guard again after a repin does not retire + an already-built bridge for data still on disk from the old lineage. diff --git a/docs/gui-testing/README.md b/docs/gui-testing/README.md index 9420df80b..91f2095c6 100644 --- a/docs/gui-testing/README.md +++ b/docs/gui-testing/README.md @@ -306,5 +306,6 @@ contract](#ab-build-comparison-contract) above applied in each file's own | [`platform-shielded-availability-after-sync.md`](scenarios/platform-shielded-availability-after-sync.md) | Shielded features correctly activate right after SPV/platform sync instead of silently staying disabled (#936, #938) | | [`dapi-budget-resilience-after-resync.md`](scenarios/dapi-budget-resilience-after-resync.md) | Repeated SPV `Syncing`↔`Synced` transitions no longer exhaust the shared DAPI request budget and break unrelated actions like identity top-up (#950) | | [`startup-storage-gate-and-sync-cancel.md`](scenarios/startup-storage-gate-and-sync-cancel.md) | Cold-boot storage preparation raises exactly one blocking gate that always releases before chain sync starts, and cancelling the SPV overlay is a two-step choice no single keypress can turn into a disconnect (#970) | +| [`migration-fixture-capture.md`](scenarios/migration-fixture-capture.md) | **Not an A/B comparison** (see its own "Deviation from the A/B contract" note) — the one-time recipe for capturing a real, GUI-produced data directory as a cross-version migration-test fixture (`tests/migration-fixtures/`) | 🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent diff --git a/docs/gui-testing/scenarios/migration-fixture-capture.md b/docs/gui-testing/scenarios/migration-fixture-capture.md new file mode 100644 index 000000000..ebee73400 --- /dev/null +++ b/docs/gui-testing/scenarios/migration-fixture-capture.md @@ -0,0 +1,252 @@ +# Scenario: Capture a v0.9.3 migration fixture + +**Verifies:** nothing about the current build — this scenario *produces* an +input for the migration matrix. It is complete when a released v0.9.3 binary +has written a data directory holding the +[`wallet-identity-dpns`](../../../tests/migration-fixtures/profiles/wallet-identity-dpns.md) +profile, and that directory has been packed as a fixture archive. + +**Tier justification:** v0.9.3 predates det-cli, the MCP server and the SPV +stack, so it has no headless entry point of any kind — the only way to make +that binary write its own on-disk shapes is to drive its real GUI. Nothing in +`kittest` or `backend-e2e` can help: both compile against *current* sources and +would produce current-era files, which is exactly what a migration fixture must +not be. + +**Deviation from the A/B contract:** the library's [A/B build comparison +contract](../README.md#ab-build-comparison-contract) does not apply here. This +scenario runs once, against one specific released binary, and the "second +build" role is played later by the migration harness replaying the archive. +Everything else in the README — isolated data directory, testnet default, +fund-movement caps, read the logs — applies unchanged. + +## Prerequisites + +- Network: **testnet**. A mainnet capture is forbidden outright; see the threat + model in [`tests/migration-fixtures/README.md`](../../../tests/migration-fixtures/README.md). +- Environment variables (names only — never paste values into a file, a report + or a command line that lands in shell history): + - `MIGRATION_FIXTURE_MNEMONIC` — the dedicated, public-by-design fixture + wallet. **Not** `E2E_WALLET_MNEMONIC`, which belongs to the funded + backend-E2E framework wallet and must never be published in an artifact. + - `MIGRATION_FIXTURE_PROTECTED_MNEMONIC` — a second, distinct phrase for the + password-protected wallet. +- `MIGRATION_V093_WALLET_PASSWORD` holds the protected wallet's password, + supplied from the operator's secure store. Never commit its value. +- **A testnet identity registered ahead of time with the CURRENT build**, from + `MIGRATION_FIXTURE_MNEMONIC`, holding a resolved, uncontested DPNS name. + v0.9.3 does ship registration screens, but it has no SPV stack: it sees funds + only through a local Dash Core testnet node over RPC/ZMQ, and without one it + cannot build the asset lock a registration needs. Record the identity ID, its + derivation index and the name before starting. +- `gh` authenticated against `dashpay/dash-evo-tool`, plus `unzip`. +- Confirm the identity and the name still resolve on testnet *today* — see the + precondition checklist in the profile file. Shared testnet is mutable. + +## Setup + +```bash +# Scratch tree — every level 0700. The current build's secret store refuses to +# open a data directory with a group/other-writable ancestor, so a fixture +# captured under a loose /tmp cannot be replayed later. +SCRATCH=$(mktemp -d); chmod 700 "$SCRATCH" + +# The released v0.9.3 binary. Asset naming changed between eras — this is the +# confirmed name for this tag, do not guess it for another one. +gh release download v0.9.3 --repo dashpay/dash-evo-tool \ + --pattern dash-evo-tool-x86_64-linux.zip --dir "$SCRATCH" +unzip -q "$SCRATCH/dash-evo-tool-x86_64-linux.zip" -d "$SCRATCH/bin" +OLD_BIN=$(find "$SCRATCH/bin" -type f -name 'dash-evo-tool*' | head -1) +chmod +x "$OLD_BIN"; "$OLD_BIN" --version 2>&1 | head -2 + +# v0.9.3 has no DASH_EVO_DATA_DIR (absent from src/app_dir.rs at that tag). +# It resolves its data directory through ProjectDirs, so XDG_CONFIG_HOME is +# the only isolation lever. Unset DASH_EVO_DATA_DIR so a value inherited from +# the shell cannot mislead anyone reading the transcript later. +FIXTURE_HOME="$SCRATCH/xdg"; mkdir -p "$FIXTURE_HOME"; chmod 700 "$FIXTURE_HOME" +DATADIR="$FIXTURE_HOME/dash-evo-tool"; mkdir -p "$DATADIR"; chmod 700 "$DATADIR" + +# Era-correct config. v0.9.3's .env.example uses the older key spelling +# (TESTNET_insight_api_url, TESTNET_show_in_ui, TESTNET_core_zmq_endpoint, …). +# Today's .env.example would be silently wrong here. +git show v0.9.3:.env.example > "$DATADIR/.env" + +pgrep -af dash-evo-tool # never disturb an instance already running +: "${DISPLAY:?Set DISPLAY to the desktop used for GUI testing}" +xdpyinfo >/dev/null + +LOG="$SCRATCH/migration-fixture-capture.log" +env -u DASH_EVO_DATA_DIR XDG_CONFIG_HOME="$FIXTURE_HOME" \ + nohup "$OLD_BIN" >"$LOG" 2>&1 & +APP_PID=$! +WID=$(xdotool search --pid "$APP_PID" | head -1) +xdotool windowsize "$WID" 1260 780; xdotool windowactivate "$WID" +``` + +Confirm before touching anything: `ls "$DATADIR"` shows `.env`, and `data.db` +and `det.log` appear as the app starts. If the data directory stayed empty, the +app resolved a *different* directory — stop, do not continue, and check +`XDG_CONFIG_HOME` before it writes into a real profile. + +## Procedure + +### 1. Select testnet + +1. Open the network chooser and select **testnet**. Record which network the + app started on rather than assuming; a fresh install does not necessarily + start where you expect. +2. Confirm the selection persisted in the UI before moving on. Every later step + writes rows tagged with the active network, and a wallet captured on the + wrong network makes the whole archive useless. + +### 2. Import the unprotected wallet (Wallet U) + +3. Go to the wallets area and start the wallet **import** flow ("Follow these + steps to import your wallet"). +4. Select the seed-phrase length matching `MIGRATION_FIXTURE_MNEMONIC`, then + enter the words. The screen has **one field per word**, not a single + paste-able box — type or `xdotool type` into each field and tab between + them. The screen validates continuously and shows "Invalid seed phrase…" + until every word is present and valid. +5. Under step 2 of that screen, set the **Wallet Name** to a recognisable, + non-default alias (e.g. `Fixture unprotected`). +6. Leave the **Optional Password** empty. Wallet U must stay unprotected — it + is what proves an upgrade never hands an unprotected wallet a password the + user cannot supply. +7. Press **Save Wallet** and confirm the wallet appears in the wallet list. + +### 3. Import the password-protected wallet (Wallet P) + +8. Repeat the import flow with `MIGRATION_FIXTURE_PROTECTED_MNEMONIC` and a + distinct alias (e.g. `Fixture protected`). +9. This time fill **Optional Password** from `MIGRATION_V093_WALLET_PASSWORD`. + v0.9.3's import screen has no password-hint field; do not go looking for + one. +10. Save, then confirm the wallet list shows two distinct wallets. If it shows + one, the two phrases were the same — the fixture is a single-wallet fixture + and the profile is not met. + +### 4. Derive and record addresses + +11. For each wallet, open its address view and make sure at least one receive + address is derived and displayed. +12. Record the addresses in the capture report (outside the archive). A later + run asserts the *same* addresses return, which is only checkable against a + recorded value. + +### 5. Adopt the pre-registered identity + +13. Open **Load Existing Identity**. +14. Prefer the **By Wallet** tab: select Wallet U, unlock it if asked, set + **Search type** to *Specific index*, enter the identity's derivation index, + and press **Search For Identity**. This path links the identity to the + wallet and derives its keys from the seed, which is what the profile wants. +15. If the wallet search does not find it, fall back to the **By Identity** tab: + paste the identity ID, set **Identity Type** to *User*, set an alias, and + load. Record which path was used — it changes what the fixture proves about + the identity/wallet link. +16. Either path fetches the identity's DPNS names as part of the load. Wait for + the load to report success and for the name to actually appear beside the + identity in the identities list. **Do not proceed on the ID alone.** +17. Screenshot the identities list showing the name (`scrot -o …`). At this era + the name lives inside the opaque `identity.data` bincode blob, so the + screenshot is the only practical evidence — no SQL query can confirm it. + +### 6. Quit cleanly and pack + +18. Quit through the app's own window close. Do not `kill` it: a half-written + WAL sidecar is not a valid fixture. +19. Confirm the process is gone (`pgrep -af dash-evo-tool`) before touching the + files. +20. Verify the shape of what was captured: + + ```bash + ls -la "$DATADIR" + sqlite3 -readonly "$DATADIR/data.db" \ + "SELECT database_version FROM settings WHERE id = 1; \ + SELECT alias, is_main, uses_password, network FROM wallet; \ + SELECT hex(id), alias, identity_type, network, wallet IS NOT NULL FROM identity;" + ``` + + Expect `settings.database_version` = 11, two wallet rows (one with `uses_password` = 1, + one with 0), and exactly one identity row. Always `-readonly`: a plain open + can checkpoint the WAL and mutate the very state being preserved. +21. Blank `MCP_API_KEY`, network `core_rpc_user`, `core_rpc_password`, and + `wallet_private_key` settings in the capture copy's `.env`, including + template placeholders. Pack per [`tests/migration-fixtures/README.md`](../../../tests/migration-fixtures/README.md) + — include `data.db` and `.env`, exclude `backups/` and `*.log` — then + upload the archive and fill in the manifest entry's `artifact` fields, + `captured_at` and `sha256`. +22. Delete the scratch tree only after the archive is uploaded and its checksum + is recorded. A capture that has to be redone from scratch costs an + identity registration. + +## Safety constraints specific to this scenario + +- **This scenario broadcasts nothing.** No send, no registration, no top-up + happens from the v0.9.3 binary. Any step that appears to offer one is a + deviation — stop and record it. +- **Never capture with a wallet that holds meaningful funds.** The archive + publishes the encrypted seed. Dust only, dedicated wallet only, and never + `E2E_WALLET_MNEMONIC`. +- **Never let v0.9.3 see the default data directory.** It has no + `DASH_EVO_DATA_DIR` override and no confirmation prompt; launching it without + `XDG_CONFIG_HOME` set would run an old build directly against a real profile + and its schema-11 expectations. +- **Do not type a recovery phrase on a command line** or leave one visible in a + screenshot. Capture screenshots before typing or after the field is cleared. +- **One fixture per data directory, always fresh.** Never capture a second + fixture on top of a directory an earlier run touched. + +## Expected outcome / pass criteria + +The capture succeeded when all of the following hold: + +- `"$DATADIR"` contains `data.db` with `settings.database_version` = **11**, and no + `det-.sqlite` and no `secrets/` directory — v0.9.3 predates both, and + their presence means a newer binary opened the directory and already migrated + it, destroying the fixture. +- Two wallet rows with distinct `seed_hash`, distinct aliases, `uses_password` + = 1 and 0 respectively, `network` = `testnet` for both. +- Exactly one `identity` row, `identity_type` `User`, `network` `testnet`, + ideally with a non-null `wallet` link (By Wallet path). +- A screenshot showing the DPNS name rendered next to that identity. +- No Rust panic (`location=…`) in `$LOG` or `$DATADIR/det.log`. +- Every item of the + [`wallet-identity-dpns`](../../../tests/migration-fixtures/profiles/wallet-identity-dpns.md) + checklist ticked, and the manifest entry filled in. + +Anything less is a `wallet-only` fixture at best. Record which profile was +actually achieved in the manifest entry rather than claiming the intended one. + +## Known gotchas + +- **`XDG_CONFIG_HOME` is the only isolation lever at this tag.** + `DASH_EVO_DATA_DIR` does not exist in v0.9.3's `src/app_dir.rs`; exporting it + isolates nothing and the app quietly uses the real profile directory. Verify + files actually appear under the scratch directory within seconds of launch. +- **Today's `.env.example` is the wrong file.** v0.9.3 reads the older key + spelling; copy the one from the tag (`git show v0.9.3:.env.example`). A + config the old build cannot parse sends it to defaults, which usually shows + up much later as an empty network list. +- **A zero balance is normal here.** Without a local Dash Core testnet node, + v0.9.3 shows no funds and an empty `utxos` table — it has no SPV. That does + not block this scenario: nothing in it spends anything. +- **The window opens at 800×600 and clips controls.** Resize before + interacting; the import screen's later steps and the Save button sit well + below the fold. +- **The seed phrase is one field per word.** A single paste into the first + field yields an invalid phrase, not a filled form. +- **DPNS names can lag the identity load.** The identity appears first and the + name arrives with the document fetch. Quitting in that window captures an + identity with no names — a fixture that then "survives" every upgrade while + proving nothing about DPNS. +- **Shared testnet state expires.** A network reset can remove the identity and + free its name for someone else. Re-verify with the current build before every + capture, not once when the fixture was designed. +- **A shared Cargo target directory is irrelevant here, but the downloaded zip + is not.** Keep the extracted v0.9.3 binary inside the scratch tree and + `sha256sum` it into the report — "the released v0.9.3 build" is a claim the + fixture's whole value rests on. + +🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent diff --git a/docs/user-stories.md b/docs/user-stories.md index 5b16660d4..435aa2489 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -314,7 +314,19 @@ As a user opening an older wallet installation, I want the app to update its sto - The desktop app asks for each password-protected wallet separately and never carries a typed password into another wallet's prompt. - The user can skip a wallet; skipped wallets stay locked, and the rest of the storage update can finish. - The previous database is read-only throughout the update, including unlock and skip paths. -- Standalone command-line and MCP use never wait for a window that is not present. They ask the user to open the desktop app once, then try again. +- Standalone command-line and MCP use never wait for a window that is not present. Without a password they ask the user to open the desktop app once, then try again. +- An operator without the desktop app can supply the wallet password non-interactively (`app_storage_update`; det-cli `--password-stdin` or `--password-file`, never as a command-line argument or environment variable). The update then finishes for every wallet sharing that password, or fails at once without skipping any wallet. + +### WAL-033: Wallets, addresses and identities survive an app upgrade [Gap] +**Persona:** Alex, Priya, Jordan + +As a user updating from any earlier version I still have installed, I want every wallet, address and identity to be exactly as I left it after the update, so that I never have to re-import a recovery phrase or reload an identity to get my funds back. + +- Updating from any released version keeps each wallet with its name, its derived addresses and its password protection: a wallet that needed a password still needs the same one, and a wallet that never had one never acquires one. +- Identities loaded before the update are still present afterwards, keeping their alias, their keys, their wallet link and their registered DPNS name, without a manual reload or refresh. +- The update completes on its own. A migration that cannot finish safely is a defect in the migration, not a situation the user is asked to repair by hand. +- Starting the updated app a second time changes nothing further, and a user whose data was already current keeps an untouched database rather than a needlessly rewritten one. +- Currently a gap: each migration mechanism is unit-tested on synthetic data, but no automated check upgrades a data directory a *released* build actually wrote and confirms the result. The design for closing it is `docs/ai-design/2026-09-10-migration-matrix/design.md`; related implemented behaviour is covered by WAL-032, IDN-016 and IDN-020. --- diff --git a/scripts/migration-fixtures/capture-headless.sh b/scripts/migration-fixtures/capture-headless.sh new file mode 100755 index 000000000..4235fd40d --- /dev/null +++ b/scripts/migration-fixtures/capture-headless.sh @@ -0,0 +1,267 @@ +#!/usr/bin/env bash +# +# Capture a migration fixture headlessly, by driving det-cli against a throwaway +# DASH_EVO_DATA_DIR until it holds a populated, discovered wallet profile. +# +# scripts/migration-fixtures/capture-headless.sh \ +# --data-dir /data/tmp/fixture-capture \ +# --network testnet \ +# --mnemonic-env FIXTURE_WALLET_MNEMONIC +# +# The sequence is the one docs/CLI.md documents for standalone (stdio, +# lazy-init) mode, and each step exists because it writes something a later +# version has to migrate: +# +# network-info boots the binary and lazy-inits AppContext, which +# creates .env, the SQLite DBs and the secret vault +# network-switch saves the chosen network and starts SPV +# core-wallet-import writes the seed through the secret seam and the +# wallet rows behind it +# core-balances-get SPV gate — retried until the chain is synced enough +# for the platform query below to be answerable +# core-address-create forces address derivation state to be persisted +# platform-addresses-list triggers identity/DPNS discovery, which is what +# populates the rows migrations actually reshape +# +# Only after discovery returns a non-empty result is the directory worth +# packing; a fixture captured before discovery finished looks like a healthy +# empty profile and silently tests nothing. Pass --allow-empty-discovery to +# override, e.g. when deliberately capturing a wallet with no platform balance. +# +# This captures the CURRENT build's profile. Capturing a historical release +# means running its own binary — and v0.9.3 predates det-cli entirely, so that +# baseline needs the GUI route under Xvfb, not this script. +# +# SECURITY NOTE: det-cli takes tool parameters on argv only, so the recovery +# phrase is briefly visible in /proc//cmdline to other processes on the +# same host for the duration of the import. The fixture wallet is a deliberately +# public, testnet-only wallet, which is what makes that acceptable here; do not +# point this script at a wallet holding anything of value. +# TODO: drop the argv exposure once core_wallet_import can take the mnemonic +# from an environment variable or stdin. + +set -euo pipefail + +DATA_DIR="" +NETWORK="testnet" +MNEMONIC_ENV="FIXTURE_WALLET_MNEMONIC" +DET_CLI="" +ALIAS="migration-fixture" +SPV_WAIT_SECS=900 +ALLOW_EMPTY_DISCOVERY=0 + +die() { + echo "::error::$*" >&2 + exit 1 +} + +note() { echo "==> $*"; } + +usage() { + cat <<'EOF' +usage: capture-headless.sh --data-dir DIR [options] + + --data-dir DIR target DASH_EVO_DATA_DIR (created if absent) + --network NAME network to capture on (default: testnet) + --mnemonic-env VAR env var holding the BIP-39 phrase (default: FIXTURE_WALLET_MNEMONIC) + --det-cli PATH det-cli binary to drive (default: auto-detected) + --alias NAME wallet alias to import under (default: migration-fixture) + --spv-wait-secs N budget for the SPV gate (default: 900) + --allow-empty-discovery do not fail when no platform addresses are discovered +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + --data-dir) + DATA_DIR="${2:-}" + shift + ;; + --network) + NETWORK="${2:-}" + shift + ;; + --mnemonic-env) + MNEMONIC_ENV="${2:-}" + shift + ;; + --det-cli) + DET_CLI="${2:-}" + shift + ;; + --alias) + ALIAS="${2:-}" + shift + ;; + --spv-wait-secs) + SPV_WAIT_SECS="${2:-}" + shift + ;; + --allow-empty-discovery) ALLOW_EMPTY_DISCOVERY=1 ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + die "unknown argument '$1'" + ;; + esac + shift +done + +[ -n "$DATA_DIR" ] || { + usage >&2 + die "--data-dir is required" +} +[ "$NETWORK" = testnet ] || die "Migration fixtures must be captured on testnet." +command -v jq >/dev/null 2>&1 || die "jq is required but not installed." + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" + +# -------------------------------------------------------------------------- +# Locate the binary. +# -------------------------------------------------------------------------- +# +# Cargo's output directory is redirectable by CARGO_TARGET_DIR or by +# build.target-dir in .cargo/config.toml, so ./target is a guess, not a fact. +# Ask cargo, and only then fall back. +if [ -z "$DET_CLI" ]; then + target_dir="${CARGO_TARGET_DIR:-}" + if [ -z "$target_dir" ] && command -v cargo >/dev/null 2>&1; then + target_dir="$(cd -- "$REPO_ROOT" && cargo metadata --format-version 1 --no-deps 2>/dev/null | + jq -r '.target_directory // empty')" + fi + target_dir="${target_dir:-$REPO_ROOT/target}" + for candidate in "$target_dir/release/det-cli" "$target_dir/debug/det-cli"; do + if [ -x "$candidate" ]; then + DET_CLI="$candidate" + break + fi + done +fi +if [ -z "$DET_CLI" ] || [ ! -x "$DET_CLI" ]; then + die "det-cli binary not found. Build it with 'cargo build --bin det-cli --features cli', or point at it with --det-cli PATH." +fi + +MNEMONIC="${!MNEMONIC_ENV:-}" +[ -n "$MNEMONIC" ] || die "Environment variable '$MNEMONIC_ENV' is unset or empty. Export the fixture wallet's recovery phrase there, or name a different variable with --mnemonic-env." + +# -------------------------------------------------------------------------- +# Prepare the data directory. +# -------------------------------------------------------------------------- + +mkdir -p "$DATA_DIR" +DATA_DIR="$(cd -- "$DATA_DIR" && pwd)" +if [ ! -f "$DATA_DIR/.env" ]; then + [ -f "$REPO_ROOT/.env.example" ] || die "No .env in $DATA_DIR and no .env.example at $REPO_ROOT to seed it from." + cp "$REPO_ROOT/.env.example" "$DATA_DIR/.env" + note "Seeded $DATA_DIR/.env from .env.example" +fi + +note "Binary: $DET_CLI" +note "Data dir: $DATA_DIR" +note "Network: $NETWORK" +note "Alias: $ALIAS" + +# Standalone mode keeps shell or .env credentials from selecting a running GUI. +det() { + env -u MCP_API_KEY \ + DASH_EVO_DATA_DIR="$DATA_DIR" \ + RUST_LOG="${RUST_LOG:-off}" \ + "$DET_CLI" --standalone "$@" +} + +# -------------------------------------------------------------------------- +# 1. Boot + lazy context init. +# -------------------------------------------------------------------------- + +note "[1/6] network-info" +det network-info >/dev/null || die "det-cli could not initialise an AppContext in $DATA_DIR. The data directory may be held by another DET process, or .env may be missing DAPI addresses for '$NETWORK'." + +# -------------------------------------------------------------------------- +# 2. Network switch (idempotent; no-op when already active). +# -------------------------------------------------------------------------- + +note "[2/6] network-switch network=$NETWORK" +switch_out="$(det network-switch "network=$NETWORK")" || + die "Failed to switch to network '$NETWORK'. Check that ${NETWORK^^}_dapi_addresses is populated in $DATA_DIR/.env." +echo "$switch_out" | jq -e --arg network "$NETWORK" '.active == $network' >/dev/null 2>&1 || + die "network-switch returned no active network: $switch_out" + +# Each command is a new process, so verify the saved choice before importing. +det network-info | jq -e --arg network "$NETWORK" '.active == $network' >/dev/null || + die "The selected network did not survive restart. Use a det-cli build that persists network-switch." + +# -------------------------------------------------------------------------- +# 3. Wallet import. +# -------------------------------------------------------------------------- +# +# Output is discarded rather than echoed: it carries the seed hash, and the +# command line already exposes enough. Import is idempotent, so re-running the +# capture against an existing data dir is safe. + +note "[3/6] core-wallet-import alias=$ALIAS (output suppressed)" +det core-wallet-import "mnemonic=$MNEMONIC" "network=$NETWORK" "alias=$ALIAS" >/dev/null || + die "Wallet import failed. Verify the phrase in \$$MNEMONIC_ENV is a valid BIP-39 mnemonic for '$NETWORK'." + +# -------------------------------------------------------------------------- +# 4. SPV gate. +# -------------------------------------------------------------------------- +# +# core-balances-get is read-only and SPV-gated, which makes it the cheapest +# probe for "is the chain synced enough to answer anything". The tool has its +# own internal 10-minute sync wait; this loop exists on top of it so a sync that +# needs longer than one attempt retries instead of failing the capture, and so +# the wait is visible in the log rather than looking like a hang. + +note "[4/6] waiting up to ${SPV_WAIT_SECS}s for SPV sync" +deadline=$((SECONDS + SPV_WAIT_SECS)) +synced=0 +attempt=0 +while [ "$SECONDS" -lt "$deadline" ]; do + attempt=$((attempt + 1)) + if det core-balances-get "wallet-id=$ALIAS" "network=$NETWORK" >/dev/null 2>&1; then + synced=1 + note "SPV ready after $attempt attempt(s), ${SECONDS}s elapsed" + break + fi + note "SPV not ready yet (attempt $attempt, ${SECONDS}s elapsed) — retrying in 15s" + sleep 15 +done +[ "$synced" -eq 1 ] || + die "SPV did not sync within ${SPV_WAIT_SECS}s. Raise --spv-wait-secs, or check the runner's outbound P2P access to the '$NETWORK' network." + +# -------------------------------------------------------------------------- +# 5. Address derivation. +# -------------------------------------------------------------------------- + +note "[5/6] core-address-create" +addr_out="$(det core-address-create "wallet-id=$ALIAS" "network=$NETWORK")" || + die "Address generation failed for wallet '$ALIAS'." +echo "$addr_out" | jq -e '.address' >/dev/null 2>&1 || + die "core-address-create returned no address: $addr_out" + +# -------------------------------------------------------------------------- +# 6. Identity / DPNS discovery. +# -------------------------------------------------------------------------- + +note "[6/6] platform-addresses-list (triggers identity discovery)" +plat_out="$(det platform-addresses-list "wallet-id=$ALIAS" "network=$NETWORK")" || + die "Platform address lookup failed for wallet '$ALIAS'." + +discovered="$(echo "$plat_out" | jq -r '.balances | length' 2>/dev/null || echo 0)" +note "Discovered platform addresses: $discovered" + +if [ "$discovered" -eq 0 ]; then + if [ "$ALLOW_EMPTY_DISCOVERY" -eq 1 ]; then + echo "::warning::No platform addresses discovered; packing anyway because --allow-empty-discovery was given." >&2 + else + die "No platform addresses were discovered, so this profile has nothing for a migration to reshape and would pass as a fixture without testing anything. +The fixture wallet most likely has no registered identity on '$NETWORK' — register one with the current build first, or re-register after a testnet reset. Pass --allow-empty-discovery to capture regardless." + fi +fi + +note "Capture complete: $DATA_DIR" +note "Pack it with: scripts/migration-fixtures/pack.sh '$DATA_DIR' " diff --git a/scripts/migration-fixtures/check-coverage.sh b/scripts/migration-fixtures/check-coverage.sh new file mode 100755 index 000000000..dde70ddf8 --- /dev/null +++ b/scripts/migration-fixtures/check-coverage.sh @@ -0,0 +1,183 @@ +#!/usr/bin/env bash +# +# Fail when a published release newer than the newest captured fixture has no +# fixture of its own. +# +# scripts/migration-fixtures/check-coverage.sh +# +# The migration matrix is only worth anything if the chain of fixtures keeps up +# with the chain of releases: the rule from the plan is that every release from +# the next one onwards gets a fixture, so that the N -> N+1 pair is always +# testable. Nothing enforces that at release time, and a gap is invisible — the +# matrix stays green while quietly testing an ever-older pair. This check is the +# enforcement, and it runs on the weekly schedule rather than per-PR because a +# gap is created by cutting a release, not by editing code. +# +# Releases BEFORE the newest fixture are not reported. Backfilling history is a +# deliberate decision, not an oversight to nag about; only forward gaps matter. +# +# Source of truth is the releases API filtered to draft == false, intersected +# with the tags API. Tags alone would false-positive: weekly-build.yml pushes +# the tag first and publishes the release at the end of the run, so a tag can +# exist for a release that was never published (and, on build failure, gets +# deleted again). + +set -euo pipefail + +# -------------------------------------------------------------------------- +# Configuration +# -------------------------------------------------------------------------- + +# Enforcement starts with the first release published AFTER this tag; this tag +# and everything before it are exempt. +# +# The agreed baseline today is v0.9.3 alone, and the weeklies already published +# are deliberately not backfilled: upgrading from v0.9.3 predates the +# platform-wallet rewrite, so it always takes the "unwire" path and builds the +# persister from scratch, which is the one case structurally immune to the pin +# divergence this whole effort exists to catch. Without this knob the check +# would open by demanding five fixtures nobody agreed to capture. +# +# Move this forward only to write off a release on purpose. +ENFORCE_AFTER="${MIGRATION_COVERAGE_ENFORCE_AFTER:-v1.0.0-weekly.20260908}" + +# -------------------------------------------------------------------------- + +REPO="${GITHUB_REPOSITORY:-dashpay/dash-evo-tool}" +MANIFEST="" + +die() { + echo "::error::$*" >&2 + exit 1 +} +warn() { echo "::warning::$*" >&2; } +note() { echo "==> $*"; } + +usage() { + cat <<'EOF' +usage: check-coverage.sh [options] + + --manifest PATH manifest to read (default: tests/migration-fixtures/manifest.json) + --repo OWNER/NAME repository whose releases to check (default: $GITHUB_REPOSITORY) + --enforce-after TAG exempt this release and everything before it +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + --manifest) + MANIFEST="${2:-}" + shift + ;; + --repo) + REPO="${2:-}" + shift + ;; + --enforce-after) + ENFORCE_AFTER="${2:-}" + shift + ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + die "unknown argument '$1'" + ;; + esac + shift +done + +command -v jq >/dev/null 2>&1 || die "jq is required but not installed." +command -v gh >/dev/null 2>&1 || die "the GitHub CLI (gh) is required but not installed." + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" +MANIFEST="${MANIFEST:-$REPO_ROOT/tests/migration-fixtures/manifest.json}" + +# -------------------------------------------------------------------------- +# Fixture tags from the manifest. +# -------------------------------------------------------------------------- + +if [ ! -f "$MANIFEST" ]; then + warn "No fixture manifest at $MANIFEST — coverage cannot be assessed yet." + exit 0 +fi + +# Tolerant of both a bare array and { "fixtures": [...] }. +FIXTURE_TAGS="$(jq -r 'if type == "array" then . else (.fixtures // []) end | .[] | .git_tag // empty' "$MANIFEST" 2>/dev/null)" || + die "Manifest $MANIFEST is not valid JSON." + +if [ -z "$FIXTURE_TAGS" ]; then + # Bootstrap state: with no fixtures at all there is no "newest fixture" to + # measure forward gaps against, so there is nothing to fail on. + warn "Manifest $MANIFEST lists no fixtures with a git_tag yet — skipping the coverage check. It starts enforcing once the first fixture is recorded." + exit 0 +fi + +newest_tag() { + jq -L "$SCRIPT_DIR" -Rsr 'include "semver"; split("\n") | map(select(length > 0)) | max_by(semver_key)' +} +NEWEST_FIXTURE="$(printf '%s\n' "$FIXTURE_TAGS" | newest_tag)" +note "Newest fixture tag: $NEWEST_FIXTURE" + +# -------------------------------------------------------------------------- +# Published release tags. +# -------------------------------------------------------------------------- + +PUBLISHED="$(gh api "repos/$REPO/releases" --paginate \ + --jq '.[] | select(.draft == false) | .tag_name' 2>/dev/null)" || + die "Could not list releases for $REPO. Check that GH_TOKEN is set and has read access." + +ALL_TAGS="$(gh api "repos/$REPO/tags" --paginate --jq '.[].name' 2>/dev/null)" || + die "Could not list tags for $REPO. Check that GH_TOKEN is set and has read access." + +# Intersection: a tag that exists AND whose release is published. +CANDIDATES="$(comm -12 \ + <(printf '%s\n' "$PUBLISHED" | LC_ALL=C sort -u) \ + <(printf '%s\n' "$ALL_TAGS" | LC_ALL=C sort -u))" + +if [ -z "$CANDIDATES" ]; then + warn "No published releases found for $REPO — nothing to check coverage against." + exit 0 +fi + +# -------------------------------------------------------------------------- +# Forward gaps. +# -------------------------------------------------------------------------- + +# Only releases newer than BOTH the newest fixture and the exemption tag count. +# Taking the greater of the two keeps the two rules from cancelling each other: +# the exemption must not silence a genuine gap above it, and a newer fixture +# must not resurrect the releases the exemption wrote off. +BASELINE="$(printf '%s\n%s\n' "$NEWEST_FIXTURE" "$ENFORCE_AFTER" | newest_tag)" +if [ "$BASELINE" != "$NEWEST_FIXTURE" ]; then + note "Enforcement baseline: $BASELINE (exempt by configuration, newer than the newest fixture)" +else + note "Enforcement baseline: $BASELINE" +fi + +missing=() +while IFS= read -r tag; do + [ -n "$tag" ] || continue + newer="$(jq -L "$SCRIPT_DIR" -nr --arg tag "$tag" --arg baseline "$BASELINE" \ + 'include "semver"; ($tag | semver_key) > ($baseline | semver_key)')" + [ "$newer" = true ] || continue + # Already covered? + if printf '%s\n' "$FIXTURE_TAGS" | grep -Fxq "$tag"; then + continue + fi + missing+=("$tag") +done <<<"$CANDIDATES" + +if [ "${#missing[@]}" -eq 0 ]; then + note "Fixture coverage OK: no published release newer than $BASELINE is missing a fixture." + exit 0 +fi + +printf 'Published releases with no migration fixture:\n' >&2 +printf ' %s\n' "${missing[@]}" >&2 +die "${#missing[@]} published release(s) newer than $BASELINE have no entry in $MANIFEST. +Until each is captured, the migration matrix silently tests an older version pair than the one users are actually upgrading across. +Capture with scripts/migration-fixtures/capture-headless.sh against that release's own binary, pack with pack.sh, upload as a build artifact, and add the entry to the manifest." diff --git a/scripts/migration-fixtures/check-pin-ancestry.sh b/scripts/migration-fixtures/check-pin-ancestry.sh new file mode 100755 index 000000000..e50e7cbfe --- /dev/null +++ b/scripts/migration-fixtures/check-pin-ancestry.sh @@ -0,0 +1,216 @@ +#!/usr/bin/env bash +# +# Guard against a platform pin that forks the wallet-storage migration history. +# +# Two independent checks, both of which must pass: +# +# (a) ANCESTRY — the rev pinned in Cargo.toml is an ancestor of TARGET_BRANCH +# upstream. A pin taken from a side branch is how DET ended up +# needing the platform_compatibility bridge in the first place. +# +# (b) FINGERPRINT — a hash over the contents of the pinned rev's migration +# sources, compared against a checked-in expected value. +# Ancestry alone is not enough: an upstream commit can change +# the SQL inside an already-released migration number without +# ever leaving the target branch, and every profile that +# already ran the old version would then carry a schema whose +# checksum the new code rejects. +# +# The fingerprint file is updated by a HUMAN, deliberately, as part of a repin: +# +# scripts/migration-fixtures/check-pin-ancestry.sh --update +# +# Reviewing that diff is the point. If the fingerprint moves without the pin +# moving, upstream rewrote a released migration and DET needs a compatibility +# bridge, not a rubber stamp. + +set -euo pipefail + +# -------------------------------------------------------------------------- +# Configuration — edit here when the upstream release line advances. +# -------------------------------------------------------------------------- + +# Branch the pin must descend from. Override with MIGRATION_PIN_TARGET_BRANCH to +# try a repin against a different line before editing this file. +TARGET_BRANCH="${MIGRATION_PIN_TARGET_BRANCH:-v4.2-dev}" + +PLATFORM_REMOTE="${MIGRATION_PIN_REMOTE:-https://github.com/dashpay/platform.git}" + +# Directory holding the refinery migration sources inside the platform repo. +MIGRATIONS_DIR="packages/rs-platform-wallet-storage/migrations" + +# Cargo.toml dependencies that must all point at the same platform rev. These +# are the crates whose migrations touch on-disk user data. +PINNED_CRATES=(platform-wallet platform-wallet-storage) + +# -------------------------------------------------------------------------- + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" +CARGO_TOML="$REPO_ROOT/Cargo.toml" +EXPECTED_FILE="$SCRIPT_DIR/expected-migration-fingerprint.txt" + +# Clone reused across runs: $RUNNER_TEMP on GitHub Actions, /data/tmp locally +# (never /tmp — that is a RAM-backed tmpfs on the dev host). +CACHE_DIR="${MIGRATION_PIN_CACHE_DIR:-${RUNNER_TEMP:-/data/tmp}/platform-pin-cache}" + +MODE=check +while [ $# -gt 0 ]; do + case "$1" in + --update) MODE=update ;; + --print) MODE=print ;; + -h | --help) + sed -n '3,26p' "${BASH_SOURCE[0]}" | sed 's/^#\{1,2\} \{0,1\}//' + exit 0 + ;; + *) + echo "error: unknown argument '$1' (expected --update, --print, or no argument)" >&2 + exit 2 + ;; + esac + shift +done + +die() { + echo "::error::$*" >&2 + exit 1 +} + +note() { echo "==> $*"; } + +# -------------------------------------------------------------------------- +# 1. Read the pinned rev out of Cargo.toml. +# -------------------------------------------------------------------------- + +[ -f "$CARGO_TOML" ] || die "Cargo.toml not found at $CARGO_TOML" + +PIN="" +for crate in "${PINNED_CRATES[@]}"; do + # Anchored on " =" so platform-wallet does not also match + # platform-wallet-storage. The rev always sits on the crate's own line. + rev="$(sed -nE "s/^${crate}[[:space:]]*=[[:space:]]*\{.*rev[[:space:]]*=[[:space:]]*\"([0-9a-fA-F]{7,40})\".*/\1/p" "$CARGO_TOML" | head -n1)" + [ -n "$rev" ] || die "Could not read a git rev for '$crate' from $CARGO_TOML. Has the dependency been renamed, switched to a path/version dependency, or reformatted across multiple lines?" + if [ -z "$PIN" ]; then + PIN="$rev" + elif [ "$PIN" != "$rev" ]; then + die "Platform crates are pinned to different revs: expected all of ${PINNED_CRATES[*]} to share one rev, but found '$PIN' and '$rev'. A split pin means two different migration histories can reach the same database file." + fi +done + +note "Pinned platform rev: $PIN" +note "Target branch: $TARGET_BRANCH" + +# -------------------------------------------------------------------------- +# 2. Fetch just enough of the platform repo. +# -------------------------------------------------------------------------- +# +# --filter=tree:0 fetches the full commit graph and no trees/blobs: a few +# megabytes and a couple of seconds, versus a multi-gigabyte full clone. +# Ancestry needs only commits; the migration blobs are pulled on demand through +# the promisor remote when git cat-file asks for them below. +# +# Deliberately NOT --depth=1: a shallow fetch has no ancestry to check. + +mkdir -p "$CACHE_DIR" +if [ ! -d "$CACHE_DIR/.git" ]; then + git init -q "$CACHE_DIR" + git -C "$CACHE_DIR" remote add origin "$PLATFORM_REMOTE" +else + git -C "$CACHE_DIR" remote set-url origin "$PLATFORM_REMOTE" +fi + +note "Fetching $PLATFORM_REMOTE ($TARGET_BRANCH + pinned rev) into $CACHE_DIR" +if ! git -C "$CACHE_DIR" fetch -q --filter=tree:0 origin "$TARGET_BRANCH" "$PIN"; then + die "Failed to fetch branch '$TARGET_BRANCH' and rev '$PIN' from $PLATFORM_REMOTE. Either the branch no longer exists (update TARGET_BRANCH at the top of this script), the pinned rev was force-pushed away upstream, or the runner has no network access." +fi + +BRANCH_REF="refs/remotes/origin/$TARGET_BRANCH" +BRANCH_TIP="$(git -C "$CACHE_DIR" rev-parse "$BRANCH_REF")" +note "Branch tip: $BRANCH_TIP" + +# -------------------------------------------------------------------------- +# 3. Ancestry. +# -------------------------------------------------------------------------- + +if ! git -C "$CACHE_DIR" merge-base --is-ancestor "$PIN" "$BRANCH_REF"; then + die "Pinned platform rev $PIN is NOT an ancestor of $TARGET_BRANCH (tip $BRANCH_TIP). +The pin sits on a side branch, so its wallet-storage migration history can diverge from the released line — exactly the failure that forced the platform_compatibility bridge into DET. +Move the pin to a commit on $TARGET_BRANCH, or, if the release line itself has advanced, update TARGET_BRANCH at the top of this script." +fi +note "Ancestry OK: pin is on $TARGET_BRANCH" + +# -------------------------------------------------------------------------- +# 4. Fingerprint of the rendered migration sources. +# -------------------------------------------------------------------------- + +mapfile -t MIGRATION_FILES < <( + git -C "$CACHE_DIR" ls-tree -r --name-only "$PIN" -- "$MIGRATIONS_DIR" | LC_ALL=C sort +) + +if [ "${#MIGRATION_FILES[@]}" -eq 0 ]; then + die "No migration files found under '$MIGRATIONS_DIR' at rev $PIN. Upstream most likely moved or renamed that directory, and fingerprinting an empty set would pass silently forever. Update MIGRATIONS_DIR at the top of this script." +fi + +# Per-file digests rather than one digest over a concatenation: when the check +# fails, the listing names exactly which migration moved. +LISTING="$( + for f in "${MIGRATION_FILES[@]}"; do + digest="$(git -C "$CACHE_DIR" cat-file blob "$PIN:$f" | sha256sum | cut -d' ' -f1)" + printf '%s %s\n' "$digest" "$f" + done +)" +FINGERPRINT="$(printf '%s\n' "$LISTING" | sha256sum | cut -d' ' -f1)" + +note "Migration files: ${#MIGRATION_FILES[@]}" +note "Fingerprint: $FINGERPRINT" + +if [ "$MODE" = print ]; then + printf '%s\n' "$LISTING" + exit 0 +fi + +if [ "$MODE" = update ]; then + cat >"$EXPECTED_FILE" < " listing of every +# file under $MIGRATIONS_DIR at that rev. +pin=$PIN +target_branch=$TARGET_BRANCH +migration_count=${#MIGRATION_FILES[@]} +fingerprint=$FINGERPRINT +EOF + note "Wrote $EXPECTED_FILE" + exit 0 +fi + +[ -f "$EXPECTED_FILE" ] || die "Expected-fingerprint file is missing: $EXPECTED_FILE. Create the baseline with: $0 --update" + +read_key() { sed -nE "s/^$1=(.*)$/\1/p" "$EXPECTED_FILE" | head -n1; } +EXPECTED_PIN="$(read_key pin)" +EXPECTED_FINGERPRINT="$(read_key fingerprint)" + +[ -n "$EXPECTED_FINGERPRINT" ] || die "No 'fingerprint=' line in $EXPECTED_FILE. Recreate it with: $0 --update" + +if [ "$FINGERPRINT" != "$EXPECTED_FINGERPRINT" ]; then + printf '%s\n' "$LISTING" >&2 + if [ "$EXPECTED_PIN" = "$PIN" ]; then + die "Migration fingerprint changed WITHOUT the platform pin changing (still $PIN). +Upstream rewrote the contents of an already-released migration in place. Every DET profile that ran the old version now holds a schema whose checksum the new code rejects, and repinning cannot undo that — it needs a compatibility bridge like src/wallet_backend/platform_compatibility/. + expected $EXPECTED_FINGERPRINT + actual $FINGERPRINT +Per-file digests are listed above." + fi + die "Migration fingerprint does not match the recorded baseline. + pin: recorded $EXPECTED_PIN -> current $PIN + fingerprint: recorded $EXPECTED_FINGERPRINT -> current $FINGERPRINT +If this repin is intentional, confirm the migration diff between the two revs is additive (new V0NN files only, no edits to existing ones), then record it: + $0 --update +Per-file digests are listed above." +fi + +note "Fingerprint OK: matches $EXPECTED_FILE" +note "Platform pin guard passed." diff --git a/scripts/migration-fixtures/download-fixtures.sh b/scripts/migration-fixtures/download-fixtures.sh new file mode 100755 index 000000000..a9c1968df --- /dev/null +++ b/scripts/migration-fixtures/download-fixtures.sh @@ -0,0 +1,269 @@ +#!/usr/bin/env bash +# +# Fetch migration fixture archives named by tests/migration-fixtures/manifest.json +# into a local directory, for MIGRATION_FIXTURES_DIR to point at. +# +# scripts/migration-fixtures/download-fixtures.sh --dest "$RUNNER_TEMP/fixtures" +# +# WHY THIS IS NOT `actions/download-artifact` +# ------------------------------------------- +# Fixtures are stored as GitHub Actions build artifacts, not Release assets (a +# deliberate decision in the migration-matrix plan). The consequence is that the +# artifact a matrix run needs was almost never produced by that run: the v0.9.3 +# baseline is uploaded once and then consumed by every future run, and each +# release's fixture is uploaded by the capture job that follows that release. +# `actions/download-artifact` without a `run-id` only sees the CURRENT run's +# artifacts, so it finds nothing here. It does accept `run-id` + `github-token` +# for cross-run downloads, but only one artifact per step and only when the id +# is already known at YAML-authoring time, which it is not — it lives in the +# manifest. +# +# So resolution happens here, in order: +# 1. the manifest entry carries an explicit run id -> download from that exact +# run. No guessing; the manifest is the durable pointer, which is the whole +# reason it is committed to the repo. +# 2. otherwise -> search the newest successful run of the named workflow for +# an artifact of the given name. Weaker (a re-run can shift which run holds +# it) but it keeps a manifest entry usable before anyone records a run id. +# +# `dawidd6/action-download-artifact` is the well-known third-party action for +# case 2 and would work. It is avoided deliberately: this job downloads data +# that later gets executed against a real binary, so the fewer third parties in +# that path the better, and `gh` gives exact run-id resolution that a +# name-pattern search cannot. If a maintainer later prefers the action, it is a +# drop-in replacement for this script's fallback branch only. +# +# ARTIFACT RETENTION is the standing hazard: artifacts expire (90 days by +# default). An entry whose artifact has expired resolves to nothing and is +# reported as such rather than silently skipped — see --strict. + +set -euo pipefail + +MANIFEST="" +DEST="" +REPO="${GITHUB_REPOSITORY:-dashpay/dash-evo-tool}" +STRICT=0 + +die() { + echo "::error::$*" >&2 + exit 1 +} +warn() { echo "::warning::$*" >&2; } +note() { echo "==> $*"; } + +usage() { + cat <<'EOF' +usage: download-fixtures.sh --dest DIR [options] + + --dest DIR directory to download and unpack fixtures into (required) + --manifest PATH manifest to read (default: tests/migration-fixtures/manifest.json) + --repo OWNER/NAME repository owning the artifacts (default: $GITHUB_REPOSITORY) + --strict exit non-zero when the manifest is empty or any entry + cannot be resolved (default: warn and continue) +EOF +} + +while [ $# -gt 0 ]; do + case "$1" in + --dest) + DEST="${2:-}" + shift + ;; + --manifest) + MANIFEST="${2:-}" + shift + ;; + --repo) + REPO="${2:-}" + shift + ;; + --strict) STRICT=1 ;; + -h | --help) + usage + exit 0 + ;; + *) + usage >&2 + die "unknown argument '$1'" + ;; + esac + shift +done + +[ -n "$DEST" ] || { + usage >&2 + die "--dest is required" +} +command -v jq >/dev/null 2>&1 || die "jq is required but not installed." +command -v gh >/dev/null 2>&1 || die "the GitHub CLI (gh) is required but not installed." + +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd -- "$SCRIPT_DIR/../.." && pwd)" +MANIFEST="${MANIFEST:-$REPO_ROOT/tests/migration-fixtures/manifest.json}" + +mkdir -p "$DEST" +DEST="$(cd -- "$DEST" && pwd)" + +# The manifest is owned by the fixture-capture workstream and may legitimately +# not exist yet. Treat absent and empty the same way. +if [ ! -f "$MANIFEST" ]; then + if [ "$STRICT" -eq 1 ]; then + die "Manifest not found: $MANIFEST" + fi + warn "No fixture manifest at $MANIFEST — nothing to download." + exit 0 +fi + +# Accept either a bare array or an object with a "fixtures" array, so the schema +# can settle without breaking this reader. +ENTRIES="$(jq -c 'if type == "array" then . else (.fixtures // []) end | .[]' "$MANIFEST" 2>/dev/null)" || + die "Manifest $MANIFEST is not valid JSON." + +if [ -z "$ENTRIES" ]; then + if [ "$STRICT" -eq 1 ]; then + die "Manifest $MANIFEST lists no fixtures." + fi + warn "Manifest $MANIFEST lists no fixtures yet — nothing to download." + exit 0 +fi + +resolved=0 +failed=0 + +while IFS= read -r entry; do + [ -n "$entry" ] || continue + + get() { echo "$entry" | jq -r "$1 // empty"; } + + id="$(get '.id')" + id="${id:-$(get '.git_tag')}" + id="${id:-unnamed}" + # The `artifact.*` keys documented in tests/migration-fixtures/README.md + # come first; the rest are shapes this reader accepted before that schema + # settled, kept so an older entry still resolves. + artifact_name="$(get '.artifact.artifact_name')" + artifact_name="${artifact_name:-$(get '.artifact.name')}" + artifact_name="${artifact_name:-$(get '.artifact_name')}" + run_id="$(get '.artifact.workflow_run_id')" + run_id="${run_id:-$(get '.artifact.run_id')}" + run_id="${run_id:-$(get '.run_id')}" + workflow="$(get '.artifact.workflow_name')" + workflow="${workflow:-$(get '.artifact.workflow')}" + workflow="${workflow:-$(get '.workflow')}" + expected_sha="$(get '.artifact.sha256')" + expected_sha="${expected_sha:-$(get '.archive.sha256')}" + expected_sha="${expected_sha:-$(get '.sha256')}" + expected_file="$(get '.artifact.archive_filename')" + + note "Fixture '$id'" + + if [ "$STRICT" -eq 1 ] && [[ ! "$expected_sha" =~ ^[0-9a-fA-F]{64}$ ]]; then + warn "Fixture '$id' needs a valid sha256 in strict mode — skipping." + failed=$((failed + 1)) + continue + fi + expected_sha="${expected_sha,,}" + + if [ -z "$artifact_name" ]; then + warn "Fixture '$id' has no artifact name in the manifest — skipping." + failed=$((failed + 1)) + continue + fi + + # --- resolve the run holding the artifact ----------------------------- + if [ -z "$run_id" ]; then + if [ -z "$workflow" ]; then + warn "Fixture '$id' gives neither an artifact run id nor a workflow to search — skipping." + failed=$((failed + 1)) + continue + fi + note " no run id recorded; searching newest successful run of $workflow" + run_id="$(gh api "repos/$REPO/actions/workflows/$workflow/runs?status=success&per_page=50" \ + --jq '.workflow_runs | sort_by(.run_started_at) | reverse | .[0].id // empty' 2>/dev/null || true)" + if [ -z "$run_id" ]; then + warn "Fixture '$id': no successful run of $workflow found in $REPO — skipping." + failed=$((failed + 1)) + continue + fi + fi + + # An expired artifact still appears in the API with expired == true, and + # downloading it fails with an unhelpful 410. Say so plainly instead. + expired="$(gh api "repos/$REPO/actions/runs/$run_id/artifacts?per_page=100" \ + --jq ".artifacts[] | select(.name == \"$artifact_name\") | .expired" 2>/dev/null | head -n1 || true)" + if [ -z "$expired" ]; then + warn "Fixture '$id': artifact '$artifact_name' is not present in run $run_id of $REPO. It may have been deleted, or the run id in the manifest may be stale." + failed=$((failed + 1)) + continue + fi + if [ "$expired" = "true" ]; then + warn "Fixture '$id': artifact '$artifact_name' in run $run_id has EXPIRED. Re-capture it, or re-upload it to refresh its retention window." + failed=$((failed + 1)) + continue + fi + + # Download into a per-fixture staging directory rather than straight into + # $DEST: it keeps two fixtures from colliding on a shared file name, and it + # makes "which file did THIS entry produce" an exact answer rather than a + # guess based on modification times. + safe_id="$(printf '%s' "$id" | tr -c 'A-Za-z0-9._-' '-')" + stage="$DEST/.staging-$safe_id" + rm -rf "$stage" + mkdir -p "$stage" + + note " downloading '$artifact_name' from run $run_id" + if ! gh run download "$run_id" --repo "$REPO" --name "$artifact_name" --dir "$stage"; then + warn "Fixture '$id': download of '$artifact_name' from run $run_id failed." + rm -rf "$stage" + failed=$((failed + 1)) + continue + fi + + mapfile -t archives < <(find "$stage" -type f \( -name '*.tar.zst' -o -name '*.tar.gz' \) | LC_ALL=C sort) + if [ "${#archives[@]}" -ne 1 ]; then + warn "Fixture '$id': expected exactly one .tar.zst/.tar.gz inside artifact '$artifact_name', found ${#archives[@]}." + rm -rf "$stage" + failed=$((failed + 1)) + continue + fi + archive_path="${archives[0]}" + + # The harness locates the archive by this name, so a mismatch here would + # only resurface later as a less specific "archive not found". + if [ -n "$expected_file" ] && [ "$(basename -- "$archive_path")" != "$expected_file" ]; then + warn "Fixture '$id': artifact '$artifact_name' holds $(basename -- "$archive_path"), but the manifest names $expected_file." + rm -rf "$stage" + failed=$((failed + 1)) + continue + fi + + # --- integrity -------------------------------------------------------- + if [ -n "$expected_sha" ]; then + actual_sha="$(sha256sum "$archive_path" | cut -d' ' -f1)" + if [ "$actual_sha" != "$expected_sha" ]; then + die "Fixture '$id': checksum mismatch on $(basename -- "$archive_path"). + manifest $expected_sha + actual $actual_sha +The artifact does not match what the manifest describes. Refusing to run migration tests against unverified fixture data." + fi + note " checksum OK" + else + warn "Fixture '$id' records no sha256 — downloaded archive is unverified." + fi + + mv "$archive_path" "$DEST/" + # Keep the .sha256 sidecar pack.sh emitted, if the artifact carried it. + find "$stage" -type f -name '*.sha256' -exec mv -t "$DEST/" {} + + rm -rf "$stage" + + resolved=$((resolved + 1)) +done <<<"$ENTRIES" + +note "Resolved $resolved fixture(s) into $DEST; $failed unresolved." + +if [ "$failed" -gt 0 ] && [ "$STRICT" -eq 1 ]; then + die "$failed fixture(s) in $MANIFEST could not be resolved." +fi +if [ "$resolved" -eq 0 ] && [ "$STRICT" -eq 1 ]; then + die "No fixtures could be resolved from $MANIFEST." +fi diff --git a/scripts/migration-fixtures/expected-migration-fingerprint.txt b/scripts/migration-fixtures/expected-migration-fingerprint.txt new file mode 100644 index 000000000..37ab43fa6 --- /dev/null +++ b/scripts/migration-fixtures/expected-migration-fingerprint.txt @@ -0,0 +1,11 @@ +# Fingerprint of the platform-wallet-storage migration sources at the pinned rev. +# +# Regenerate ONLY as a deliberate part of a repin, and read the resulting diff: +# scripts/migration-fixtures/check-pin-ancestry.sh --update +# +# fingerprint = sha256 of the LC_ALL=C-sorted " " listing of every +# file under packages/rs-platform-wallet-storage/migrations at that rev. +pin=63cf57f40d0000bf3b2b26026c8fa1c71162852d +target_branch=v4.2-dev +migration_count=18 +fingerprint=1c6a683d1b781045f4528048b49b1e945f4da6caeb71e72d8de7429904399b99 diff --git a/scripts/migration-fixtures/pack.sh b/scripts/migration-fixtures/pack.sh new file mode 100755 index 000000000..ad40824c6 --- /dev/null +++ b/scripts/migration-fixtures/pack.sh @@ -0,0 +1,136 @@ +#!/usr/bin/env bash +# +# Pack a DASH_EVO_DATA_DIR-style data directory into a migration fixture archive. +# +# scripts/migration-fixtures/pack.sh +# +# is a path WITHOUT extension; the script appends .tar.zst when +# zstd is available and .tar.gz otherwise, and writes a matching .sha256 next to +# it. The final archive path is echoed on stdout as the last line, and exported +# as archive/sha256/format to $GITHUB_OUTPUT when running under Actions. +# +# Excluded from the archive: +# spv/ chain data — hundreds of MB, re-synced from the network anyway +# backups/ DET's own pre-migration copies; a fixture must capture the state +# the app is asked to migrate, not a previous migration's leftovers +# *.log runtime noise, and the most likely place for stray secrets +# +# Archives are built with reproducible tar flags so that re-packing an unchanged +# directory produces a byte-identical file and the .sha256 stays meaningful. + +set -euo pipefail + +die() { + echo "::error::$*" >&2 + exit 1 +} + +note() { echo "==> $*"; } + +[ $# -eq 2 ] || die "usage: $0 + a DASH_EVO_DATA_DIR to pack (must contain .env) + output path without extension, e.g. out/fixture-v0.9.3-testnet" + +DATA_DIR="$1" +OUT_PREFIX="$2" + +[ -d "$DATA_DIR" ] || die "Data directory does not exist: $DATA_DIR" +DATA_DIR="$(cd -- "$DATA_DIR" && pwd)" + +# A data dir with no .env is almost always a typo'd path or a capture that never +# got as far as initialising the app. Packing it would produce a fixture that +# fails at boot for reasons unrelated to migration. +[ -f "$DATA_DIR/.env" ] || die "No .env in $DATA_DIR — this does not look like an initialised DET data directory. Run the capture script first." + +# -------------------------------------------------------------------------- +# Secret check. +# -------------------------------------------------------------------------- +# +# Fixtures are published as build artifacts that anyone with read access to the +# repo can download. MCP_API_KEY authorises control of a running DET instance, +# so shipping a live one inside a fixture is a credential leak. The fixture +# wallet's own seed is a different matter: it is a deliberately public +# testnet-only wallet, and the vault is the thing under test. +credential_keys="$(awk ' + /^[[:space:]]*(#|$)/ { next } + /=/ { + key = substr($0, 1, index($0, "=") - 1) + sub(/^[[:space:]]*(export[[:space:]]+)?/, "", key) + sub(/[[:space:]]+$/, "", key) + name = tolower(key) + if (name != "mcp_api_key" && name !~ /_(core_rpc_(user|password)|wallet_private_key)$/) next + value = substr($0, index($0, "=") + 1) + sub(/^[[:space:]]+/, "", value) + sub(/[[:space:]]+#.*$/, "", value) + sub(/[[:space:]]+$/, "", value) + if (value != "" && value != "\"\"" && value != "\047\047") print key + } +' "$DATA_DIR/.env")" +if [ -n "$credential_keys" ]; then + die "Refusing to pack: $DATA_DIR/.env contains credential settings: +$credential_keys +Blank these settings in the capture copy before publishing, then re-run." +fi + +# -------------------------------------------------------------------------- +# Format selection. +# -------------------------------------------------------------------------- + +if command -v zstd >/dev/null 2>&1; then + FORMAT="tar.zst" + COMPRESS=(--zstd) +else + note "zstd not found — falling back to gzip" + FORMAT="tar.gz" + COMPRESS=(--gzip) +fi + +ARCHIVE="${OUT_PREFIX}.${FORMAT}" +OUT_DIR="$(dirname -- "$ARCHIVE")" +mkdir -p "$OUT_DIR" +OUT_DIR="$(cd -- "$OUT_DIR" && pwd)" +ARCHIVE="$OUT_DIR/$(basename -- "$ARCHIVE")" + +# -------------------------------------------------------------------------- +# Pack. +# -------------------------------------------------------------------------- +# +# --sort=name, a fixed --mtime and zeroed ownership make the archive a pure +# function of the directory contents. Without them the same data dir packs to a +# different checksum on every run and the .sha256 only proves "nothing was +# corrupted in transit", not "this is the fixture the manifest names". +# +# -C "$DATA_DIR" . stores paths relative to the data dir, so unpacking with +# `tar -xf archive -C "$target"` yields a usable DASH_EVO_DATA_DIR directly. + +note "Packing $DATA_DIR -> $ARCHIVE" +tar \ + --create \ + "${COMPRESS[@]}" \ + --file "$ARCHIVE" \ + --directory "$DATA_DIR" \ + --exclude="./spv" \ + --exclude="./backups" \ + --exclude="*.log" \ + --sort=name \ + --mtime="@0" \ + --owner=0 --group=0 --numeric-owner \ + . + +SHA="$(sha256sum "$ARCHIVE" | cut -d' ' -f1)" +# Basename-relative so `cd "$(dirname archive)" && sha256sum -c archive.sha256` +# verifies wherever the pair is later downloaded to. +printf '%s %s\n' "$SHA" "$(basename -- "$ARCHIVE")" >"$ARCHIVE.sha256" + +note "Size: $(du -h "$ARCHIVE" | cut -f1)" +note "sha256: $SHA" + +if [ -n "${GITHUB_OUTPUT:-}" ]; then + { + echo "archive=$ARCHIVE" + echo "sha256=$SHA" + echo "format=$FORMAT" + } >>"$GITHUB_OUTPUT" +fi + +echo "$ARCHIVE" diff --git a/scripts/migration-fixtures/semver.jq b/scripts/migration-fixtures/semver.jq new file mode 100644 index 000000000..78bd87857 --- /dev/null +++ b/scripts/migration-fixtures/semver.jq @@ -0,0 +1,10 @@ +# SemVer precedence ignores build metadata and orders final releases last. +def semver_key: + . as $tag | + capture("^v?(?0|[1-9][0-9]*)\\.(?0|[1-9][0-9]*)\\.(?0|[1-9][0-9]*)(?:-(?
[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$") // error("Invalid release tag: \($tag)") |
+    [(.major | tonumber), (.minor | tonumber), (.patch | tonumber),
+     (if .pre == null then 1 else 0 end),
+     ((.pre // "") | split(".") | map(
+         if test("^[0-9]+$") then
+             if test("^0[0-9]") then error("Invalid prerelease: \($tag)") else tonumber end
+         else . end))];
diff --git a/scripts/migration-fixtures/test-scripts.sh b/scripts/migration-fixtures/test-scripts.sh
new file mode 100644
index 000000000..22ab490b3
--- /dev/null
+++ b/scripts/migration-fixtures/test-scripts.sh
@@ -0,0 +1,111 @@
+#!/usr/bin/env bash
+# Offline regression checks; all inputs and artifacts are disposable.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
+scratch="$(mktemp -d "${TMPDIR:-${RUNNER_TEMP:-/data/tmp}}/migration-script-tests.XXXXXX")"
+trap 'rm -rf "$scratch"' EXIT
+mkdir -p "$scratch/data" "$scratch/bin"
+
+fail() { echo "FAIL: $*" >&2; exit 1; }
+printf 'MCP_API_KEY=\nTESTNET_core_rpc_password=""\nTESTNET_core_rpc_user=\n' > "$scratch/data/.env"
+bash "$SCRIPT_DIR/pack.sh" "$scratch/data" "$scratch/clean" > "$scratch/pack.log"
+for key in MCP_API_KEY TESTNET_core_rpc_password MAINNET_core_rpc_user LOCAL_wallet_private_key; do
+    # Generated disposable text, never an operator credential.
+    printf '%s=%s\n' "$key" "$RANDOM-$RANDOM" > "$scratch/data/.env"
+    if bash "$SCRIPT_DIR/pack.sh" "$scratch/data" "$scratch/rejected" > "$scratch/pack.log" 2>&1; then
+        fail "pack accepted $key"
+    fi
+    grep -Fq "$key" "$scratch/pack.log" || fail "pack did not identify $key"
+done
+printf ' export TESTNET_core_rpc_password = "" # empty\nMCP_API_KEY=\n' > "$scratch/data/.env"
+bash "$SCRIPT_DIR/pack.sh" "$scratch/data" "$scratch/clean-export" > "$scratch/pack.log"
+echo 'PASS: fixture credential checks'
+
+if bash "$SCRIPT_DIR/capture-headless.sh" --network mainnet --data-dir "$scratch/capture" > "$scratch/capture.log" 2>&1; then
+    fail 'capture accepted mainnet'
+fi
+grep -q 'must be captured on testnet' "$scratch/capture.log" || fail 'testnet guard did not run first'
+echo 'PASS: capture testnet guard'
+
+cat > "$scratch/bin/det-cli" <<'EOF'
+#!/usr/bin/env bash
+set -euo pipefail
+[ "${1:-}" = --standalone ] || exit 1
+shift
+case "$1" in
+    network-info)
+        if [ -f "$DASH_EVO_DATA_DIR/network-choice" ]; then
+            echo '{"active":"testnet"}'
+        else
+            echo '{"active":"mainnet"}'
+        fi ;;
+
+    core-wallet-import | core-balances-get) echo '{}' ;;
+    network-switch)
+        if [ "${FORGET_NETWORK:-0}" != 1 ]; then
+            touch "$DASH_EVO_DATA_DIR/network-choice"
+        fi
+        echo '{"active":"testnet"}' ;;
+
+    core-address-create) echo '{"address":"mock-address"}' ;;
+    platform-addresses-list) echo '{"balances":[{}]}' ;;
+    *) exit 1 ;;
+esac
+EOF
+chmod +x "$scratch/bin/det-cli"
+mkdir -p "$scratch/capture"
+printf 'MCP_API_KEY=%s\n' "$RANDOM-$RANDOM" > "$scratch/capture/.env"
+FIXTURE_WALLET_MNEMONIC="$RANDOM-$RANDOM" bash "$SCRIPT_DIR/capture-headless.sh" \
+    --data-dir "$scratch/capture" --det-cli "$scratch/bin/det-cli" > "$scratch/capture.log" 2>&1 || fail 'capture did not force standalone mode'
+echo 'PASS: capture standalone mode'
+if FORGET_NETWORK=1 FIXTURE_WALLET_MNEMONIC="$RANDOM-$RANDOM" bash "$SCRIPT_DIR/capture-headless.sh" \
+    --data-dir "$scratch/forget-network" --det-cli "$scratch/bin/det-cli" > "$scratch/forget-network.log" 2>&1; then
+    fail 'capture accepted a network switch lost on restart'
+fi
+grep -q 'did not survive restart' "$scratch/forget-network.log" || fail 'capture did not report lost network selection'
+echo 'PASS: capture rejects a network switch lost on restart'
+
+
+cat > "$scratch/bin/gh" <<'EOF'
+#!/usr/bin/env bash
+set -euo pipefail
+printf 'called\n' >> "$GH_CALL_LOG"
+case "$*" in
+    *'/releases'*) printf '%s\n' "$TEST_RELEASES" ;;
+    *'/tags'*) printf '%s\n' "$TEST_RELEASES" ;;
+    *) exit 1 ;;
+esac
+EOF
+chmod +x "$scratch/bin/gh"
+export PATH="$scratch/bin:$PATH" GH_CALL_LOG="$scratch/gh.log"
+for digest in '' invalid; do
+    jq -n --arg sha "$digest" '{fixtures:[{id:"test",artifact:{artifact_name:"fixture",workflow_run_id:1,sha256:$sha}}]}' > "$scratch/manifest.json"
+    if bash "$SCRIPT_DIR/download-fixtures.sh" --manifest "$scratch/manifest.json" --dest "$scratch/download" --strict > "$scratch/download.log" 2>&1; then
+        fail 'strict downloader accepted invalid digest'
+    fi
+    grep -q 'valid sha256' "$scratch/download.log" || fail 'digest validation did not fail first'
+    [ ! -e "$GH_CALL_LOG" ] || fail 'invalid digest reached the network'
+done
+echo 'PASS: strict digest validation before network access'
+
+check_coverage() {
+    local baseline="$1" release="$2" expected="$3"
+    jq -n --arg tag "$baseline" '{fixtures:[{git_tag:$tag}]}' > "$scratch/manifest.json"
+    export TEST_RELEASES="$release"
+    local result=0
+    bash "$SCRIPT_DIR/check-coverage.sh" --manifest "$scratch/manifest.json" --enforce-after "$baseline" > "$scratch/coverage.log" 2>&1 || result=$?
+    if [ "$expected" = missing ]; then
+        [ "$result" -ne 0 ] || fail "coverage missed $release after $baseline"
+        grep -q 'Published releases with no migration fixture' "$scratch/coverage.log" || fail 'coverage failed for an unrelated reason'
+    else
+        [ "$result" -eq 0 ] || fail "coverage incorrectly requires $release after $baseline"
+    fi
+}
+check_coverage v1.0.0-weekly.20260908 v1.0.0 missing
+check_coverage v1.0.0 v1.0.0-weekly.20260908 covered
+check_coverage v1.0.0-weekly.9 v1.0.0-weekly.10 missing
+check_coverage v1.0.0-beta.11 v1.0.0-rc.1 missing
+check_coverage v1.9.0 v1.10.0 missing
+check_coverage v1.0.0+one v1.0.0+two covered
+echo 'PASS: release precedence coverage'
diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs
index b5e17062d..dc9d6e847 100644
--- a/src/backend_task/error.rs
+++ b/src/backend_task/error.rs
@@ -2567,6 +2567,18 @@ pub enum TaskError {
         source: std::sync::Arc,
     },
 
+    /// A non-interactive storage update was given a wallet password that does
+    /// not open every password-protected wallet. No wallet is skipped on the
+    /// user's behalf, so the update stays unfinished until it is retried with
+    /// the right password or finished in the desktop app.
+    #[error(
+        "The password does not open every password-protected wallet. Check the password and try again, or open the Dash Evo Tool desktop app to finish the storage update."
+    )]
+    StorageUpdatePasswordRejected {
+        #[source]
+        source: std::sync::Arc,
+    },
+
     /// An HD wallet seed envelope decoded cleanly but its plaintext
     /// length is not the expected 64 bytes. Surfaced when the cold-boot
     /// hydration path would otherwise have silently degraded the
@@ -2689,8 +2701,10 @@ pub enum TaskError {
     /// A secret was needed but no interactive prompt is available in this
     /// context — the operation ran headless (MCP / CLI), where there is no
     /// window to ask for a passphrase. Per the Q-HEADLESS security ruling
-    /// there is no environment-variable or flag fallback for the
-    /// passphrase, so the operation cannot proceed here. Fieldless: this
+    /// there is no environment-variable or flag fallback for a signing
+    /// passphrase, so the operation cannot proceed here. Only the storage
+    /// update accepts a password non-interactively (`app_storage_update`),
+    /// and it does not go through this path. Fieldless: this
     /// carries no upstream diagnostic and, by design, never any secret.
     #[error(
         "This wallet is protected by a passphrase, which can only be entered in the app window. Open Dash Evo Tool and run this action there."
diff --git a/src/backend_task/migration/finish_unwire.rs b/src/backend_task/migration/finish_unwire.rs
index a448696ef..b6261970b 100644
--- a/src/backend_task/migration/finish_unwire.rs
+++ b/src/backend_task/migration/finish_unwire.rs
@@ -13,15 +13,17 @@ use std::sync::Arc;
 use dash_sdk::dpp::dashcore::Network;
 use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
 use dash_sdk::platform::Identifier;
+use platform_wallet_storage::secrets::SecretString;
 use rusqlite::Connection;
 use serde::{Deserialize, Serialize};
 
 use crate::backend_task::dapi_discovery::persist_dapi_addresses;
 use crate::backend_task::error::TaskError;
-use crate::context::AppContext;
 use crate::context::migration_status::{MigrationState, MigrationStep};
+use crate::context::{AppContext, WalletUnlockRetention};
 use crate::model::qualified_identity::QualifiedIdentity;
 use crate::model::wallet::WalletSeedHash;
+use crate::wallet_backend::secret_access::is_wrong_passphrase;
 use crate::wallet_backend::{DetScope, KvAdapterError, network_prefix};
 
 /// Sentinel key format string. The migration body filters every
@@ -277,6 +279,27 @@ pub enum MigrationError {
     )]
     InteractivePromptUnavailable,
 
+    /// The password supplied for a non-interactive storage update does not
+    /// open one of the password-protected wallets. Nothing is skipped on the
+    /// user's behalf: the completion sentinel is withheld, and the update can
+    /// be retried with the right password or finished in the desktop app.
+    #[error(
+        "The password does not open every password-protected wallet. Check the password and try again, or open the Dash Evo Tool desktop app to finish the storage update."
+    )]
+    WalletPasswordRejected {
+        #[source]
+        source: Box,
+    },
+
+    /// A supplied password could not open a wallet for a reason other than the
+    /// password itself: the vault read or the re-seal under that password
+    /// failed. The completion sentinel is withheld so a re-run retries.
+    #[error("could not open a password-protected wallet with the supplied password")]
+    WalletUnlockFailed {
+        #[source]
+        source: Box,
+    },
+
     /// A pass reported an error that is not a [`MigrationError`]. Every pass is
     /// meant to report through one of the typed variants above; this catch-all
     /// exists so a stray error still reaches a terminal banner. Leaving one
@@ -347,7 +370,8 @@ pub(crate) fn migration_error_chain(error: TaskError) -> Arc {
         TaskError::MigrationFailed { source }
         | TaskError::SavedDataTooOld { source }
         | TaskError::SavedDataTooNew { source }
-        | TaskError::StorageUpdateNeedsDesktop { source } => source,
+        | TaskError::StorageUpdateNeedsDesktop { source }
+        | TaskError::StorageUpdatePasswordRejected { source } => source,
         other => Arc::new(MigrationError::Unexpected {
             source: Box::new(other),
         }),
@@ -603,7 +627,8 @@ pub async fn run(app_context: &Arc) -> Result {
         Err(_) => {
             let guard = app_context.lock_prepare_gate().await;
             match app_context.migration_status().state().as_ref() {
-                MigrationState::Failed { error } => {
+                MigrationState::Failed { error }
+                | MigrationState::FailedWithUnreadableIdentities { error, .. } => {
                     let result = Err(super::migration_task_error(Arc::clone(error)));
                     drop(guard);
                     return result;
@@ -617,7 +642,7 @@ pub async fn run(app_context: &Arc) -> Result {
         }
     };
 
-    run_gated(app_context, &_run_guard).await
+    run_gated(app_context, &_run_guard, None).await
 }
 
 /// The drain body, for a caller that already owns
@@ -630,14 +655,19 @@ pub async fn run(app_context: &Arc) -> Result {
 /// guard parameter is proof, not decoration: without it this function is a
 /// silently unguarded copy of [`run`] that any future caller could reach.
 ///
+/// `wallet_password` is the non-interactive storage update's password for the
+/// password-protected wallets; see [`register_migrated_wallets`].
+///
 /// # Errors
 ///
-/// Same as [`run`].
+/// Same as [`run`], plus [`TaskError::StorageUpdatePasswordRejected`] when
+/// `wallet_password` does not open every locked wallet.
 pub(crate) async fn run_gated(
     app_context: &Arc,
     _gate: &crate::context::PrepareGateGuard<'_>,
+    wallet_password: Option<&SecretString>,
 ) -> Result {
-    match run_under_guard(app_context).await {
+    match run_under_guard(app_context, wallet_password).await {
         Ok(did_work) => Ok(did_work),
         Err(task_error) => {
             if !app_context.migration_status().state().is_in_progress() {
@@ -668,17 +698,21 @@ where
 }
 
 /// Queues refresh before migration so its waiter acquires the guard at completion.
-async fn run_under_guard(app_context: &Arc) -> Result {
+async fn run_under_guard(
+    app_context: &Arc,
+    wallet_password: Option<&SecretString>,
+) -> Result {
     let ctx = Arc::clone(app_context);
     std::mem::drop(spawn_dapi_refresh(app_context, async move {
         refresh_dapi_nodes_once(&ctx).await;
     }));
-    run_under_guard_with_dapi_refresh(app_context, std::future::ready(())).await
+    run_under_guard_with_dapi_refresh(app_context, std::future::ready(()), wallet_password).await
 }
 
 async fn run_under_guard_with_dapi_refresh(
     app_context: &Arc,
     dapi_refresh: F,
+    wallet_password: Option<&SecretString>,
 ) -> Result
 where
     F: Future,
@@ -703,7 +737,7 @@ where
     // is what restores access to funds, so nothing about DET's own rows may gate
     // it. Propagating here would let one bad vote row wedge the drain on every
     // launch, with no user-reachable way out.
-    let wallet_moved = match drain_wallets(app_context).await {
+    let wallet_moved = match drain_wallets(app_context, wallet_password).await {
         Ok(moved) => moved,
         Err(drain_error) => {
             if let Err(app_data_error) = &app_data {
@@ -921,7 +955,10 @@ where
 /// no-op paths (sentinel already present, or no legacy rows at all). This is
 /// the funds path: [`run`] keeps it free of every DET-owned concern so nothing
 /// but a genuine wallet-migration failure can withhold access to a seed.
-async fn drain_wallets(app_context: &Arc) -> Result {
+async fn drain_wallets(
+    app_context: &Arc,
+    wallet_password: Option<&SecretString>,
+) -> Result {
     let status = app_context.migration_status();
     let app_kv = app_context.app_kv();
     let network = app_context.network;
@@ -996,7 +1033,7 @@ async fn drain_wallets(app_context: &Arc) -> Result
     // wallet is still absent from `det-.sqlite`. On failure
     // this returns `Err` (the sentinel is skipped) so the next cold start — or
     // the "Retry now" banner — re-runs the idempotent migration.
-    register_migrated_wallets(app_context).await?;
+    register_migrated_wallets(app_context, wallet_password).await?;
 
     write_sentinel(&app_kv, network, 1)?;
 
@@ -1044,7 +1081,17 @@ impl Drop for RunSeedLeases<'_> {
 /// and neither ordering is guaranteed. The run therefore holds its own lease on
 /// every seed it prompted for (`WalletUnlockRetention::UntilStorageUpdateComplete`)
 /// rather than depending on the unlock subtask still being alive.
-async fn register_migrated_wallets(app_context: &Arc) -> Result<(), MigrationError> {
+///
+/// `wallet_password` is supplied by the non-interactive storage update: it is
+/// tried on every locked wallet (see [`unlock_with_supplied_password`]) before
+/// any prompt is considered, so a correct one finishes the update headless and
+/// a wrong one fails it immediately. Without it, a headless caller still gets
+/// [`MigrationError::InteractivePromptUnavailable`] at once — nothing here
+/// ever waits for a person who is not there.
+async fn register_migrated_wallets(
+    app_context: &Arc,
+    wallet_password: Option<&SecretString>,
+) -> Result<(), MigrationError> {
     let _seed_leases = RunSeedLeases(app_context);
 
     let backend = app_context
@@ -1070,6 +1117,11 @@ async fn register_migrated_wallets(app_context: &Arc) -> Result<(),
     app_context
         .migration_status()
         .begin_wallet_password_collection();
+    if let Some(password) = wallet_password {
+        unlock_with_supplied_password(app_context, password)?;
+        // Same re-drive the prompt loop below runs after each unlock.
+        app_context.bootstrap_loaded_wallets().await;
+    }
     loop {
         let wallets = app_context
             .migration_status()
@@ -1097,6 +1149,47 @@ async fn register_migrated_wallets(app_context: &Arc) -> Result<(),
     Ok(())
 }
 
+/// Opens every migrated wallet still locked with `password`, through
+/// [`AppContext::handle_wallet_unlocked`] — the verification boundary the
+/// desktop password prompt submits to — and holds each seed until the update
+/// ends, exactly as a prompt unlock does
+/// ([`WalletUnlockRetention::UntilStorageUpdateComplete`]).
+///
+/// One password serves every locked wallet. A wallet it does not open fails
+/// the update with [`MigrationError::WalletPasswordRejected`] instead of being
+/// skipped: skipping is the user's decision, and a mistyped password must not
+/// make it for them. Wallets opened before the rejection stay registered and
+/// protected; the completion sentinel is withheld, so a re-run revisits them.
+fn unlock_with_supplied_password(
+    app_context: &Arc,
+    password: &SecretString,
+) -> Result<(), MigrationError> {
+    let locked = app_context
+        .migration_status()
+        .pending_wallet_passwords(app_context.locked_wallet_hashes());
+    for seed_hash in locked {
+        // A wallet removed since the listing has nothing left to unlock.
+        let Ok(wallet) = app_context.wallet_arc(&seed_hash) else {
+            continue;
+        };
+        app_context
+            .handle_wallet_unlocked(
+                &wallet,
+                password.expose_secret(),
+                WalletUnlockRetention::UntilStorageUpdateComplete,
+            )
+            .map_err(|source| {
+                let source = Box::new(source);
+                if is_wrong_passphrase(&source) {
+                    MigrationError::WalletPasswordRejected { source }
+                } else {
+                    MigrationError::WalletUnlockFailed { source }
+                }
+            })?;
+    }
+    Ok(())
+}
+
 /// Per-network sentinel for the DET app-data import (scheduled votes and
 /// top-up history). Separate from the wallet-drain sentinel on purpose: an
 /// install that already completed the wallet drain under an earlier build
@@ -3120,7 +3213,7 @@ mod tests {
             calls.fetch_add(1, Ordering::SeqCst);
             Err(crate::backend_task::dapi_discovery::DapiDiscoveryError::Timeout)
         });
-        let did_work = run_under_guard_with_dapi_refresh(&ctx, refresh)
+        let did_work = run_under_guard_with_dapi_refresh(&ctx, refresh, None)
             .await
             .expect("DAPI discovery must not fail the migration");
 
@@ -5319,6 +5412,38 @@ mod tests {
         ));
     }
 
+    #[tokio::test]
+    async fn public_migration_follower_returns_the_combined_failure() {
+        let tmp = tempfile::tempdir().expect("tempdir");
+        let ctx = fresh_app_context(tmp.path());
+        let migration_guard = ctx.try_lock_prepare_gate().expect("claim migration lock");
+        let source = Arc::new(MigrationError::WalletBackendUnavailable);
+        ctx.migration_status()
+            .set_state(MigrationState::FailedWithUnreadableIdentities {
+                count: 1,
+                error: Arc::clone(&source),
+            });
+        let follower_ctx = Arc::clone(&ctx);
+        let follower = tokio::spawn(async move { run(&follower_ctx).await });
+        tokio::task::yield_now().await;
+
+        assert!(
+            !follower.is_finished(),
+            "the follower must wait for the leader"
+        );
+        drop(migration_guard);
+        let error = follower
+            .await
+            .expect("join")
+            .expect_err("the follower must return the leader's failure");
+
+        assert!(matches!(
+            error,
+            TaskError::MigrationFailed { source: returned }
+                if Arc::ptr_eq(&returned, &source)
+        ));
+    }
+
     #[test]
     fn identity_deletion_before_migration_is_recorded_for_the_retry_filter() {
         let tmp = tempfile::tempdir().expect("tempdir");
@@ -5974,6 +6099,153 @@ mod tests {
             .await;
     }
 
+    /// Runs the non-interactive storage update exactly as the
+    /// `app_storage_update` MCP tool does, bounded so a regression that waits
+    /// for a person fails instead of hanging.
+    async fn prepare_with_password(ctx: &Arc, password: &str) -> Result<(), TaskError> {
+        let (tx, _rx) = tokio::sync::mpsc::channel::(32);
+        let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, ctx.egui_ctx().clone());
+        let supplied = SecretString::new(password);
+        tokio::time::timeout(
+            std::time::Duration::from_secs(60),
+            ctx.prepare_storage_with_wallet_password(sender, Some(&supplied)),
+        )
+        .await
+        .expect("a non-interactive storage update must never wait for a person")
+    }
+
+    /// A headless caller that supplies the right password finishes the update
+    /// for every protected wallet sharing it: each is registered, keeps its
+    /// password protection, and its seed is forgotten once the update ends.
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn supplied_password_finishes_a_headless_storage_update() {
+        use crate::wallet_backend::SecretScope;
+        use crate::wallet_backend::secret_seam::SecretScheme;
+
+        let tmp = tempfile::tempdir().expect("tempdir");
+        let ctx = fresh_app_context(tmp.path());
+        let password = "shared-headless-password";
+        let wallets = [
+            seed_legacy_protected_wallet(&ctx, &[0xD5; 64], password, "Savings", Network::Testnet),
+            seed_legacy_protected_wallet(&ctx, &[0xD6; 64], password, "Spending", Network::Testnet),
+        ];
+        let legacy_path = tmp.path().join("data.db");
+        let before = std::fs::read(&legacy_path).expect("snapshot legacy database before run");
+        wire_backend(&ctx).await;
+        assert!(
+            !ctx.has_interactive_secret_prompt(),
+            "precondition: a headless context with no password prompt"
+        );
+
+        prepare_with_password(&ctx, password)
+            .await
+            .expect("the right password must finish the storage update headless");
+
+        assert!(
+            read_sentinel(&ctx.app_kv(), Network::Testnet)
+                .expect("read the completion sentinel")
+                .is_some(),
+            "a finished update must record its completion"
+        );
+        let backend = ctx.wallet_backend().expect("backend wired");
+        let store = ctx.secret_store();
+        let view = crate::wallet_backend::WalletSeedView::new(&store);
+        for seed_hash in wallets {
+            assert!(
+                backend.is_wallet_registered(&seed_hash),
+                "every wallet the password opens must be registered"
+            );
+            assert_eq!(
+                view.scheme(&seed_hash).expect("scheme after the update"),
+                SecretScheme::Protected,
+                "a password-protected wallet must stay password-protected"
+            );
+        }
+
+        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
+        while wallets.iter().any(|seed_hash| {
+            backend
+                .secret_access()
+                .is_session_cached(&SecretScope::HdSeed {
+                    seed_hash: *seed_hash,
+                })
+        }) {
+            assert!(
+                tokio::time::Instant::now() < deadline,
+                "a seed unlocked for the storage update must not outlive it"
+            );
+            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+        }
+        assert_eq!(
+            std::fs::read(&legacy_path).expect("snapshot legacy database after run"),
+            before,
+            "the legacy database bytes must never change"
+        );
+
+        backend.shutdown().await;
+    }
+
+    /// One password serves every protected wallet. A wallet it does not open
+    /// fails the whole update at once — nothing is skipped, no completion is
+    /// recorded, no prompt is published — and the rejection never echoes the
+    /// password.
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn a_password_that_does_not_open_every_wallet_fails_closed() {
+        let tmp = tempfile::tempdir().expect("tempdir");
+        let ctx = fresh_app_context(tmp.path());
+        let supplied = "opens-only-the-first-wallet";
+        seed_legacy_protected_wallet(&ctx, &[0xD7; 64], supplied, "Opens", Network::Testnet);
+        let refused = seed_legacy_protected_wallet(
+            &ctx,
+            &[0xD8; 64],
+            "a-different-password",
+            "Refuses",
+            Network::Testnet,
+        );
+        wire_backend(&ctx).await;
+
+        let error = prepare_with_password(&ctx, supplied)
+            .await
+            .expect_err("a password that does not open every wallet must fail");
+
+        match &error {
+            TaskError::StorageUpdatePasswordRejected { source } => assert!(
+                matches!(
+                    source.as_ref(),
+                    MigrationError::WalletPasswordRejected { .. }
+                ),
+                "unexpected source: {source:?}"
+            ),
+            other => panic!("expected the dedicated rejected-password error, got {other:?}"),
+        }
+        assert!(
+            !error.to_string().contains(supplied) && !format!("{error:?}").contains(supplied),
+            "the error must never carry the password"
+        );
+        assert!(
+            read_sentinel(&ctx.app_kv(), Network::Testnet)
+                .expect("read the completion sentinel")
+                .is_none(),
+            "an unfinished update must not record completion"
+        );
+        assert!(
+            ctx.locked_wallet_hashes().contains(&refused),
+            "the wallet the password does not open stays locked"
+        );
+        assert!(
+            !matches!(
+                ctx.migration_status().state().as_ref(),
+                MigrationState::AwaitingWalletPasswords { .. }
+            ),
+            "a headless context must never publish a prompt nobody can render"
+        );
+
+        ctx.wallet_backend()
+            .expect("backend wired")
+            .shutdown()
+            .await;
+    }
+
     /// The old SQLite file is a recovery artifact, not migration-owned state.
     /// A complete run that unlocks one protected wallet and skips another must
     /// leave the file byte-for-byte unchanged, and both copied legacy envelopes
@@ -6320,10 +6592,11 @@ mod tests {
         wire_backend(&ctx).await;
         let backend = ctx.wallet_backend().expect("backend wired");
 
-        let did_work = run(&ctx)
+        let (tx, _rx) = tokio::sync::mpsc::channel(32);
+        let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, ctx.egui_ctx().clone());
+        ctx.prepare_storage(sender.clone())
             .await
-            .expect("both failures are non-fatal to the run — it publishes its own terminal state");
-        assert!(did_work, "the wallet drain moved data");
+            .expect("the combined failure publishes its own state");
 
         // Both signals in one terminal state: the identity count AND the app-data
         // error chain. The pre-fix `SucceededWithUnreadableIdentities` would have
@@ -6368,6 +6641,25 @@ mod tests {
              reported by the durable warning rather than retried forever",
         );
 
+        Connection::open(tmp.path().join("data.db"))
+            .expect("open fixture")
+            .execute_batch("ALTER TABLE top_up ADD COLUMN amount INTEGER NOT NULL DEFAULT 1;")
+            .expect("repair fixture schema");
+        ctx.prepare_storage(sender)
+            .await
+            .expect("retry preparation");
+        assert!(
+            ctx.app_kv()
+                .get::(DetScope::Global, &app_data_sentinel_key_for(network))
+                .expect("read completion")
+                .is_some(),
+            "preparation must retry the unfinished app-data pass"
+        );
+        assert!(matches!(
+            *ctx.migration_status().state(),
+            MigrationState::SucceededWithUnreadableData { identities: 1, .. }
+        ));
+
         backend.shutdown().await;
     }
 
diff --git a/src/backend_task/migration/mod.rs b/src/backend_task/migration/mod.rs
index 36e378a6d..1d1f74877 100644
--- a/src/backend_task/migration/mod.rs
+++ b/src/backend_task/migration/mod.rs
@@ -88,6 +88,9 @@ pub(crate) fn migration_task_error(source: Arc) -> TaskError {
         MigrationError::InteractivePromptUnavailable => {
             TaskError::StorageUpdateNeedsDesktop { source }
         }
+        MigrationError::WalletPasswordRejected { .. } => {
+            TaskError::StorageUpdatePasswordRejected { source }
+        }
         MigrationError::LegacyDataTooOld { .. } => TaskError::SavedDataTooOld { source },
         MigrationError::LegacyDataTooNew { .. } => TaskError::SavedDataTooNew { source },
         _ => TaskError::MigrationFailed { source },
diff --git a/src/backend_task/migration/v093_upgrade.rs b/src/backend_task/migration/v093_upgrade.rs
index 4087977c1..7052213e2 100644
--- a/src/backend_task/migration/v093_upgrade.rs
+++ b/src/backend_task/migration/v093_upgrade.rs
@@ -19,7 +19,9 @@
 
 use std::collections::BTreeMap;
 use std::str::FromStr;
-use std::sync::Arc;
+use std::sync::{Arc, LazyLock};
+
+use rand::Rng;
 
 use dash_sdk::dpp::dashcore::Network;
 use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
@@ -62,9 +64,6 @@ const V093_DB_VERSION: u16 = 11;
 /// v0.9.3 testnet user must not be relaunched on mainnet.
 const USER_NETWORK: Network = Network::Testnet;
 
-const UNPROTECTED_SEED: [u8; 64] = [0xA9; 64];
-const PROTECTED_SEED: [u8; 64] = [0xC7; 64];
-const PROTECTED_PASSWORD: &str = "correct horse battery staple";
 const TOP_UP_AMOUNT: u64 = 123_456;
 const CONTESTED_NAME: &str = "quantum";
 
@@ -84,13 +83,41 @@ const PROTECTED_IDENTITY_ID: [u8; 32] = [0xCD; 32];
 /// Row F — a local row whose `data` blob is NULL (v0.9.3 allowed it).
 const NULL_BLOB_IDENTITY_ID: [u8; 32] = [0xEF; 32];
 
-/// The masternode owner key held `Clear` in row A's legacy blob. After the
-/// import it must exist only in the vault — never in `det-app.sqlite`.
-const OWNER_PRIVATE_KEY: [u8; 32] = [0x11; 32];
-/// The masternode voting key held `Clear` in row A's legacy blob.
-const VOTING_PRIVATE_KEY: [u8; 32] = [0x22; 32];
-/// The `Clear` key held by the wallet-less evonode identity (row C).
-const EVONODE_PRIVATE_KEY: [u8; 32] = [0x33; 32];
+struct TestSecrets {
+    unprotected_seed: [u8; 64],
+    protected_seed: [u8; 64],
+    password: String,
+    owner_key: [u8; 32],
+    voting_key: [u8; 32],
+    evonode_key: [u8; 32],
+}
+
+fn secrets() -> &'static TestSecrets {
+    static SECRETS: LazyLock = LazyLock::new(|| {
+        let mut unprotected_seed = [0; 64];
+        let mut protected_seed = [0; 64];
+        rand::rng().fill_bytes(&mut unprotected_seed);
+        rand::rng().fill_bytes(&mut protected_seed);
+        TestSecrets {
+            unprotected_seed,
+            protected_seed,
+            password: hex::encode(rand::random::<[u8; 32]>()),
+            owner_key: random_private_key(),
+            voting_key: random_private_key(),
+            evonode_key: random_private_key(),
+        }
+    });
+    &SECRETS
+}
+
+fn random_private_key() -> [u8; 32] {
+    loop {
+        let bytes = rand::random::<[u8; 32]>();
+        if dash_sdk::dpp::dashcore::secp256k1::SecretKey::from_slice(&bytes).is_ok() {
+            return bytes;
+        }
+    }
+}
 
 /// Legacy `identity.status` column values. The bincode blob does **not** carry
 /// status, so these are what prove the column is restored on import rather than
@@ -99,27 +126,27 @@ const STATUS_ACTIVE: u8 = 2;
 const STATUS_PENDING_CREATION: u8 = 1;
 const STATUS_NOT_FOUND: u8 = 3;
 
-/// A **genuine v0.9.3** `QualifiedIdentity::to_bytes()` — the masternode
-/// identity of row A, carrying `Clear` owner and voting keys.
-///
-/// This is the wire-format contract between the two builds. v0.9.3 encodes with
-/// bincode `2.0.0-rc.3`; this tree decodes with `2.0.1`. Everything else about
-/// the import is reasoning about struct layout — this constant is the only proof
-/// that the actual bytes a real user has on disk still decode here.
-///
-/// To regenerate: build a throwaway crate (not a workspace member) depending on
-/// `dash-evo-tool` tag `v0.9.3`, construct the identity below — id
-/// [`IDENTITY_ID`], voter id [`VOTER_IDENTITY_ID`], type `Masternode`, alias
-/// `my-masternode`, `associated_owner_key_id = Some(0)`, an `OWNER` key (id 0,
-/// `Clear`([`OWNER_PRIVATE_KEY`]), `ECDSA_HASH160`) on
-/// `PrivateKeyOnMainIdentity` and a `VOTING` key (id 1,
-/// `Clear`([`VOTING_PRIVATE_KEY`]), `ECDSA_HASH160`) on
-/// `PrivateKeyOnVoterIdentity` — and print `hex::encode(qi.to_bytes())`.
-const V093_MASTERNODE_BLOB_HEX: &str = "00bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb02000000060000020014fc7250a211deddc70ee5a2738de5f07817351cef00010001050000020014531260aa2a199e228c537dfa42c82bea2c7c1f4d00fc40420f00010100bcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbc01010001050000020014531260aa2a199e228c537dfa42c82bea2c7c1f4d00fc40420f00010001050000020014531260aa2a199e228c537dfa42c82bea2c7c1f4d0000010001010d6d792d6d61737465726e6f64650200000000060000020014fc7250a211deddc70ee5a2738de5f07817351cef000001111111111111111111111111111111111111111111111111111111111111111101010001050000020014531260aa2a199e228c537dfa42c82bea2c7c1f4d000001222222222222222222222222222222222222222222222222222222222222222200";
-
-/// The legacy blob of row A, exactly as a v0.9.3 install holds it on disk.
+/// v0.9.3 rc.3 wire-format template, with secret and public-key payloads replaced at runtime.
+/// The captured field layout pins compatibility with the current bincode decoder.
+const V093_MASTERNODE_BLOB_HEX: &str = "00bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb02000000060000020014{owner_public}00010001050000020014{voting_public}00fc40420f00010100bcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbc01010001050000020014{voting_public}00fc40420f00010001050000020014{voting_public}0000010001010d6d792d6d61737465726e6f64650200000000060000020014{owner_public}000001{owner}01010001050000020014{voting_public}000001{voting}00";
+
+/// Populate only key payloads, preserving the captured v0.9.3 encoding layout.
 fn v093_masternode_blob() -> Vec {
-    hex::decode(V093_MASTERNODE_BLOB_HEX).expect("the golden blob is valid hex")
+    use dash_sdk::dpp::dashcore::{
+        hashes::{Hash, hash160},
+        secp256k1::{PublicKey, Secp256k1, SecretKey},
+    };
+    let public_hash = |key: &[u8; 32]| {
+        let key = SecretKey::from_slice(key).expect("generated valid key");
+        let public = PublicKey::from_secret_key(&Secp256k1::new(), &key);
+        hex::encode(hash160::Hash::hash(&public.serialize()).to_byte_array())
+    };
+    let encoded = V093_MASTERNODE_BLOB_HEX
+        .replace("{owner}", &hex::encode(secrets().owner_key))
+        .replace("{voting}", &hex::encode(secrets().voting_key))
+        .replace("{owner_public}", &public_hash(&secrets().owner_key))
+        .replace("{voting_public}", &public_hash(&secrets().voting_key));
+    hex::decode(encoded).expect("the populated template is valid hex")
 }
 
 fn identity_public_key(id: KeyID, purpose: Purpose) -> IdentityPublicKey {
@@ -132,7 +159,7 @@ fn identity_public_key(id: KeyID, purpose: Purpose) -> IdentityPublicKey {
         read_only: false,
         // 20 bytes: the shape of a hash160 key. The import never checks a key
         // against its public data, so a stand-in value is enough here — row A's
-        // keys, the ones that matter, come from the real v0.9.3 blob instead.
+        // keys, the ones that matter, use matching public hashes in the v0.9.3 template instead.
         data: BinaryData::new(vec![id as u8; 20]),
         disabled_at: None,
     })
@@ -140,7 +167,7 @@ fn identity_public_key(id: KeyID, purpose: Purpose) -> IdentityPublicKey {
 
 /// Encode a `QualifiedIdentity` the way v0.9.3 did — same manual `Encode`, same
 /// bincode config. Used for the fixture rows whose exact bytes do not matter;
-/// row A instead carries the real v0.9.3 blob, which is what pins the wire format.
+/// row A uses the captured v0.9.3 template to pin the wire format.
 fn legacy_identity_blob(
     id: [u8; 32],
     identity_type: IdentityType,
@@ -433,7 +460,7 @@ fn write_v093_database(dir: &std::path::Path) -> Fixture {
 
     // Unprotected wallet: v0.9.3 stores the raw 64-byte seed with EMPTY salt and
     // nonce (`add_new_wallet_screen.rs`: `(seed.to_vec(), vec![], vec![], false)`).
-    let unprotected = ClosedKeyItem::compute_seed_hash(&UNPROTECTED_SEED);
+    let unprotected = ClosedKeyItem::compute_seed_hash(&secrets().unprotected_seed);
     conn.execute(
         "INSERT INTO wallet
             (seed_hash, encrypted_seed, salt, nonce, master_ecdsa_bip44_account_0_epk,
@@ -441,10 +468,10 @@ fn write_v093_database(dir: &std::path::Path) -> Fixture {
          VALUES (?1, ?2, ?3, ?4, ?5, 'Masternode Owner Wallet', 1, 0, NULL, ?6)",
         params![
             unprotected.as_slice(),
-            UNPROTECTED_SEED.as_slice(),
+            secrets().unprotected_seed.as_slice(),
             Vec::::new(),
             Vec::::new(),
-            legacy_master_epk_bytes(&UNPROTECTED_SEED, USER_NETWORK),
+            legacy_master_epk_bytes(&secrets().unprotected_seed, USER_NETWORK),
             USER_NETWORK.to_string(),
         ],
     )
@@ -452,8 +479,9 @@ fn write_v093_database(dir: &std::path::Path) -> Fixture {
 
     // Protected wallet: the legacy Argon2 + AES-256-GCM envelope, produced by the
     // very function v0.9.3 used, so the bytes under test are real ciphertext.
-    let envelope = encrypt_message(&PROTECTED_SEED, PROTECTED_PASSWORD).expect("encrypt seed");
-    let protected = ClosedKeyItem::compute_seed_hash(&PROTECTED_SEED);
+    let envelope =
+        encrypt_message(&secrets().protected_seed, &secrets().password).expect("encrypt seed");
+    let protected = ClosedKeyItem::compute_seed_hash(&secrets().protected_seed);
     conn.execute(
         "INSERT INTO wallet
             (seed_hash, encrypted_seed, salt, nonce, master_ecdsa_bip44_account_0_epk,
@@ -464,7 +492,7 @@ fn write_v093_database(dir: &std::path::Path) -> Fixture {
             envelope.ciphertext.as_slice(),
             envelope.salt.as_slice(),
             envelope.nonce.as_slice(),
-            legacy_master_epk_bytes(&PROTECTED_SEED, USER_NETWORK),
+            legacy_master_epk_bytes(&secrets().protected_seed, USER_NETWORK),
             USER_NETWORK.to_string(),
         ],
     )
@@ -520,7 +548,7 @@ fn write_v093_database(dir: &std::path::Path) -> Fixture {
                 PrivateKeyTarget::PrivateKeyOnMainIdentity,
                 0,
                 Purpose::OWNER,
-                PrivateKeyData::Clear(EVONODE_PRIVATE_KEY),
+                PrivateKeyData::Clear(secrets().evonode_key),
             )],
         )),
         IdentityStatus::NotFound,
@@ -693,11 +721,11 @@ async fn run_migration_with_wallet_passwords(
                         .write()
                         .expect("wallet lock")
                         .wallet_seed
-                        .open(PROTECTED_PASSWORD)
+                        .open(&secrets().password)
                         .expect("fixture password opens protected wallet");
                     ctx.handle_wallet_unlocked(
                         &wallet,
-                        PROTECTED_PASSWORD,
+                        &secrets().password,
                         crate::context::WalletUnlockRetention::UntilAppClose,
                     )
                     .expect("the protected seed must land in the current vault");
@@ -864,7 +892,7 @@ async fn v093_install_upgrades_with_wallets_settings_votes_and_history_intact()
         .expect("the unprotected seed must be readable from the vault after the upgrade");
     assert_eq!(
         raw_seed.as_slice(),
-        UNPROTECTED_SEED.as_slice(),
+        secrets().unprotected_seed.as_slice(),
         "the seed bytes are the wallet — they must arrive verbatim",
     );
     assert_eq!(
@@ -909,7 +937,7 @@ async fn v093_install_upgrades_with_wallets_settings_votes_and_history_intact()
     assert!(!meta.uses_password);
     assert_eq!(
         meta.xpub_encoded,
-        legacy_master_epk_bytes(&UNPROTECTED_SEED, USER_NETWORK),
+        legacy_master_epk_bytes(&secrets().unprotected_seed, USER_NETWORK),
         "the master xpub must survive — the cold-boot picker renders addresses from it",
     );
     assert!(
@@ -1104,7 +1132,7 @@ async fn v093_install_upgrades_with_wallets_settings_votes_and_history_intact()
 
 /// The cross-version wire contract, in isolation: a `QualifiedIdentity` encoded
 /// by the **real v0.9.3 binary** (bincode `2.0.0-rc.3`) still decodes on this
-/// tree (bincode `2.0.1`).
+/// tree (`grovedb-bincode` via the `bincode` alias).
 ///
 /// Everything else about the identity import is reasoning about struct layout.
 /// This is the one test that reads bytes a real user actually has on disk. If
@@ -1113,7 +1141,7 @@ async fn v093_install_upgrades_with_wallets_settings_votes_and_history_intact()
 #[test]
 fn a_real_v093_identity_blob_still_decodes() {
     let qi = QualifiedIdentity::from_bytes(&v093_masternode_blob())
-        .expect("a genuine v0.9.3 identity blob must decode on the current bincode");
+        .expect("the populated v0.9.3 template must decode on the current bincode");
 
     assert_eq!(qi.identity.id().to_buffer(), IDENTITY_ID);
     assert_eq!(qi.identity_type, IdentityType::Masternode);
@@ -1135,13 +1163,13 @@ fn a_real_v093_identity_blob_still_decodes() {
     assert_eq!(
         keys.entry_at(&(PrivateKeyTarget::PrivateKeyOnMainIdentity, 0))
             .map(|(_, data)| data.clone()),
-        Some(PrivateKeyData::Clear(OWNER_PRIVATE_KEY)),
+        Some(PrivateKeyData::Clear(secrets().owner_key)),
         "the masternode owner key must decode byte-for-byte",
     );
     assert_eq!(
         keys.entry_at(&(PrivateKeyTarget::PrivateKeyOnVoterIdentity, 1))
             .map(|(_, data)| data.clone()),
-        Some(PrivateKeyData::Clear(VOTING_PRIVATE_KEY)),
+        Some(PrivateKeyData::Clear(secrets().voting_key)),
         "the masternode voting key must decode byte-for-byte",
     );
 
@@ -1155,7 +1183,7 @@ fn a_real_v093_identity_blob_still_decodes() {
     );
 }
 
-/// The same real v0.9.3 blob, but asking the question a user asks: are these
+/// The same v0.9.3 template, but asking the question a user asks: are these
 /// keys *usable* after the upgrade?
 ///
 /// Decoding proves the bytes survived; it does not prove anything can find them.
@@ -1172,7 +1200,7 @@ fn both_keys_of_a_real_v093_blob_resolve_to_their_own_material() {
     use dash_sdk::dpp::identity::signer::Signer;
 
     let qi = QualifiedIdentity::from_bytes(&v093_masternode_blob())
-        .expect("a genuine v0.9.3 identity blob must decode on the current bincode");
+        .expect("the populated v0.9.3 template must decode on the current bincode");
 
     let owner = qi
         .identity
@@ -1365,7 +1393,11 @@ async fn the_import_never_writes_a_plaintext_key_to_disk() {
             "{label}: a `Clear`/`AlwaysClear` key must never survive the import to disk — \
              it must be vaulted: got {key_data:?}",
         );
-        for key in [OWNER_PRIVATE_KEY, VOTING_PRIVATE_KEY, EVONODE_PRIVATE_KEY] {
+        for key in [
+            secrets().owner_key,
+            secrets().voting_key,
+            secrets().evonode_key,
+        ] {
             assert!(
                 !contains_bytes(&stored.qi_bytes, &key),
                 "{label}: raw private-key bytes must appear nowhere in the stored blob",
@@ -1384,7 +1416,7 @@ async fn the_import_never_writes_a_plaintext_key_to_disk() {
             .expect("read owner key from the vault")
             .expect("the owner key must be in the vault")
             .as_slice(),
-        OWNER_PRIVATE_KEY.as_slice(),
+        secrets().owner_key.as_slice(),
         "the owner key must arrive in the vault intact",
     );
     assert_eq!(
@@ -1393,7 +1425,7 @@ async fn the_import_never_writes_a_plaintext_key_to_disk() {
             .expect("read voting key from the vault")
             .expect("the voting key must be in the vault")
             .as_slice(),
-        VOTING_PRIVATE_KEY.as_slice(),
+        secrets().voting_key.as_slice(),
         "the voting key must arrive in the vault intact",
     );
 
@@ -1454,7 +1486,7 @@ async fn a_corrupt_vote_index_never_strands_the_identity_keys() {
             .expect("read owner key from the vault")
             .expect("the owner key must be in the vault")
             .as_slice(),
-        OWNER_PRIVATE_KEY.as_slice(),
+        secrets().owner_key.as_slice(),
         "the masternode owner key must reach the vault even when the vote import fails — \
          otherwise a broken vote queue permanently costs the user control of their node",
     );
diff --git a/src/bin/det_cli/connect.rs b/src/bin/det_cli/connect.rs
index 1a7201148..33d70718e 100644
--- a/src/bin/det_cli/connect.rs
+++ b/src/bin/det_cli/connect.rs
@@ -96,7 +96,122 @@ pub(super) async fn connect_http(
         // `Bearer Bearer ` on the wire and fail server-side auth.
         config = config.auth_header(token.to_string());
     }
-    let transport = StreamableHttpClientTransport::from_config(config);
+    let transport = StreamableHttpClientTransport::with_client(http_client()?, config);
     let client = ().serve(transport).await?;
     Ok(client)
 }
+
+fn http_client() -> Result {
+    reqwest::Client::builder()
+        .pool_max_idle_per_host(0)
+        // Loopback tool arguments must never leave this machine through a proxy.
+        .no_proxy()
+        // Tool arguments must stay at the destination validated by the CLI.
+        .redirect(reqwest::redirect::Policy::none())
+        .build()
+}
+
+#[cfg(test)]
+mod tests {
+    #[test]
+    fn review_regression_http_client_bypasses_environment_proxy() {
+        const CHILD: &str = "DET_PROXY_TEST_CHILD";
+        if std::env::var_os(CHILD).is_some() {
+            let runtime = tokio::runtime::Runtime::new().unwrap();
+            runtime.block_on(async {
+                let response = super::http_client()
+                    .unwrap()
+                    .post(std::env::var("DET_PROXY_TEST_URL").unwrap())
+                    .body(rand::random::().to_string())
+                    .timeout(std::time::Duration::from_secs(5))
+                    .send()
+                    .await
+                    .unwrap();
+                assert_eq!(response.status(), reqwest::StatusCode::NO_CONTENT);
+            });
+            return;
+        }
+        let destination = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+        let proxy = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+        destination.set_nonblocking(true).unwrap();
+        proxy.set_nonblocking(true).unwrap();
+        let mut child = std::process::Command::new(std::env::current_exe().unwrap())
+            .args([
+                "--exact",
+                "connect::tests::review_regression_http_client_bypasses_environment_proxy",
+                "--nocapture",
+            ])
+            .env(CHILD, "1")
+            .env(
+                "DET_PROXY_TEST_URL",
+                format!("http://{}/", destination.local_addr().unwrap()),
+            )
+            .env(
+                "HTTP_PROXY",
+                format!("http://{}", proxy.local_addr().unwrap()),
+            )
+            .env(
+                "http_proxy",
+                format!("http://{}", proxy.local_addr().unwrap()),
+            )
+            .env_remove("NO_PROXY")
+            .env_remove("no_proxy")
+            .spawn()
+            .unwrap();
+        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+        let mut proxied = false;
+        loop {
+            use std::io::{Read as _, Write as _};
+            for (listener, is_proxy) in [(&destination, false), (&proxy, true)] {
+                if let Ok((mut stream, _)) = listener.accept() {
+                    proxied |= is_proxy;
+                    stream
+                        .set_read_timeout(Some(std::time::Duration::from_secs(2)))
+                        .unwrap();
+                    let _ = stream.read(&mut [0; 4096]);
+                    stream
+                        .write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
+                        .unwrap();
+                }
+            }
+            if let Some(status) = child.try_wait().unwrap() {
+                assert!(status.success(), "transport subprocess failed");
+                break;
+            }
+            if std::time::Instant::now() > deadline {
+                child.kill().unwrap();
+                child.wait().unwrap();
+                panic!("transport subprocess timed out");
+            }
+            std::thread::sleep(std::time::Duration::from_millis(10));
+        }
+        assert!(!proxied, "loopback request reached the configured proxy");
+    }
+
+    #[tokio::test]
+    async fn http_client_returns_redirect_without_following_it() {
+        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+        let addr = listener.local_addr().unwrap();
+        let server = tokio::spawn(async move {
+            let (mut stream, _) = listener.accept().await.unwrap();
+            let mut request = [0; 1024];
+            let bytes_read = stream.read(&mut request).await.unwrap();
+            assert!(bytes_read > 0, "client closed before sending a request");
+            stream
+                .write_all(b"HTTP/1.1 302 Found\r\nLocation: /other\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
+                .await
+                .unwrap();
+        });
+        let response = super::http_client()
+            .unwrap()
+            .get(format!("http://{addr}/"))
+            .timeout(std::time::Duration::from_secs(5))
+            .send()
+            .await
+            .unwrap();
+        assert_eq!(response.status(), reqwest::StatusCode::FOUND);
+        server.await.unwrap();
+    }
+}
diff --git a/src/bin/det_cli/help.rs b/src/bin/det_cli/help.rs
index 6f550b85c..6c9ba8bb1 100644
--- a/src/bin/det_cli/help.rs
+++ b/src/bin/det_cli/help.rs
@@ -51,6 +51,13 @@ pub(super) fn print_tool_help(mcp_name: &str) -> bool {
                     };
                     println!("  {:<28} {}{}", cli_param, pdesc, req);
                 }
+                if obj.contains_key(super::password::PASSWORD_PARAM) {
+                    println!();
+                    println!(
+                        "Supply the password with --password-stdin or --password-file . \
+                         A password given as password=... is refused."
+                    );
+                }
             } else {
                 println!();
                 println!("This command takes no parameters.");
@@ -66,6 +73,21 @@ pub(super) fn print_tool_help(mcp_name: &str) -> bool {
     }
 }
 
+/// Whether the cached schema of `mcp_name` declares the parameter `param`.
+///
+/// `None` when the cache is missing or stale, or does not list the tool — the
+/// caller cannot tell, and must not guess.
+pub(super) fn cached_tool_takes_param(mcp_name: &str, param: &str) -> Option {
+    let cache = load_cache().filter(|c| c.version == PKG_VERSION)?;
+    let tool = cache.tools.iter().find(|t| *t.name == *mcp_name)?;
+    Some(
+        tool.input_schema
+            .get("properties")
+            .and_then(|props| props.as_object())
+            .is_some_and(|props| props.contains_key(param)),
+    )
+}
+
 /// Print help output with integrated tool list.
 /// When `tools` is `Some`, uses the provided list (live from server).
 /// When `None`, falls back to the disk cache.
diff --git a/src/bin/det_cli/main.rs b/src/bin/det_cli/main.rs
index 4da161dba..0e8eb8d63 100644
--- a/src/bin/det_cli/main.rs
+++ b/src/bin/det_cli/main.rs
@@ -15,6 +15,7 @@ mod connect;
 #[cfg(feature = "headless")]
 mod headless;
 mod help;
+mod password;
 
 type McpClient = RunningService;
 
@@ -114,13 +115,21 @@ fn main() -> Result<(), Box> {
     }
 
     // Logging is off by default -- set RUST_LOG to enable (e.g. RUST_LOG=debug).
-    let _ = tracing_subscriber::fmt()
-        .with_env_filter(
-            tracing_subscriber::EnvFilter::try_from_default_env()
-                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")),
-        )
-        .with_writer(std::io::stderr)
-        .try_init();
+    // The cap keeps rmcp's raw request logging (tool arguments, secrets
+    // included) out of the output whatever RUST_LOG says.
+    {
+        use tracing_subscriber::layer::SubscriberExt as _;
+        use tracing_subscriber::util::SubscriberInitExt as _;
+        let _ = tracing_subscriber::fmt()
+            .with_env_filter(
+                tracing_subscriber::EnvFilter::try_from_default_env()
+                    .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")),
+            )
+            .with_writer(std::io::stderr)
+            .finish()
+            .with(dash_evo_tool::logging::sensitive_target_cap())
+            .try_init();
+    }
 
     let runtime = tokio::runtime::Builder::new_multi_thread()
         .worker_threads(2)
@@ -146,37 +155,110 @@ fn main() -> Result<(), Box> {
     let _ = std::io::stdout().lock().flush();
     let _ = std::io::stderr().lock().flush();
     // TODO(graceful-teardown): replace with normal return once WalletBackend::quiesce() joins coordinator threads.
+    // Until then no SQLite connection is closed, so the WAL is never checkpointed on exit: a data
+    // directory det-cli wrote last carries MB-sized -wal sidecars, which is what bloats migration
+    // fixture archives (tests/migration-fixtures/README.md).
     std::process::exit(exit_code);
 }
 
+/// What a client-mode invocation does once connected.
+enum Action {
+    ListTools,
+    CallTool(Box),
+}
+
+/// Resolves a tool call's name and arguments before any connection is made —
+/// including reading the password when a password flag names a source — so
+/// bad input or an unsafe password file fails without booting the app.
+///
+/// `http_addr` is the server address in HTTP mode and `None` in-process; a
+/// password is only sent over HTTP to a destination that keeps it private.
+///
+/// Returns `None` when the invocation only asked for the tool's help, which is
+/// printed here.
+fn prepare_tool_call(
+    args: &[String],
+    http_addr: Option<&str>,
+) -> Result, String> {
+    let tool_name = args.first().ok_or("tool name required".to_string())?;
+    let mcp_name = tool_name.replace('-', "_");
+
+    if args[1..].iter().any(|a| a == "--help" || a == "-h") {
+        if !help::print_tool_help(&mcp_name) {
+            Err(format!("Unknown tool '{tool_name}'"))?;
+        }
+        return Ok(None);
+    }
+
+    let mut params = args[1..].to_vec();
+    let password_source =
+        password::take_password_source(&mut params).map_err(|e| password::describe(&e))?;
+    let mut arguments = help::parse_params(¶ms).map_err(|e| e.to_string())?;
+    password::reject_inline_password(&arguments).map_err(|e| password::describe(&e))?;
+    if let Some(source) = password_source {
+        // Checked before reading, so a mistyped command never consumes stdin.
+        // An unknown (uncached) tool is let through: the server is the
+        // authority on its parameters.
+        if help::cached_tool_takes_param(&mcp_name, password::PASSWORD_PARAM) == Some(false) {
+            let error = password::PasswordArgError::ToolTakesNoPassword {
+                tool: tool_name.clone(),
+            };
+            return Err(password::describe(&error));
+        }
+        if let Some(addr) = http_addr {
+            password::ensure_safe_destination(addr).map_err(|e| password::describe(&e))?;
+        }
+        let secret = password::read_password(&source).map_err(|e| password::describe(&e))?;
+        password::insert_password(&mut arguments, &secret);
+    }
+
+    let mut request = CallToolRequestParams::new(mcp_name);
+    if !arguments.is_empty() {
+        request.arguments = Some(arguments);
+    }
+    Ok(Some(request))
+}
+
 async fn run(cli: Cli) -> Result<(), String> {
+    let Cli {
+        standalone,
+        addr,
+        bearer,
+        command,
+    } = cli;
+
     // An empty/whitespace bearer means "no key": the default .env ships
     // `MCP_API_KEY=` (empty), which dotenvy sets as an empty string, so clap's
     // env binding yields `Some("")`. Treat that exactly like an unset key —
     // matching the HTTP server, which also disables auth on an empty key.
-    let bearer = cli
-        .bearer
-        .as_deref()
-        .map(str::trim)
-        .filter(|b| !b.is_empty());
+    let bearer = bearer.as_deref().map(str::trim).filter(|b| !b.is_empty());
 
     // Mode selection: --standalone or no bearer -> stdio; bearer present -> HTTP.
-    let use_stdio = cli.standalone || bearer.is_none();
+    let use_stdio = standalone || bearer.is_none();
+    let http_addr = (!use_stdio).then(|| resolve_addr(addr));
+
+    let action = match command.unwrap_or(Commands::Tools) {
+        Commands::Tools => Action::ListTools,
+        Commands::Tool(args) => match prepare_tool_call(&args, http_addr.as_deref())? {
+            Some(request) => Action::CallTool(Box::new(request)),
+            None => return Ok(()),
+        },
+        Commands::Serve | Commands::Completion { .. } => unreachable!(),
+        #[cfg(feature = "headless")]
+        Commands::Headless => unreachable!(),
+    };
 
-    let client: McpClient = if use_stdio {
-        connect::connect_in_process()
+    let client: McpClient = match http_addr.as_deref() {
+        None => connect::connect_in_process()
             .await
-            .map_err(|e| e.to_string())?
-    } else {
-        let addr = resolve_addr(cli.addr);
-        connect::connect_http(&addr, bearer)
+            .map_err(|e| e.to_string())?,
+        Some(addr) => connect::connect_http(addr, bearer)
             .await
-            .map_err(|e| e.to_string())?
+            .map_err(|e| e.to_string())?,
     };
 
-    let command = cli.command.unwrap_or(Commands::Tools);
-    match command {
-        Commands::Tools => {
+    match action {
+        Action::ListTools => {
             let tools = client
                 .peer()
                 .list_all_tools()
@@ -185,33 +267,14 @@ async fn run(cli: Cli) -> Result<(), String> {
             cache::save_cache(&client, &tools);
             help::print_help(Some(&tools));
         }
-        Commands::Tool(args) => {
-            let tool_name = args.first().ok_or("tool name required".to_string())?;
-
-            if args[1..].iter().any(|a| a == "--help" || a == "-h") {
-                let mcp_name = tool_name.replace('-', "_");
-                if !help::print_tool_help(&mcp_name) {
-                    Err(format!("Unknown tool '{tool_name}'"))?;
-                }
-                return Ok(());
-            }
-
-            let mcp_name = tool_name.replace('-', "_");
-            let arguments = help::parse_params(&args[1..]).map_err(|e| e.to_string())?;
-            let mut request = CallToolRequestParams::new(mcp_name);
-            if !arguments.is_empty() {
-                request.arguments = Some(arguments);
-            }
+        Action::CallTool(request) => {
             let result = client
                 .peer()
-                .call_tool(request)
+                .call_tool(*request)
                 .await
                 .map_err(connect::format_service_error)?;
             help::print_result(&result);
         }
-        Commands::Serve | Commands::Completion { .. } => unreachable!(),
-        #[cfg(feature = "headless")]
-        Commands::Headless => unreachable!(),
     }
 
     Ok(())
diff --git a/src/bin/det_cli/password.rs b/src/bin/det_cli/password.rs
new file mode 100644
index 000000000..dc0e2932e
--- /dev/null
+++ b/src/bin/det_cli/password.rs
@@ -0,0 +1,647 @@
+//! Non-interactive password input: `--password-stdin` and `--password-file`.
+//!
+//! A password never travels as a `password=...` argument — `ps` shows every
+//! process's arguments to every local user, and shells save them in history —
+//! and never through an environment variable, which is readable through
+//! `/proc//environ`, inherited by every child process and swept into
+//! crash reports and CI logs. These flags read it from a pipe or from an
+//! owner-only file instead, then deliver it as the tool's `password`
+//! parameter. The tool itself (`src/mcp/tools/`) never learns where it came
+//! from.
+
+use std::io::{IsTerminal as _, Read};
+use std::path::{Path, PathBuf};
+
+use platform_wallet_storage::secrets::{MAX_PASSPHRASE_LEN, SecretString};
+use serde_json::{Map, Value};
+use zeroize::Zeroizing;
+
+/// Tool parameter the password is delivered as.
+pub(super) const PASSWORD_PARAM: &str = "password";
+
+const STDIN_FLAG: &str = "--password-stdin";
+const FILE_FLAG: &str = "--password-file";
+
+/// Bytes read before giving up: the longest accepted password, a CRLF line
+/// ending, and one more byte so an over-long input is refused rather than
+/// silently truncated.
+const READ_LIMIT: usize = MAX_PASSPHRASE_LEN + 3;
+
+/// Permission bits that let anyone but the owner read or change the file.
+/// OpenSSH refuses a private key with any of them set.
+#[cfg(unix)]
+const GROUP_OR_OTHER_ACCESS: u32 = 0o077;
+
+/// Where the password comes from.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(super) enum PasswordSource {
+    Stdin,
+    File(PathBuf),
+}
+
+/// A password flag used wrongly on the command line.
+#[derive(Debug, thiserror::Error)]
+pub(super) enum PasswordArgError {
+    #[error("Choose one password source: --password-stdin or --password-file, given once.")]
+    ConflictingSources,
+    #[error("--password-file needs the path of the file that holds the password.")]
+    MissingFilePath,
+    #[error(
+        "A password given as password=... is visible to other users of this computer and is saved in shell history. Pass it with --password-stdin or --password-file instead."
+    )]
+    InlinePassword,
+    #[error(
+        "The command {tool} does not take a password, so --password-stdin and --password-file do not apply to it."
+    )]
+    ToolTakesNoPassword { tool: String },
+    #[error(
+        "The password would travel unencrypted to {addr}. Send it only to this computer (127.0.0.1, ::1 or localhost) or to an https address."
+    )]
+    InsecureDestination { addr: String },
+}
+
+/// The password could not be read, or was refused. No variant carries any
+/// part of the password.
+#[derive(Debug, thiserror::Error)]
+pub(super) enum PasswordReadError {
+    #[error(
+        "--password-stdin reads the password from a pipe or a redirected file. On a terminal the password would be shown as you type it, so pipe it in or use --password-file."
+    )]
+    StdinIsTerminal,
+    #[error("Could not read the password from standard input")]
+    ReadStdin {
+        #[source]
+        source: std::io::Error,
+    },
+    #[error("Could not read the password file {}", .path.display())]
+    ReadFile {
+        path: PathBuf,
+        #[source]
+        source: std::io::Error,
+    },
+    #[error("The password file {} is a directory, not a file.", .path.display())]
+    NotAFile { path: PathBuf },
+    #[cfg(unix)]
+    #[error(
+        "The password file {} can be read or changed by other users (permissions {mode:04o}). Restrict it to your user, for example with: chmod 600 {}",
+        .path.display(),
+        .path.display()
+    )]
+    InsecurePermissions { path: PathBuf, mode: u32 },
+    #[cfg(not(unix))]
+    #[error(
+        "--password-file is not available on this platform, because the file's permissions cannot be checked. Use --password-stdin instead."
+    )]
+    FileUnsupportedOnPlatform,
+    #[error("The password is empty.")]
+    Empty,
+    #[error("The password must be a single line.")]
+    MultipleLines,
+    #[error("The password is longer than {max} bytes.")]
+    TooLong { max: usize },
+    #[error("The password is not valid UTF-8 text.")]
+    NotUtf8,
+}
+
+/// Renders an error with its whole `source` chain, for the one-line
+/// `Error: ...` det-cli prints.
+pub(super) fn describe(error: &dyn std::error::Error) -> String {
+    let mut text = error.to_string();
+    let mut cause = error.source();
+    while let Some(inner) = cause {
+        text.push_str(": ");
+        text.push_str(&inner.to_string());
+        cause = inner.source();
+    }
+    text
+}
+
+/// Removes the password flags from `params` — a tool's arguments after its
+/// name — and returns the source they name, if any.
+///
+/// # Errors
+///
+/// [`PasswordArgError::ConflictingSources`] when more than one flag is given,
+/// [`PasswordArgError::MissingFilePath`] when `--password-file` has no path.
+pub(super) fn take_password_source(
+    params: &mut Vec,
+) -> Result, PasswordArgError> {
+    let mut source = None;
+    let mut kept = Vec::with_capacity(params.len());
+    let mut args = std::mem::take(params).into_iter();
+    while let Some(arg) = args.next() {
+        let named = if arg == STDIN_FLAG {
+            PasswordSource::Stdin
+        } else if arg == FILE_FLAG {
+            match args.next() {
+                Some(path) if !path.is_empty() && !path.starts_with("--") => {
+                    PasswordSource::File(PathBuf::from(path))
+                }
+                _ => return Err(PasswordArgError::MissingFilePath),
+            }
+        } else if let Some(path) = arg
+            .strip_prefix(FILE_FLAG)
+            .and_then(|rest| rest.strip_prefix('='))
+        {
+            if path.is_empty() {
+                return Err(PasswordArgError::MissingFilePath);
+            }
+            PasswordSource::File(PathBuf::from(path))
+        } else {
+            kept.push(arg);
+            continue;
+        };
+        if source.replace(named).is_some() {
+            return Err(PasswordArgError::ConflictingSources);
+        }
+    }
+    *params = kept;
+    Ok(source)
+}
+
+/// Refuses a password passed as an ordinary `password=...` argument.
+///
+/// # Errors
+///
+/// [`PasswordArgError::InlinePassword`] when `arguments` holds a password.
+pub(super) fn reject_inline_password(
+    arguments: &Map,
+) -> Result<(), PasswordArgError> {
+    match arguments.contains_key(PASSWORD_PARAM) {
+        true => Err(PasswordArgError::InlinePassword),
+        false => Ok(()),
+    }
+}
+
+/// Reads the password from `source`.
+///
+/// # Errors
+///
+/// [`PasswordReadError`] when the source cannot be read safely, or holds
+/// anything but exactly one non-empty line.
+pub(super) fn read_password(source: &PasswordSource) -> Result {
+    match source {
+        PasswordSource::Stdin => {
+            if std::io::stdin().is_terminal() {
+                return Err(PasswordReadError::StdinIsTerminal);
+            }
+            let raw = raw_stdin()
+                .and_then(read_bounded)
+                .map_err(|source| PasswordReadError::ReadStdin { source })?;
+            parse_password(&raw)
+        }
+        PasswordSource::File(path) => read_password_file(path),
+    }
+}
+
+/// Standard input as an unbuffered `File` over a duplicate of its descriptor.
+///
+/// `std::io::stdin()` reads through a process-wide 8 KiB buffer that is never
+/// wiped, so a password read through it would outlive the zeroizing buffer of
+/// [`read_bounded`]. Reading the duplicated descriptor directly leaves that
+/// buffer untouched: the only user-space copy is the zeroizing one.
+#[cfg(unix)]
+fn raw_stdin() -> std::io::Result {
+    use std::os::fd::AsFd as _;
+    Ok(std::fs::File::from(
+        std::io::stdin().as_fd().try_clone_to_owned()?,
+    ))
+}
+
+/// See the Unix variant: the same bypass of std's stdin buffer, over a
+/// duplicated handle.
+#[cfg(windows)]
+fn raw_stdin() -> std::io::Result {
+    use std::os::windows::io::AsHandle as _;
+    Ok(std::fs::File::from(
+        std::io::stdin().as_handle().try_clone_to_owned()?,
+    ))
+}
+
+/// Refuses to send a password over plain HTTP anywhere but this computer.
+///
+/// Over the HTTP transport the password travels in the request body. `https`
+/// protects it on any network; plain `http` only on loopback, where it never
+/// leaves the machine.
+///
+/// # Errors
+///
+/// [`PasswordArgError::InsecureDestination`] for plain HTTP to a non-loopback
+/// host, and for an address that does not parse — an unknown destination is
+/// not a safe one.
+pub(super) fn ensure_safe_destination(addr: &str) -> Result<(), PasswordArgError> {
+    let safe = match reqwest::Url::parse(addr) {
+        Ok(url) if url.scheme() == "https" => true,
+        Ok(url) if url.scheme() == "http" => url.host_str().is_some_and(is_loopback_host),
+        _ => false,
+    };
+    if safe {
+        Ok(())
+    } else {
+        Err(PasswordArgError::InsecureDestination {
+            addr: addr.to_owned(),
+        })
+    }
+}
+
+/// Whether a parsed URL host names this computer.
+///
+/// The URL parser has already normalized the host: IPv4 forms such as
+/// `0x7f.1` read as dotted quads, domains are lowercase, and IPv6 literals
+/// keep their brackets.
+fn is_loopback_host(host: &str) -> bool {
+    let ip_literal = host
+        .strip_prefix('[')
+        .and_then(|h| h.strip_suffix(']'))
+        .unwrap_or(host);
+    match ip_literal.parse::() {
+        Ok(ip) => ip.is_loopback(),
+        Err(_) => host == "localhost",
+    }
+}
+
+/// Adds the password to a tool call's arguments.
+///
+/// The JSON value is an ordinary `String`: the MCP transport serializes it,
+/// so that copy lives outside `SecretString`'s guarded memory — the residual
+/// every secret tool parameter shares.
+pub(super) fn insert_password(arguments: &mut Map, password: &SecretString) {
+    arguments.insert(
+        PASSWORD_PARAM.to_owned(),
+        Value::String(password.expose_secret().to_owned()),
+    );
+}
+
+#[cfg(unix)]
+fn read_password_file(path: &Path) -> Result {
+    use std::os::unix::fs::PermissionsExt as _;
+
+    let read_error = |source: std::io::Error| PasswordReadError::ReadFile {
+        path: path.to_path_buf(),
+        source,
+    };
+    let file = std::fs::File::open(path).map_err(read_error)?;
+    // Checked on the opened descriptor rather than the path, so the file
+    // cannot be swapped between the check and the read.
+    let metadata = file.metadata().map_err(read_error)?;
+    if metadata.is_dir() {
+        return Err(PasswordReadError::NotAFile {
+            path: path.to_path_buf(),
+        });
+    }
+    let mode = metadata.permissions().mode();
+    if mode & GROUP_OR_OTHER_ACCESS != 0 {
+        return Err(PasswordReadError::InsecurePermissions {
+            path: path.to_path_buf(),
+            mode: mode & 0o7777,
+        });
+    }
+    let raw = read_bounded(file).map_err(read_error)?;
+    parse_password(&raw)
+}
+
+#[cfg(not(unix))]
+fn read_password_file(_path: &Path) -> Result {
+    // TODO(windows): accept the file once its ACL is verified to grant access
+    // to the current user only, as OpenSSH for Windows does for private keys.
+    // Until then a file other users can read cannot be told apart, so refuse.
+    Err(PasswordReadError::FileUnsupportedOnPlatform)
+}
+
+/// Reads at most [`READ_LIMIT`] bytes into a zeroizing buffer allocated once
+/// up front, so no reallocation leaves an unwiped copy of the password behind.
+fn read_bounded(mut reader: impl Read) -> std::io::Result>> {
+    let mut buffer = Zeroizing::new(vec![0u8; READ_LIMIT]);
+    let mut filled = 0;
+    while filled < buffer.len() {
+        match reader.read(&mut buffer[filled..]) {
+            Ok(0) => break,
+            Ok(read) => filled += read,
+            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
+            Err(error) => return Err(error),
+        }
+    }
+    buffer.truncate(filled);
+    Ok(buffer)
+}
+
+/// Accepts exactly one line: strips a single trailing `\n` or `\r\n`, keeps
+/// every other byte (spaces included), and refuses anything that would make
+/// the password ambiguous.
+fn parse_password(raw: &[u8]) -> Result {
+    let line = match raw.strip_suffix(b"\n") {
+        Some(line) => line.strip_suffix(b"\r").unwrap_or(line),
+        None => raw,
+    };
+    if line.is_empty() {
+        return Err(PasswordReadError::Empty);
+    }
+    if line.len() > MAX_PASSPHRASE_LEN {
+        return Err(PasswordReadError::TooLong {
+            max: MAX_PASSPHRASE_LEN,
+        });
+    }
+    if line.iter().any(|byte| matches!(byte, b'\n' | b'\r')) {
+        return Err(PasswordReadError::MultipleLines);
+    }
+    let text = std::str::from_utf8(line).map_err(|_| PasswordReadError::NotUtf8)?;
+    Ok(SecretString::from(text))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    const PASSWORD: &str = "correct horse canary staple";
+
+    fn args(list: &[&str]) -> Vec {
+        list.iter().map(|arg| (*arg).to_owned()).collect()
+    }
+
+    /// Asserts that neither rendering of `error` carries the password.
+    fn assert_no_password(error: &dyn std::error::Error) {
+        let rendered = format!("{} {error:?} {}", error, describe(error));
+        assert!(
+            !rendered.contains(PASSWORD) && !rendered.contains("canary"),
+            "an error must never carry the password: {rendered}"
+        );
+    }
+
+    #[test]
+    fn password_flags_are_taken_out_of_the_tool_arguments() {
+        let mut params = args(&["network=testnet", "--password-stdin", "alias=x"]);
+        let source = take_password_source(&mut params).expect("valid flags");
+        assert_eq!(source, Some(PasswordSource::Stdin));
+        assert_eq!(params, args(&["network=testnet", "alias=x"]));
+
+        let mut params = args(&["--password-file", "/run/pw", "network=testnet"]);
+        let source = take_password_source(&mut params).expect("valid flags");
+        assert_eq!(source, Some(PasswordSource::File("/run/pw".into())));
+        assert_eq!(params, args(&["network=testnet"]));
+
+        let mut params = args(&["--password-file=/run/pw"]);
+        let source = take_password_source(&mut params).expect("valid flags");
+        assert_eq!(source, Some(PasswordSource::File("/run/pw".into())));
+        assert!(params.is_empty());
+
+        let mut params = args(&["network=testnet"]);
+        assert_eq!(take_password_source(&mut params).expect("no flags"), None);
+        assert_eq!(params, args(&["network=testnet"]));
+    }
+
+    #[test]
+    fn more_than_one_password_source_is_refused() {
+        for list in [
+            &["--password-stdin", "--password-file", "/run/pw"][..],
+            &["--password-file=/a", "--password-file=/b"][..],
+            &["--password-stdin", "--password-stdin"][..],
+        ] {
+            let mut params = args(list);
+            assert!(
+                matches!(
+                    take_password_source(&mut params),
+                    Err(PasswordArgError::ConflictingSources)
+                ),
+                "{list:?} must be refused"
+            );
+        }
+    }
+
+    #[test]
+    fn a_password_file_flag_without_a_path_is_refused() {
+        for list in [
+            &["--password-file"][..],
+            &["--password-file", "--password-stdin"][..],
+            &["--password-file="][..],
+            &["--password-file", ""][..],
+        ] {
+            let mut params = args(list);
+            assert!(
+                matches!(
+                    take_password_source(&mut params),
+                    Err(PasswordArgError::MissingFilePath)
+                ),
+                "{list:?} must be refused"
+            );
+        }
+    }
+
+    #[test]
+    fn a_password_on_the_command_line_is_refused() {
+        let mut arguments = Map::new();
+        arguments.insert("network".to_owned(), Value::String("testnet".to_owned()));
+        assert!(reject_inline_password(&arguments).is_ok());
+
+        arguments.insert(
+            PASSWORD_PARAM.to_owned(),
+            Value::String(PASSWORD.to_owned()),
+        );
+        let error = reject_inline_password(&arguments).expect_err("inline password");
+        assert!(matches!(error, PasswordArgError::InlinePassword));
+        assert_no_password(&error);
+    }
+
+    #[test]
+    fn exactly_one_line_is_accepted_and_only_its_line_ending_is_stripped() {
+        for raw in [
+            PASSWORD.to_owned(),
+            format!("{PASSWORD}\n"),
+            format!("{PASSWORD}\r\n"),
+        ] {
+            let secret = parse_password(raw.as_bytes()).expect("one line");
+            assert_eq!(secret.expose_secret(), PASSWORD, "from {raw:?}");
+        }
+        let padded = parse_password(b" padded \n").expect("spaces are password bytes");
+        assert_eq!(padded.expose_secret(), " padded ");
+    }
+
+    #[test]
+    fn anything_but_one_non_empty_line_is_refused() {
+        assert!(matches!(parse_password(b""), Err(PasswordReadError::Empty)));
+        assert!(matches!(
+            parse_password(b"\n"),
+            Err(PasswordReadError::Empty)
+        ));
+        assert!(matches!(
+            parse_password(b"\r\n"),
+            Err(PasswordReadError::Empty)
+        ));
+        for raw in [
+            format!("{PASSWORD}\nsecond line"),
+            format!("{PASSWORD}\n\n"),
+            format!("{PASSWORD}\rrest"),
+        ] {
+            let error = parse_password(raw.as_bytes()).expect_err("more than one line");
+            assert!(matches!(error, PasswordReadError::MultipleLines), "{raw:?}");
+            assert_no_password(&error);
+        }
+        assert!(matches!(
+            parse_password(&[0xff, 0xfe]),
+            Err(PasswordReadError::NotUtf8)
+        ));
+    }
+
+    #[test]
+    fn an_over_long_password_is_refused_not_truncated() {
+        let longest = "a".repeat(MAX_PASSPHRASE_LEN);
+        assert!(parse_password(longest.as_bytes()).is_ok());
+
+        let too_long = "a".repeat(MAX_PASSPHRASE_LEN + 1);
+        assert!(matches!(
+            parse_password(too_long.as_bytes()),
+            Err(PasswordReadError::TooLong { .. })
+        ));
+
+        // A reader stops at the limit, and what it returns is still refused.
+        let endless = std::io::repeat(b'a');
+        let raw = read_bounded(endless.take(10 * READ_LIMIT as u64)).expect("bounded read");
+        assert_eq!(raw.len(), READ_LIMIT);
+        assert!(matches!(
+            parse_password(&raw),
+            Err(PasswordReadError::TooLong { .. })
+        ));
+    }
+
+    #[test]
+    fn a_pipe_is_read_to_its_single_line() {
+        let raw = read_bounded(std::io::Cursor::new(format!("{PASSWORD}\n"))).expect("read");
+        let secret = parse_password(&raw).expect("one line");
+        assert_eq!(secret.expose_secret(), PASSWORD);
+    }
+
+    #[test]
+    fn the_password_is_never_in_debug_output() {
+        let secret = parse_password(PASSWORD.as_bytes()).expect("one line");
+        let debug = format!("{secret:?}");
+        assert!(!debug.contains(PASSWORD), "Debug must redact: {debug}");
+
+        let mut arguments = Map::new();
+        insert_password(&mut arguments, &secret);
+        assert_eq!(
+            arguments.get(PASSWORD_PARAM).and_then(Value::as_str),
+            Some(PASSWORD),
+            "the tool receives the password under its parameter name"
+        );
+    }
+
+    #[cfg(unix)]
+    fn password_file(mode: u32) -> (tempfile::TempDir, PathBuf) {
+        use std::os::unix::fs::PermissionsExt as _;
+
+        let dir = tempfile::tempdir().expect("tempdir");
+        let path = dir.path().join("wallet-password");
+        std::fs::write(&path, format!("{PASSWORD}\n")).expect("write password file");
+        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode))
+            .expect("set permissions");
+        (dir, path)
+    }
+
+    #[cfg(unix)]
+    #[test]
+    fn an_owner_only_password_file_is_read() {
+        for mode in [0o600, 0o400] {
+            let (_dir, path) = password_file(mode);
+            let secret = read_password(&PasswordSource::File(path)).expect("owner-only file");
+            assert_eq!(secret.expose_secret(), PASSWORD, "mode {mode:o}");
+        }
+    }
+
+    #[cfg(unix)]
+    #[test]
+    fn a_password_file_other_users_can_reach_is_refused() {
+        for mode in [0o644, 0o640, 0o604, 0o620, 0o602, 0o660, 0o666] {
+            let (_dir, path) = password_file(mode);
+            let error = read_password(&PasswordSource::File(path.clone()))
+                .expect_err("group- or world-accessible file");
+            match &error {
+                PasswordReadError::InsecurePermissions {
+                    path: reported,
+                    mode: reported_mode,
+                } => {
+                    assert_eq!(reported, &path);
+                    assert_eq!(*reported_mode, mode);
+                }
+                other => panic!("mode {mode:o}: expected InsecurePermissions, got {other:?}"),
+            }
+            assert!(
+                error.to_string().contains("chmod 600"),
+                "the refusal names the fix: {error}"
+            );
+            assert_no_password(&error);
+        }
+    }
+
+    #[cfg(unix)]
+    #[test]
+    fn a_missing_file_or_a_directory_is_refused() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let missing = dir.path().join("absent");
+        let error = read_password(&PasswordSource::File(missing)).expect_err("missing file");
+        assert!(matches!(error, PasswordReadError::ReadFile { .. }));
+        assert!(
+            describe(&error).contains("absent:"),
+            "the cause is rendered after the path: {}",
+            describe(&error)
+        );
+
+        use std::os::unix::fs::PermissionsExt as _;
+        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700))
+            .expect("owner-only directory");
+        let error = read_password(&PasswordSource::File(dir.path().to_path_buf()))
+            .expect_err("a directory");
+        assert!(
+            matches!(error, PasswordReadError::NotAFile { .. }),
+            "{error:?}"
+        );
+    }
+
+    #[test]
+    fn a_password_goes_over_http_only_to_this_computer() {
+        for addr in [
+            "http://127.0.0.1:9527/mcp",
+            "http://127.8.0.1:9527/mcp",
+            "http://localhost:9527/mcp",
+            "http://LocalHost:9527/mcp",
+            "http://[::1]:9527/mcp",
+            "http://0x7f.1:9527/mcp",
+        ] {
+            assert!(
+                ensure_safe_destination(addr).is_ok(),
+                "{addr} is this computer"
+            );
+        }
+    }
+
+    #[test]
+    fn a_password_goes_anywhere_over_https() {
+        for addr in [
+            "https://det.example.com/mcp",
+            "https://192.168.1.5:9527/mcp",
+        ] {
+            assert!(ensure_safe_destination(addr).is_ok(), "{addr} is encrypted");
+        }
+    }
+
+    #[test]
+    fn a_password_never_goes_unencrypted_off_this_computer() {
+        for addr in [
+            "http://192.168.1.5:9527/mcp",
+            "http://det.example.com/mcp",
+            "http://localhost.example.com/mcp",
+            "http://127.0.0.1.nip.io/mcp",
+            "http://0.0.0.0:9527/mcp",
+            "http://[::]:9527/mcp",
+            "http://[::ffff:127.0.0.1]:9527/mcp",
+            "ws://127.0.0.1:9527/mcp",
+            "127.0.0.1:9527/mcp",
+            "not a url",
+        ] {
+            match ensure_safe_destination(addr) {
+                Err(PasswordArgError::InsecureDestination { addr: reported }) => {
+                    assert_eq!(reported, addr);
+                }
+                other => panic!("{addr}: expected InsecureDestination, got {other:?}"),
+            }
+        }
+    }
+}
diff --git a/src/context/wallet_lifecycle/prepare.rs b/src/context/wallet_lifecycle/prepare.rs
index b8499c286..a92b0ed0a 100644
--- a/src/context/wallet_lifecycle/prepare.rs
+++ b/src/context/wallet_lifecycle/prepare.rs
@@ -78,6 +78,31 @@ impl AppContext {
     pub async fn prepare_storage(
         self: &Arc,
         task_result_sender: crate::utils::egui_mpsc::SenderAsync,
+    ) -> Result<(), TaskError> {
+        self.prepare_storage_with_wallet_password(task_result_sender, None)
+            .await
+    }
+
+    /// [`Self::prepare_storage`] for a caller that supplies the password of the
+    /// password-protected wallets up front: the non-interactive storage update
+    /// behind the `app_storage_update` MCP tool.
+    ///
+    /// The drain tries `wallet_password` on every wallet still locked after the
+    /// copy, through the same verification the desktop password prompt submits
+    /// to, before a prompt would otherwise be needed. The password is borrowed
+    /// for this call only and never stored. `None` is exactly
+    /// [`Self::prepare_storage`]; a preparation that already completed returns
+    /// immediately without using the password.
+    ///
+    /// # Errors
+    ///
+    /// As [`Self::prepare_storage`], plus
+    /// [`TaskError::StorageUpdatePasswordRejected`] when the password does not
+    /// open every locked wallet.
+    pub async fn prepare_storage_with_wallet_password(
+        self: &Arc,
+        task_result_sender: crate::utils::egui_mpsc::SenderAsync,
+        wallet_password: Option<&platform_wallet_storage::secrets::SecretString>,
     ) -> Result<(), TaskError> {
         let gate = self.lock_prepare_gate().await;
         if self.storage_prepared.load(Ordering::Acquire) {
@@ -101,7 +126,9 @@ impl AppContext {
             return Err(error);
         }
 
-        let drain = crate::backend_task::migration::finish_unwire::run_gated(self, &gate).await;
+        let drain =
+            crate::backend_task::migration::finish_unwire::run_gated(self, &gate, wallet_password)
+                .await;
 
         // Run the sweep on the drain's failure path too: a deterministic drain
         // failure would otherwise postpone the only recovery path for orphaned
@@ -114,7 +141,13 @@ impl AppContext {
         self.run_pending_vault_cleanup_sweep(&gate);
 
         drain?;
-        self.storage_prepared.store(true, Ordering::Release);
+        // The combined failure publishes its own banner but returns Ok to keep wallets usable.
+        if !matches!(
+            status.state().as_ref(),
+            MigrationState::FailedWithUnreadableIdentities { .. }
+        ) {
+            self.storage_prepared.store(true, Ordering::Release);
+        }
         Ok(())
     }
 
diff --git a/src/database/mod.rs b/src/database/mod.rs
index 25311f79a..221dfef38 100644
--- a/src/database/mod.rs
+++ b/src/database/mod.rs
@@ -1,6 +1,11 @@
 mod initialization;
-#[cfg(test)]
-pub(crate) use initialization::DEFAULT_DB_VERSION;
+/// Schema version a boot migrates `data.db` up to. Re-exported (plain `pub`,
+/// unconditional) so external consumers can read the authoritative value
+/// instead of hardcoding or re-parsing a copy that silently goes stale: the
+/// `app_storage_status` MCP tool reports the stored `data.db` version against
+/// it, and the cross-version migration matrix (`tests/migration-matrix/`, a
+/// separate integration-test crate) asserts against it directly.
+pub use initialization::DEFAULT_DB_VERSION;
 pub(crate) mod legacy_import;
 mod settings;
 mod single_key_wallet;
diff --git a/src/logging.rs b/src/logging.rs
index 9318e7466..e45773404 100644
--- a/src/logging.rs
+++ b/src/logging.rs
@@ -10,9 +10,30 @@ use std::sync::atomic::AtomicI32;
 use std::sync::atomic::{AtomicBool, Ordering};
 use tracing::{error, info};
 use tracing_subscriber::EnvFilter;
+use tracing_subscriber::filter::{LevelFilter, Targets};
+use tracing_subscriber::layer::SubscriberExt;
 
 static INIT_LOGGER: Once = Once::new();
 
+/// Log target of the MCP protocol library.
+const RMCP_TARGET: &str = "rmcp";
+
+/// Hard ceiling on log targets that write raw MCP traffic.
+///
+/// rmcp logs every inbound request with its raw tool arguments at DEBUG
+/// (`received request`) and every HTTP response message at TRACE. Tool
+/// arguments carry secrets — recovery phrases, private keys, wallet
+/// passwords — so those lines must never be written, whatever `RUST_LOG`
+/// says. Layered as a separate global filter, it is ANDed with the
+/// `EnvFilter`: no directive, however specific, can lift it.
+///
+/// Every tracing subscriber a DET entry point installs must layer this.
+pub fn sensitive_target_cap() -> Targets {
+    Targets::new()
+        .with_default(LevelFilter::TRACE)
+        .with_target(RMCP_TARGET, LevelFilter::INFO)
+}
+
 /// Duplicate of the real terminal stderr (fd 2), saved before it is redirected
 /// to the crash sidecar. Lets [`report_startup_failure_to_terminal`] surface a
 /// user-facing notice on the terminal even while fd 2 points at the log file.
@@ -65,7 +86,8 @@ fn initialize_logger_internal() {
                 .with_env_filter(filter)
                 .with_writer(log_file)
                 .with_ansi(false)
-                .finish();
+                .finish()
+                .with(sensitive_target_cap());
             let set = tracing::subscriber::set_global_default(subscriber).is_ok();
             if set {
                 LOGGER_USES_FILE.store(true, Ordering::SeqCst);
@@ -78,7 +100,8 @@ fn initialize_logger_internal() {
                 .with_env_filter(filter)
                 .with_writer(std::io::stderr)
                 .with_ansi(true)
-                .finish();
+                .finish()
+                .with(sensitive_target_cap());
             let set = tracing::subscriber::set_global_default(subscriber).is_ok();
             if set {
                 tracing::warn!(
@@ -531,6 +554,83 @@ mod tests {
     use super::*;
     use std::fs;
 
+    /// Captures everything a subscriber writes, for asserting on log output.
+    #[derive(Clone, Default)]
+    struct Capture(std::sync::Arc>>);
+
+    impl std::io::Write for Capture {
+        fn write(&mut self, buf: &[u8]) -> std::io::Result {
+            self.0
+                .lock()
+                .unwrap_or_else(|poisoned| poisoned.into_inner())
+                .extend_from_slice(buf);
+            Ok(buf.len())
+        }
+
+        fn flush(&mut self) -> std::io::Result<()> {
+            Ok(())
+        }
+    }
+
+    impl Capture {
+        fn text(&self) -> String {
+            let bytes = self
+                .0
+                .lock()
+                .unwrap_or_else(|poisoned| poisoned.into_inner())
+                .clone();
+            String::from_utf8(bytes).expect("log output is UTF-8")
+        }
+    }
+
+    /// Emits what rmcp logs for an inbound tool call (raw arguments at DEBUG
+    /// and TRACE) under `filter`, with the cap layered exactly as the entry
+    /// points layer it, and returns the written log text.
+    fn log_mcp_traffic_under(filter: &str) -> String {
+        let capture = Capture::default();
+        let sink = capture.clone();
+        let subscriber = tracing_subscriber::fmt()
+            .with_env_filter(EnvFilter::new(filter))
+            .with_writer(move || sink.clone())
+            .with_ansi(false)
+            .finish()
+            .with(sensitive_target_cap());
+
+        tracing::subscriber::with_default(subscriber, || {
+            tracing::debug!(target: "rmcp::service", request = "raw-secret-at-debug", "received request");
+            tracing::trace!(
+                target: "rmcp::transport::streamable_http_server::tower",
+                message = "raw-secret-at-trace"
+            );
+            tracing::info!(target: "rmcp::service", "rmcp info is kept");
+            tracing::trace!(target: "dash_evo_tool::mcp", "det trace is kept");
+        });
+        capture.text()
+    }
+
+    #[test]
+    fn raw_mcp_traffic_never_reaches_the_log_under_a_global_trace_filter() {
+        let text = log_mcp_traffic_under("trace");
+        assert!(
+            !text.contains("raw-secret"),
+            "rmcp's raw request/response logging must stay capped, got:\n{text}"
+        );
+        assert!(
+            text.contains("rmcp info is kept") && text.contains("det trace is kept"),
+            "the cap must not silence anything else, got:\n{text}"
+        );
+    }
+
+    #[test]
+    fn raw_mcp_traffic_stays_capped_even_when_rust_log_names_rmcp() {
+        let text = log_mcp_traffic_under("rmcp=trace,rmcp::service=trace");
+        assert!(
+            !text.contains("raw-secret"),
+            "an explicit RUST_LOG directive for rmcp must not lift the cap, got:\n{text}"
+        );
+        assert!(text.contains("rmcp info is kept"), "got:\n{text}");
+    }
+
     #[test]
     fn rotated_name_is_zero_padded() {
         assert_eq!(rotated_name("det", 42), "det.0000000042.log");
diff --git a/src/mcp/error.rs b/src/mcp/error.rs
index 4734ae458..a79a2a1fa 100644
--- a/src/mcp/error.rs
+++ b/src/mcp/error.rs
@@ -20,10 +20,30 @@ pub enum McpToolError {
     /// the migration that runs after the wallet backend is first wired.
     #[error("Wallet storage is still starting up. Please wait a moment and retry.")]
     StorageNotReady,
+    /// The desktop app owns the wallet password prompt of this session, so a
+    /// tool must not open a second, remote channel for the same password.
+    #[error(
+        "The Dash Evo Tool desktop app is running and asks for wallet passwords in its own window. Enter the password there to finish the storage update."
+    )]
+    DesktopOwnsPasswordPrompt,
     #[error("Backend task failed: {0}")]
     TaskFailed(#[source] TaskError),
     #[error("{0}")]
     Internal(String),
+    #[error(
+        "The saved storage state could not be read. Close other copies of Dash Evo Tool and retry."
+    )]
+    StorageInspection {
+        #[source]
+        source: rusqlite::Error,
+    },
+    #[error(
+        "The saved storage metadata could not be read. Close other copies of Dash Evo Tool and retry."
+    )]
+    StorageMetadata {
+        #[source]
+        source: crate::wallet_backend::KvAdapterError,
+    },
 }
 
 impl From for McpToolError {
@@ -41,6 +61,7 @@ const CODE_NETWORK_MISMATCH: i32 = -32002;
 const CODE_SPV_SYNC_FAILED: i32 = -32003;
 const CODE_TASK_FAILED: i32 = -32004;
 const CODE_STORAGE_NOT_READY: i32 = -32005;
+const CODE_DESKTOP_OWNS_PASSWORD_PROMPT: i32 = -32006;
 const CODE_INTERNAL: i32 = -32603; // standard JSON-RPC internal error
 
 impl From for McpError {
@@ -51,6 +72,9 @@ impl From for McpError {
             McpToolError::NetworkMismatch { .. } => (CODE_NETWORK_MISMATCH, e.to_string(), None),
             McpToolError::SpvSyncFailed => (CODE_SPV_SYNC_FAILED, e.to_string(), None),
             McpToolError::StorageNotReady => (CODE_STORAGE_NOT_READY, e.to_string(), None),
+            McpToolError::DesktopOwnsPasswordPrompt => {
+                (CODE_DESKTOP_OWNS_PASSWORD_PROMPT, e.to_string(), None)
+            }
             McpToolError::TaskFailed(task_err) => {
                 // Include the full Debug error chain so MCP clients can see
                 // the underlying cause (e.g. SDK/DAPI errors) instead of just
@@ -63,6 +87,8 @@ impl From for McpError {
                 )
             }
             McpToolError::Internal(_) => (CODE_INTERNAL, e.to_string(), None),
+            McpToolError::StorageInspection { .. } => (CODE_INTERNAL, e.to_string(), None),
+            McpToolError::StorageMetadata { .. } => (CODE_INTERNAL, e.to_string(), None),
         };
         McpError {
             code: ErrorCode(code),
diff --git a/src/mcp/resolve.rs b/src/mcp/resolve.rs
index e39a9dff4..6b3dfffbd 100644
--- a/src/mcp/resolve.rs
+++ b/src/mcp/resolve.rs
@@ -123,9 +123,27 @@ pub(crate) fn wallet_arc(
 ///
 /// Unlike [`ensure_spv_synced`], this does not start SPV or wait for chain sync.
 pub(crate) async fn ensure_wallets_hydrated(ctx: &Arc) -> Result<(), McpToolError> {
+    hydrate_wallets(ctx, None).await
+}
+
+/// [`ensure_wallets_hydrated`] for the non-interactive storage update: the
+/// drain opens the password-protected wallets with `wallet_password` instead
+/// of requiring the desktop app's password prompt. The password is borrowed
+/// for this call only.
+pub(crate) async fn ensure_wallets_hydrated_with_password(
+    ctx: &Arc,
+    wallet_password: &platform_wallet_storage::secrets::SecretString,
+) -> Result<(), McpToolError> {
+    hydrate_wallets(ctx, Some(wallet_password)).await
+}
+
+async fn hydrate_wallets(
+    ctx: &Arc,
+    wallet_password: Option<&platform_wallet_storage::secrets::SecretString>,
+) -> Result<(), McpToolError> {
     let (tx, _) = tokio::sync::mpsc::channel::(32);
     let sender = crate::utils::egui_mpsc::SenderAsync::new(tx, egui::Context::default());
-    ctx.prepare_storage(sender)
+    ctx.prepare_storage_with_wallet_password(sender, wallet_password)
         .await
         .map_err(McpToolError::TaskFailed)?;
     // Only the join remains: `prepare_storage` has already run the drain, and
diff --git a/src/mcp/server.rs b/src/mcp/server.rs
index b1ffc3ca8..b088483d2 100644
--- a/src/mcp/server.rs
+++ b/src/mcp/server.rs
@@ -130,6 +130,11 @@ impl std::fmt::Debug for DashMcpService {
 }
 
 impl DashMcpService {
+    /// Observe an initialized context without starting standalone storage.
+    pub(crate) fn initialized_ctx(&self) -> Option> {
+        self.ctx.load()
+    }
+
     /// For HTTP mode: wrap the GUI's shared ArcSwap (same reference).
     #[cfg(feature = "mcp")]
     pub fn new_shared(app_context: Arc>) -> Self {
@@ -279,7 +284,10 @@ impl DashMcpService {
             .with_async_tool::()
             .with_async_tool::()
             .with_async_tool::()
+            .with_async_tool::()
+            .with_async_tool::()
             // Identity tools
+            .with_async_tool::()
             .with_async_tool::()
             .with_async_tool::()
             .with_async_tool::()
@@ -398,6 +406,33 @@ pub async fn init_app_context() -> Result, McpError> {
             McpError::internal_error(format!("secret store open: {e}"), None)
         }
     })?;
+
+    // Carry an upgrading user's preferences (network, theme, onboarding) out
+    // of legacy `data.db` before the network is read below — the same import
+    // the GUI boot runs in `AppState::new_inner`. Skipping it boots a first
+    // post-upgrade launch on mainnet, where the legacy wallet drain finds none
+    // of a testnet user's wallets. The GUI answers a failure with a forced
+    // network chooser; det-cli has no one to ask, so it refuses to guess and
+    // the unwritten sentinel makes the next launch retry.
+    // TODO: move into the planned "doctor" module that consolidates DET data
+    // migrations and wallet repair (out of scope for now).
+    match crate::backend_task::migration::legacy_settings::import_legacy_settings(&app_kv, &db) {
+        Ok(outcome) => tracing::debug!(?outcome, "Legacy settings import"),
+        Err(e) => {
+            tracing::warn!(
+                error = ?e,
+                "Could not import preferences from the previous version — refusing to guess the network",
+            );
+            return Err(McpError::internal_error(
+                "Your network choice could not be restored from the previous version. \
+                 Open the Dash Evo Tool desktop app and confirm the network, then run this \
+                 command again."
+                    .to_string(),
+                None,
+            ));
+        }
+    }
+
     let network = app_kv
         .get::(
             crate::wallet_backend::DetScope::Global,
diff --git a/src/mcp/tests.rs b/src/mcp/tests.rs
index 98dc1c970..1c87f433b 100644
--- a/src/mcp/tests.rs
+++ b/src/mcp/tests.rs
@@ -3,6 +3,134 @@
 use crate::mcp::error::McpToolError;
 use crate::mcp::resolve;
 
+#[cfg(feature = "cli")]
+struct DataDirOverride {
+    prior: Option,
+    _lock: std::sync::MutexGuard<'static, ()>,
+}
+
+#[cfg(feature = "cli")]
+impl DataDirOverride {
+    fn new(path: &std::path::Path) -> Self {
+        let lock = crate::test_support::DASH_EVO_DATA_DIR_LOCK
+            .lock()
+            .unwrap_or_else(|error| error.into_inner());
+        let prior = std::env::var_os("DASH_EVO_DATA_DIR");
+        // Safety: the data-directory mutex serializes this override.
+        unsafe { std::env::set_var("DASH_EVO_DATA_DIR", path) };
+        Self { prior, _lock: lock }
+    }
+}
+
+#[cfg(feature = "cli")]
+impl Drop for DataDirOverride {
+    fn drop(&mut self) {
+        // Safety: `_lock` is held until after the original value is restored.
+        unsafe {
+            match &self.prior {
+                Some(value) => std::env::set_var("DASH_EVO_DATA_DIR", value),
+                None => std::env::remove_var("DASH_EVO_DATA_DIR"),
+            }
+        }
+    }
+}
+
+#[cfg(feature = "cli")]
+#[tokio::test]
+async fn standalone_storage_status_does_not_initialize_a_profile() {
+    use crate::mcp::server::DashMcpService;
+    use crate::mcp::tools::{NetworkParams, meta::AppStorageStatus};
+    use rmcp::handler::server::router::tool::AsyncTool;
+
+    let dir = tempfile::tempdir().expect("tempdir");
+    let _override = DataDirOverride::new(dir.path());
+    let service = DashMcpService::new_lazy();
+    let output = AppStorageStatus::invoke(&service, NetworkParams::default())
+        .await
+        .expect("inspect an empty profile");
+    let json = serde_json::to_value(output).expect("serialize status");
+    assert!(json["data_db_version"].is_null());
+    assert!(json["wallet_storage_lineage"].is_null());
+    assert_eq!(
+        std::fs::read_dir(dir.path())
+            .expect("read directory")
+            .count(),
+        0
+    );
+}
+
+#[cfg(feature = "mcp")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn identity_list_reports_only_the_persisted_wallet_binding() {
+    use crate::mcp::server::DashMcpService;
+    use crate::mcp::tools::{NetworkParams, identity::ListIdentitiesTool};
+    use crate::model::qualified_identity::{IdentityStatus, IdentityType, QualifiedIdentity};
+    use dash_sdk::dpp::{dashcore::Network, identity::Identity, prelude::Identifier};
+    use rmcp::handler::server::router::tool::AsyncTool;
+    use std::sync::Arc;
+
+    let dir = tempfile::tempdir().unwrap();
+    let ctx = legacy_wallet_context(dir.path());
+    let mut hashes = Vec::new();
+    for (seed, alias) in [([0x92; 64], "Owner"), ([0x93; 64], "Unrelated")] {
+        let hash = crate::model::wallet::ClosedKeyItem::compute_seed_hash(&seed);
+        let xpub = crate::database::test_helpers::legacy_master_epk_bytes(&seed, Network::Testnet);
+        crate::database::test_helpers::seed_legacy_unprotected_hd_wallet_row(
+            &ctx.db,
+            &hash,
+            &seed,
+            &xpub,
+            alias,
+            Network::Testnet,
+        )
+        .unwrap();
+        hashes.push(hash);
+    }
+    resolve::ensure_wallets_hydrated(&ctx).await.unwrap();
+    for (byte, link) in [(1, Some((hashes[0], 7))), (2, None)] {
+        let identity = QualifiedIdentity {
+            identity: Identity::create_basic_identity(
+                Identifier::new([byte; 32]),
+                dash_sdk::dpp::version::PlatformVersion::latest(),
+            )
+            .unwrap(),
+            associated_voter_identity: None,
+            associated_operator_identity: None,
+            associated_owner_key_id: None,
+            identity_type: IdentityType::User,
+            alias: None,
+            private_keys: Default::default(),
+            dpns_names: Vec::new(),
+            associated_wallets: Default::default(),
+            secret_access: None,
+            wallet_index: None,
+            top_ups: Default::default(),
+            status: IdentityStatus::Active,
+            network: Network::Testnet,
+        };
+        ctx.insert_local_qualified_identity(&identity, &link)
+            .unwrap();
+    }
+    let loaded = ctx.load_local_qualified_identities().unwrap();
+    assert!(loaded.iter().all(|qi| qi.associated_wallets.len() == 2));
+    let service = DashMcpService::new_shared(Arc::new(arc_swap::ArcSwap::new(Arc::clone(&ctx))));
+    let output = ListIdentitiesTool::invoke(&service, NetworkParams::default())
+        .await
+        .unwrap();
+    let json = serde_json::to_value(output).unwrap();
+    ctx.wallet_backend().unwrap().shutdown().await;
+    assert_eq!(
+        json["identities"][0]["wallet_seed_hashes"],
+        serde_json::json!([hex::encode(hashes[0])])
+    );
+    assert_eq!(json["identities"][0]["wallet_index"], 7);
+    assert_eq!(
+        json["identities"][1]["wallet_seed_hashes"],
+        serde_json::json!([])
+    );
+    assert!(json["identities"][1]["wallet_index"].is_null());
+}
+
 pub(super) fn legacy_wallet_context(
     data_dir: &std::path::Path,
 ) -> std::sync::Arc {
@@ -194,6 +322,7 @@ fn error_codes_are_distinct() {
         McpToolError::SpvSyncFailed,
         McpToolError::StorageNotReady,
         McpToolError::Internal("x".into()),
+        McpToolError::DesktopOwnsPasswordPrompt,
     ];
 
     let codes: Vec = variants
@@ -204,8 +333,9 @@ fn error_codes_are_distinct() {
         })
         .collect();
 
-    // WalletNotFound, NetworkMismatch, SpvSyncFailed, StorageNotReady should have unique custom codes
-    let custom_codes: Vec = vec![codes[0], codes[2], codes[3], codes[4]];
+    // WalletNotFound, NetworkMismatch, SpvSyncFailed, StorageNotReady and
+    // DesktopOwnsPasswordPrompt should have unique custom codes
+    let custom_codes: Vec = vec![codes[0], codes[2], codes[3], codes[4], codes[6]];
     let unique: std::collections::HashSet = custom_codes.iter().copied().collect();
     assert_eq!(
         unique.len(),
@@ -214,6 +344,49 @@ fn error_codes_are_distinct() {
     );
 }
 
+/// A standalone det-cli boot must restore the network an upgrading v0.9.3 user
+/// saved in `data.db`, exactly as the GUI boot does. Falling back to mainnet
+/// points the legacy wallet drain at a network holding none of their wallets.
+#[cfg(feature = "cli")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn standalone_boot_restores_the_legacy_network() {
+    use dash_sdk::dpp::dashcore::Network;
+
+    let dir = tempfile::tempdir().expect("tempdir");
+    {
+        let conn = rusqlite::Connection::open(dir.path().join("data.db")).expect("create data.db");
+        // The `settings` table exactly as v0.9.3 (schema version 11) left it.
+        conn.execute_batch(
+            "CREATE TABLE settings (
+                id INTEGER PRIMARY KEY CHECK (id = 1),
+                password_check BLOB,
+                main_password_salt BLOB,
+                main_password_nonce BLOB,
+                network TEXT NOT NULL,
+                start_root_screen INTEGER NOT NULL,
+                custom_dash_qt_path TEXT,
+                overwrite_dash_conf INTEGER,
+                theme_preference TEXT DEFAULT 'System',
+                database_version INTEGER NOT NULL
+            );
+            INSERT INTO settings (id, network, start_root_screen, database_version)
+            VALUES (1, 'testnet', 5, 11);",
+        )
+        .expect("write the v0.9.3 settings row");
+    }
+    let _override = DataDirOverride::new(dir.path());
+
+    let ctx = crate::mcp::server::init_app_context()
+        .await
+        .expect("standalone boot over a v0.9.3 data dir");
+
+    assert_eq!(
+        ctx.network(),
+        Network::Testnet,
+        "an upgrading testnet user must not boot on mainnet"
+    );
+}
+
 #[test]
 fn storage_not_ready_display_is_actionable() {
     let err = McpToolError::StorageNotReady;
@@ -240,3 +413,90 @@ fn storage_not_ready_has_dedicated_error_code() {
         "StorageNotReady code should be in the custom range"
     );
 }
+
+// ── app_storage_update ─────────────────────────────────────────
+
+/// Drives `app_storage_update` through its real `invoke` against `ctx`, over
+/// the shared (GUI-embedded) service shape.
+#[cfg(feature = "mcp")]
+async fn invoke_storage_update(
+    ctx: &std::sync::Arc,
+    password: &str,
+) -> Result {
+    use rmcp::handler::server::router::tool::AsyncTool;
+
+    let service = crate::mcp::server::DashMcpService::new_shared(std::sync::Arc::new(
+        arc_swap::ArcSwap::new(std::sync::Arc::clone(ctx)),
+    ));
+    let params: crate::mcp::tools::meta::AppStorageUpdateParams =
+        serde_json::from_value(serde_json::json!({ "password": password }))
+            .expect("parameters deserialize");
+    crate::mcp::tools::meta::AppStorageUpdate::invoke(&service, params).await
+}
+
+/// A desktop session asks for wallet passwords in its own window, so the tool
+/// refuses before touching storage rather than open a remote channel into it.
+#[cfg(feature = "mcp")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn storage_update_is_refused_while_the_desktop_owns_the_password_prompt() {
+    use crate::context::migration_status::MigrationState;
+
+    let temp_dir = tempfile::tempdir().expect("tempdir");
+    let ctx = legacy_wallet_context(temp_dir.path());
+    ctx.install_secret_prompt(std::sync::Arc::new(
+        crate::wallet_backend::secret_prompt::test_support::TestPrompt::never(),
+    ));
+
+    let result = invoke_storage_update(&ctx, "any-wallet-password").await;
+
+    assert!(
+        matches!(result, Err(McpToolError::DesktopOwnsPasswordPrompt)),
+        "a desktop session must refuse the tool"
+    );
+    assert_eq!(
+        *ctx.migration_status().state(),
+        MigrationState::Idle,
+        "a refused call must not start the storage update"
+    );
+}
+
+#[cfg(feature = "mcp")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn storage_update_refuses_an_empty_password() {
+    let temp_dir = tempfile::tempdir().expect("tempdir");
+    let ctx = legacy_wallet_context(temp_dir.path());
+
+    let result = invoke_storage_update(&ctx, "").await;
+
+    assert!(
+        matches!(result, Err(McpToolError::InvalidParam { .. })),
+        "an empty password must be refused"
+    );
+}
+
+/// A headless call prepares storage end to end and reports the terminal state.
+/// With no protected wallet on disk the password is simply unused.
+#[cfg(feature = "mcp")]
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn storage_update_runs_the_update_headless_and_reports_its_state() {
+    let temp_dir = tempfile::tempdir().expect("tempdir");
+    let ctx = legacy_wallet_context(temp_dir.path());
+
+    let output = invoke_storage_update(&ctx, "unused-wallet-password")
+        .await
+        .expect("a headless storage update with nothing to unlock succeeds");
+    let json = serde_json::to_value(&output).expect("output serializes");
+    if let Ok(backend) = ctx.wallet_backend() {
+        backend.shutdown().await;
+    }
+
+    let state = json["migration"]["state"].as_str();
+    assert!(
+        matches!(state, Some("ready") | Some("success")),
+        "expected a terminal success state, got {json}"
+    );
+    assert!(
+        !json.to_string().contains("unused-wallet-password"),
+        "the output must never echo the password"
+    );
+}
diff --git a/src/mcp/tools/identity.rs b/src/mcp/tools/identity.rs
index 6f4a0895d..e0a571d4a 100644
--- a/src/mcp/tools/identity.rs
+++ b/src/mcp/tools/identity.rs
@@ -1,4 +1,4 @@
-//! Identity-related MCP tools: top-up, transfer, withdraw.
+//! Identity-related MCP tools: listing, top-up, transfer, withdraw.
 
 use std::borrow::Cow;
 use std::collections::BTreeMap;
@@ -15,6 +15,102 @@ use crate::mcp::dispatch::dispatch_task;
 use crate::mcp::error::McpToolError;
 use crate::mcp::resolve;
 use crate::mcp::server::DashMcpService;
+use crate::mcp::tools::NetworkParams;
+
+// ---------------------------------------------------------------------------
+// ListIdentitiesTool
+// ---------------------------------------------------------------------------
+
+/// List the identities persisted locally for the active network.
+pub struct ListIdentitiesTool;
+
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct IdentityEntry {
+    /// Base58-encoded identity ID.
+    id: String,
+    alias: Option,
+    /// `User`, `Masternode` or `Evonode`.
+    identity_type: String,
+    /// Last known Platform status, e.g. `Active` or `Unknown`.
+    status: String,
+    balance_credits: u64,
+    /// DPNS names as last persisted locally; empty until a name refresh ran.
+    dpns_names: Vec,
+    /// HD index this identity was registered at, when it belongs to a wallet.
+    wallet_index: Option,
+    /// Hex seed hashes of the wallets this identity is bound to.
+    wallet_seed_hashes: Vec,
+}
+
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct ListIdentitiesOutput {
+    identities: Vec,
+}
+
+impl ToolBase for ListIdentitiesTool {
+    type Parameter = NetworkParams;
+    type Output = ListIdentitiesOutput;
+    type Error = McpToolError;
+
+    fn name() -> Cow<'static, str> {
+        "identity_list".into()
+    }
+
+    fn description() -> Option> {
+        Some(
+            "List the identities saved for the active network, with their DPNS names, \
+             balances and wallet bindings. Prepares local storage when needed, then \
+             reads saved identities without refreshing them from Platform."
+                .into(),
+        )
+    }
+
+    fn annotations() -> Option {
+        Some(ToolAnnotations::default().read_only(true).open_world(false))
+    }
+}
+
+impl AsyncTool for ListIdentitiesTool {
+    async fn invoke(
+        service: &DashMcpService,
+        param: NetworkParams,
+    ) -> Result {
+        let ctx = service.tool_ctx().await?;
+        resolve::verify_network(&ctx, param.network.as_deref())?;
+        // Opens this network's storage so the identity read has a store to read
+        // from. No SPV gate: every field below comes from persisted state, so
+        // this reports what is on disk rather than what the chain currently says.
+        resolve::ensure_wallets_hydrated(&ctx).await?;
+
+        let identities = ctx
+            .load_local_qualified_identities()
+            .map_err(McpToolError::TaskFailed)?
+            .into_iter()
+            .map(|qi| {
+                let link = ctx
+                    .stored_identity_wallet_link(&qi.identity.id())
+                    .map_err(McpToolError::TaskFailed)?;
+                Ok(IdentityEntry {
+                    id: qi.identity.id().to_string(
+                        dash_sdk::dpp::platform_value::string_encoding::Encoding::Base58,
+                    ),
+                    identity_type: qi.identity_type.to_string(),
+                    status: qi.status.to_string(),
+                    balance_credits: qi.identity.balance(),
+                    alias: qi.alias,
+                    dpns_names: qi.dpns_names.into_iter().map(|name| name.name).collect(),
+                    wallet_index: link.map(|(_, index)| index),
+                    wallet_seed_hashes: link
+                        .map(|(hash, _)| hex::encode(hash))
+                        .into_iter()
+                        .collect(),
+                })
+            })
+            .collect::>()?;
+
+        Ok(ListIdentitiesOutput { identities })
+    }
+}
 
 // ---------------------------------------------------------------------------
 // IdentityCreditsTopup (Core -> Identity via asset lock)
diff --git a/src/mcp/tools/meta.rs b/src/mcp/tools/meta.rs
index 3a85663f5..d9be4f987 100644
--- a/src/mcp/tools/meta.rs
+++ b/src/mcp/tools/meta.rs
@@ -1,15 +1,32 @@
-//! Meta MCP tool: describe_tool.
+//! Meta MCP tools: `tool_describe`, `app_storage_status` and
+//! `app_storage_update`.
 
 use std::borrow::Cow;
+use std::path::Path;
+use std::time::Duration;
 
+use dash_sdk::dpp::dashcore::Network;
+use platform_wallet_storage::secrets::SecretString;
 use rmcp::handler::server::router::tool::{AsyncTool, ToolBase};
 use rmcp::model::ToolAnnotations;
 use rmcp::schemars;
-use serde::Serialize;
+use rusqlite::{Connection, OpenFlags, OptionalExtension};
+use serde::{Deserialize, Serialize};
 
+use crate::backend_task::migration::MigrationError;
+use crate::backend_task::migration::finish_unwire::{
+    MigrationCompletion, app_data_sentinel_key_for, dapi_refresh_sentinel_key_for,
+    identities_sentinel_key_for, sentinel_key_for,
+};
+use crate::context::migration_status::{MigrationState, MigrationStep};
+use crate::database::DEFAULT_DB_VERSION;
+use crate::database::{Database, table_exists};
 use crate::mcp::error::McpToolError;
-use crate::mcp::server::DashMcpService;
-use crate::mcp::tools::ToolNameParams;
+use crate::mcp::resolve;
+use crate::mcp::server::{DashMcpService, network_display_name};
+use crate::mcp::tools::{NetworkParams, ToolNameParams};
+use crate::model::settings::AppSettings;
+use crate::wallet_backend::{DetKv, DetScope};
 
 /// Return the full tool definition (schema, annotations, description) for a tool.
 pub struct DescribeTool;
@@ -71,3 +88,713 @@ impl AsyncTool for DescribeTool {
         Ok(DescribeToolOutput { tool: value })
     }
 }
+
+// ---------------------------------------------------------------------------
+// AppStorageStatus
+// ---------------------------------------------------------------------------
+
+/// Every network whose upgrade markers live in the cross-network app store.
+const ALL_NETWORKS: [Network; 4] = [
+    Network::Mainnet,
+    Network::Testnet,
+    Network::Devnet,
+    Network::Regtest,
+];
+
+/// The persister keeps `det-app.sqlite` open, so wait for a concurrent write
+/// rather than reporting a false "no schema history".
+const SCHEMA_HISTORY_BUSY_TIMEOUT: Duration = Duration::from_secs(5);
+
+/// Report the on-disk storage state that an upgrade is expected to change.
+pub struct AppStorageStatus;
+
+/// One completion marker as the migration wrote it.
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct SentinelRecord {
+    /// Unix-epoch seconds at which the pass completed.
+    completed_at: i64,
+    /// Version of the build that wrote the marker.
+    sha: String,
+    network_count: u32,
+}
+
+/// The four independent upgrade passes, per network. `None` means the pass has
+/// not completed for that network — it will run (or re-run) on the next launch.
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct NetworkSentinels {
+    network: String,
+    wallet_drain: Option,
+    app_data: Option,
+    identities: Option,
+    dapi_refresh: Option,
+}
+
+/// Legacy rows a completed upgrade could not decode.
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct UnreadableCounts {
+    identities: u32,
+    votes: u32,
+    top_ups: u32,
+}
+
+/// The live migration state machine, flattened for a JSON client.
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct MigrationSummary {
+    /// Machine-readable state name, e.g. `idle`, `running`, `success`, `failed`.
+    state: String,
+    /// Which pass is executing, set only while `state` is `running`.
+    step: Option,
+    /// Failure text, set only for the two failed states.
+    error: Option,
+    unreadable: Option,
+}
+
+/// Newest migration applied to the upstream wallet-storage schema.
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct WalletStorageLineage {
+    version: i64,
+    name: String,
+    checksum: String,
+}
+
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct AppStorageStatusOutput {
+    /// Version of the running build.
+    app_version: String,
+    active_network: String,
+    /// `data.db` schema version as stored; `null` when the settings table is absent.
+    data_db_version: Option,
+    /// Version this build's schema ladder brings `data.db` to.
+    data_db_expected_version: u16,
+    data_db_up_to_date: bool,
+    /// Identifies which upstream schema line the profile is on. `null` when the
+    /// app store has no migration history yet — a fresh profile, or one written
+    /// by a build that predates the upstream store.
+    wallet_storage_lineage: Option,
+    /// In-memory state of the process answering this call, so a one-shot CLI
+    /// invocation reports `idle`. The durable record is `sentinels`.
+    migration: MigrationSummary,
+    sentinels: Vec,
+}
+
+impl ToolBase for AppStorageStatus {
+    type Parameter = NetworkParams;
+    type Output = AppStorageStatusOutput;
+    type Error = McpToolError;
+
+    fn name() -> Cow<'static, str> {
+        "app_storage_status".into()
+    }
+
+    fn description() -> Option> {
+        Some(
+            "Report the local storage state: the app database schema version against \
+             the version this build expects, the upstream wallet-storage schema lineage, \
+             the live migration state, and each network's upgrade completion markers. \
+             Diagnostic only — it reads on-disk state without starting or advancing an upgrade."
+                .into(),
+        )
+    }
+
+    fn annotations() -> Option {
+        Some(ToolAnnotations::default().read_only(true).open_world(false))
+    }
+}
+
+impl AsyncTool for AppStorageStatus {
+    async fn invoke(
+        service: &DashMcpService,
+        param: NetworkParams,
+    ) -> Result {
+        let Some(ctx) = service.initialized_ctx() else {
+            let data_dir = crate::app_dir::app_user_data_dir_path().map_err(|source| {
+                McpToolError::TaskFailed(crate::backend_task::error::TaskError::FileSystem {
+                    source,
+                })
+            })?;
+            return inspect_storage(&data_dir, param.network.as_deref());
+        };
+        resolve::verify_network(&ctx, param.network.as_deref())?;
+        // Deliberately no `ensure_wallets_hydrated` / `ensure_spv_synced`: this
+        // tool must observe the upgrade, not trigger it. Everything it reads is
+        // reachable straight off `AppContext`.
+
+        let data_db_version = ctx.db.stored_data_version().map_err(storage_read_error)?;
+
+        let app_kv = ctx.app_kv();
+        let mut sentinels = Vec::with_capacity(ALL_NETWORKS.len());
+        for network in ALL_NETWORKS {
+            sentinels.push(NetworkSentinels {
+                network: network_display_name(network).to_owned(),
+                wallet_drain: read_sentinel(&app_kv, &sentinel_key_for(network))?,
+                app_data: read_sentinel(&app_kv, &app_data_sentinel_key_for(network))?,
+                identities: read_sentinel(&app_kv, &identities_sentinel_key_for(network))?,
+                dapi_refresh: read_sentinel(&app_kv, &dapi_refresh_sentinel_key_for(network))?,
+            });
+        }
+
+        Ok(AppStorageStatusOutput {
+            app_version: crate::VERSION.to_owned(),
+            active_network: network_display_name(ctx.network()).to_owned(),
+            data_db_version,
+            data_db_expected_version: DEFAULT_DB_VERSION,
+            data_db_up_to_date: data_db_version == Some(i64::from(DEFAULT_DB_VERSION)),
+            wallet_storage_lineage: wallet_storage_lineage(ctx.data_dir())?,
+            migration: summarize_migration(&ctx.migration_status().state()),
+            sentinels,
+        })
+    }
+}
+
+/// Read one completion marker through the same k/v access the upgrade uses.
+fn read_sentinel(app_kv: &DetKv, key: &str) -> Result, McpToolError> {
+    app_kv
+        .get::(DetScope::Global, key)
+        .map(|found| {
+            found.map(|completion| SentinelRecord {
+                completed_at: completion.completed_at,
+                sha: completion.sha,
+                network_count: completion.network_count,
+            })
+        })
+        .map_err(|source| McpToolError::TaskFailed(MigrationError::Sentinel { source }.into()))
+}
+
+/// Missing storage or history is absent; unreadable or corrupt storage is an error.
+fn wallet_storage_lineage(data_dir: &Path) -> Result, McpToolError> {
+    let Some(conn) = open_existing(&data_dir.join("det-app.sqlite"))? else {
+        return Ok(None);
+    };
+    read_wallet_storage_lineage(&conn).map_err(storage_read_error)
+}
+
+fn read_wallet_storage_lineage(
+    conn: &Connection,
+) -> rusqlite::Result> {
+    if !table_exists(conn, "refinery_schema_history")? {
+        return Ok(None);
+    }
+    conn.query_row(
+        "SELECT version, name, checksum FROM refinery_schema_history \
+         ORDER BY version DESC LIMIT 1",
+        [],
+        |row| {
+            Ok(WalletStorageLineage {
+                version: row.get(0)?,
+                name: row.get(1)?,
+                checksum: row.get(2)?,
+            })
+        },
+    )
+    .optional()
+}
+
+fn storage_read_error(source: rusqlite::Error) -> McpToolError {
+    McpToolError::StorageInspection { source }
+}
+
+fn open_existing(path: &Path) -> Result, McpToolError> {
+    if !path.try_exists().map_err(|source| {
+        McpToolError::TaskFailed(crate::backend_task::error::TaskError::FileSystem { source })
+    })? {
+        return Ok(None);
+    }
+    let conn = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
+        .map_err(storage_read_error)?;
+    conn.busy_timeout(SCHEMA_HISTORY_BUSY_TIMEOUT)
+        .map_err(storage_read_error)?;
+    Ok(Some(conn))
+}
+
+fn inspect_storage(
+    data_dir: &Path,
+    expected: Option<&str>,
+) -> Result {
+    let app = open_existing(&data_dir.join("det-app.sqlite"))?;
+    let legacy_path = data_dir.join("data.db");
+    let legacy = if open_existing(&legacy_path)?.is_some() {
+        Some(Database::open_legacy_read_only(&legacy_path).map_err(storage_read_error)?)
+    } else {
+        None
+    };
+    let data_db_version = legacy
+        .as_ref()
+        .map(Database::stored_data_version)
+        .transpose()
+        .map_err(storage_read_error)?
+        .flatten();
+    let settings: Option = app
+        .as_ref()
+        .map(|conn| DetKv::read_global(conn, AppSettings::KV_KEY))
+        .transpose()
+        .map_err(|source| McpToolError::StorageMetadata { source })?
+        .flatten();
+    let network = match settings {
+        Some(settings) => settings.network,
+        None => legacy
+            .as_ref()
+            .map(Database::read_legacy_app_settings)
+            .transpose()
+            .map_err(storage_read_error)?
+            .flatten()
+            .map(|settings| settings.network)
+            .unwrap_or(Network::Mainnet),
+    };
+    let active_network = network_display_name(network).to_owned();
+    if let Some(expected) = expected
+        && !expected.eq_ignore_ascii_case(&active_network)
+    {
+        return Err(McpToolError::NetworkMismatch {
+            expected: expected.to_owned(),
+            actual: active_network,
+        });
+    }
+    let read = |key: &str| -> Result, McpToolError> {
+        Ok(app
+            .as_ref()
+            .map(|conn| DetKv::read_global::(conn, key))
+            .transpose()
+            .map_err(|source| McpToolError::TaskFailed(MigrationError::Sentinel { source }.into()))?
+            .flatten()
+            .map(|completion| SentinelRecord {
+                completed_at: completion.completed_at,
+                sha: completion.sha,
+                network_count: completion.network_count,
+            }))
+    };
+    let sentinels = ALL_NETWORKS
+        .into_iter()
+        .map(|network| {
+            Ok(NetworkSentinels {
+                network: network_display_name(network).to_owned(),
+                wallet_drain: read(&sentinel_key_for(network))?,
+                app_data: read(&app_data_sentinel_key_for(network))?,
+                identities: read(&identities_sentinel_key_for(network))?,
+                dapi_refresh: read(&dapi_refresh_sentinel_key_for(network))?,
+            })
+        })
+        .collect::>()?;
+    Ok(AppStorageStatusOutput {
+        app_version: crate::VERSION.to_owned(),
+        active_network,
+        data_db_version,
+        data_db_expected_version: DEFAULT_DB_VERSION,
+        data_db_up_to_date: data_db_version == Some(i64::from(DEFAULT_DB_VERSION)),
+        wallet_storage_lineage: app
+            .as_ref()
+            .map(read_wallet_storage_lineage)
+            .transpose()
+            .map_err(storage_read_error)?
+            .flatten(),
+        migration: summarize_migration(&MigrationState::Idle),
+        sentinels,
+    })
+}
+
+/// Finish the storage update for password-protected wallets without the
+/// desktop app's password prompt.
+pub struct AppStorageUpdate;
+
+/// Parameters for `app_storage_update`.
+///
+/// `password` deserializes straight into guarded memory and its `Debug` is
+/// redacted, so the derived `Debug` cannot leak it into a log line or into an
+/// MCP error's `data` payload. It carries no `serde(default)`, so the schema
+/// holds no default value either.
+#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
+pub struct AppStorageUpdateParams {
+    /// Password of the wallets that were password-protected in the previous
+    /// version. It is tried on every such wallet, so they must all share it.
+    /// Never stored and never echoed. From det-cli, pass it with
+    /// --password-stdin or --password-file.
+    #[schemars(with = "String")]
+    pub password: SecretString,
+    /// Expected network (e.g. "mainnet", "testnet"). If provided, the request
+    /// fails when it doesn't match the server's active network.
+    #[serde(default)]
+    pub network: Option,
+}
+
+#[derive(Serialize, schemars::JsonSchema)]
+pub struct AppStorageUpdateOutput {
+    /// Migration state once the update has run, as `app_storage_status`
+    /// reports it.
+    migration: MigrationSummary,
+}
+
+impl ToolBase for AppStorageUpdate {
+    type Parameter = AppStorageUpdateParams;
+    type Output = AppStorageUpdateOutput;
+    type Error = McpToolError;
+
+    fn name() -> Cow<'static, str> {
+        "app_storage_update".into()
+    }
+
+    fn description() -> Option> {
+        Some(
+            "Finish the storage update of an upgraded installation whose wallets were \
+             password-protected, without the desktop app. The password is tried on every \
+             wallet that is still locked, so they must all share it; a wallet it does not \
+             open fails the update and nothing is skipped. The password is never stored \
+             or echoed. A no-op once the storage update has finished. Refused while the \
+             desktop app is running, which asks for the password itself. From det-cli, \
+             supply the password with --password-stdin or --password-file, never as \
+             password=...."
+                .into(),
+        )
+    }
+
+    fn annotations() -> Option {
+        Some(
+            ToolAnnotations::default()
+                .read_only(false)
+                .destructive(false)
+                .idempotent(true)
+                .open_world(false),
+        )
+    }
+}
+
+impl AsyncTool for AppStorageUpdate {
+    async fn invoke(
+        service: &DashMcpService,
+        param: AppStorageUpdateParams,
+    ) -> Result {
+        let ctx = service.tool_ctx().await?;
+        resolve::verify_network(&ctx, param.network.as_deref())?;
+        // A desktop session collects wallet passwords in its own window, and its
+        // storage update may be parked on that prompt while holding the
+        // preparation gate. Never add a remote channel for the same password.
+        // TODO: this sees only a desktop app in this process. A
+        // standalone det-cli sharing the data directory with a running desktop
+        // app in another process is not refused; that needs a cross-process
+        // lock on the data directory. Accepted limitation, see
+        // docs/ai-design/2026-07-14-migration-password-prompt/design.md.
+        if ctx.has_interactive_secret_prompt() {
+            return Err(McpToolError::DesktopOwnsPasswordPrompt);
+        }
+        if param.password.is_empty() {
+            return Err(McpToolError::InvalidParam {
+                message:
+                    "The password is empty. Supply the password of your password-protected wallets."
+                        .to_owned(),
+            });
+        }
+
+        // TODO: wrong passwords are not rate-limited. Every call costs
+        // one Argon2id derivation per locked wallet and nothing more, so a
+        // bearer-token holder can guess repeatedly. Needs attempt throttling
+        // with backoff. Accepted limitation, see
+        // docs/ai-design/2026-07-14-migration-password-prompt/design.md.
+        resolve::ensure_wallets_hydrated_with_password(&ctx, ¶m.password).await?;
+
+        Ok(AppStorageUpdateOutput {
+            migration: summarize_migration(&ctx.migration_status().state()),
+        })
+    }
+}
+
+/// Flatten the migration state machine. Matched exhaustively so a new state or
+/// step fails the build here instead of silently reporting the wrong thing.
+fn summarize_migration(state: &MigrationState) -> MigrationSummary {
+    let summary = |state: &str| MigrationSummary {
+        state: state.to_owned(),
+        step: None,
+        error: None,
+        unreadable: None,
+    };
+
+    match state {
+        MigrationState::Idle => summary("idle"),
+        MigrationState::Ready => summary("ready"),
+        MigrationState::Running { step } => MigrationSummary {
+            step: Some(step_name(*step).to_owned()),
+            ..summary("running")
+        },
+        MigrationState::AwaitingWalletPasswords { .. } => summary("awaiting_wallet_passwords"),
+        MigrationState::Success => summary("success"),
+        MigrationState::SucceededWithUnreadableData {
+            identities,
+            votes,
+            top_ups,
+        } => MigrationSummary {
+            unreadable: Some(UnreadableCounts {
+                identities: *identities,
+                votes: *votes,
+                top_ups: *top_ups,
+            }),
+            ..summary("succeeded_with_unreadable_data")
+        },
+        MigrationState::FailedWithUnreadableIdentities { count, error } => MigrationSummary {
+            error: Some(error.to_string()),
+            unreadable: Some(UnreadableCounts {
+                identities: *count,
+                votes: 0,
+                top_ups: 0,
+            }),
+            ..summary("failed_with_unreadable_identities")
+        },
+        MigrationState::Failed { error } => MigrationSummary {
+            error: Some(error.to_string()),
+            ..summary("failed")
+        },
+    }
+}
+
+fn step_name(step: MigrationStep) -> &'static str {
+    match step {
+        MigrationStep::Wiring => "wiring",
+        MigrationStep::Detecting => "detecting",
+        MigrationStep::AppData => "app_data",
+        MigrationStep::SingleKey => "single_key",
+        MigrationStep::Shielded => "shielded",
+        MigrationStep::WalletSeeds => "wallet_seeds",
+        MigrationStep::WalletMeta => "wallet_meta",
+        MigrationStep::Identities => "identities",
+        MigrationStep::Finalize => "finalize",
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::collections::BTreeSet;
+    use std::sync::Arc;
+
+    fn failure() -> Arc {
+        Arc::new(MigrationError::WalletBackendUnavailable)
+    }
+
+    const PASSWORD: &str = "correct-horse-canary";
+
+    /// The password lands in guarded memory intact, and neither the derived
+    /// `Debug` of the parameters nor anything built from it reveals it.
+    #[test]
+    fn storage_update_params_never_reveal_the_password() {
+        let params: AppStorageUpdateParams = serde_json::from_value(serde_json::json!({
+            "password": PASSWORD,
+            "network": "testnet",
+        }))
+        .expect("parameters deserialize");
+
+        assert_eq!(params.password.expose_secret(), PASSWORD);
+        let debug = format!("{params:?}");
+        assert!(
+            !debug.contains(PASSWORD),
+            "Debug must redact the password: {debug}"
+        );
+        assert!(
+            debug.contains("testnet"),
+            "Debug still shows the rest: {debug}"
+        );
+    }
+
+    /// The advertised schema is a plain required string: no `$ref` an MCP client
+    /// may not resolve, and no default, example or length policy to leak.
+    #[test]
+    fn storage_update_schema_advertises_the_password_as_a_plain_required_string() {
+        let schema = AppStorageUpdate::input_schema().expect("the tool takes parameters");
+        let password = schema
+            .get("properties")
+            .and_then(|properties| properties.get("password"))
+            .and_then(|password| password.as_object())
+            .expect("a password property");
+
+        assert_eq!(
+            password.get("type").and_then(|t| t.as_str()),
+            Some("string")
+        );
+        for leaked in [
+            "$ref",
+            "default",
+            "examples",
+            "minLength",
+            "maxLength",
+            "pattern",
+        ] {
+            assert!(
+                !password.contains_key(leaked),
+                "the password schema must not carry `{leaked}`: {password:?}"
+            );
+        }
+        let required: Vec<&str> = schema
+            .get("required")
+            .and_then(|required| required.as_array())
+            .map(|required| required.iter().filter_map(|v| v.as_str()).collect())
+            .unwrap_or_default();
+        assert_eq!(required, ["password"]);
+    }
+
+    /// Every step needs its own name, or a caller reading `step` cannot tell two
+    /// passes apart.
+    #[test]
+    fn every_migration_step_has_a_distinct_name() {
+        let names: BTreeSet<&str> = MigrationStep::ALL.iter().map(|s| step_name(*s)).collect();
+
+        assert_eq!(names.len(), MigrationStep::ALL.len());
+        assert!(names.iter().all(|name| !name.is_empty()));
+    }
+
+    /// An executing upgrade names the pass it is on; a terminal one has no pass.
+    #[test]
+    fn running_reports_its_step_and_a_terminal_state_does_not() {
+        let running = summarize_migration(&MigrationState::Running {
+            step: MigrationStep::WalletSeeds,
+        });
+        assert_eq!(running.state, "running");
+        assert_eq!(running.step.as_deref(), Some("wallet_seeds"));
+        assert!(running.error.is_none());
+
+        let success = summarize_migration(&MigrationState::Success);
+        assert_eq!(success.state, "success");
+        assert!(success.step.is_none());
+        assert!(success.unreadable.is_none());
+    }
+
+    /// Failure states carry the typed error's own text — never a message this
+    /// tool invents — and the partial one also reports the rows left behind.
+    #[test]
+    fn failure_states_carry_error_text_and_unreadable_counts() {
+        let expected = failure().to_string();
+
+        let failed = summarize_migration(&MigrationState::Failed { error: failure() });
+        assert_eq!(failed.state, "failed");
+        assert_eq!(failed.error.as_deref(), Some(expected.as_str()));
+        assert!(failed.unreadable.is_none());
+
+        let partial = summarize_migration(&MigrationState::FailedWithUnreadableIdentities {
+            count: 3,
+            error: failure(),
+        });
+        assert_eq!(partial.state, "failed_with_unreadable_identities");
+        assert_eq!(partial.error.as_deref(), Some(expected.as_str()));
+        assert_eq!(partial.unreadable.expect("counts").identities, 3);
+    }
+
+    /// A completed-with-damage upgrade reports each counter separately, so a
+    /// reader can tell which kind of row was lost.
+    #[test]
+    fn succeeded_with_unreadable_data_reports_every_counter() {
+        let summary = summarize_migration(&MigrationState::SucceededWithUnreadableData {
+            identities: 1,
+            votes: 2,
+            top_ups: 3,
+        });
+
+        assert_eq!(summary.state, "succeeded_with_unreadable_data");
+        assert!(summary.error.is_none());
+        let counts = summary.unreadable.expect("counts");
+        assert_eq!((counts.identities, counts.votes, counts.top_ups), (1, 2, 3));
+    }
+
+    /// A profile with no app store is a legitimate "nothing applied yet", not a
+    /// failure — the lineage read must report `None` rather than propagate.
+    #[test]
+    fn missing_app_store_reports_no_lineage() {
+        let dir = tempfile::tempdir().expect("tempdir");
+
+        assert!(
+            wallet_storage_lineage(dir.path())
+                .expect("missing store")
+                .is_none()
+        );
+    }
+
+    #[test]
+    fn storage_status_preserves_a_legacy_profile_and_its_network() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let path = dir.path().join("data.db");
+        {
+            let conn = Connection::open(&path).unwrap();
+            conn.execute_batch(
+                "CREATE TABLE settings (id INTEGER, network TEXT, database_version INTEGER);
+                INSERT INTO settings VALUES (1, 'testnet', 11);",
+            )
+            .unwrap();
+        }
+        let before = std::fs::read(&path).unwrap();
+        let output = inspect_storage(dir.path(), Some("testnet")).expect("inspect legacy storage");
+        assert_eq!(output.active_network, "testnet");
+        assert_eq!(output.data_db_version, Some(11));
+        assert!(!output.data_db_up_to_date);
+        assert!(output.sentinels.iter().all(|s| s.wallet_drain.is_none()));
+        assert_eq!(std::fs::read(&path).unwrap(), before);
+        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
+        assert!(matches!(
+            inspect_storage(dir.path(), Some("mainnet")),
+            Err(McpToolError::NetworkMismatch { .. })
+        ));
+    }
+
+    #[test]
+    fn storage_status_reads_current_settings_and_markers_without_upgrading() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let kv = crate::context::AppContext::open_app_kv(dir.path()).unwrap();
+        kv.put(
+            DetScope::Global,
+            AppSettings::KV_KEY,
+            &AppSettings {
+                network: Network::Regtest,
+                ..AppSettings::default()
+            },
+        )
+        .unwrap();
+        let completion = MigrationCompletion {
+            completed_at: 123,
+            sha: "fixture".to_owned(),
+            network_count: 2,
+        };
+        kv.put(
+            DetScope::Global,
+            &sentinel_key_for(Network::Regtest),
+            &completion,
+        )
+        .unwrap();
+        let output = inspect_storage(dir.path(), Some("local")).unwrap();
+        assert_eq!(output.active_network, "local");
+        let marker = output
+            .sentinels
+            .iter()
+            .find(|s| s.network == "local")
+            .and_then(|s| s.wallet_drain.as_ref())
+            .expect("persisted marker");
+        assert_eq!((marker.completed_at, marker.network_count), (123, 2));
+        assert_eq!(marker.sha, "fixture");
+        assert!(output.wallet_storage_lineage.is_some());
+        assert!(!dir.path().join("secrets").exists());
+    }
+
+    #[test]
+    fn storage_status_distinguishes_missing_history_from_broken_storage() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let path = dir.path().join("det-app.sqlite");
+        {
+            let conn = Connection::open(&path).unwrap();
+            assert!(wallet_storage_lineage(dir.path()).unwrap().is_none());
+            conn.execute_batch("CREATE TABLE refinery_schema_history (version INTEGER);")
+                .unwrap();
+            assert!(wallet_storage_lineage(dir.path()).is_err());
+        }
+        std::fs::write(&path, b"invalid sqlite database").unwrap();
+        assert!(wallet_storage_lineage(dir.path()).is_err());
+        assert!(inspect_storage(dir.path(), None).is_err());
+    }
+
+    #[test]
+    fn storage_status_rejects_corrupted_metadata() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let conn = Connection::open(dir.path().join("det-app.sqlite")).unwrap();
+        conn.execute_batch("CREATE TABLE meta_global (key TEXT PRIMARY KEY, value BLOB);")
+            .unwrap();
+        conn.execute(
+            "INSERT INTO meta_global VALUES (?1, ?2)",
+            rusqlite::params![AppSettings::KV_KEY, vec![255_u8]],
+        )
+        .unwrap();
+        assert!(matches!(
+            inspect_storage(dir.path(), None),
+            Err(McpToolError::StorageMetadata { .. })
+        ));
+    }
+}
diff --git a/src/mcp/tools/network.rs b/src/mcp/tools/network.rs
index bb61e010c..8ad85ca95 100644
--- a/src/mcp/tools/network.rs
+++ b/src/mcp/tools/network.rs
@@ -7,6 +7,7 @@ use rmcp::model::ToolAnnotations;
 use rmcp::schemars;
 use serde::{Deserialize, Serialize};
 
+use crate::backend_task::error::TaskError;
 use crate::backend_task::{BackendTask, BackendTaskSuccessResult};
 use crate::mcp::dispatch::{dispatch_task, dispatch_task_with};
 use crate::mcp::error::McpToolError;
@@ -174,7 +175,7 @@ impl ToolBase for NetworkSwitch {
 
     fn description() -> Option> {
         Some(
-            "Switch the active network. Creates the context if needed (may take \
+            "Switch and save the active network for subsequent startups. Creates the context if needed (may take \
              a few seconds). Requires that the target network has DAPI addresses \
              configured."
                 .into(),
@@ -214,8 +215,12 @@ impl AsyncTool for NetworkSwitch {
 
         let ctx = service.tool_ctx().await?;
 
-        // Already on the target network — no-op.
+        // A context can be selected without its network having been persisted.
         if ctx.network() == target {
+            ctx.update_app_settings(|settings| settings.network = target)
+                .map_err(|source| {
+                    McpToolError::TaskFailed(TaskError::AppSettingsWrite { source })
+                })?;
             let spv_running = ctx.connection_status().spv_status().is_active();
             return Ok(NetworkSwitchOutput {
                 active: network_display_name(target).to_owned(),
@@ -237,6 +242,16 @@ impl AsyncTool for NetworkSwitch {
                     spv_started,
                     ..
                 } => {
+                    if let Err(source) =
+                        context.update_app_settings(|settings| settings.network = target)
+                    {
+                        if let Ok(backend) = context.wallet_backend() {
+                            backend.shutdown().await;
+                        }
+                        return Err(McpToolError::TaskFailed(TaskError::AppSettingsWrite {
+                            source,
+                        }));
+                    }
                     if let Ok(backend) = outgoing_context.wallet_backend() {
                         backend.shutdown().await;
                     }
@@ -268,6 +283,71 @@ mod tests {
     use crate::wallet_backend::{IdentityKeyView, SecretPrompt};
     use platform_wallet_storage::secrets::SecretString;
 
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn failed_network_save_keeps_the_active_context() {
+        use crate::context::test_support::test_app_context_with_kv;
+        use crate::wallet_backend::DetKv;
+        use crate::wallet_backend::kv_test_support::FailingKv;
+        let tmp = tempfile::tempdir().unwrap();
+        let store = Arc::new(FailingKv::default());
+        let ctx = test_app_context_with_kv(tmp.path(), Arc::new(DetKv::from_store(store.clone())));
+        let service =
+            DashMcpService::new_shared(Arc::new(arc_swap::ArcSwap::from(Arc::clone(&ctx))));
+        store.fail_next_puts(usize::MAX);
+        let result = NetworkSwitch::invoke(
+            &service,
+            NetworkSwitchParams {
+                network: "mainnet".to_owned(),
+            },
+        )
+        .await;
+        let active = service.tool_ctx().await.unwrap();
+        service.shutdown_wallet_backend().await;
+        assert!(matches!(
+            result,
+            Err(McpToolError::TaskFailed(TaskError::AppSettingsWrite { .. }))
+        ));
+        assert!(
+            Arc::ptr_eq(&active, &ctx),
+            "a failed save must not replace the active context"
+        );
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn review_regression_network_switch_persists_the_selected_network() {
+        let tmp = tempfile::tempdir().unwrap();
+        let ctx = test_app_context(tmp.path());
+        ctx.update_app_settings(|settings| {
+            settings.network = Network::Mainnet;
+            settings.onboarding_completed = true;
+        })
+        .unwrap();
+        let service = DashMcpService::new_shared(Arc::new(arc_swap::ArcSwap::from(ctx)));
+        // Even a switch to the current context must persist the chosen network.
+        for network in ["testnet", "mainnet", "testnet"] {
+            NetworkSwitch::invoke(
+                &service,
+                NetworkSwitchParams {
+                    network: network.to_owned(),
+                },
+            )
+            .await
+            .unwrap();
+            let switched = service.tool_ctx().await.unwrap();
+            let settings = switched
+                .app_kv()
+                .get::(
+                    crate::wallet_backend::DetScope::Global,
+                    crate::model::settings::AppSettings::KV_KEY,
+                )
+                .unwrap()
+                .unwrap();
+            assert_eq!(settings.network, parse_network(network).unwrap());
+            assert!(settings.onboarding_completed);
+        }
+        service.shutdown_wallet_backend().await;
+    }
+
     #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
     async fn network_switch_tool_preserves_secret_prompt_identity() {
         let tmp = tempfile::tempdir().expect("tempdir");
diff --git a/src/wallet_backend/kv.rs b/src/wallet_backend/kv.rs
index 43f1cd062..309903caa 100644
--- a/src/wallet_backend/kv.rs
+++ b/src/wallet_backend/kv.rs
@@ -165,18 +165,53 @@ impl DetKv {
         let Some(bytes) = raw else {
             return Ok(None);
         };
-        let (&first, rest) = bytes.split_first().ok_or(KvAdapterError::Truncated)?;
-        if first != SCHEMA_VERSION {
-            return Err(KvAdapterError::SchemaVersion {
-                expected: SCHEMA_VERSION,
-                found: first,
-            });
+        decode_value(&bytes).map(Some)
+    }
+
+    /// Read an existing app-store value without opening the migrating persister.
+    #[cfg(any(feature = "cli", feature = "mcp"))]
+    pub(crate) fn read_global(
+        conn: &rusqlite::Connection,
+        key: &str,
+    ) -> Result, KvAdapterError> {
+        use rusqlite::OptionalExtension;
+        let sqlite_error = |source| KvAdapterError::Store(KvError::Sqlite(source));
+        if !crate::database::table_exists(conn, "meta_global").map_err(sqlite_error)? {
+            return Ok(None);
         }
-        let (value, _) =
-            bincode::serde::decode_from_slice::(rest, bincode::config::standard())?;
-        Ok(Some(value))
+        conn.query_row(
+            "SELECT value FROM meta_global WHERE key = ?1",
+            [key],
+            |row| {
+                let bytes = row.get_ref(0)?.as_blob()?;
+                if bytes.len() > platform_wallet_storage::SIZE_LIMIT_BYTES {
+                    return Ok(Err(KvAdapterError::Store(KvError::ValueTooLarge {
+                        found: bytes.len(),
+                        max: platform_wallet_storage::SIZE_LIMIT_BYTES,
+                    })));
+                }
+                Ok(decode_value(bytes))
+            },
+        )
+        .optional()
+        .map_err(sqlite_error)?
+        .transpose()
+    }
+}
+
+fn decode_value(bytes: &[u8]) -> Result {
+    let (&first, rest) = bytes.split_first().ok_or(KvAdapterError::Truncated)?;
+    if first != SCHEMA_VERSION {
+        return Err(KvAdapterError::SchemaVersion {
+            expected: SCHEMA_VERSION,
+            found: first,
+        });
     }
+    let (value, _) = bincode::serde::decode_from_slice::(rest, bincode::config::standard())?;
+    Ok(value)
+}
 
+impl DetKv {
     /// Encode and upsert the value bound to `(scope, key)`.
     pub fn put(
         &self,
diff --git a/src/wallet_backend/platform_compatibility/mod.rs b/src/wallet_backend/platform_compatibility/mod.rs
index 657d05bdb..14cd2efee 100644
--- a/src/wallet_backend/platform_compatibility/mod.rs
+++ b/src/wallet_backend/platform_compatibility/mod.rs
@@ -56,6 +56,9 @@ fn upgrade(config: &SqlitePersisterConfig) -> Result {
     }
 }
 
+#[cfg(test)]
+mod real_fixture_tests;
+
 #[cfg(test)]
 mod tests {
     use super::*;
diff --git a/src/wallet_backend/platform_compatibility/real_fixture_tests.rs b/src/wallet_backend/platform_compatibility/real_fixture_tests.rs
new file mode 100644
index 000000000..dd3809818
--- /dev/null
+++ b/src/wallet_backend/platform_compatibility/real_fixture_tests.rs
@@ -0,0 +1,320 @@
+//! Real-data regression test for the bridge: a profile the released
+//! `v1.0.0-weekly.20260908` build (Platform pin 67d4ef3) wrote on testnet,
+//! published as a migration-fixture artifact (`tests/migration-fixtures/`).
+//!
+//! The synthetic tests next door prove the bridge on rows written for them.
+//! This one feeds it bytes a real build wrote: a funded wallet's UTXO,
+//! transaction, address pool and sync state, and an uncheckpointed WAL left by
+//! the app's own clean shutdown.
+//!
+//! Env-gated. It runs only when `MIGRATION_FIXTURES_DIR` points at the
+//! downloaded fixture archives, as the migration-matrix workflow does, and
+//! otherwise reports the skip and passes. With the variable set, a missing or
+//! altered archive fails: silently testing nothing is the failure mode the
+//! fixture exists to prevent.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use platform_wallet::changeset::PlatformWalletPersistence;
+use platform_wallet_storage::{SqlitePersister, SqlitePersisterConfig, WalletStorageError};
+use sha2::{Digest, Sha256};
+
+use super::open;
+
+/// Directory of fixture archives, shared with the migration-matrix harness.
+const FIXTURES_DIR_ENV: &str = "MIGRATION_FIXTURES_DIR";
+/// The manifest entry this test reads.
+const FIXTURE_ID: &str = "v1.0.0-weekly.20260908-wallet-only";
+/// The committed manifest: the archive name and checksum the download is held to.
+const MANIFEST: &str = include_str!("../../../tests/migration-fixtures/manifest.json");
+/// The fixture wallet's balance at capture: one faucet payment of 1 tDASH.
+const CAPTURED_BALANCE_DUFFS: u64 = 100_000_000;
+/// Per-network store holding the fixture wallet.
+const NETWORK_DB: &str = "det-testnet.sqlite";
+/// Cross-network app store.
+const APP_DB: &str = "det-app.sqlite";
+/// Version bookkeeping the upgrade rewrites by design; every other table must
+/// keep its rows.
+const VERSION_TABLES: [&str; 2] = ["refinery_schema_history", "meta_data_versions"];
+/// Marker in the name of the backup the bridge retains next to an upgraded
+/// database.
+const BACKUP_MARKER: &str = ".platform-67d4ef3-backup-";
+
+#[test]
+fn platform_compatibility_upgrades_the_real_weekly_20260908_profile() {
+    let Some(staged) = stage() else {
+        return;
+    };
+
+    assert_eq!(
+        assert_upgrade(&staged, NETWORK_DB),
+        [CAPTURED_BALANCE_DUFFS],
+        "{NETWORK_DB} must still load its one captured wallet, with the captured balance"
+    );
+    assert_upgrade(&staged, APP_DB);
+}
+
+/// The fixture unpacked into an owner-only temporary data directory.
+struct Staged {
+    root: tempfile::TempDir,
+    data_dir: PathBuf,
+}
+
+impl Staged {
+    /// A fresh directory for copies, so reading a database never checkpoints
+    /// the WAL of the file under test.
+    fn scratch(&self, label: &str) -> PathBuf {
+        let dir = self.root.path().join("scratch").join(label);
+        // The wallet store refuses a database below a group- or
+        // other-writable directory, so every level is created owner-only
+        // whatever the umask.
+        let mut builder = std::fs::DirBuilder::new();
+        builder.recursive(true);
+        #[cfg(unix)]
+        std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
+        builder.create(&dir).expect("scratch directory");
+        dir
+    }
+}
+
+/// Unpacks the fixture named by [`FIXTURE_ID`], or returns `None` when
+/// [`FIXTURES_DIR_ENV`] is unset.
+fn stage() -> Option {
+    let Some(fixtures_dir) = std::env::var_os(FIXTURES_DIR_ENV).filter(|dir| !dir.is_empty())
+    else {
+        eprintln!(
+            "skipped: {FIXTURES_DIR_ENV} is unset; the migration-matrix workflow points it at the downloaded fixture archives"
+        );
+        return None;
+    };
+    let manifest: serde_json::Value =
+        serde_json::from_str(MANIFEST).expect("the committed manifest parses");
+    let entry = manifest["fixtures"]
+        .as_array()
+        .expect("the manifest lists fixtures")
+        .iter()
+        .find(|fixture| fixture["id"] == FIXTURE_ID)
+        .unwrap_or_else(|| panic!("the manifest has no `{FIXTURE_ID}` entry"));
+    let artifact = &entry["artifact"];
+    let archive_name = artifact["archive_filename"]
+        .as_str()
+        .expect("the entry names its archive");
+    let expected_sha256 = artifact["sha256"]
+        .as_str()
+        .expect("the entry records the archive checksum");
+
+    let archive = Path::new(&fixtures_dir).join(archive_name);
+    let bytes = std::fs::read(&archive).unwrap_or_else(|error| {
+        panic!(
+            "{FIXTURES_DIR_ENV} is set, but {} cannot be read: {error}",
+            archive.display()
+        )
+    });
+    assert_eq!(
+        hex::encode(Sha256::digest(&bytes)),
+        expected_sha256,
+        "{} does not match the manifest checksum",
+        archive.display()
+    );
+
+    // Owner-only whatever the umask, like the bridge's own staging directory:
+    // the wallet store refuses a database below a group-writable ancestor.
+    let mut builder = tempfile::Builder::new();
+    builder.prefix("platform-real-fixture-");
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+        builder.permissions(std::fs::Permissions::from_mode(0o700));
+    }
+    let root = builder.tempdir().expect("temporary directory");
+    let data_dir = root.path().join("data");
+    crate::app_dir::ensure_data_dir_exists(&data_dir).expect("owner-only data directory");
+    let status = Command::new("tar")
+        .arg("-xf")
+        .arg(&archive)
+        .arg("-C")
+        .arg(&data_dir)
+        .status()
+        .expect("tar runs");
+    assert!(
+        status.success(),
+        "tar could not unpack {}",
+        archive.display()
+    );
+    Some(Staged { root, data_dir })
+}
+
+/// Opens `db_name` through the bridge exactly as the app does and asserts the
+/// bridge's contract on it. Returns the balance of every wallet the upgraded
+/// store loads.
+///
+/// The contract: the captured file really is the divergent 67d4ef3 schema (it
+/// does not open without the bridge); the bridge opens it and the typed loads
+/// succeed; no row is lost (see [`assert_rows_kept`]); one backup of the
+/// original is retained with the same rows; and a second open changes nothing.
+fn assert_upgrade(staged: &Staged, db_name: &str) -> Vec {
+    let path = staged.data_dir.join(db_name);
+    let before = table_counts(&path, &staged.scratch(&format!("{db_name}-before")));
+    assert!(
+        !before.is_empty(),
+        "{db_name} is missing from the fixture or has no tables"
+    );
+    assert_needs_bridge(&path, &staged.scratch(&format!("{db_name}-precondition")));
+
+    let persister = open(SqlitePersisterConfig::new(&path))
+        .unwrap_or_else(|error| panic!("the bridge could not open {db_name}: {error:?}"));
+    let loaded = persister.load().unwrap_or_else(|error| {
+        panic!("{db_name}: typed load failed after the upgrade: {error:?}")
+    });
+    persister.load_unowned_identities().unwrap_or_else(|error| {
+        panic!("{db_name}: identity load failed after the upgrade: {error:?}")
+    });
+    let balances = loaded
+        .wallets
+        .values()
+        .map(|wallet| wallet.wallet_info.balance.total())
+        .collect();
+    drop(persister);
+
+    let after = table_counts(&path, &staged.scratch(&format!("{db_name}-after")));
+    assert_rows_kept(db_name, &before, &after);
+
+    let backups = backup_files(&path);
+    let [backup] = &backups.iter().collect::>()[..] else {
+        panic!("{db_name}: expected exactly one retained backup, found {backups:?}");
+    };
+    assert_eq!(
+        table_counts(backup, &staged.scratch(&format!("{db_name}-backup"))),
+        before,
+        "{db_name}: the retained backup must hold the original rows"
+    );
+
+    drop(
+        open(SqlitePersisterConfig::new(&path))
+            .unwrap_or_else(|error| panic!("{db_name}: a second open failed: {error:?}")),
+    );
+    assert_eq!(
+        backup_files(&path),
+        backups,
+        "{db_name}: a second open must not upgrade again"
+    );
+
+    eprintln!("{db_name}: upgraded, rows kept {:?}", data_tables(&after));
+    balances
+}
+
+/// The captured file must fail the plain open with a migration error: proof
+/// that it carries the divergent history the bridge exists for, rather than a
+/// schema the current pin already accepts. Checked on a copy, because the open
+/// may checkpoint the WAL of the file under test.
+fn assert_needs_bridge(path: &Path, scratch: &Path) {
+    let copy = copy_database(path, scratch);
+    let config = SqlitePersisterConfig::new(©)
+        .with_auto_backup_dir(Some(scratch.join("precondition-backup")));
+    match SqlitePersister::open(config) {
+        Err(WalletStorageError::Migration(_)) => {}
+        Ok(_) => panic!(
+            "{} opened without the bridge; the fixture no longer exercises it",
+            path.display()
+        ),
+        Err(error) => panic!(
+            "{} must fail with a migration error without the bridge, got {error:?}",
+            path.display()
+        ),
+    }
+}
+
+/// Row count of every table, read from a copy of the database and its WAL.
+fn table_counts(path: &Path, scratch: &Path) -> BTreeMap {
+    let copy = copy_database(path, scratch);
+    let conn = rusqlite::Connection::open(©).expect("open the copy");
+    let tables: Vec = conn
+        .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'")
+        .and_then(|mut statement| {
+            statement
+                .query_map([], |row| row.get(0))?
+                .collect::>()
+        })
+        .expect("list tables");
+    tables
+        .into_iter()
+        .map(|table| {
+            let count = conn
+                .query_row(&format!("SELECT count(*) FROM \"{table}\""), [], |row| {
+                    row.get(0)
+                })
+                .expect("count rows");
+            (table, count)
+        })
+        .collect()
+}
+
+/// The upgrade loses no row: every data table keeps its row count (a table
+/// the target schema drops may disappear only if it was empty), and every
+/// table the target schema adds starts empty.
+fn assert_rows_kept(db_name: &str, before: &BTreeMap, after: &BTreeMap) {
+    for (table, rows) in data_tables(before) {
+        assert_eq!(
+            after.get(table).copied().unwrap_or(0),
+            rows,
+            "{db_name}: `{table}` must keep its {rows} rows through the upgrade"
+        );
+    }
+    let filled_new_tables: BTreeMap<&str, i64> = data_tables(after)
+        .into_iter()
+        .filter(|(table, rows)| !before.contains_key(*table) && *rows != 0)
+        .collect();
+    assert!(
+        filled_new_tables.is_empty(),
+        "{db_name}: tables the upgrade created must start empty, found {filled_new_tables:?}"
+    );
+}
+
+/// `counts` without the version bookkeeping tables.
+fn data_tables(counts: &BTreeMap) -> BTreeMap<&str, i64> {
+    counts
+        .iter()
+        .filter(|(table, _)| !VERSION_TABLES.contains(&table.as_str()))
+        .map(|(table, count)| (table.as_str(), *count))
+        .collect()
+}
+
+/// Copies a database with its `-wal` and `-shm` sidecars into `scratch`.
+fn copy_database(path: &Path, scratch: &Path) -> PathBuf {
+    let name = path.file_name().expect("database file name");
+    let copy = scratch.join(name);
+    std::fs::copy(path, ©)
+        .unwrap_or_else(|error| panic!("could not copy {}: {error}", path.display()));
+    for suffix in ["-wal", "-shm"] {
+        let mut sidecar = path.as_os_str().to_owned();
+        sidecar.push(suffix);
+        let sidecar = PathBuf::from(sidecar);
+        if sidecar.exists() {
+            let mut target = copy.as_os_str().to_owned();
+            target.push(suffix);
+            std::fs::copy(&sidecar, PathBuf::from(target))
+                .unwrap_or_else(|error| panic!("could not copy {}: {error}", sidecar.display()));
+        }
+    }
+    copy
+}
+
+/// Backups the bridge retained next to `path`.
+fn backup_files(path: &Path) -> BTreeSet {
+    let prefix = format!(
+        "{}{BACKUP_MARKER}",
+        path.file_name().expect("file name").to_string_lossy()
+    );
+    std::fs::read_dir(path.parent().expect("parent directory"))
+        .expect("read the data directory")
+        .map(|entry| entry.expect("directory entry").path())
+        .filter(|candidate| {
+            candidate
+                .file_name()
+                .map(|name| name.to_string_lossy())
+                .is_some_and(|name| name.starts_with(&prefix) && name.ends_with(".sqlite"))
+        })
+        .collect()
+}
diff --git a/src/wallet_backend/secret_access.rs b/src/wallet_backend/secret_access.rs
index c3a0021cc..d023d2632 100644
--- a/src/wallet_backend/secret_access.rs
+++ b/src/wallet_backend/secret_access.rs
@@ -1185,7 +1185,7 @@ fn handle_lazy_tier2_rewrap_result(result: Result<(), TaskError>) -> Result<(),
 
 /// Whether `e` is the "wrong passphrase" condition that the re-ask loop
 /// catches and re-prompts on (rather than aborting).
-fn is_wrong_passphrase(e: &TaskError) -> bool {
+pub(crate) fn is_wrong_passphrase(e: &TaskError) -> bool {
     match e {
         TaskError::SingleKeyPassphraseIncorrect
         | TaskError::HdPassphraseIncorrect
diff --git a/src/wallet_backend/secret_prompt.rs b/src/wallet_backend/secret_prompt.rs
index 393162aef..9d77dbe7c 100644
--- a/src/wallet_backend/secret_prompt.rs
+++ b/src/wallet_backend/secret_prompt.rs
@@ -214,7 +214,10 @@ pub trait SecretPrompt: Send + Sync {
 /// [`TaskError::SecretPromptUnavailable`](crate::backend_task::error::TaskError::SecretPromptUnavailable)
 /// for the caller. Per the Q-HEADLESS security ruling there is **no**
 /// environment-variable or CLI-flag passphrase fallback: a passphrase-
-/// protected secret simply cannot be unlocked headless. Unprotected scopes
+/// protected secret cannot be unlocked through this host. The storage update's
+/// explicit, non-interactive password (`app_storage_update`, see
+/// `docs/ai-design/2026-07-14-migration-password-prompt/design.md`) is the one
+/// headless password path, and it never goes through a prompt. Unprotected scopes
 /// never reach the prompt (the chokepoint's fast-path decrypts them with no
 /// passphrase), so this host does not block read-only or no-password flows.
 #[derive(Debug, Default, Clone, Copy)]
diff --git a/src/wallet_backend/single_key.rs b/src/wallet_backend/single_key.rs
index 4e65987ff..685232c5d 100644
--- a/src/wallet_backend/single_key.rs
+++ b/src/wallet_backend/single_key.rs
@@ -35,10 +35,6 @@ use crate::wallet_backend::secret_seam::{SecretScheme, SecretSeam};
 use crate::wallet_backend::single_key_entry::SingleKeyEntry;
 use crate::wallet_backend::{DetKv, DetScope};
 
-/// Minimum length (in characters) for a per-key passphrase. Re-exported
-/// from the model so the rule has a single home; both this backend and
-/// the import/restore dialogs share the same value.
-pub use crate::model::wallet::passphrase::MIN_SINGLE_KEY_PASSPHRASE_LEN;
 use crate::model::wallet::passphrase::validate_single_key_passphrase;
 
 /// Fixed per-backend namespace id for single-key entries.
@@ -930,6 +926,7 @@ fn sign_message_with_raw_key(bytes: &[u8; 32], msg: &[u8; 32]) -> Result {
-                assert_eq!(min, super::MIN_SINGLE_KEY_PASSPHRASE_LEN as u32);
+                assert_eq!(min, MIN_SINGLE_KEY_PASSPHRASE_LEN as u32);
             }
             other => panic!("expected SingleKeyPassphraseTooShort, got {other:?}"),
         }
diff --git a/tests/migration-fixtures/README.md b/tests/migration-fixtures/README.md
new file mode 100644
index 000000000..ca9dd22a5
--- /dev/null
+++ b/tests/migration-fixtures/README.md
@@ -0,0 +1,295 @@
+# Migration fixtures
+
+A **migration fixture** is a captured Dash Evo Tool data directory, produced by
+one specific released build, packed as an archive, and replayed later against a
+newer build to prove that upgrading does not lose or corrupt local data.
+
+The fixture is the *input* of the migration matrix. It is never generated by
+the current build: it must come from the old binary itself, because the whole
+point is to exercise the on-disk shapes that binary actually wrote — schema
+version, table set, blob encodings, vault format, config keys.
+
+Wallet archives live outside git as GitHub Actions build artifacts;
+[`manifest.json`](manifest.json) indexes them. The additional
+[`v0.9.3-public-identities`](v0.9.3-public-identities/PROVENANCE.md) profile is a
+small, checked-in SQL snapshot containing only public explorer data, written
+using the actual v0.9.3 schema and serializer. It contains a user identity with
+DPNS and an Evonode identity with OWNER/TRANSFER public keys, without wallets
+or private keys. It was prepared programmatically, not captured through the GUI.
+
+`public_identity_fixture_migrates` restores this SQL and boots the real CLI twice.
+It checks aliases, types, status, balances, revisions, DPNS names and timestamps,
+and every public key including contract bounds against independent expected
+metadata, then verifies `identity-list`. It runs in the matrix CI job and with
+`--all-features`; a testing-only build needs `DET_CLI_BIN`. No live explorer
+access or fixture password is required. This covers public metadata preservation,
+not signing, voter/operator associations, or fetching proofs with the old SDK.
+
+## Why this exists
+
+DET has three independent migration mechanisms, and a fixture exercises all
+three in the order a real user hits them:
+
+1. The `data.db` read-only contract. Since the platform-wallet rewrite (#860)
+   every boot opens an existing `data.db` read-only, and the schema ladder
+   (`src/database/initialization.rs`) only builds a fresh file, so a fixture's
+   `data.db` must come out byte-identical.
+2. The one-shot "unwire" drain of legacy `data.db` rows into the
+   `platform-wallet-storage` k/v store, gated by
+   `MIN_DIRECT_MIGRATION_VERSION` / `MAX_DIRECT_MIGRATION_VERSION`
+   (`src/model/data_migration.rs`).
+3. The `refinery` migrations inside `platform-wallet-storage`, shared by
+   `det-app.sqlite` and `det-.sqlite`, plus the compatibility bridge in
+   `src/wallet_backend/platform_compatibility/` that converts databases written
+   by the previously pinned upstream lineage.
+
+The bridge's own tests use synthetic upstream schemas rather than a profile a
+real binary wrote. Fixtures close exactly that gap. See
+[`docs/ai-design/2026-09-10-migration-matrix/design.md`](../../docs/ai-design/2026-09-10-migration-matrix/design.md)
+for the full design and its relationship to PR #981.
+
+## Threat model — read before capturing anything
+
+A fixture archive is uploaded to CI and downloaded by every future matrix run.
+Treat every byte in it as **published**.
+
+- **The fixture wallet is public by design.** Its recovery phrase, its
+  encrypted seed, its addresses and its identity are all recoverable by anyone
+  who can read the artifact. That is accepted, not mitigated.
+- **Use a dedicated wallet.** Never reuse the backend-E2E framework wallet
+  (`E2E_WALLET_MNEMONIC`) or any wallet that holds funds you care about.
+  A funded wallet whose seed is published is a wallet that will be drained.
+- **Testnet only.** No fixture is ever captured on mainnet, at any profile.
+- **Dust only.** Keep the fixture wallet's balance at the minimum the capture
+  needs (enough for the identity registration performed by the *current* build
+  when the profile requires one). Sweep anything above that back out. A fixture
+  wallet is not a faucet and must never become a place funds accumulate.
+- **The recovery phrase is still never committed.** Even though it is public by
+  design, it does not go into this repository — not into `manifest.json`, not
+  into a profile checklist, not into a scenario file, and not into a commit
+  message. Capture reads it at run time from `MIGRATION_FIXTURE_MNEMONIC`
+  (protected wallet: `MIGRATION_FIXTURE_PROTECTED_MNEMONIC`; the
+  `v1.0.0-weekly.20260908` wallet: `MIGRATION_FIXTURE_WEEKLY_MNEMONIC`), matching the
+  `tests/backend-e2e/` convention of referring to environment variable *names*
+  only.
+- **The protected wallet's password is supplied at runtime** through
+  `MIGRATION_V093_WALLET_PASSWORD`, from the operator's secure store or the
+  matching CI secret. The manifest records only this environment variable's
+  name. Do not commit the value, even for public testnet fixtures.
+- **If a fixture wallet is ever funded beyond dust, or is ever used on
+  mainnet, it is burned.** Abandon it, mint a fresh one, and recapture. Do not
+  try to reclaim it.
+
+## Storage model
+
+Fixture archives are stored as **GitHub Actions build artifacts**
+(`actions/upload-artifact` / `actions/download-artifact`), not as GitHub
+Release assets.
+
+Consequences that any workflow consuming this directory must handle:
+
+- **Artifacts expire.** The repository default is bounded (typically 90 days).
+  A baseline that has to survive every future matrix run therefore needs an
+  explicit, long `retention-days` and/or a periodic refresh job that re-uploads
+  the same bytes under a new expiry. A one-shot upload is not durable storage.
+- **`manifest.json` is the only durable index.** It records which workflow run
+  and which artifact name holds which fixture. If the manifest and the artifact
+  disagree, the manifest is the statement of intent and the run is the evidence.
+- **A missing or expired artifact must fail loudly.** A matrix job that cannot
+  download its input fails; it never silently skips, and it never falls back to
+  regenerating the fixture with a current build (which would test nothing).
+- **A hand capture reaches Actions storage through
+  `.github/workflows/migration-fixture-bootstrap.yml`.** Every `gui` capture,
+  the v0.9.3 baseline included, is produced outside CI. Dispatch that workflow
+  with the entry's `id` and the archive: it checks the bytes against the
+  entry's `sha256` and `bytes`, uploads them as `artifact_name`, and prints the
+  `workflow_run_id` and `expires_at` to record. An archive up to ~48 KB travels
+  base64-encoded in the `archive_b64` input. A larger one travels through a
+  temporary **draft** release: attach the archive to a draft, dispatch with
+  `release_tag` instead, and delete the draft once the run has succeeded (the
+  workflow header has the commands). Re-dispatching the same bytes before
+  `expires_at` is the refresh path.
+- **Artifact name convention:** `migration-fixture--` — e.g.
+  `migration-fixture-v0.9.3-wallet-identity-dpns`. The template also lives in
+  the manifest as `artifact_name_template` so tooling does not re-derive it.
+
+## What goes into an archive
+
+Pack the isolated data directory the capture ran against, with these
+exclusions:
+
+| Path | Packed? | Why |
+|---|---|---|
+| `data.db` (≤ v0.9.3 era) | Yes | The unwire drain and the legacy settings import (network, theme) both read it |
+| `det-app.sqlite`, `det-.sqlite` (current era) | Yes | The `platform-wallet-storage` layer under test |
+| `secrets/det-secrets.pwsvault` (current era) | Yes | Password-protected wallet assertions need the real vault |
+| `.env` | Yes | Era-correct config keys are part of what migrates |
+| `backups/` | No | Written by the migration itself; packing it pre-seeds the outcome |
+| `spv/` and other chain caches | No | Large, re-derivable, and not migration state |
+| `det.log`, `det-stderr.log`, `*.log` | No | Noise; may embed host paths |
+
+Archive as `tar.zst` (or `tar.gz` where `zstd` is not available on the runner),
+rooted at the data directory itself so extraction reproduces it verbatim,
+preserving mode bits — the secret store refuses to open a data directory whose
+ancestor chain is group- or other-writable.
+
+Record `sha256` and `bytes` of the finished archive in the manifest entry.
+Before packing, blank `MCP_API_KEY`, every network's `core_rpc_user` and
+`core_rpc_password`, and `wallet_private_key` in the capture copy's `.env`.
+This includes template placeholders. `pack.sh` refuses nonempty credential
+settings and reports only their names.
+
+## Capture methods
+
+### `gui` — required for v0.9.3
+
+v0.9.3 predates det-cli, the MCP server and the SPV stack, so there is no
+headless entry point at all: the only way to make that binary write its data
+directory is to drive the real GUI. It also predates `DASH_EVO_DATA_DIR`
+(absent from `src/app_dir.rs` at that tag), so isolation is done with
+`XDG_CONFIG_HOME`, and its `.env.example` uses the older key spelling
+(`TESTNET_insight_api_url`, `TESTNET_show_in_ui`, `TESTNET_core_zmq_endpoint`,
+…) — always copy the one from the tag being captured, never today's.
+
+Step-by-step recipe:
+[`docs/gui-testing/scenarios/migration-fixture-capture.md`](../../docs/gui-testing/scenarios/migration-fixture-capture.md).
+
+### `headless` — from the next release forward
+
+Builds that ship det-cli can capture without a display: import the wallet,
+derive an address, wait for SPV, and run a tool that triggers identity/DPNS
+discovery. Two things still need the GUI until the tooling catches up, and a
+manifest entry must say `gui` when either applies:
+
+- Importing a **password-protected** wallet — `core_wallet_import` has no
+  password parameter.
+- Any capture that has to react to a testnet reset (re-registering an identity,
+  re-claiming a name).
+
+### `gui+det-cli` — current-era builds
+
+`v1.0.0-weekly.20260908` was captured this way. Its det-cli does everything
+the profile needs headless (import, address derivation, the SPV-gated balance,
+discovery), but its `network_switch` is not persisted: a fresh process starts
+on the network stored in the app settings, which defaults to mainnet. A purely
+headless capture therefore produces a testnet wallet in a profile that boots
+on mainnet, and a later build never opens the testnet store. One launch of the
+same release's GUI selects testnet the way a user does; everything else is
+headless.
+
+- Drive `det-cli serve` over stdio, so the network switch and every tool call
+  share one process. Pass the recovery phrase as a JSON-RPC argument read from
+  the environment inside the driver, never on a command line.
+- Fund the wallet from the public testnet faucet, never from the E2E framework
+  wallet.
+- Run the GUI on a private X server (`Xvfb`), not on a shared desktop. The
+  network selector is disabled while SPV runs, so disconnect first. Quit
+  through the window's close request (`WM_DELETE_WINDOW`), never with `kill`.
+- The app's clean shutdown does not checkpoint the SQLite WAL, so the archive
+  carries `-wal` sidecars. That is the state a real profile is in: do not
+  checkpoint or `VACUUM` a capture to shrink it.
+
+## Adding a fixture for a new version
+
+1. **Pick the profile.** See [`profiles/`](profiles/). `wallet-only` is the
+   floor; `wallet-identity-dpns` is what the baseline matrix asserts against.
+2. **Check the preconditions listed by the profile.** Shared testnet state
+   changes underneath you — an identity registered months ago may not survive a
+   network reset, and a DPNS name may have been re-registered by someone else.
+   Verify with the *current* build before spending time on the old one.
+3. **Do the parts the old binary cannot do, with the current build first** —
+   for v0.9.3 that means registering the identity and its DPNS name, since that
+   binary has no SPV and can only see funds through a local Dash Core node.
+4. **Capture with the released binary**, in a fully reset, isolated data
+   directory. Never capture two fixtures into the same directory, and never
+   capture on top of a directory a previous run touched.
+5. **Confirm the profile checklist item by item before quitting the app.**
+   Discovery that has not finished yet is the most common way to capture a
+   fixture that silently proves nothing.
+6. **Quit cleanly** and confirm the process exited before packing — a live
+   SQLite WAL sidecar is not a valid fixture.
+7. **Pack, upload (`migration-fixture-bootstrap.yml` for a hand capture), and
+   add the manifest entry** with the real `workflow_run_id`,
+   `artifact_name`, `sha256`, `bytes`, `captured_at` and `retention_days`.
+8. **Commit the manifest change.** The archive stays out of git.
+
+## `manifest.json` field reference
+
+JSON permits no comments, so the schema is documented here.
+
+Top level:
+
+| Field | Meaning |
+|---|---|
+| `schema_version` | Integer. Bump when a field's meaning changes; consumers must reject an unknown value rather than guess. |
+| `artifact_name_template` | The naming convention for uploaded archives. Tooling substitutes `` and ``. |
+| `fixtures` | Array of fixture entries. |
+
+Per fixture entry:
+
+| Field | Meaning |
+|---|---|
+| `id` | Stable identifier, `-`. Used by the harness to select a case. |
+| `git_tag` | The tag whose released binary produced the data. |
+| `det_version` | The version string that build reports, without the `v` prefix. |
+| `capture_method` | `gui`, `headless` or `gui+det-cli` — see "Capture methods". |
+| `profile` | `wallet-only` or `wallet-identity-dpns`; the matching file in `profiles/` is the acceptance checklist. |
+| `network` | Always `testnet` today; the field exists so a future non-testnet case cannot be mistaken for one. |
+| `host_platform` | Where the capture ran. Linux x86-64 only in v1; Windows/macOS are an open decision, not an omission. |
+| `binary_asset` | The exact release asset downloaded for the capture. Asset naming changed between eras, so it is recorded per fixture rather than derived. |
+| `data_dir_env` | The environment variable that isolated the capture: `XDG_CONFIG_HOME` before `DASH_EVO_DATA_DIR` existed, `DASH_EVO_DATA_DIR` afterwards. |
+| `platform_rev` | The `dashpay/platform` revision the build pinned. Recorded for a current-era profile, whose wallet store a later build may have to upgrade through the `platform_compatibility` bridge. |
+| `capture_scenario` | Repo-relative path of the procedure that produced it, or `null` for a purely scripted headless capture. |
+| `captured_at` | RFC 3339 UTC timestamp of the capture, or `null` while unpacked. |
+| `artifact` | Where the archive lives; every field is `null` until an upload exists. |
+| `notes` | Free text: anything a future reader needs that the fields cannot express. |
+
+`artifact` sub-fields — all `null` until the fixture is actually packed and
+uploaded:
+
+| Field | Meaning |
+|---|---|
+| `workflow_name` | The workflow file that produced the upload. |
+| `workflow_run_id` | The run whose artifacts contain the archive. This is the durable coordinate; artifact names repeat across runs. |
+| `artifact_name` | Pre-filled from `artifact_name_template`, so the expected name is reviewable before any upload exists. |
+| `archive_filename` | The file inside the artifact. |
+| `sha256` | Hex digest of the archive. The harness verifies it after download; a mismatch fails the job. |
+| `bytes` | Size of the archive, for sanity-checking a truncated download. |
+| `retention_days` | The retention explicitly requested at upload. `null` here means "not uploaded yet", never "repository default". |
+| `expires_at` | RFC 3339 UTC expiry, so a refresh job can act before an artifact disappears rather than after. |
+| `staging_note` | Present only until the upload exists: how the archive will reach Actions storage. Drop it when recording the run. |
+
+`expect` — what the harness must observe after booting the fixture. Every field is optional:
+
+| Field | Meaning |
+|---|---|
+| `wallet_aliases` | Aliases `core-wallets-list` must report. Added to the aliases of every `migrated` wallet in `contents.wallets`. |
+| `public_identities` | Complete public-only identity metadata to verify in the source database, migrated storage, and CLI listing. |
+| `identity_ids` | Lowercase hex identity ids that must survive the migration. |
+| `starting_db_version` | The `data.db` schema version at capture. The boot fails if the staged file disagrees. |
+| `finish_unwire_sentinel` | Whether the boot must record the storage-update completion sentinel. Default `true`. |
+| `derive_address` | Whether to derive a receive address for every listed wallet. Needs a synced chain. Default `true`. |
+
+`contents.wallets[]` — one entry per wallet in the captured `data.db`. A
+current-era profile keeps its wallets in `det-.sqlite` instead: it
+leaves this list empty and names them in `expect.wallet_aliases`.
+
+| Field | Meaning |
+|---|---|
+| `alias` | The wallet's alias in `data.db`. The harness finds the wallet by it. |
+| `uses_password` | Whether the wallet is password-protected. |
+| `password_env` | Name of the runtime environment variable holding the wallet password. A `password_runs` entry hands the resolved value to det-cli; the harness never prints it, and fails a run whose output contains it. |
+| `expected_outcome` | What a headless det-cli boot **without a supplied password** must do with this wallet. `migrated` (the default): the wallet is registered in `det-.sqlite`. `needs_desktop`: a password-protected wallet. det-cli never prompts for a password (`docs/ai-design/2026-07-14-migration-password-prompt/design.md`), so the boot must fail with `StorageUpdateNeedsDesktop`, the wallet must stay unregistered, and the wallet-drain sentinel must stay unwritten. Any other result fails the matrix. |
+
+`password_runs[]` — optional extra boots of the same fixture with the wallet password supplied non-interactively. Each runs on a freshly staged copy, after the boot without a password:
+
+| Field | Meaning |
+|---|---|
+| `source` | How det-cli receives the password. `file`: the harness writes it to an owner-only (`0600`) file and runs `app-storage-update --password-file ` before the wallet boots. |
+| `expected_outcomes` | Per-alias outcomes that differ from the wallet's `expected_outcome` in this run, e.g. `{"migration-fixture-v093-protected": "migrated"}`. `needs_desktop` is rejected here: with the password supplied, the update either opens every protected wallet or fails. |
+
+Every wallet with a `password_env` must resolve to the same password: one supplied password opens them all, or the update fails and nothing is skipped. Supply the named variable from your secure store before running the matrix. A missing value fails the password scenario. The `app-storage-update` boot logs DET, det-cli and rmcp at `trace`, and the run fails if any command's output contains the password. The second boot gets no password: once the update has finished, a plain boot must need nothing more.
+
+For fork pull requests, CI sets `MIGRATION_MATRIX_SKIP_PASSWORDS=true` because repository secrets are unavailable. It explicitly reports the skipped password scenarios and still runs every password-free scenario, including the protected wallet's refusal to update without a password. Same-repository runs require the password scenarios to pass; a missing secret remains an error.
+
+🤖 Co-authored by [Claudius the Magnificent](https://github.com/lklimek/claudius) AI Agent
diff --git a/tests/migration-fixtures/manifest.json b/tests/migration-fixtures/manifest.json
new file mode 100644
index 000000000..5027535bc
--- /dev/null
+++ b/tests/migration-fixtures/manifest.json
@@ -0,0 +1,96 @@
+{
+  "schema_version": 1,
+  "artifact_name_template": "migration-fixture--",
+  "fixtures": [
+    {
+      "id": "v0.9.3-wallet-only",
+      "git_tag": "v0.9.3",
+      "det_version": "0.9.3",
+      "capture_method": "gui",
+      "profile": "wallet-only",
+      "network": "testnet",
+      "host_platform": "x86_64-linux",
+      "binary_asset": "dash-evo-tool-x86_64-linux.zip",
+      "data_dir_env": "XDG_CONFIG_HOME",
+      "capture_scenario": "docs/gui-testing/scenarios/migration-fixture-capture.md",
+      "captured_at": "2026-09-11",
+      "expect": {
+        "derive_address": false
+      },
+      "artifact": {
+        "workflow_name": "migration-fixture-bootstrap.yml",
+        "workflow_run_id": 34579191654,
+        "artifact_name": "migration-fixture-v0.9.3-wallet-only",
+        "archive_filename": "dash-evo-tool-v093-fixture.tar.zst",
+        "sha256": "3c9939f8061f836b9494ecc4a9b393791eb868ff6e4033fbd1424bf9e4e5cdbc",
+        "bytes": 6032,
+        "retention_days": 90,
+        "expires_at": "2026-12-10T08:26:30Z"
+      },
+      "contents": {
+        "wallets": [
+          {
+            "alias": "migration-fixture-v093",
+            "uses_password": false,
+            "expected_outcome": "migrated",
+            "mnemonic_env_convention": "MIGRATION_FIXTURE_MNEMONIC",
+            "note": "Public, testnet-only, dust-only fixture wallet. Funded with 0.03 tDASH from the E2E framework wallet; ~0.0276 DASH went into a Platform asset lock, ~0.0024 DASH was Core network fee."
+          },
+          {
+            "alias": "migration-fixture-v093-protected",
+            "uses_password": true,
+            "expected_outcome": "needs_desktop",
+            "password_env": "MIGRATION_V093_WALLET_PASSWORD",
+            "mnemonic_env_convention": "MIGRATION_FIXTURE_PROTECTED_MNEMONIC",
+            "note": "Empty/unfunded. Exists only to exercise the protected-wallet code path. Supply its password through the named runtime environment variable."
+          }
+        ],
+        "identity": null
+      },
+      "password_runs": [
+        {
+          "source": "file",
+          "expected_outcomes": {
+            "migration-fixture-v093-protected": "migrated"
+          }
+        }
+      ],
+      "notes": "Required baseline. v0.9.3 writes data.db at schema version 11 and has no det-.sqlite, so it always upgrades through the legacy drain rather than the platform_compatibility bridge (structurally immune to the platform-wallet-storage DivergentVersion class of bug — see the approved plan). It predates DASH_EVO_DATA_DIR, det-cli and the SPV stack, hence XDG_CONFIG_HOME isolation and a GUI capture.",
+      "known_limitations": "Profile is wallet-only, NOT wallet-identity-dpns, despite an identity being genuinely registered on testnet for this fixture wallet. A Platform identity (51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE) and DPNS name (migtestfixture093.dash) were registered on testnet using the current build (commit 9cbf464f3) specifically for this capture, but v0.9.3's SDK cannot load ANY identity from the current testnet: its GroveDB proof-verification code only understands proof variant 0, while current testnet nodes return variant 1 ('Proof verification error: ... UnexpectedVariant { allowed: Range { min: 0, max: 0 }, found: 1 }'). This is a permanent client/network protocol incompatibility, not a config or timing issue, and blocks EVERY identity load attempt from v0.9.3 against today's testnet, not just this one. data.db's identity table therefore has 0 rows in this fixture. The on-chain identity+DPNS registration remains independently verifiable and reusable (e.g. to test 'does a newer build see an identity that existed before the fixture's wallet was captured', which does not require v0.9.3 itself to render it) but this fixture cannot be used to assert 'identity/DPNS data survives a v0.9.3 upgrade' end-to-end. Also note: v0.9.3's own .env.example ships a dead TESTNET_dapi_addresses list (all 18 addresses unreachable); the packed .env has that one value replaced with the current fixed address list so the app can reach DAPI at all, everything else left at v0.9.3's original format."
+    },
+    {
+      "id": "v1.0.0-weekly.20260908-wallet-only",
+      "git_tag": "v1.0.0-weekly.20260908",
+      "det_version": "1.0.0-weekly.20260908+13d8309e3",
+      "capture_method": "gui+det-cli",
+      "profile": "wallet-only",
+      "network": "testnet",
+      "host_platform": "x86_64-linux",
+      "binary_asset": "dash-evo-tool-linux-x86_64.zip",
+      "data_dir_env": "DASH_EVO_DATA_DIR",
+      "platform_rev": "67d4ef3f6340a1e983229b6870ef60cf7573602a",
+      "capture_scenario": null,
+      "captured_at": "2026-09-11",
+      "artifact": {
+        "workflow_name": "migration-fixture-bootstrap.yml",
+        "workflow_run_id": 34597906288,
+        "artifact_name": "migration-fixture-v1.0.0-weekly.20260908-wallet-only",
+        "archive_filename": "v1.0.0-weekly.20260908-wallet-only.tar.zst",
+        "sha256": "c7e21762a762c6a5892dcdff952c54583c7df8bd649fbd3c960696057ca17624",
+        "bytes": 277402,
+        "retention_days": 90,
+        "expires_at": "2026-12-10T12:14:31Z"
+      },
+      "expect": {
+        "wallet_aliases": ["weekly-fixture"],
+        "starting_db_version": 38
+      },
+      "contents": {
+        "wallets": [],
+        "identity": null
+      },
+      "notes": "First current-era fixture, and the first that runs the platform_compatibility bridge on real bytes. The released v1.0.0-weekly.20260908 build (commit 13d8309e3) pins Platform 67d4ef3f, whose wallet-storage migration history diverges from the current pin at V003 (3:unified 4:invitations). Booting it with the current build therefore upgrades det-app.sqlite and det-testnet.sqlite through the bridge, which keeps a *.platform-67d4ef3-backup-*.sqlite copy of each. The wallet lives in det-testnet.sqlite, not data.db (data.db is at version 38 with no wallet table), so the harness asserts it by alias through expect.wallet_aliases rather than contents.wallets. Wallet: alias weekly-fixture, seed hash 0a90903e8dfb8ea0bf5a89c6524df7d8daa7e0024a312c2c751b27901714e929. It is a fresh, public, testnet-only wallet whose recovery phrase is read from MIGRATION_FIXTURE_WEEKLY_MNEMONIC and never committed. It was funded with one 1 tDASH payment from the public testnet faucet (txid 5b5a40a0595f7a591e3e9f0d34a2e28d2e1f45a88aa3e8083299711bbcb53b78), which gives real core_transactions, core_utxos and core_instant_locks rows, plus 400 core_address_pool rows, 13 account_registrations and sync state. The capture ran the weekly's own det-cli serve (import, two addresses, balance, discovery), then launched the weekly GUI once on a private Xvfb display to select testnet (det-cli's network switch is not persisted) and quit cleanly. src/wallet_backend/platform_compatibility/real_fixture_tests.rs opens the same archive directly through the bridge.",
+      "known_limitations": "wallet-only: no identity and no DPNS name. The weekly det-cli cannot register an identity; the bridge's synthetic public-rows.sql covers identity and contact rows. The app's clean shutdown does not checkpoint the SQLite WAL, so the archive carries the -wal sidecars (det-testnet.sqlite-wal is 3.6 MB uncompressed). They are kept on purpose, because that is the state a real profile is in, and they are why the archive is 277 KB. The GUI's first start on mainnet also left empty det-mainnet*.sqlite files."
+    }
+  ]
+}
diff --git a/tests/migration-fixtures/profiles/wallet-identity-dpns.md b/tests/migration-fixtures/profiles/wallet-identity-dpns.md
new file mode 100644
index 000000000..50820a47e
--- /dev/null
+++ b/tests/migration-fixtures/profiles/wallet-identity-dpns.md
@@ -0,0 +1,108 @@
+# Profile: `wallet-identity-dpns`
+
+The baseline profile the migration matrix asserts against. Everything in
+[`wallet-only`](wallet-only.md), plus a Platform identity carrying a resolved
+DPNS name — the state a real user actually has, and the state whose loss after
+an upgrade would be most visible and least recoverable.
+
+## Required content
+
+Everything required by [`wallet-only`](wallet-only.md) still applies. In
+addition, at the moment the app is quit:
+
+### Identity
+
+- [ ] Exactly one identity is present, of type **User**, on testnet.
+- [ ] It was registered **beforehand, with the current build**, from
+      `MIGRATION_FIXTURE_MNEMONIC` — the same recovery phrase as Wallet U — and
+      only *loaded by ID* in the capture itself. See "Why registration happens
+      elsewhere" below.
+- [ ] It is loaded on Wallet U (the unprotected wallet), not Wallet P. A
+      protected wallet would make every post-upgrade identity assertion depend
+      on the unlock flow as well, and confound the two failures.
+- [ ] It has a non-default alias, so an upgrade that keeps the identity but
+      drops the local metadata around it is still caught.
+- [ ] Its identity ID is recorded in the capture report, outside the archive.
+
+### DPNS
+
+- [ ] Exactly one DPNS name is registered to that identity and is fully
+      resolved — visible next to the identity in the app before quitting.
+- [ ] The name is recorded in the capture report, outside the archive.
+- [ ] The name is **not** in an active contest. A contested name's displayed
+      state changes on its own as the contest resolves, which would make a
+      post-upgrade comparison non-deterministic.
+- [ ] Name resolution has actually completed. Quitting while the fetch is still
+      in flight produces an identity with an empty name list, which then
+      "survives" the upgrade perfectly while proving nothing.
+
+## Why registration happens elsewhere
+
+v0.9.3 does ship identity-registration and DPNS-registration screens, so the
+constraint is not a missing feature. It is that v0.9.3 predates the SPV stack
+entirely (there is no `src/spv/` at that tag): wallet funds and UTXOs are
+visible only through a local Dash Core testnet node reached over RPC and ZMQ
+(`TESTNET_core_host`, `TESTNET_core_rpc_*`, `TESTNET_core_zmq_endpoint` in that
+era's `.env.example`). Without such a node the binary sees a zero balance and
+cannot build the asset lock a registration requires.
+
+Loading an identity by ID does not touch that path — it queries Platform over
+`TESTNET_dapi_addresses` — and it fetches the identity's DPNS names as part of
+the load, storing them with the identity. So registration is done ahead of time
+with the current build, and the old binary only has to *adopt* the result.
+
+A capture host that does run a synced Dash Core testnet node may register from
+the old binary directly. Record that in the fixture's `notes`; it changes what
+the fixture proves, so it must not be silently substituted.
+
+## Verification
+
+**Era ≤ v0.9.3** — the identity row is in `data.db`:
+
+```sql
+-- sqlite3 -readonly data.db
+SELECT hex(id), alias, identity_type, is_local, network,
+       wallet IS NOT NULL AS linked_to_wallet
+FROM identity;
+```
+
+**The DPNS name is not SQL-checkable at this era.** `identity.data` is an
+opaque bincode blob holding the `QualifiedIdentity`, and the fetched names live
+inside it. Verify the name in the UI, on the identity's row, and capture a
+screenshot for the report. Do not attempt to decode the blob out-of-band; do
+not treat "the row exists" as proof the name is there.
+
+**Current era** — read through the app's own paths (det-cli, or the identity
+list) rather than SQL, for the same reason: identity metadata is serialized
+into the k/v store.
+
+## Post-upgrade assertions this profile enables
+
+- Every `wallet-only` assertion.
+- The identity is present after the upgrade, with the same ID, the same alias,
+  the same type, and still linked to Wallet U.
+- Its DPNS name is still shown, without needing a manual refresh or a re-load
+  by ID. A name that returns only after the user re-fetches it is a partial
+  failure, not a pass.
+- The identity's keys are still usable — an upgrade that keeps the identity but
+  loses its keys leaves the user unable to sign.
+- No duplicate identity appears: the legacy drain runs once and adopts the
+  existing row rather than adding a second one.
+- A second boot changes nothing further.
+
+## Preconditions to re-check before every capture
+
+Shared testnet is mutable and the fixture's on-chain state is months old by the
+time it matters. Before spending time on the old binary, confirm with the
+**current** build that:
+
+- [ ] The identity ID still resolves on testnet and still has a positive credit
+      balance.
+- [ ] The DPNS name still resolves to that identity (a network reset can drop
+      it, and the name can then be taken by someone else).
+- [ ] The fixture wallet still holds dust-level funds and nothing more.
+
+If any of these fail, fix the on-chain state first, or capture
+[`wallet-only`](wallet-only.md) and record why in the fixture's `notes`. A
+fixture captured against stale on-chain state fails the matrix later for a
+reason that has nothing to do with migration.
diff --git a/tests/migration-fixtures/profiles/wallet-only.md b/tests/migration-fixtures/profiles/wallet-only.md
new file mode 100644
index 000000000..80d73e96b
--- /dev/null
+++ b/tests/migration-fixtures/profiles/wallet-only.md
@@ -0,0 +1,95 @@
+# Profile: `wallet-only`
+
+The floor profile. Proves that wallets — including a password-protected one —
+survive an upgrade with their aliases, derived addresses and at-rest protection
+intact. No Platform identity is involved, so this profile can be captured
+without any on-chain registration and without waiting on Platform state.
+
+Use it for versions where a full `wallet-identity-dpns` capture is blocked
+(testnet reset, no funded fixture wallet, no identity available). It is a
+weaker fixture, not a substitute: the baseline matrix asserts against
+[`wallet-identity-dpns`](wallet-identity-dpns.md).
+
+## Required content
+
+A captured data directory satisfies this profile when **all** of the following
+are true at the moment the app is quit.
+
+### Wallets
+
+- [ ] Exactly two recovery-phrase wallets exist.
+- [ ] **Wallet U** (unprotected) is imported from `MIGRATION_FIXTURE_MNEMONIC`,
+      has a non-default alias, and is the main/selected wallet.
+- [ ] **Wallet P** (protected) is imported from
+      `MIGRATION_FIXTURE_PROTECTED_MNEMONIC` with the password supplied through
+      `MIGRATION_V093_WALLET_PASSWORD`, and has its own distinct non-default
+      alias. A password *hint* is set only where the era's import screen offers
+      the field — v0.9.3's does not, and always stores `password_hint` as
+      `NULL`, so a fixture from that tag must not be failed for its absence.
+- [ ] The two wallets have different seeds. Importing the same phrase twice
+      produces one wallet, not two, and silently reduces this profile to a
+      single-wallet fixture.
+- [ ] Wallet U is *not* password-protected. Its whole purpose is to catch an
+      upgrade that hands an unprotected wallet a password the user cannot
+      supply.
+
+### Addresses
+
+- [ ] At least one receive address is derived and visible for each wallet, so
+      the fixture carries derivation state and not just wallet metadata.
+- [ ] Addresses are recorded outside the archive too — in the capture report —
+      so a post-upgrade run can assert that the *same* addresses come back
+      rather than merely that some addresses exist.
+
+### Settings
+
+- [ ] The network selector is on **testnet** and that choice is persisted (it
+      is the network the upgraded build must come back on).
+- [ ] No mainnet wallet, identity or setting is present anywhere in the
+      directory.
+
+### Balance
+
+- [ ] Dust only. This profile needs no funds at all; if the wallet holds a
+      balance from an earlier capture, that is tolerated but must stay at the
+      minimum. See the threat model in [`../README.md`](../README.md).
+
+## Verification
+
+**Era ≤ v0.9.3** — single `data.db`, schema version 11:
+
+```sql
+-- read-only, always; a plain open can checkpoint the WAL and mutate the fixture
+-- sqlite3 -readonly data.db
+SELECT database_version FROM settings WHERE id = 1;    -- expect 11 at v0.9.3
+SELECT alias, is_main, uses_password, network FROM wallet;
+SELECT COUNT(*) FROM wallet_addresses GROUP BY seed_hash;
+```
+
+**Current era** — `det-app.sqlite` plus `det-.sqlite` plus
+`secrets/det-secrets.pwsvault`. Wallet metadata lives in the k/v store as
+serialized values rather than typed columns, so prefer the app's own read paths
+(det-cli `core-wallets-list`) over hand-written SQL.
+
+## Post-upgrade assertions this profile enables
+
+The harness owns the assertions; they are listed here so a capture that cannot
+support one is recognised as incomplete before it is packed.
+
+- Both wallets are present after the upgrade, with their aliases unchanged.
+- Wallet U opens with no password prompt.
+- Wallet P still requires a password: the runtime password opens it, and a wrong
+  password is rejected. At-rest protection survived — it was not downgraded to
+  an unprotected seed in passing.
+- Every recorded address comes back identical.
+- The upgraded app starts on testnet.
+- A second boot changes nothing further: migration is idempotent, and no
+  migration banner reappears.
+
+## Known limitations
+
+- v0.9.3 has no SPV stack; balances and UTXOs came only from a local Dash Core
+  node over RPC/ZMQ. A capture made without such a node shows a zero balance
+  and an empty `utxos` table. That is expected and does not invalidate the
+  fixture — this profile asserts on wallets, addresses and protection, never on
+  balance.
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/PROVENANCE.md b/tests/migration-fixtures/v0.9.3-public-identities/PROVENANCE.md
new file mode 100644
index 000000000..8ec5176be
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/PROVENANCE.md
@@ -0,0 +1,20 @@
+# Public historical identity fixture
+
+Generator: fixture-writer.rs, compiled as an example inside dash-evo-tool tag v0.9.3 (3268b7366dc6d7a65e8a534d9411330eafbf4763) using Rust 1.89 and the unchanged historical Cargo.lock. Database schema initialization and QualifiedIdentity bincode encoding come from that checkout. No private keys or wallet ownership associations are supplied.
+
+Public explorer snapshots downloaded 2026-09-17:
+
+- user.json: https://testnet.platform-explorer.pshenmic.dev/identity/51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE
+- masternode.json: https://testnet.platform-explorer.pshenmic.dev/identity/PJUBWbXWmzEYCs99rAAbnCiHRzrnhKLQrXbmSsuPBYB
+- validator.json: https://testnet.platform-explorer.pshenmic.dev/validators?limit=1
+- documents.json: https://testnet.platform-explorer.pshenmic.dev/identity/51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE/documents
+- domain.json: https://testnet.platform-explorer.pshenmic.dev/document/6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs
+- domain-transaction.json: https://testnet.platform-explorer.pshenmic.dev/transaction/908845682B350F1001E514045429981289CF7A11C09FE6365522B8504ECE99DA
+
+DPNS uses the historical label-only representation. The acquired_at timestamp is the explorer's domain creation timestamp (corroborated by its successful creation transaction and identity alias), 2026-09-11T00:47:47.422Z. The explorer does not expose a separate $createdAt field; revision 1 and DOCUMENT_CREATE are checked. Public preorder salt/entropy and transaction signature in snapshots are published chain data, not signing secrets.
+
+The fixture represents locally imported public identities. Local aliases and active status are fixture metadata. It does not establish possession of the public identity's private keys. The masternode has real public OWNER and TRANSFER keys; its Evonode classification is corroborated by validator.json proTxInfo.type=Evo with the same identity. No voter/operator association is invented.
+
+Reproduce: copy fixture-writer.rs to examples/fixture-writer.rs in the pinned checkout, then run `cargo +1.89 run --locked --example fixture-writer -- /path/to/snapshots /path/to/new-output-directory`. Source directory must contain user.json, masternode.json, domain.json and validator.json; output data.db must not already exist. The executable asserts an old-codec round trip and exactly two identities, zero wallets.
+
+Export the resulting database with `sqlite3 /path/to/new-output-directory/data.db .dump > data.sql`. The harness disables foreign keys while restoring the dump and checks them afterward. The checked-in SQL is fixed historical input; CI never regenerates it with current code.
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/data.sql b/tests/migration-fixtures/v0.9.3-public-identities/data.sql
new file mode 100644
index 000000000..d5da2e52e
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/data.sql
@@ -0,0 +1,180 @@
+BEGIN TRANSACTION;
+CREATE TABLE asset_lock_transaction (
+                        tx_id BLOB PRIMARY KEY,
+                        transaction_data BLOB NOT NULL,
+                        amount INTEGER,
+                        instant_lock_data BLOB,
+                        chain_locked_height INTEGER,
+                        identity_id BLOB,
+                        identity_id_potentially_in_creation BLOB,
+                        wallet BLOB NOT NULL,
+                        network TEXT NOT NULL,
+                        FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE SET NULL,
+                        FOREIGN KEY (identity_id_potentially_in_creation) REFERENCES identity(id) ON DELETE SET NULL,
+                        FOREIGN KEY (wallet) REFERENCES wallet(seed_hash) ON DELETE CASCADE
+                    );
+CREATE TABLE contestant (
+                        normalized_contested_name TEXT NOT NULL,
+                        identity_id BLOB NOT NULL,
+                        name TEXT,
+                        votes INTEGER,
+                        created_at INTEGER,
+                        created_at_block_height INTEGER,
+                        created_at_core_block_height INTEGER,
+                        document_id BLOB,
+                        network TEXT NOT NULL,
+                        PRIMARY KEY (normalized_contested_name, identity_id, network),
+                        FOREIGN KEY (normalized_contested_name, network) REFERENCES contested_name(normalized_contested_name, network) ON DELETE CASCADE
+                    );
+CREATE TABLE contested_name (
+                        normalized_contested_name TEXT NOT NULL,
+                        locked_votes INTEGER,
+                        abstain_votes INTEGER,
+                        awarded_to BLOB,
+                        end_time INTEGER,
+                        locked INTEGER NOT NULL DEFAULT 0,
+                        last_updated INTEGER,
+                        network TEXT NOT NULL,
+                        PRIMARY KEY (normalized_contested_name, network)
+                    );
+CREATE TABLE contract (
+                        contract_id BLOB,
+                        contract BLOB,
+                        alias TEXT,
+                        network TEXT NOT NULL,
+                        PRIMARY KEY (contract_id, network)
+                    );
+CREATE TABLE identity (
+                        id BLOB PRIMARY KEY,
+                        data BLOB,
+                        status INTEGER NOT NULL DEFAULT 0,
+                        is_local INTEGER NOT NULL,
+                        alias TEXT,
+                        info TEXT,
+                        wallet BLOB,
+                        wallet_index INTEGER,
+                        identity_type TEXT,
+                        network TEXT NOT NULL,
+                        CHECK ((wallet IS NOT NULL AND wallet_index IS NOT NULL) OR (wallet IS NULL AND wallet_index IS NULL)),
+                        FOREIGN KEY (wallet) REFERENCES wallet(seed_hash) ON DELETE CASCADE
+                    );
+INSERT INTO "identity" VALUES(X'3B9DA97EBC06C07C0C0C48695EA5D36CAECE9E19E4944AAE5548691D9A80FAE5',X'003B9DA97EBC06C07C0C0C48695EA5D36CAECE9E19E4944AAE5548691D9A80FAE506000000000000020014A9EF1846DE6CC6A5DAD6B2426053740E4CCE5B8D00010001000100020014A9448477330E75AE4E53CC97C270404B6BD98052000200020002000200147B83198C15A671201E7D3706EFE485904D9FBBAF000300030301000200143F93EC2AF939780305355081FCA1D618D11E71090004000401030101A2A1B4AC6FEF22EA2A1A68E8123644B357875F6B412C18109281C146E7B271BC0E636F6E746163745265717565737400002102DA714F474A0764F27BFB7E285248C3673348F9CC20E7BC1CB3BAD014112B94FF0005000502030101A2A1B4AC6FEF22EA2A1A68E8123644B357875F6B412C18109281C146E7B271BC0E636F6E746163745265717565737400002102C02DC205DF2C5A13C6A55A214F6067305B1728FDDC8AA56F74240B8414DC3A9A00FCEC957594000000000001107075626C69632D64706E732D757365720001116D69677465737466697874757265303933FDDE54EF8DA0010000',2,1,'public-dpns-user',NULL,NULL,NULL,'User','testnet');
+INSERT INTO "identity" VALUES(X'05B687978344FA2433B2AA99D41F643E2D8581A789CDC23084889CECA5244EA8',X'0005B687978344FA2433B2AA99D41F643E2D8581A789CDC23084889CECA5244EA802000000030100020114C69A0BDA7DAAAE481BE8DEF95E5F347A1D00A4B400010001060100020114EC83A5F23EC17737F590153EB7EED16F7B2F132700FD7893EDB812F60A000000000002010E7075626C69632D65766F6E6F64650000',2,1,'public-evonode',NULL,NULL,NULL,'Evonode','testnet');
+CREATE TABLE identity_order (
+            pos INTEGER NOT NULL,
+            identity_id BLOB NOT NULL,
+            PRIMARY KEY(pos),
+            FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE CASCADE
+        );
+CREATE TABLE identity_token_balances (
+                token_id BLOB NOT NULL,
+                identity_id BLOB NOT NULL,
+                balance INTEGER NOT NULL,
+                network TEXT NOT NULL,
+                PRIMARY KEY(token_id, identity_id, network),
+                FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE CASCADE,
+                FOREIGN KEY (token_id) REFERENCES token(id) ON DELETE CASCADE
+             );
+CREATE TABLE proof_log (
+                        proof_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                        request_type INTEGER NOT NULL,
+                        request_bytes BLOB NOT NULL,
+                        path_query_bytes BLOB NOT NULL,
+                        height INTEGER NOT NULL,
+                        time_ms INTEGER NOT NULL,
+                        proof_bytes BLOB NOT NULL,
+                        error TEXT
+                    );
+CREATE TABLE scheduled_votes (
+                identity_id BLOB NOT NULL,
+                contested_name TEXT NOT NULL,
+                vote_choice TEXT NOT NULL,
+                time INTEGER NOT NULL,
+                executed INTEGER NOT NULL DEFAULT 0,
+                network TEXT NOT NULL,
+                PRIMARY KEY (identity_id, contested_name),
+                FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE CASCADE
+            );
+CREATE TABLE settings (
+            id INTEGER PRIMARY KEY CHECK (id = 1),
+            password_check BLOB,
+            main_password_salt BLOB,
+            main_password_nonce BLOB,
+            network TEXT NOT NULL,
+            start_root_screen INTEGER NOT NULL,
+            custom_dash_qt_path TEXT,
+            overwrite_dash_conf INTEGER,
+            theme_preference TEXT DEFAULT 'System',
+            database_version INTEGER NOT NULL
+        );
+INSERT INTO "settings" VALUES(1,NULL,NULL,NULL,'testnet',0,NULL,NULL,'System',11);
+CREATE TABLE token (
+                id BLOB PRIMARY KEY,
+                token_alias TEXT NOT NULL,
+                token_config BLOB NOT NULL,
+                data_contract_id BLOB NOT NULL,
+                token_position INTEGER NOT NULL,
+                network TEXT NOT NULL,
+                FOREIGN KEY (data_contract_id, network)
+                    REFERENCES contract(contract_id, network)
+                    ON DELETE CASCADE
+            );
+CREATE TABLE token_order (
+            pos INTEGER NOT NULL,
+            token_id BLOB NOT NULL,
+            identity_id BLOB NOT NULL,
+            PRIMARY KEY(pos, token_id),
+            FOREIGN KEY (token_id) REFERENCES token(id) ON DELETE CASCADE,
+            FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE CASCADE
+        );
+CREATE TABLE top_up (
+                identity_id BLOB NOT NULL,
+                top_up_index INTEGER NOT NULL,
+                amount INTEGER NOT NULL,
+                PRIMARY KEY (identity_id, top_up_index),
+                FOREIGN KEY (identity_id) REFERENCES identity(id) ON DELETE CASCADE
+            );
+CREATE TABLE utxos (
+                        txid BLOB NOT NULL,
+                        vout INTEGER NOT NULL,
+                        address TEXT NOT NULL,
+                        value INTEGER NOT NULL,
+                        script_pubkey BLOB NOT NULL,
+                        network TEXT NOT NULL,
+                        PRIMARY KEY (txid, vout, network)
+                    );
+CREATE TABLE wallet (
+                seed_hash BLOB NOT NULL PRIMARY KEY,
+                encrypted_seed BLOB NOT NULL,
+                salt BLOB NOT NULL,
+                nonce BLOB NOT NULL,
+                master_ecdsa_bip44_account_0_epk BLOB NOT NULL,
+                alias TEXT,
+                is_main INTEGER,
+                uses_password INTEGER NOT NULL,
+                password_hint TEXT,
+                network TEXT NOT NULL
+            );
+CREATE TABLE wallet_addresses (
+                seed_hash BLOB NOT NULL,
+                address TEXT NOT NULL,
+                derivation_path TEXT NOT NULL,
+                balance INTEGER,
+                path_reference INTEGER NOT NULL,
+                path_type INTEGER NOT NULL,
+                PRIMARY KEY (seed_hash, address),
+                FOREIGN KEY (seed_hash) REFERENCES wallet(seed_hash) ON DELETE CASCADE
+            );
+CREATE INDEX idx_wallet_addresses_path_reference ON wallet_addresses (path_reference);
+CREATE INDEX idx_wallet_addresses_path_type ON wallet_addresses (path_type);
+CREATE INDEX idx_utxos_address ON utxos (address);
+CREATE INDEX idx_utxos_network ON utxos (network);
+CREATE INDEX idx_identity_local_network_type
+             ON identity (is_local, network, identity_type);
+CREATE INDEX idx_alias_network ON contract (alias, network);
+CREATE INDEX idx_proof_log_request_type_time ON proof_log (request_type, time_ms);
+CREATE INDEX idx_proof_log_time ON proof_log (time_ms);
+CREATE INDEX idx_proof_log_error_request_type_time ON proof_log (error, request_type, time_ms);
+CREATE INDEX idx_proof_log_error_time ON proof_log (error, time_ms);
+DELETE FROM "sqlite_sequence";
+COMMIT;
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/documents.json b/tests/migration-fixtures/v0.9.3-public-identities/documents.json
new file mode 100644
index 000000000..df9db4dd5
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/documents.json
@@ -0,0 +1 @@
+{"resultSet":[{"identifier":"2V4mi4eaaESL5DzPPZWcNn3CSkKJZEg9AEsX6zwAJAVP","dataContractIdentifier":"GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec","revision":1,"txHash":"5A5843214455C494CA34C7F56C3219D13D164388A69E62A71733BD2D1DB4A7B6","deleted":false,"data":null,"timestamp":"2026-09-11T00:47:45.532Z","system":false,"entropy":null,"prefundedVotingBalance":null,"documentTypeName":"preorder","transitionType":null,"identityContractNonce":null,"gasUsed":null,"totalGasUsed":null,"owner":{"identifier":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE","aliases":[{"alias":"migtestfixture093.dash","status":"ok","timestamp":"2026-09-11T00:47:47.422Z","documentId":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","contested":false}]}},{"identifier":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","dataContractIdentifier":"GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec","revision":1,"txHash":"908845682B350F1001E514045429981289CF7A11C09FE6365522B8504ECE99DA","deleted":false,"data":null,"timestamp":"2026-09-11T00:47:47.422Z","system":false,"entropy":null,"prefundedVotingBalance":null,"documentTypeName":"domain","transitionType":null,"identityContractNonce":null,"gasUsed":null,"totalGasUsed":null,"owner":{"identifier":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE","aliases":[{"alias":"migtestfixture093.dash","status":"ok","timestamp":"2026-09-11T00:47:47.422Z","documentId":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","contested":false}]}}],"pagination":{"page":1,"limit":10,"total":2}}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/domain-transaction.json b/tests/migration-fixtures/v0.9.3-public-identities/domain-transaction.json
new file mode 100644
index 000000000..026299a02
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/domain-transaction.json
@@ -0,0 +1 @@
+{"hash":"908845682B350F1001E514045429981289CF7A11C09FE6365522B8504ECE99DA","index":0,"blockHash":"A7AD5CED7ABAC5DE8D213F001A33C13CAD0A9B49F6E0057B82B58A337305905D","blockHeight":570706,"type":"BATCH","batchType":0,"data":"AgE7nal+vAbAfAwMSGlepdNsrs6eGeSUSq5VSGkdmoD65QEAAAABURBP58oQOe3X/slyJz39C3F6Ioqqd8AATd2AL8BYXLYCBmRvbWFpbuZoxlmvZq7h5ywYbd57W34KHXEqCcQNVyH2Ir9TxTFVAJ0yaQG6w2IbqbsuLimw+uMYeKqrfSBO0JvqmW+P2ioFBwVsYWJlbBIRbWlndGVzdGZpeHR1cmUwOTMPbm9ybWFsaXplZExhYmVsEhFtMWd0ZXN0ZjF4dHVyZTA5Mxpub3JtYWxpemVkUGFyZW50RG9tYWluTmFtZRIEZGFzaBBwYXJlbnREb21haW5OYW1lEgRkYXNoDHByZW9yZGVyU2FsdAzLLBsKqoUk4DIKtosi2QN5PyHR87PW8vioL6MEIbFfjgdyZWNvcmRzFgESCGlkZW50aXR5EDudqX68BsB8DAxIaV6l02yuzp4Z5JRKrlVIaR2agPrlDnN1YmRvbWFpblJ1bGVzFgESD2FsbG93U3ViZG9tYWlucxMAAAACQSAFhfgO2/5B0BxLepe3pL482HPCew1mHeAe82O2eI6a6gZOOI9aZlGgaslCqJRAAY2aRfQP7nE3Z6jZRuV1Sp9e","timestamp":"2026-09-11T00:47:47.422Z","gasUsed":42188020,"status":"SUCCESS","error":null,"owner":{"identifier":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE","aliases":[{"alias":"migtestfixture093.dash","status":"ok","timestamp":"2026-09-11T00:47:47.422Z","documentId":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","contested":false}]},"incoming":null,"amount":null,"base58Address":null,"bech32mAddress":null,"shielded":null}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/domain.json b/tests/migration-fixtures/v0.9.3-public-identities/domain.json
new file mode 100644
index 000000000..fdb298ef1
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/domain.json
@@ -0,0 +1 @@
+{"identifier":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","dataContractIdentifier":"GWRSAVFMjXx8HpQFaNJMqBV7MBgMK4br5UESsB4S31Ec","revision":1,"txHash":"908845682B350F1001E514045429981289CF7A11C09FE6365522B8504ECE99DA","deleted":false,"data":"{\"label\":\"migtestfixture093\",\"records\":{\"identity\":\"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE\"},\"preorderSalt\":\"yywbCqqFJOAyCraLItkDeT8h0fOz1vL4qC+jBCGxX44=\",\"subdomainRules\":{\"allowSubdomains\":false},\"normalizedLabel\":\"m1gtestf1xture093\",\"parentDomainName\":\"dash\",\"normalizedParentDomainName\":\"dash\"}","timestamp":"2026-09-11T00:47:47.422Z","system":false,"entropy":"9d326901bac3621ba9bb2e2e29b0fae31878aaab7d204ed09bea996f8fda2a05","prefundedVotingBalance":null,"documentTypeName":"domain","transitionType":"DOCUMENT_CREATE","identityContractNonce":null,"gasUsed":null,"totalGasUsed":42188020,"owner":{"identifier":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE","aliases":[{"alias":"migtestfixture093.dash","status":"ok","timestamp":"2026-09-11T00:47:47.422Z","documentId":"6TST6y5sktpeN9ts6FLidnVHjjhUaZqTW7V5cw3e1QDs","contested":false}]}}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/expected.json b/tests/migration-fixtures/v0.9.3-public-identities/expected.json
new file mode 100644
index 000000000..4e0b4da9d
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/expected.json
@@ -0,0 +1,123 @@
+{
+  "identities": [
+    {
+      "id": "51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE",
+      "alias": "public-dpns-user",
+      "identity_type": "User",
+      "network": "testnet",
+      "status": "Active",
+      "balance_credits": 2490734060,
+      "revision": 0,
+      "public_keys": [
+        {
+          "id": 0,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "AUTHENTICATION",
+          "security_level": "MASTER",
+          "data": "a9ef1846de6cc6a5dad6b2426053740e4cce5b8d",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": null
+        },
+        {
+          "id": 1,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "AUTHENTICATION",
+          "security_level": "CRITICAL",
+          "data": "a9448477330e75ae4e53cc97c270404b6bd98052",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": null
+        },
+        {
+          "id": 2,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "AUTHENTICATION",
+          "security_level": "HIGH",
+          "data": "7b83198c15a671201e7d3706efe485904d9fbbaf",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": null
+        },
+        {
+          "id": 3,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "TRANSFER",
+          "security_level": "CRITICAL",
+          "data": "3f93ec2af939780305355081fca1d618d11e7109",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": null
+        },
+        {
+          "id": 4,
+          "key_type": "ECDSA_SECP256K1",
+          "purpose": "ENCRYPTION",
+          "security_level": "MEDIUM",
+          "data": "02da714f474a0764f27bfb7e285248c3673348f9cc20e7bc1cb3bad014112b94ff",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": {
+            "type": "documentType",
+            "id": "Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7",
+            "document_type_name": "contactRequest"
+          }
+        },
+        {
+          "id": 5,
+          "key_type": "ECDSA_SECP256K1",
+          "purpose": "DECRYPTION",
+          "security_level": "MEDIUM",
+          "data": "02c02dc205df2c5a13c6a55a214f6067305b1728fddc8aa56f74240b8414dc3a9a",
+          "read_only": false,
+          "disabled_at": null,
+          "contract_bounds": {
+            "type": "documentType",
+            "id": "Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7",
+            "document_type_name": "contactRequest"
+          }
+        }
+      ],
+      "private_key_count": 0,
+      "dpns_names": [
+        {
+          "name": "migtestfixture093",
+          "acquired_at": 1789087667422
+        }
+      ]
+    },
+    {
+      "id": "PJUBWbXWmzEYCs99rAAbnCiHRzrnhKLQrXbmSsuPBYB",
+      "alias": "public-evonode",
+      "identity_type": "Evonode",
+      "network": "testnet",
+      "status": "Active",
+      "balance_credits": 3085310039528312,
+      "revision": 0,
+      "public_keys": [
+        {
+          "id": 0,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "TRANSFER",
+          "security_level": "CRITICAL",
+          "data": "c69a0bda7daaae481be8def95e5f347a1d00a4b4",
+          "read_only": true,
+          "disabled_at": null,
+          "contract_bounds": null
+        },
+        {
+          "id": 1,
+          "key_type": "ECDSA_HASH160",
+          "purpose": "OWNER",
+          "security_level": "CRITICAL",
+          "data": "ec83a5f23ec17737f590153eb7eed16f7b2f1327",
+          "read_only": true,
+          "disabled_at": null,
+          "contract_bounds": null
+        }
+      ],
+      "private_key_count": 0,
+      "dpns_names": []
+    }
+  ]
+}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/fixture-writer.rs b/tests/migration-fixtures/v0.9.3-public-identities/fixture-writer.rs
new file mode 100644
index 000000000..af26f4343
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/fixture-writer.rs
@@ -0,0 +1,169 @@
+use dash_evo_tool::database::Database;
+use dash_evo_tool::model::qualified_identity::encrypted_key_storage::KeyStorage;
+use dash_evo_tool::model::qualified_identity::{
+    DPNSNameInfo, IdentityStatus, IdentityType, QualifiedIdentity,
+};
+use dash_sdk::dpp::dashcore::Network;
+use dash_sdk::dpp::identity::identity_public_key::contract_bounds::ContractBounds;
+use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0;
+use dash_sdk::dpp::identity::v0::IdentityV0;
+use dash_sdk::dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel};
+use dash_sdk::dpp::platform_value::string_encoding::Encoding;
+use dash_sdk::platform::Identifier;
+use serde_json::{Value, json};
+use std::{collections::BTreeMap, error::Error, fs, path::PathBuf};
+
+fn text<'a>(v: &'a Value, field: &str) -> Result<&'a str, Box> {
+    v[field]
+        .as_str()
+        .ok_or_else(|| format!("missing string {field}").into())
+}
+
+fn main() -> Result<(), Box> {
+    let mut args = std::env::args().skip(1);
+    let source = PathBuf::from(args.next().ok_or("expected source directory")?);
+    let output = PathBuf::from(args.next().ok_or("expected output directory")?);
+    if args.next().is_some() {
+        return Err("unexpected extra argument".into());
+    }
+    fs::create_dir_all(&output)?;
+    let path = output.join("data.db");
+    if path.exists() {
+        return Err("output database already exists".into());
+    }
+    let db = Database::new(&path)?;
+    db.initialize(&path)?;
+    db.execute("UPDATE settings SET network = 'testnet' WHERE id = 1", [])?;
+    let mut expected = Vec::new();
+    for (file, identity_type, alias) in [
+        ("user.json", IdentityType::User, "public-dpns-user"),
+        ("masternode.json", IdentityType::Evonode, "public-evonode"),
+    ] {
+        let input: Value = serde_json::from_slice(&fs::read(source.join(file))?)?;
+        if file == "masternode.json" {
+            let validators: Value =
+                serde_json::from_slice(&fs::read(source.join("validator.json"))?)?;
+            let validator = &validators["resultSet"][0];
+            assert_eq!(validator["identity"], input["identifier"]);
+            assert_eq!(validator["proTxInfo"]["type"], "Evo");
+        }
+        let id = Identifier::from_string(text(&input, "identifier")?, Encoding::Base58)?;
+        let mut keys = BTreeMap::new();
+        let mut expected_keys = Vec::new();
+        for key in input["publicKeys"].as_array().ok_or("missing publicKeys")? {
+            let contract_bounds = if key["contractBounds"].is_null() {
+                None
+            } else {
+                let bounds = &key["contractBounds"];
+                let id = Identifier::from_string(text(bounds, "identifier")?, Encoding::Base58)?;
+                Some(match bounds["documentTypeName"].as_str() {
+                    Some(name) => ContractBounds::SingleContractDocumentType {
+                        id,
+                        document_type_name: name.into(),
+                    },
+                    None => ContractBounds::SingleContract { id },
+                })
+            };
+            let purpose = match text(key, "purpose")? {
+                "AUTHENTICATION" => Purpose::AUTHENTICATION,
+                "TRANSFER" => Purpose::TRANSFER,
+                "OWNER" => Purpose::OWNER,
+                "ENCRYPTION" => Purpose::ENCRYPTION,
+                "DECRYPTION" => Purpose::DECRYPTION,
+                other => return Err(format!("unsupported purpose {other}").into()),
+            };
+            let security_level = match text(key, "securityLevel")? {
+                "MASTER" => SecurityLevel::MASTER,
+                "CRITICAL" => SecurityLevel::CRITICAL,
+                "HIGH" => SecurityLevel::HIGH,
+                "MEDIUM" => SecurityLevel::MEDIUM,
+                other => return Err(format!("unsupported security level {other}").into()),
+            };
+            let key_type = match text(key, "keyType")? {
+                "ECDSA_HASH160" => KeyType::ECDSA_HASH160,
+                "ECDSA_SECP256K1" => KeyType::ECDSA_SECP256K1,
+                other => return Err(format!("unsupported key type {other}").into()),
+            };
+            let key_id = u32::try_from(key["keyId"].as_u64().ok_or("invalid keyId")?)?;
+            let disabled_at = if key["disabledAt"].is_null() {
+                None
+            } else {
+                Some(key["disabledAt"].as_u64().ok_or("invalid disabledAt")?)
+            };
+            let public_key = IdentityPublicKey::V0(IdentityPublicKeyV0 {
+                id: key_id,
+                purpose,
+                security_level,
+                contract_bounds: contract_bounds.clone(),
+                key_type,
+                read_only: key["readOnly"].as_bool().ok_or("invalid readOnly")?,
+                data: hex::decode(text(key, "data")?)?.into(),
+                disabled_at,
+            });
+            expected_keys.push(json!({"id": key_id, "key_type": key["keyType"], "purpose": key["purpose"], "security_level": key["securityLevel"], "data": key["data"], "read_only": key["readOnly"], "disabled_at": key["disabledAt"], "contract_bounds": serde_json::to_value(&contract_bounds)?}));
+            if keys.insert(key_id, public_key).is_some() {
+                return Err("duplicate keyId".into());
+            }
+        }
+        let dpns_names = if file == "user.json" {
+            let domain: Value = serde_json::from_slice(&fs::read(source.join("domain.json"))?)?;
+            let data: Value = serde_json::from_str(text(&domain, "data")?)?;
+            assert_eq!(domain["documentTypeName"], "domain");
+            assert_eq!(domain["transitionType"], "DOCUMENT_CREATE");
+            assert_eq!(domain["revision"], 1);
+            assert_eq!(data["records"]["identity"], input["identifier"]);
+            assert_eq!(domain["owner"]["identifier"], input["identifier"]);
+            let acquired_at = u64::try_from(
+                chrono::DateTime::parse_from_rfc3339(text(&domain, "timestamp")?)?
+                    .timestamp_millis(),
+            )?;
+            vec![DPNSNameInfo {
+                name: text(&data, "label")?.into(),
+                acquired_at,
+            }]
+        } else {
+            Vec::new()
+        };
+        let qi = QualifiedIdentity {
+            identity: Identity::V0(IdentityV0 {
+                id,
+                public_keys: keys,
+                balance: text(&input, "balance")?.parse()?,
+                revision: text(&input, "revision")?.parse()?,
+            }),
+            associated_voter_identity: None,
+            associated_operator_identity: None,
+            associated_owner_key_id: None,
+            identity_type,
+            alias: Some(alias.into()),
+            private_keys: KeyStorage::default(),
+            dpns_names,
+            associated_wallets: BTreeMap::new(),
+            wallet_index: None,
+            top_ups: BTreeMap::new(),
+            status: IdentityStatus::Active,
+            network: Network::Testnet,
+        };
+        let bytes = qi.to_bytes();
+        assert_eq!(qi, QualifiedIdentity::from_bytes(&bytes));
+        assert!(qi.private_keys.private_keys.is_empty());
+        db.execute("INSERT INTO identity (id,data,is_local,alias,identity_type,network,status) VALUES (?, ?, 1, ?, ?, 'testnet', 2)", rusqlite::params![id.to_vec(), bytes, alias, format!("{identity_type:?}")])?;
+        expected.push(json!({
+            "id": input["identifier"], "alias": alias, "identity_type": format!("{identity_type:?}"),
+            "network": "testnet", "status": "Active", "balance_credits": text(&input, "balance")?.parse::()?, "revision": text(&input, "revision")?.parse::()?,
+            "public_keys": expected_keys, "private_key_count": 0,
+            "dpns_names": qi.dpns_names.iter().map(|n| json!({"name": n.name, "acquired_at": n.acquired_at})).collect::>()
+        }));
+    }
+    drop(db);
+    let conn = rusqlite::Connection::open(&path)?;
+    let count: i64 = conn.query_row("SELECT COUNT(*) FROM identity", [], |r| r.get(0))?;
+    let wallets: i64 = conn.query_row("SELECT COUNT(*) FROM wallet", [], |r| r.get(0))?;
+    assert_eq!((count, wallets), (2, 0));
+    fs::write(
+        output.join("expected.json"),
+        serde_json::to_string_pretty(&json!({"identities": expected}))?,
+    )?;
+    println!("Validated {count} public identities, {wallets} wallets, no private keys");
+    Ok(())
+}
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/masternode.json b/tests/migration-fixtures/v0.9.3-public-identities/masternode.json
new file mode 100644
index 000000000..05aac6a9c
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/masternode.json
@@ -0,0 +1 @@
+{"identifier":"PJUBWbXWmzEYCs99rAAbnCiHRzrnhKLQrXbmSsuPBYB","revision":"0","balance":"3085310039528312","timestamp":null,"txHash":null,"totalTxs":0,"totalTransfers":0,"totalDocuments":0,"totalDataContracts":0,"isSystem":false,"aliases":[],"totalGasSpent":0,"averageGasSpent":0,"totalTopUpsAmount":0,"totalWithdrawalsAmount":0,"lastWithdrawalHash":null,"publicKeys":[{"keyId":0,"keyType":"ECDSA_HASH160","raw":"0000030100020114c69a0bda7daaae481be8def95e5f347a1d00a4b400","data":"c69a0bda7daaae481be8def95e5f347a1d00a4b4","purpose":"TRANSFER","securityLevel":"CRITICAL","readOnly":true,"publicKeyHash":"c69a0bda7daaae481be8def95e5f347a1d00a4b4","contractBounds":null,"disabledAt":null},{"keyId":1,"keyType":"ECDSA_HASH160","raw":"0001060100020114ec83a5f23ec17737f590153eb7eed16f7b2f132700","data":"ec83a5f23ec17737f590153eb7eed16f7b2f1327","purpose":"OWNER","securityLevel":"CRITICAL","readOnly":true,"publicKeyHash":"ec83a5f23ec17737f590153eb7eed16f7b2f1327","contractBounds":null,"disabledAt":null}],"fundingCoreTx":null,"totalTopUps":0,"totalWithdrawals":0,"lastWithdrawalTimestamp":null,"nonce":"0","type":"masternode","owner":"PJUBWbXWmzEYCs99rAAbnCiHRzrnhKLQrXbmSsuPBYB"}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/user.json b/tests/migration-fixtures/v0.9.3-public-identities/user.json
new file mode 100644
index 000000000..8bf3e6ba9
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/user.json
@@ -0,0 +1 @@
+{"identifier":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE","revision":"0","balance":"2490734060","timestamp":"2026-09-11T00:46:48.383Z","txHash":"ADB924DB4CD8CF92D03F5D53ADB4A56200B28E21B7B2232B91A41F2AF543AB7E","totalTxs":3,"totalTransfers":1,"totalDocuments":2,"totalDataContracts":0,"isSystem":false,"aliases":[{"alias":"migtestfixture093.dash","status":"ok","contested":false,"timestamp":"2026-09-11T00:47:47.422Z","txHash":"908845682B350F1001E514045429981289CF7A11C09FE6365522B8504ECE99DA"}],"totalGasSpent":268036940,"averageGasSpent":89345647,"totalTopUpsAmount":2758771000,"totalWithdrawalsAmount":0,"lastWithdrawalHash":null,"publicKeys":[{"keyId":0,"keyType":"ECDSA_HASH160","raw":"0000000000020014a9ef1846de6cc6a5dad6b2426053740e4cce5b8d00","data":"a9ef1846de6cc6a5dad6b2426053740e4cce5b8d","purpose":"AUTHENTICATION","securityLevel":"MASTER","readOnly":false,"publicKeyHash":"a9ef1846de6cc6a5dad6b2426053740e4cce5b8d","contractBounds":null,"disabledAt":null},{"keyId":1,"keyType":"ECDSA_HASH160","raw":"0001000100020014a9448477330e75ae4e53cc97c270404b6bd9805200","data":"a9448477330e75ae4e53cc97c270404b6bd98052","purpose":"AUTHENTICATION","securityLevel":"CRITICAL","readOnly":false,"publicKeyHash":"a9448477330e75ae4e53cc97c270404b6bd98052","contractBounds":null,"disabledAt":null},{"keyId":2,"keyType":"ECDSA_HASH160","raw":"00020002000200147b83198c15a671201e7d3706efe485904d9fbbaf00","data":"7b83198c15a671201e7d3706efe485904d9fbbaf","purpose":"AUTHENTICATION","securityLevel":"HIGH","readOnly":false,"publicKeyHash":"7b83198c15a671201e7d3706efe485904d9fbbaf","contractBounds":null,"disabledAt":null},{"keyId":3,"keyType":"ECDSA_HASH160","raw":"00030301000200143f93ec2af939780305355081fca1d618d11e710900","data":"3f93ec2af939780305355081fca1d618d11e7109","purpose":"TRANSFER","securityLevel":"CRITICAL","readOnly":false,"publicKeyHash":"3f93ec2af939780305355081fca1d618d11e7109","contractBounds":null,"disabledAt":null},{"keyId":4,"keyType":"ECDSA_SECP256K1","raw":"000401030101a2a1b4ac6fef22ea2a1a68e8123644b357875f6b412c18109281c146e7b271bc0e636f6e746163745265717565737400002102da714f474a0764f27bfb7e285248c3673348f9cc20e7bc1cb3bad014112b94ff00","data":"02da714f474a0764f27bfb7e285248c3673348f9cc20e7bc1cb3bad014112b94ff","purpose":"ENCRYPTION","securityLevel":"MEDIUM","readOnly":false,"publicKeyHash":"cb8fec4ef749f04d03de47fbe525affd5823f5d1","contractBounds":{"identifier":"Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7","documentTypeName":"contactRequest"},"disabledAt":null},{"keyId":5,"keyType":"ECDSA_SECP256K1","raw":"000502030101a2a1b4ac6fef22ea2a1a68e8123644b357875f6b412c18109281c146e7b271bc0e636f6e746163745265717565737400002102c02dc205df2c5a13c6a55a214f6067305b1728fddc8aa56f74240b8414dc3a9a00","data":"02c02dc205df2c5a13c6a55a214f6067305b1728fddc8aa56f74240b8414dc3a9a","purpose":"DECRYPTION","securityLevel":"MEDIUM","readOnly":false,"publicKeyHash":"2fda414b47cdf1a540808285b327bdc8ca73c565","contractBounds":{"identifier":"Bwr4WHCPz5rFVAD87RqTs3izo4zpzwsEdKPWUT1NS1C7","documentTypeName":"contactRequest"},"disabledAt":null}],"fundingCoreTx":"eb2b3673a224f9401549a841ab58ac1b36fe9b3f707cb802f81d27c268b03bad","totalTopUps":0,"totalWithdrawals":0,"lastWithdrawalTimestamp":null,"nonce":"0","type":"regular","owner":"51iVVoMU8ANbxDv7wySh5Sk6mZGSEMpCkeqtkr24mHdE"}
\ No newline at end of file
diff --git a/tests/migration-fixtures/v0.9.3-public-identities/validator.json b/tests/migration-fixtures/v0.9.3-public-identities/validator.json
new file mode 100644
index 000000000..088e875ac
--- /dev/null
+++ b/tests/migration-fixtures/v0.9.3-public-identities/validator.json
@@ -0,0 +1 @@
+{"pagination":{"page":1,"limit":1,"total":88},"resultSet":[{"proTxHash":"05B687978344FA2433B2AA99D41F643E2D8581A789CDC23084889CECA5244EA8","isActive":true,"proposedBlocksAmount":21206,"lastProposedBlockHeader":{"hash":"9ACAF75AEC45125D88AF7620594D3F1429CACF813FBC3BA39CF4F1A9FAAE2B05","height":585458,"timestamp":"2026-09-17T13:56:54.810Z","blockVersion":14,"appVersion":13,"l1LockedHeight":1555493,"validator":"05B687978344FA2433B2AA99D41F643E2D8581A789CDC23084889CECA5244EA8","totalGasUsed":0,"appHash":"26C3363138BFC5C4E4373769D28706B1275A15B19AA68360A6CCD9EB3D5C01F7","quorumHash":"000000E36A344BFC1901BEF923AAC9F28147BE73FFF84095BB663B002C1540E1"},"proTxInfo":{"type":"Evo","collateralHash":"6ce8545e25d4f03aba1527062d9583ae01827c65b234bd979aca5954c6ae3a59","collateralIndex":9,"collateralAddress":"yRxmN1L3FMfiDYHnnghP7bEr7tsqxAhyWe","operatorReward":0,"confirmations":705162,"state":{"version":2,"service":"68.67.122.24:19999","addresses":{"core_p2p":["68.67.122.24:19999"],"platform_https":["68.67.122.24:1443"],"platform_p2p":["68.67.122.24:36656"]},"registeredHeight":850334,"lastPaidHeight":1555432,"consecutivePayments":0,"PoSePenalty":0,"PoSeRevivedHeight":1367849,"PoSeBanHeight":-1,"revocationReason":0,"ownerAddress":"yht22Z6kN4y7nQzJr6PZX2ct5aGVHrAPFY","votingAddress":"yht22Z6kN4y7nQzJr6PZX2ct5aGVHrAPFY","platformNodeID":"8feb00404d6f765856c95e587b2523a365bc7258","platformP2PPort":36656,"platformHTTPPort":1443,"payoutAddress":"yeRZBWYfeNE4yVUHV4ZLs83Ppn9aMRH57A","pubKeyOperator":"80f8efb42f65ed9650078785be5d13e6e90eb9df87a99261d4de34df2b4b79a9c9b8c5e1aec7ac068ebef14636ceac4c"}},"identity":"PJUBWbXWmzEYCs99rAAbnCiHRzrnhKLQrXbmSsuPBYB","identityBalance":"3085310039528312","epochInfo":{"number":18972,"firstBlockHeight":"585276","firstCoreBlockHeight":1555491,"startTime":1789652413478,"feeMultiplier":"1000","endTime":1789656013478,"totalBlocksInEpoch":null,"totalProcessingFees":null,"totalDistributedStorageFees":null,"totalCreatedStorageFees":null,"coreBlockRewards":null,"blockProposers":null},"totalReward":null,"epochReward":null,"withdrawalsCount":null,"lastWithdrawal":null,"lastWithdrawalTime":null,"endpoints":null,"geoIpInfo":{"ipv4":"68.67.122.24","countryCode":"US","city":"Mesa","latitude":33.415199279785156,"longitude":-111.83100128173828}}]}
\ No newline at end of file
diff --git a/tests/migration-matrix/assertions.rs b/tests/migration-matrix/assertions.rs
new file mode 100644
index 000000000..76fcef1d2
--- /dev/null
+++ b/tests/migration-matrix/assertions.rs
@@ -0,0 +1,1340 @@
+//! The checks a migrated profile has to satisfy.
+//!
+//! Every check is conditional on what the fixture actually started from: a
+//! `data.db` it carried must come out byte-identical (every boot path opens it
+//! read-only), a missing one must be created at [`DEFAULT_DB_VERSION`], and a
+//! fixture holding a password-protected wallet must stop at the documented
+//! `StorageUpdateNeedsDesktop` instead of completing.
+//!
+//! SQLite files are never opened in place. Each read copies the database (and
+//! its `-wal` / `-shm` siblings) into a scratch directory first, so a read can
+//! neither checkpoint the file under test nor disturb a byte-identity check.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+use dash_evo_tool::backend_task::migration::finish_unwire::{
+    dapi_refresh_sentinel_key_for, sentinel_key_for,
+};
+use dash_evo_tool::database::DEFAULT_DB_VERSION;
+use dash_sdk::dpp::dashcore::{Network, base58};
+use rusqlite::{Connection, OptionalExtension};
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+
+use crate::cli::CliRun;
+use crate::manifest::{ExpectedWallet, WalletOutcome};
+
+/// Legacy DET database carrying the `settings.database_version` ladder.
+pub const DATA_DB: &str = "data.db";
+
+/// Cross-network app store holding the migration sentinels.
+pub const APP_DB: &str = "det-app.sqlite";
+
+/// Key every stored identity lives under in the per-network store
+/// (`IDENTITY_KEY` in `src/context/identity_db.rs`).
+const IDENTITY_KEY: &str = "det:identity:v1";
+
+/// Namespace shared by every migration sentinel. Discovering keys by prefix
+/// picks up the ones whose constants are private (the legacy-settings import)
+/// without this harness guessing at their spelling.
+const SENTINEL_PREFIX: &str = "det:migration:";
+
+/// Text that must never appear in a boot's output. A panic or an
+/// incompatibility verdict is a migration defect, not a condition to work
+/// around — the matrix fails rather than falling back.
+const FAILURE_MARKERS: &[&str] = &[
+    "panicked at",
+    "WalletDataIncompatible",
+    "Your wallet data is not compatible with this version of the app",
+];
+
+/// On-disk token for a network, matching `wallet_backend::network_prefix`
+/// (which is crate-private) — used for the per-network database file name.
+fn storage_token(network: Network) -> &'static str {
+    match network {
+        Network::Mainnet => "mainnet",
+        Network::Testnet => "testnet",
+        Network::Devnet => "devnet",
+        Network::Regtest => "regtest",
+    }
+}
+
+/// Network spelling `network_info` reports, matching
+/// `mcp::server::network_display_name` — note `local`, not `regtest`.
+pub fn display_name(network: Network) -> &'static str {
+    match network {
+        Network::Regtest => "local",
+        other => storage_token(other),
+    }
+}
+
+/// The durable per-network wallet database, sibling of [`APP_DB`].
+pub fn network_db_name(network: Network) -> String {
+    format!("det-{}.sqlite", storage_token(network))
+}
+
+/// A boot that ran to completion without panicking or declaring the data
+/// incompatible.
+pub fn check_boot(run: &CliRun, label: &str) -> Result<(), String> {
+    if !run.succeeded() {
+        return Err(format!("{label} did not complete\n{}", run.report()));
+    }
+    for marker in FAILURE_MARKERS {
+        if run.stdout.contains(marker) || run.stderr.contains(marker) {
+            return Err(format!("{label} reported `{marker}`\n{}", run.report()));
+        }
+    }
+    Ok(())
+}
+
+/// How a wallet-gated boot ends when the fixture holds a wallet only the
+/// desktop app can migrate: the typed error the MCP layer carries in the
+/// error `data`, which rmcp logs to stderr at `warn` (inside the harness's
+/// default `info` filter). Matching the variant rather than the user-facing
+/// message keeps a copy edit from breaking the check; a log filter that hides
+/// the line fails the check instead of passing it.
+const NEEDS_DESKTOP_MARKER: &str =
+    "StorageUpdateNeedsDesktop { source: InteractivePromptUnavailable }";
+
+/// A wallet-gated boot over a fixture holding a password-protected wallet.
+/// det-cli cannot prompt for the password by design
+/// (`docs/ai-design/2026-07-14-migration-password-prompt/design.md`), so the
+/// boot must fail with exactly [`NEEDS_DESKTOP_MARKER`]. Completing, or
+/// failing in any other way, is a regression.
+pub fn check_needs_desktop(run: &CliRun, label: &str) -> Result<(), String> {
+    for marker in FAILURE_MARKERS {
+        if run.stdout.contains(marker) || run.stderr.contains(marker) {
+            return Err(format!("{label} reported `{marker}`\n{}", run.report()));
+        }
+    }
+    if run.succeeded() {
+        return Err(format!(
+            "{label} completed, but the fixture holds a password-protected wallet that a headless \
+             boot cannot migrate; it must stop at StorageUpdateNeedsDesktop\n{}",
+            run.report()
+        ));
+    }
+    if run.timed_out || run.exit_code.is_none() || !run.stderr.contains(NEEDS_DESKTOP_MARKER) {
+        return Err(format!(
+            "{label} failed, but not with `{NEEDS_DESKTOP_MARKER}`\n{}",
+            run.report()
+        ));
+    }
+    Ok(())
+}
+
+/// `data.db`'s schema as it can be compared across a boot: the version the
+/// ladder records, every schema object, and the committed rows including WAL data.
+#[derive(Debug, PartialEq, Eq)]
+pub struct SchemaSnapshot {
+    pub version: Option,
+    objects: Vec<(String, String, String)>,
+    rows: BTreeMap>,
+}
+
+impl SchemaSnapshot {
+    fn describe_version(&self) -> String {
+        match self.version {
+            Some(version) => version.to_string(),
+            None => "unknown (no settings row)".to_string(),
+        }
+    }
+}
+
+/// Reads a `data.db` snapshot, or `None` when the fixture has no such file.
+pub fn schema_snapshot(
+    data_db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result, String> {
+    let Some(conn) = open_copy(data_db, scratch, label)? else {
+        return Ok(None);
+    };
+    let version = conn
+        .query_row(
+            "SELECT database_version FROM settings WHERE id = 1",
+            [],
+            |row| row.get::<_, u16>(0),
+        )
+        .optional()
+        .map_err(|e| {
+            format!(
+                "could not read the schema version of {}: {e}",
+                data_db.display()
+            )
+        })?;
+    let mut statement = conn
+        .prepare("SELECT type, name, IFNULL(sql, '') FROM sqlite_master ORDER BY type, name")
+        .map_err(|e| format!("could not read the schema of {}: {e}", data_db.display()))?;
+    let objects = statement
+        .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
+        .and_then(|rows| rows.collect::, _>>())
+        .map_err(|e| format!("could not read the schema of {}: {e}", data_db.display()))?;
+    let rows = table_rows(&conn, &objects)
+        .map_err(|e| format!("could not snapshot rows in {}: {e}", data_db.display()))?;
+    Ok(Some(SchemaSnapshot {
+        version,
+        objects,
+        rows,
+    }))
+}
+
+// Hash typed values, retaining duplicate rows while ignoring physical page order.
+fn table_rows(
+    conn: &Connection,
+    objects: &[(String, String, String)],
+) -> rusqlite::Result>> {
+    use rusqlite::types::ValueRef;
+    let mut tables = BTreeMap::new();
+    for (_, name, _) in objects.iter().filter(|(kind, _, _)| kind == "table") {
+        let quoted = name.replace('"', "\"\"");
+        let mut statement = conn.prepare(&format!("SELECT * FROM \"{quoted}\""))?;
+        let columns = statement.column_count();
+        let mut rows = statement
+            .query_map([], |row| {
+                let mut hash = Sha256::new();
+                for column in 0..columns {
+                    match row.get_ref(column)? {
+                        ValueRef::Null => hash.update([0]),
+                        ValueRef::Integer(value) => {
+                            hash.update([1]);
+                            hash.update(value.to_le_bytes());
+                        }
+                        ValueRef::Real(value) => {
+                            hash.update([2]);
+                            hash.update(value.to_bits().to_le_bytes());
+                        }
+                        ValueRef::Text(value) | ValueRef::Blob(value) => {
+                            hash.update([if matches!(row.get_ref(column)?, ValueRef::Text(_)) {
+                                3
+                            } else {
+                                4
+                            }]);
+                            hash.update((value.len() as u64).to_le_bytes());
+                            hash.update(value);
+                        }
+                    }
+                }
+                Ok(hash.finalize().into())
+            })?
+            .collect::>>()?;
+        rows.sort_unstable();
+        tables.insert(name.clone(), rows);
+    }
+    Ok(tables)
+}
+
+/// The legacy `data.db` verdict, conditional on where the fixture started.
+///
+/// Every boot path (GUI and det-cli) opens an existing `data.db` with SQLite
+/// writes disabled: it is the recovery artifact the storage update reads
+/// from, never a file it upgrades. The version ladder in
+/// `Database::initialize` runs only when no `data.db` exists yet. So:
+///
+/// - present → version and schema exactly as captured;
+/// - above [`DEFAULT_DB_VERSION`] → the fixture was captured by a newer build
+///   than the one under test, which the matrix reports rather than silently
+///   passing;
+/// - absent → a fresh file must be created at [`DEFAULT_DB_VERSION`].
+pub fn check_schema_outcome(
+    before: Option<&SchemaSnapshot>,
+    after: Option<&SchemaSnapshot>,
+) -> Result<(), String> {
+    let Some(after) = after else {
+        return Err(format!("the boot left no {DATA_DB} behind"));
+    };
+    let Some(before) = before else {
+        return match after.version {
+            Some(DEFAULT_DB_VERSION) => Ok(()),
+            _ => Err(format!(
+                "a fixture without {DATA_DB} must get a fresh one at version {DEFAULT_DB_VERSION}, found {}",
+                after.describe_version()
+            )),
+        };
+    };
+
+    if let Some(version) = before.version
+        && version > DEFAULT_DB_VERSION
+    {
+        return Err(format!(
+            "fixture {DATA_DB} is at version {version}, newer than this build's {DEFAULT_DB_VERSION} — \
+             the fixture was captured by a newer DET than the binary under test"
+        ));
+    }
+    if before == after {
+        return Ok(());
+    }
+    Err(format!(
+        "the boot changed the pre-update {DATA_DB} (version {} -> {}), which every boot path must \
+         open read-only",
+        before.describe_version(),
+        after.describe_version()
+    ))
+}
+
+/// Reads a file whole, or `None` when it does not exist.
+pub fn file_bytes(path: &Path) -> Result>, String> {
+    match fs::read(path) {
+        Ok(bytes) => Ok(Some(bytes)),
+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+        Err(e) => Err(format!("could not read {}: {e}", path.display())),
+    }
+}
+
+/// Byte identity of a pre-update `data.db` across a boot. Stronger than
+/// [`check_schema_outcome`]: a read-only open cannot write a single page, so
+/// any difference means something opened the file for writing.
+pub fn check_bytes_unchanged(
+    before: Option<&Vec>,
+    after: Option<&Vec>,
+    label: &str,
+) -> Result<(), String> {
+    match (before, after) {
+        (Some(before), Some(after)) if before == after => Ok(()),
+        (Some(before), Some(after)) if before.len() == after.len() => Err(format!(
+            "{label} must be byte-identical across a boot, but its content changed ({} bytes)",
+            after.len()
+        )),
+        (Some(before), Some(after)) => Err(format!(
+            "{label} must be byte-identical across a boot, but its size went from {} to {} bytes",
+            before.len(),
+            after.len()
+        )),
+        (None, None) => Ok(()),
+        (None, Some(_)) => Err(format!(
+            "{label} did not exist before the boot but does now"
+        )),
+        (Some(_), None) => Err(format!("{label} existed before the boot but is gone")),
+    }
+}
+
+/// The active network `network-info` reports, which is what proves the
+/// migrated settings kept the profile's network.
+pub fn check_network(expected: Network, run: &CliRun) -> Result<(), String> {
+    let json = run.json()?;
+    let active = json
+        .get("active")
+        .and_then(Value::as_str)
+        .ok_or_else(|| format!("network-info printed no `active` field\n{}", run.report()))?;
+    if active != display_name(expected) {
+        return Err(format!(
+            "fixture declares network `{}` but the boot came up on `{active}`",
+            display_name(expected)
+        ));
+    }
+    Ok(())
+}
+
+/// Checks the complete wallet roster and returns aliases for `core-address-create`.
+pub fn check_wallets(expected_aliases: &[String], run: &CliRun) -> Result, String> {
+    let json = run.json()?;
+    let wallets = json
+        .get("wallets")
+        .and_then(Value::as_array)
+        .ok_or_else(|| {
+            format!(
+                "core-wallets-list printed no `wallets` array\n{}",
+                run.report()
+            )
+        })?;
+
+    let mut aliases = BTreeSet::new();
+    let mut identifiers = Vec::new();
+    for wallet in wallets {
+        let alias = wallet.get("alias").and_then(Value::as_str).ok_or_else(|| {
+            format!(
+                "a listed wallet has no alias to match against the manifest\n{}",
+                run.report()
+            )
+        })?;
+        if !aliases.insert(alias.to_string()) {
+            return Err(format!("duplicate wallet alias after migration: {alias:?}"));
+        }
+        identifiers.push(alias.to_string());
+    }
+
+    let missing: Vec<&String> = expected_aliases
+        .iter()
+        .filter(|alias| !aliases.contains(*alias))
+        .collect();
+    if !missing.is_empty() {
+        return Err(format!(
+            "wallets missing after the migration: {missing:?} — the boot listed {aliases:?}"
+        ));
+    }
+    let extra: Vec<_> = aliases
+        .iter()
+        .filter(|alias| !expected_aliases.contains(alias))
+        .collect();
+    if !extra.is_empty() {
+        return Err(format!(
+            "wallets absent from the manifest were listed after migration: {extra:?}"
+        ));
+    }
+    Ok(identifiers)
+}
+
+/// A derived receive address, proving the migrated seed is usable and not
+/// merely present.
+pub fn check_address(run: &CliRun) -> Result {
+    let json = run.json()?;
+    let address = json
+        .get("address")
+        .and_then(Value::as_str)
+        .ok_or_else(|| format!("core-address-create printed no `address`\n{}", run.report()))?;
+    if address.trim().is_empty() {
+        return Err(format!(
+            "core-address-create returned an empty address\n{}",
+            run.report()
+        ));
+    }
+    Ok(address.to_string())
+}
+
+/// Every migration sentinel in the app store, keyed as written. Empty when the
+/// store does not exist yet.
+pub fn migration_sentinels(
+    app_db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result>, String> {
+    let Some(conn) = open_copy(app_db, scratch, label)? else {
+        return Ok(BTreeMap::new());
+    };
+    let mut statement = conn
+        .prepare("SELECT key, value FROM meta_global WHERE key LIKE ?1 ORDER BY key")
+        .map_err(|e| {
+            format!(
+                "could not read migration sentinels from {}: {e} — the upstream `meta_global` \
+                 table is where `DetKv` stores global-scope values",
+                app_db.display()
+            )
+        })?;
+    let rows = statement
+        .query_map([format!("{SENTINEL_PREFIX}%")], |row| {
+            Ok((row.get::<_, String>(0)?, row.get::<_, Vec>(1)?))
+        })
+        .and_then(|rows| rows.collect::>, _>>())
+        .map_err(|e| {
+            format!(
+                "could not read migration sentinels from {}: {e}",
+                app_db.display()
+            )
+        })?;
+    Ok(rows)
+}
+
+/// Completed migrations in the captured profile must retain their exact markers.
+pub fn check_existing_sentinels(
+    before: &BTreeMap>,
+    after: &BTreeMap>,
+) -> Result<(), String> {
+    let changed: Vec<_> = before
+        .iter()
+        .filter(|(key, value)| after.get(*key) != Some(*value))
+        .map(|(key, _)| key)
+        .collect();
+    if !changed.is_empty() {
+        return Err(format!(
+            "the first boot changed captured migration sentinels: {changed:?}"
+        ));
+    }
+    Ok(())
+}
+
+/// The completion sentinel the legacy drain records once it finishes.
+pub fn check_sentinel_recorded(
+    sentinels: &BTreeMap>,
+    network: Network,
+) -> Result<(), String> {
+    let key = sentinel_key_for(network);
+    if sentinels.contains_key(&key) {
+        return Ok(());
+    }
+    Err(format!(
+        "the boot recorded no `{key}` completion sentinel in {APP_DB}; present migration keys: {:?}",
+        sentinels.keys().collect::>()
+    ))
+}
+
+/// The completion sentinel must not exist while the storage update is
+/// unfinished: a wallet still waiting for its password is not migrated.
+pub fn check_sentinel_absent(
+    sentinels: &BTreeMap>,
+    network: Network,
+) -> Result<(), String> {
+    let key = sentinel_key_for(network);
+    if sentinels.contains_key(&key) {
+        return Err(format!(
+            "the boot recorded the `{key}` completion sentinel although the storage update could \
+             not finish"
+        ));
+    }
+    Ok(())
+}
+
+/// Whether each aliased wallet of a v0.9.3-era `data.db` is registered in the
+/// per-network store, keyed by alias. `None` when the fixture has no
+/// `data.db`.
+///
+/// The two stores share no wallet id: `data.db` keys wallets by seed hash, the
+/// upstream store by its own id. Both do keep the BIP44 account-0 xpub —
+/// `data.db` as the 78-byte serialization, `account_registrations` as its
+/// base58check text — so the match is a byte search for that text, with no
+/// key derivation in the harness.
+pub fn legacy_wallet_registrations(
+    data_db: &Path,
+    network_db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result>, String> {
+    let Some(legacy) = open_copy(data_db, scratch, label)? else {
+        return Ok(None);
+    };
+    let read_error = |e: rusqlite::Error| {
+        format!(
+            "could not read legacy wallets from {}: {e}",
+            data_db.display()
+        )
+    };
+    if !legacy
+        .query_row(
+            "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'wallet')",
+            [],
+            |row| row.get::<_, bool>(0),
+        )
+        .map_err(read_error)?
+    {
+        return Ok(None);
+    }
+    let mut statement = legacy
+        .prepare("SELECT alias, master_ecdsa_bip44_account_0_epk FROM wallet")
+        .map_err(read_error)?;
+    let wallets = statement
+        .query_map([], |row| {
+            Ok((row.get::<_, Option>(0)?, row.get::<_, Vec>(1)?))
+        })
+        .and_then(|rows| rows.collect::, _>>())
+        .map_err(read_error)?;
+
+    let store = open_copy(network_db, scratch, label)?;
+    let mut registered = BTreeMap::new();
+    for (alias, account_xpub) in wallets {
+        let alias = alias.ok_or_else(|| {
+            "a captured wallet has no alias to match against contents.wallets".to_owned()
+        })?;
+        if registered.contains_key(&alias) {
+            return Err(format!("duplicate captured wallet alias: {alias:?}"));
+        }
+        let found = match &store {
+            None => false,
+            Some(conn) => conn
+                .query_row(
+                    "SELECT EXISTS (SELECT 1 FROM account_registrations \
+                     WHERE account_type = 'standard_bip44' AND account_index = 0 \
+                     AND instr(account_xpub_bytes, CAST(?1 AS BLOB)) > 0)",
+                    [base58::encode_check(&account_xpub)],
+                    |row| row.get::<_, bool>(0),
+                )
+                .map_err(|e| {
+                    format!(
+                        "could not read wallet registrations from {}: {e}",
+                        network_db.display()
+                    )
+                })?,
+        };
+        registered.insert(alias, found);
+    }
+    Ok(Some(registered))
+}
+
+/// Every captured wallet must have an explicit outcome and match it.
+pub fn check_wallet_outcomes(
+    expected: &[ExpectedWallet],
+    registered: &BTreeMap,
+) -> Result<(), String> {
+    let undeclared: Vec<_> = registered
+        .keys()
+        .filter(|alias| !expected.iter().any(|wallet| &wallet.alias == *alias))
+        .collect();
+    if !undeclared.is_empty() {
+        return Err(format!(
+            "captured wallets missing from contents.wallets: {undeclared:?}"
+        ));
+    }
+    let problems: Vec = expected
+        .iter()
+        .filter_map(|wallet| {
+            let alias = &wallet.alias;
+            match (wallet.outcome, registered.get(alias)) {
+                (_, None) => Some(format!("`{alias}` is not a wallet in {DATA_DB}")),
+                (WalletOutcome::Migrated, Some(false)) => Some(format!(
+                    "`{alias}` was not registered in the per-network store"
+                )),
+                (WalletOutcome::NeedsDesktop, Some(true)) => Some(format!(
+                    "`{alias}` is password-protected, yet was registered without its password"
+                )),
+                _ => None,
+            }
+        })
+        .collect();
+    match problems.is_empty() {
+        true => Ok(()),
+        false => Err(format!(
+            "wallet outcomes differ from the manifest: {}",
+            problems.join("; ")
+        )),
+    }
+}
+
+/// A supplied password must never be printed — not in a tool result, not in an
+/// error, not in any log line at any level. The failure names the command and
+/// the stream only, never the password.
+pub fn check_password_not_echoed(run: &CliRun, password: &str) -> Result<(), String> {
+    let streams: Vec<&str> = [("stdout", &run.stdout), ("stderr", &run.stderr)]
+        .into_iter()
+        .filter(|(_, text)| text.contains(password))
+        .map(|(stream, _)| stream)
+        .collect();
+    match streams.is_empty() {
+        true => Ok(()),
+        false => Err(format!(
+            "`{}` printed the supplied wallet password on {}",
+            run.command,
+            streams.join(" and ")
+        )),
+    }
+}
+
+/// Backup files a boot created, by path relative to the data dir. Covers the
+/// `platform_compatibility` bridge's `*-backup-*.sqlite` copies and the
+/// generic `.bak` convention.
+pub fn backup_files(data_dir: &Path) -> Result, String> {
+    let mut found = BTreeMap::new();
+    collect_backups(data_dir, data_dir, &mut found)?;
+    Ok(found)
+}
+
+fn collect_backups(
+    root: &Path,
+    dir: &Path,
+    found: &mut BTreeMap,
+) -> Result<(), String> {
+    let entries =
+        fs::read_dir(dir).map_err(|e| format!("could not read {}: {e}", dir.display()))?;
+    for entry in entries {
+        let entry = entry.map_err(|e| format!("could not walk {}: {e}", dir.display()))?;
+        let path = entry.path();
+        let meta = entry
+            .metadata()
+            .map_err(|e| format!("could not stat {}: {e}", path.display()))?;
+        if meta.is_dir() {
+            collect_backups(root, &path, found)?;
+            continue;
+        }
+        let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
+        if name.contains("backup") || name.ends_with(".bak") {
+            let relative = path
+                .strip_prefix(root)
+                .unwrap_or(&path)
+                .to_string_lossy()
+                .into_owned();
+            found.insert(relative, meta.len());
+        }
+    }
+    Ok(())
+}
+
+/// A second boot must be a no-op: no fresh backup copies, and the sentinels
+/// still carrying the marker the first boot wrote.
+pub fn check_idempotent(
+    first: (&BTreeMap, &BTreeMap>),
+    second: (&BTreeMap, &BTreeMap>),
+) -> Result<(), String> {
+    let (first_backups, first_sentinels) = first;
+    let (second_backups, second_sentinels) = second;
+
+    let new_backups: Vec<&String> = second_backups
+        .keys()
+        .filter(|name| !first_backups.contains_key(*name))
+        .collect();
+    if !new_backups.is_empty() {
+        return Err(format!(
+            "the second boot created new backup files: {new_backups:?}"
+        ));
+    }
+
+    if first_sentinels != second_sentinels {
+        let changed: Vec<&String> = second_sentinels
+            .keys()
+            .chain(first_sentinels.keys())
+            .filter(|key| first_sentinels.get(*key) != second_sentinels.get(*key))
+            .collect();
+        return Err(format!(
+            "the second boot rewrote migration sentinels: {changed:?} — a completed migration must \
+             short-circuit on its sentinel"
+        ));
+    }
+    Ok(())
+}
+
+/// Identity ids stored in the per-network database, lowercase hex.
+///
+// TODO: switch to identity_list/app_storage_status MCP tool once merged —
+// reading the store directly couples this harness to the upstream kv table
+// layout (`meta_identity`), which a read-only tool would hide.
+pub fn identity_ids(
+    network_db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result, String> {
+    let Some(conn) = open_copy(network_db, scratch, label)? else {
+        return Ok(BTreeSet::new());
+    };
+    let mut statement = conn
+        .prepare("SELECT lower(hex(identity_id)) FROM meta_identity WHERE key = ?1")
+        .map_err(|e| {
+            format!(
+                "could not read identities from {}: {e}",
+                network_db.display()
+            )
+        })?;
+    let ids = statement
+        .query_map([IDENTITY_KEY], |row| row.get::<_, String>(0))
+        .and_then(|rows| rows.collect::, _>>())
+        .map_err(|e| {
+            format!(
+                "could not read identities from {}: {e}",
+                network_db.display()
+            )
+        })?;
+    Ok(ids)
+}
+
+/// Every identity the fixture recorded must still be there afterwards.
+pub fn check_identities(expected: &[String], found: &BTreeSet) -> Result<(), String> {
+    let missing: Vec = expected
+        .iter()
+        .map(|id| id.to_ascii_lowercase())
+        .filter(|id| !found.contains(id))
+        .collect();
+    if !missing.is_empty() {
+        return Err(format!(
+            "identities missing after the migration: {missing:?} — the store holds {found:?}"
+        ));
+    }
+    Ok(())
+}
+
+/// Opens a copy of a SQLite database, carrying its `-wal` / `-shm` siblings so
+/// uncheckpointed commits are visible. Returns `None` when the database does
+/// not exist.
+pub(crate) fn open_copy(
+    db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result, String> {
+    if !db.exists() {
+        return Ok(None);
+    }
+    let file_name = db
+        .file_name()
+        .ok_or_else(|| format!("{} has no file name", db.display()))?;
+    fs::create_dir_all(scratch)
+        .map_err(|e| format!("could not create {}: {e}", scratch.display()))?;
+    let dir = tempfile::Builder::new()
+        .prefix(label)
+        .tempdir_in(scratch)
+        .map_err(|e| format!("could not create snapshot directory: {e}"))?;
+
+    let copy: PathBuf = dir.keep().join(file_name);
+    fs::copy(db, ©).map_err(|e| format!("could not copy {}: {e}", db.display()))?;
+    for suffix in ["-wal", "-shm"] {
+        let sibling = PathBuf::from(format!("{}{suffix}", db.display()));
+        if sibling.exists() {
+            let target = PathBuf::from(format!("{}{suffix}", copy.display()));
+            fs::copy(&sibling, &target)
+                .map_err(|e| format!("could not copy {}: {e}", sibling.display()))?;
+        }
+    }
+
+    Connection::open(©)
+        .map(Some)
+        .map_err(|e| format!("could not open {}: {e}", copy.display()))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn snapshot(version: Option, extra_table: bool) -> SchemaSnapshot {
+        let mut objects = vec![(
+            "table".to_string(),
+            "settings".to_string(),
+            "CREATE TABLE settings(id INTEGER, database_version INTEGER)".to_string(),
+        )];
+        if extra_table {
+            objects.push((
+                "table".to_string(),
+                "tokens".to_string(),
+                "CREATE TABLE tokens(id INTEGER)".to_string(),
+            ));
+        }
+        SchemaSnapshot {
+            version,
+            objects,
+            rows: BTreeMap::new(),
+        }
+    }
+
+    /// Every boot path opens an existing `data.db` read-only, so the legacy
+    /// ladder never runs on it — whatever version it was left at.
+    #[test]
+    fn a_pre_update_data_db_must_be_left_untouched() {
+        for version in [11, DEFAULT_DB_VERSION] {
+            let before = snapshot(Some(version), false);
+            check_schema_outcome(Some(&before), Some(&snapshot(Some(version), false)))
+                .unwrap_or_else(|e| panic!("an untouched v{version} file must pass: {e}"));
+
+            let migrated = snapshot(Some(DEFAULT_DB_VERSION), true);
+            let error = check_schema_outcome(Some(&before), Some(&migrated))
+                .expect_err("any schema change to a pre-update data.db must fail");
+            assert!(error.contains("read-only"), "{error}");
+        }
+    }
+
+    #[test]
+    fn a_fixture_from_a_newer_build_is_named_as_such() {
+        let before = snapshot(Some(DEFAULT_DB_VERSION + 1), false);
+        let error = check_schema_outcome(
+            Some(&before),
+            Some(&snapshot(Some(DEFAULT_DB_VERSION + 1), false)),
+        )
+        .expect_err("a newer fixture must be rejected");
+        assert!(error.contains("newer than this build"), "{error}");
+    }
+
+    #[test]
+    fn a_missing_data_db_is_created_at_the_current_version() {
+        check_schema_outcome(None, Some(&snapshot(Some(DEFAULT_DB_VERSION), false)))
+            .expect("a fresh file at the current version passes");
+        let error = check_schema_outcome(None, Some(&snapshot(Some(11), false)))
+            .expect_err("a fresh file below the current version must fail");
+        assert!(error.contains("fresh one at version"), "{error}");
+    }
+
+    #[test]
+    fn a_second_boot_may_not_add_backups_or_rewrite_sentinels() {
+        let key = sentinel_key_for(Network::Testnet);
+        let backups =
+            BTreeMap::from([("det-app.platform-67d4ef3-backup-1.sqlite".to_string(), 10)]);
+        let sentinels = BTreeMap::from([(key.clone(), vec![1, 2, 3])]);
+
+        check_idempotent((&backups, &sentinels), (&backups, &sentinels))
+            .expect("an unchanged footprint is idempotent");
+
+        let mut more_backups = backups.clone();
+        more_backups.insert("det-app.platform-67d4ef3-backup-2.sqlite".to_string(), 10);
+        let error = check_idempotent((&backups, &sentinels), (&more_backups, &sentinels))
+            .expect_err("a new backup file must fail");
+        assert!(error.contains("backup-2"), "{error}");
+
+        let rewritten = BTreeMap::from([(key.clone(), vec![9])]);
+        let error = check_idempotent((&backups, &sentinels), (&backups, &rewritten))
+            .expect_err("a rewritten sentinel must fail");
+        assert!(error.contains(&key), "{error}");
+    }
+
+    #[test]
+    fn a_missing_completion_sentinel_names_the_key_it_wanted() {
+        let error = check_sentinel_recorded(&BTreeMap::new(), Network::Testnet)
+            .expect_err("an unrecorded migration must fail");
+        assert!(
+            error.contains(&sentinel_key_for(Network::Testnet)),
+            "{error}"
+        );
+        assert_ne!(
+            sentinel_key_for(Network::Testnet),
+            dapi_refresh_sentinel_key_for(Network::Testnet),
+            "the drain and the DAPI refresh must not share a sentinel"
+        );
+    }
+
+    #[test]
+    fn regtest_is_reported_as_local() {
+        assert_eq!(display_name(Network::Regtest), "local");
+        assert_eq!(network_db_name(Network::Regtest), "det-regtest.sqlite");
+        assert_eq!(network_db_name(Network::Testnet), "det-testnet.sqlite");
+    }
+
+    #[test]
+    fn a_panicking_boot_is_a_failure_even_on_exit_zero() {
+        let run = CliRun {
+            command: "det-cli --standalone core-wallets-list".to_string(),
+            exit_code: Some(0),
+            stdout: "{\"wallets\":[]}".to_string(),
+            stderr: "thread 'main' panicked at src/lib.rs:1:1".to_string(),
+            timed_out: false,
+        };
+        let error = check_boot(&run, "first boot").expect_err("a panic must fail the boot");
+        assert!(error.contains("panicked at"), "{error}");
+    }
+
+    #[test]
+    fn incompatible_wallet_data_fails_rather_than_falling_back() {
+        let run = CliRun {
+            command: "det-cli --standalone core-wallets-list".to_string(),
+            exit_code: Some(1),
+            stdout: String::new(),
+            stderr: "Error: Your wallet data is not compatible with this version of the app"
+                .to_string(),
+            timed_out: false,
+        };
+        let error = check_boot(&run, "first boot").expect_err("an incompatibility must fail");
+        assert!(error.contains("did not complete"), "{error}");
+    }
+
+    #[test]
+    fn wallet_list_rejects_unexpected_and_duplicate_wallets() {
+        for wallets in [
+            r#"[{"alias":"extra"}]"#,
+            r#"[{"alias":null,"seed_hash":"ab01"}]"#,
+            r#"[{"alias":"savings"},{"alias":"savings"}]"#,
+        ] {
+            let run = CliRun {
+                command: "core-wallets-list".to_string(),
+                exit_code: Some(0),
+                stdout: format!(r#"{{"wallets":{wallets}}}"#),
+                stderr: String::new(),
+                timed_out: false,
+            };
+            let expected = if wallets.contains("savings") {
+                vec!["savings".to_string()]
+            } else {
+                vec![]
+            };
+            assert!(check_wallets(&expected, &run).is_err(), "{wallets}");
+        }
+    }
+
+    #[test]
+    fn wallet_identifiers_match_the_expected_aliases() {
+        let run = CliRun {
+            command: "det-cli --standalone core-wallets-list".to_string(),
+            exit_code: Some(0),
+            stdout: r#"{"wallets":[{"seed_hash":"ab01","alias":"savings"}]}"#.to_string(),
+            stderr: String::new(),
+            timed_out: false,
+        };
+
+        let ids = check_wallets(&["savings".to_string()], &run).expect("expected alias present");
+        assert_eq!(ids, ["savings"]);
+
+        let error =
+            check_wallets(&["pension".to_string()], &run).expect_err("a missing wallet must fail");
+        assert!(error.contains("pension"), "{error}");
+    }
+
+    #[test]
+    fn the_reported_network_must_match_the_fixture() {
+        let run = CliRun {
+            command: "det-cli --standalone network-info".to_string(),
+            exit_code: Some(0),
+            stdout: r#"{"active":"testnet","available":["testnet"]}"#.to_string(),
+            stderr: String::new(),
+            timed_out: false,
+        };
+
+        check_network(Network::Testnet, &run).expect("matching network passes");
+        let error = check_network(Network::Mainnet, &run).expect_err("a drifted network must fail");
+        assert!(
+            error.contains("mainnet") && error.contains("testnet"),
+            "{error}"
+        );
+    }
+
+    fn run(exit_code: Option, stderr: &str) -> CliRun {
+        CliRun {
+            command: "det-cli --standalone core-wallets-list".to_string(),
+            exit_code,
+            stdout: String::new(),
+            stderr: stderr.to_string(),
+            timed_out: false,
+        }
+    }
+
+    #[test]
+    fn a_needs_desktop_boot_must_stop_at_exactly_that_error() {
+        let expected = format!("WARN rmcp::service: response error data: {NEEDS_DESKTOP_MARKER}");
+        check_needs_desktop(&run(Some(1), &expected), "boot").expect("the documented outcome");
+        check_needs_desktop(&run(None, &expected), "boot")
+            .expect_err("a signal after the expected diagnostic must fail");
+
+        let completed = check_needs_desktop(&run(Some(0), ""), "boot")
+            .expect_err("completing must fail: the protected wallet cannot migrate headless");
+        assert!(completed.contains("completed"), "{completed}");
+
+        let other = check_needs_desktop(&run(Some(1), "StorageUpdateNeedsDesktop"), "boot")
+            .expect_err("a different failure must not pass for the documented one");
+        assert!(other.contains("not with"), "{other}");
+
+        let panicked = check_needs_desktop(
+            &run(Some(101), &format!("panicked at x\n{NEEDS_DESKTOP_MARKER}")),
+            "boot",
+        )
+        .expect_err("a panic is never the expected outcome");
+        assert!(panicked.contains("panicked at"), "{panicked}");
+    }
+
+    fn fixture_wallet(alias: &str, outcome: WalletOutcome) -> ExpectedWallet {
+        ExpectedWallet {
+            alias: alias.to_string(),
+            outcome,
+        }
+    }
+
+    #[test]
+    fn a_printed_password_fails_without_being_quoted() {
+        let password = "fixture-password-canary";
+        let clean = CliRun {
+            command: "det-cli --standalone app-storage-update --password-file /x".to_string(),
+            exit_code: Some(0),
+            stdout: "{\"migration\":{\"state\":\"success\"}}".to_string(),
+            stderr: "INFO rmcp: serving".to_string(),
+            timed_out: false,
+        };
+        check_password_not_echoed(&clean, password).expect("nothing printed");
+
+        let leaked = CliRun {
+            stderr: format!("DEBUG received request arguments={password}"),
+            ..clean
+        };
+        let error = check_password_not_echoed(&leaked, password).expect_err("printed");
+        assert!(error.contains("on stderr"), "{error}");
+        assert!(
+            !error.contains(password),
+            "the failure must not quote it: {error}"
+        );
+    }
+
+    #[test]
+    fn wallet_outcomes_are_checked_per_wallet() {
+        let expected = [
+            fixture_wallet("plain", WalletOutcome::Migrated),
+            fixture_wallet("locked", WalletOutcome::NeedsDesktop),
+        ];
+        let as_expected =
+            BTreeMap::from([("plain".to_string(), true), ("locked".to_string(), false)]);
+        check_wallet_outcomes(&expected, &as_expected).expect("both as the manifest says");
+        check_wallet_outcomes(&expected[..1], &as_expected)
+            .expect_err("every captured wallet needs an explicit outcome");
+        check_wallet_outcomes(&[], &as_expected)
+            .expect_err("an empty manifest must not hide captured wallets");
+
+        let both = BTreeMap::from([("plain".to_string(), true), ("locked".to_string(), true)]);
+        let error =
+            check_wallet_outcomes(&expected, &both).expect_err("a protected wallet registered");
+        assert!(error.contains("`locked` is password-protected"), "{error}");
+
+        let neither = BTreeMap::from([("plain".to_string(), false), ("locked".to_string(), false)]);
+        let error =
+            check_wallet_outcomes(&expected, &neither).expect_err("the plain wallet missing");
+        assert!(error.contains("`plain` was not registered"), "{error}");
+
+        let error =
+            check_wallet_outcomes(&expected, &BTreeMap::new()).expect_err("unknown aliases");
+        assert!(error.contains("is not a wallet in"), "{error}");
+    }
+
+    #[test]
+    fn an_unfinished_update_must_not_record_the_completion_sentinel() {
+        check_sentinel_absent(&BTreeMap::new(), Network::Testnet).expect("absent is correct");
+        let recorded = BTreeMap::from([(sentinel_key_for(Network::Testnet), vec![1])]);
+        check_sentinel_absent(&recorded, Network::Testnet).expect_err("recorded is a regression");
+    }
+
+    /// BIP32 test vector 1, master key: the 78-byte serialization `data.db`
+    /// stores must encode to the exact text the upstream store keeps.
+    #[test]
+    fn a_legacy_account_xpub_encodes_to_its_base58check_text() {
+        let serialized = hex::decode(
+            "0488b21e000000000000000000873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508\
+             0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2",
+        )
+        .expect("test vector hex");
+        assert_eq!(
+            base58::encode_check(&serialized),
+            "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"
+        );
+    }
+
+    /// The wallet the upstream store registered is found by its account xpub,
+    /// under the length-prefixed text encoding the store actually uses.
+    #[test]
+    fn legacy_wallets_are_matched_to_registrations_by_account_xpub() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let scratch = dir.path().join("scratch");
+        let data_db = dir.path().join(DATA_DB);
+        let network_db = dir.path().join(network_db_name(Network::Testnet));
+        let plain_xpub = vec![0x04, 0x35, 0x87, 0xcf, 1, 2, 3];
+        let locked_xpub = vec![0x04, 0x35, 0x87, 0xcf, 9, 9, 9];
+
+        let legacy = Connection::open(&data_db).expect("create data.db");
+        legacy
+            .execute_batch(
+                "CREATE TABLE wallet (alias TEXT, master_ecdsa_bip44_account_0_epk BLOB NOT NULL);",
+            )
+            .expect("create wallet table");
+        for (alias, xpub) in [("plain", &plain_xpub), ("locked", &locked_xpub)] {
+            legacy
+                .execute(
+                    "INSERT INTO wallet (alias, master_ecdsa_bip44_account_0_epk) VALUES (?1, ?2)",
+                    rusqlite::params![alias, xpub],
+                )
+                .expect("insert legacy wallet");
+        }
+
+        let store = Connection::open(&network_db).expect("create network db");
+        store
+            .execute_batch(
+                "CREATE TABLE account_registrations (account_type TEXT, account_index INTEGER, \
+                 account_xpub_bytes BLOB NOT NULL);",
+            )
+            .expect("create registrations");
+        let text = base58::encode_check(&plain_xpub);
+        let mut stored = (text.len() as u32).to_be_bytes().to_vec();
+        stored.extend_from_slice(text.as_bytes());
+        store
+            .execute(
+                "INSERT INTO account_registrations VALUES ('standard_bip44', 0, ?1)",
+                [stored],
+            )
+            .expect("register the plain wallet");
+        drop((legacy, store));
+
+        let registered = legacy_wallet_registrations(&data_db, &network_db, &scratch, "t")
+            .expect("read registrations")
+            .expect("data.db exists");
+        assert_eq!(
+            registered,
+            BTreeMap::from([("locked".to_string(), false), ("plain".to_string(), true)])
+        );
+
+        let absent =
+            legacy_wallet_registrations(&dir.path().join("missing.db"), &network_db, &scratch, "t")
+                .expect("no data.db is not an error");
+        assert!(absent.is_none());
+    }
+
+    #[test]
+    fn legacy_wallet_aliases_must_be_unique_and_declared() {
+        let dir = tempfile::tempdir().unwrap();
+        let db = dir.path().join(DATA_DB);
+        let conn = Connection::open(&db).unwrap();
+        conn.execute_batch("CREATE TABLE wallet(alias TEXT, master_ecdsa_bip44_account_0_epk BLOB); INSERT INTO wallet VALUES(NULL, x'01');").unwrap();
+        let read = || {
+            legacy_wallet_registrations(
+                &db,
+                &dir.path().join("absent.sqlite"),
+                &dir.path().join("scratch"),
+                "inspect",
+            )
+        };
+        assert!(read().is_err());
+        conn.execute_batch(
+            "UPDATE wallet SET alias='duplicate'; INSERT INTO wallet SELECT * FROM wallet;",
+        )
+        .unwrap();
+        assert!(read().is_err());
+    }
+
+    #[test]
+    fn review_regression_committed_wal_row_changes_fail_preservation() {
+        let dir = tempfile::tempdir().unwrap();
+        let db = dir.path().join(DATA_DB);
+        let scratch = dir.path().join("scratch");
+        let conn = Connection::open(&db).unwrap();
+        conn.execute_batch("PRAGMA journal_mode=WAL; PRAGMA wal_autocheckpoint=0; CREATE TABLE settings(id INTEGER, database_version INTEGER); INSERT INTO settings VALUES(1, 11); CREATE TABLE records(value BLOB); INSERT INTO records VALUES(x'01'); PRAGMA wal_checkpoint(TRUNCATE);").unwrap();
+        let before_bytes = file_bytes(&db).unwrap();
+        let before = schema_snapshot(&db, &scratch, "before").unwrap();
+        conn.execute_batch("UPDATE records SET value=x'02';")
+            .unwrap();
+        assert_eq!(
+            before_bytes,
+            file_bytes(&db).unwrap(),
+            "update stays in WAL"
+        );
+        let after = schema_snapshot(&db, &scratch, "after").unwrap();
+        assert!(check_schema_outcome(before.as_ref(), after.as_ref()).is_err());
+    }
+
+    #[test]
+    fn unchanged_wal_and_checkpointed_rows_have_the_same_snapshot() {
+        let dir = tempfile::tempdir().unwrap();
+        let db = dir.path().join(DATA_DB);
+        let scratch = dir.path().join("scratch");
+        let conn = Connection::open(&db).unwrap();
+        conn.execute_batch("PRAGMA journal_mode=WAL; CREATE TABLE settings(id INTEGER, database_version INTEGER); INSERT INTO settings VALUES(1, 11); CREATE TABLE records(t TEXT, b BLOB, i INTEGER, r REAL); INSERT INTO records VALUES('value', x'01', 3, 0.5);").unwrap();
+        let before = schema_snapshot(&db, &scratch, "same-label").unwrap();
+        let repeated = schema_snapshot(&db, &scratch, "same-label").unwrap();
+        check_schema_outcome(before.as_ref(), repeated.as_ref()).unwrap();
+        conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
+            .unwrap();
+        let checkpointed = schema_snapshot(&db, &scratch, "same-label").unwrap();
+        check_schema_outcome(before.as_ref(), checkpointed.as_ref()).unwrap();
+        conn.execute_batch("INSERT INTO records SELECT * FROM records;")
+            .unwrap();
+        let duplicate = schema_snapshot(&db, &scratch, "same-label").unwrap();
+        assert!(check_schema_outcome(before.as_ref(), duplicate.as_ref()).is_err());
+    }
+
+    #[test]
+    fn review_regression_captured_sentinels_must_survive_the_first_boot() {
+        let before = BTreeMap::from([("det:migration:existing".to_owned(), vec![1])]);
+        let mut after = before.clone();
+        after.insert("det:migration:new".to_owned(), vec![2]);
+        check_existing_sentinels(&before, &after).unwrap();
+        after.insert("det:migration:existing".to_owned(), vec![3]);
+        assert!(check_existing_sentinels(&before, &after).is_err());
+        assert!(check_existing_sentinels(&before, &BTreeMap::new()).is_err());
+    }
+
+    #[test]
+    fn byte_identity_reports_the_size_change() {
+        check_bytes_unchanged(Some(&vec![1, 2]), Some(&vec![1, 2]), DATA_DB).expect("identical");
+        let error = check_bytes_unchanged(Some(&vec![1, 2]), Some(&vec![1, 2, 3]), DATA_DB)
+            .expect_err("changed bytes must fail");
+        assert!(error.contains("2 to 3 bytes"), "{error}");
+        let error = check_bytes_unchanged(Some(&vec![1, 2]), Some(&vec![1, 3]), DATA_DB)
+            .expect_err("a same-size rewrite must fail too");
+        assert!(error.contains("content changed"), "{error}");
+    }
+
+    #[test]
+    fn a_real_sqlite_file_round_trips_through_a_scratch_copy() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let db = dir.path().join(DATA_DB);
+        let conn = Connection::open(&db).expect("create db");
+        conn.execute_batch(
+            "CREATE TABLE settings (id INTEGER PRIMARY KEY, database_version INTEGER);
+             INSERT INTO settings (id, database_version) VALUES (1, 11);",
+        )
+        .expect("seed schema");
+        drop(conn);
+
+        let scratch = dir.path().join("scratch");
+        let snapshot = schema_snapshot(&db, &scratch, "before")
+            .expect("snapshot")
+            .expect("the file exists");
+        assert_eq!(snapshot.version, Some(11));
+        assert!(
+            snapshot
+                .objects
+                .iter()
+                .any(|(_, name, _)| name == "settings")
+        );
+
+        assert!(
+            schema_snapshot(&dir.path().join("absent.db"), &scratch, "missing")
+                .expect("a missing file is not an error")
+                .is_none()
+        );
+    }
+
+    #[test]
+    fn schema_snapshot_rejects_malformed_settings() {
+        for sql in [
+            "CREATE TABLE other (id INTEGER);",
+            "CREATE TABLE settings (id INTEGER); INSERT INTO settings VALUES (1);",
+            "CREATE TABLE settings (id INTEGER, database_version); INSERT INTO settings VALUES (1, 'bad');",
+            "CREATE TABLE settings (id INTEGER, database_version); INSERT INTO settings VALUES (1, NULL);",
+            "CREATE TABLE settings (id INTEGER, database_version); INSERT INTO settings VALUES (1, -1);",
+        ] {
+            let dir = tempfile::tempdir().expect("tempdir");
+            let db = dir.path().join(DATA_DB);
+            Connection::open(&db).unwrap().execute_batch(sql).unwrap();
+            assert!(
+                schema_snapshot(&db, &dir.path().join("scratch"), "before").is_err(),
+                "{sql}"
+            );
+        }
+    }
+
+    #[test]
+    fn schema_snapshot_allows_an_absent_settings_row() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let db = dir.path().join(DATA_DB);
+        Connection::open(&db)
+            .unwrap()
+            .execute_batch("CREATE TABLE settings (id INTEGER, database_version INTEGER);")
+            .unwrap();
+        assert_eq!(
+            schema_snapshot(&db, &dir.path().join("scratch"), "before")
+                .unwrap()
+                .unwrap()
+                .version,
+            None
+        );
+    }
+
+    #[test]
+    fn sentinels_and_identities_are_read_from_the_upstream_kv_tables() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        let app_db = dir.path().join(APP_DB);
+        let conn = Connection::open(&app_db).expect("create app db");
+        conn.execute_batch("CREATE TABLE meta_global (key TEXT PRIMARY KEY, value BLOB);")
+            .expect("create meta_global");
+        let key = sentinel_key_for(Network::Testnet);
+        conn.execute(
+            "INSERT INTO meta_global (key, value) VALUES (?1, X'0102')",
+            [&key],
+        )
+        .expect("write sentinel");
+        conn.execute(
+            "INSERT INTO meta_global (key, value) VALUES ('det:settings:v1', X'03')",
+            [],
+        )
+        .expect("write unrelated key");
+        drop(conn);
+
+        let scratch = dir.path().join("scratch");
+        let sentinels = migration_sentinels(&app_db, &scratch, "after").expect("read sentinels");
+        assert_eq!(sentinels.get(&key), Some(&vec![1u8, 2]));
+        assert_eq!(sentinels.len(), 1, "only migration keys are collected");
+        check_sentinel_recorded(&sentinels, Network::Testnet).expect("the sentinel is recorded");
+
+        let network_db = dir.path().join(network_db_name(Network::Testnet));
+        let conn = Connection::open(&network_db).expect("create network db");
+        conn.execute_batch(
+            "CREATE TABLE meta_identity (identity_id BLOB, key TEXT, value BLOB);
+             INSERT INTO meta_identity (identity_id, key, value) VALUES (X'AABB', 'det:identity:v1', X'00');",
+        )
+        .expect("seed identity");
+        drop(conn);
+
+        let ids = identity_ids(&network_db, &scratch, "after").expect("read identities");
+        check_identities(&["AABB".to_string()], &ids).expect("case-insensitive match");
+        let error = check_identities(&["ccdd".to_string()], &ids)
+            .expect_err("a dropped identity must fail");
+        assert!(error.contains("ccdd"), "{error}");
+    }
+
+    #[test]
+    fn backup_files_are_found_below_the_data_dir() {
+        let dir = tempfile::tempdir().expect("tempdir");
+        fs::create_dir_all(dir.path().join("spv/testnet")).expect("create nested dir");
+        fs::write(
+            dir.path().join("det-app.platform-67d4ef3-backup-1.sqlite"),
+            b"x",
+        )
+        .expect("write backup");
+        fs::write(dir.path().join("spv/testnet/notes.bak"), b"yy").expect("write nested backup");
+        fs::write(dir.path().join(DATA_DB), b"zzz").expect("write live db");
+
+        let found = backup_files(dir.path()).expect("scan");
+        assert_eq!(found.len(), 2, "found {found:?}");
+        assert_eq!(found.get("spv/testnet/notes.bak"), Some(&2));
+    }
+}
diff --git a/tests/migration-matrix/cli.rs b/tests/migration-matrix/cli.rs
new file mode 100644
index 000000000..e17fcd4dd
--- /dev/null
+++ b/tests/migration-matrix/cli.rs
@@ -0,0 +1,323 @@
+//! Drives a staged fixture through the real `det-cli` binary.
+//!
+//! The whole point of the matrix is that migration is exercised by a genuine
+//! production boot: an in-process `AppState` under the `testing` feature
+//! substitutes an in-memory database, which would make every assertion below
+//! vacuous. So the harness spawns the compiled binary as a subprocess with
+//! `DASH_EVO_DATA_DIR` pointed at the staged directory and reads its stdout.
+//!
+//! `core-wallets-list` is the boot of record: it runs
+//! `resolve::ensure_wallets_hydrated`, which prepares this network's storage,
+//! runs the legacy drain, and waits for a terminal migration state — the same
+//! path the GUI takes on cold start, minus the display.
+
+use std::io::Read;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Stdio};
+use std::time::{Duration, Instant};
+
+use serde_json::Value;
+
+use crate::stage::StagedFixture;
+
+/// Overrides the binary under test (a release build, a downloaded artifact).
+pub const BINARY_ENV: &str = "DET_CLI_BIN";
+
+/// Log filter of the password-supplied boot: everything DET, det-cli and rmcp
+/// can emit, the rest at `info` to keep the capture readable.
+const STORAGE_UPDATE_LOG_FILTER: &str = "info,dash_evo_tool=trace,det_cli=trace,rmcp=trace";
+
+/// Path Cargo hands us when `det-cli` is built alongside this test — i.e.
+/// whenever the `cli` feature is on, as it is under `--all-features`.
+const CARGO_BIN: Option<&str> = option_env!("CARGO_BIN_EXE_det-cli");
+
+/// One subprocess invocation, captured whole. Both streams are kept: the tool
+/// result lands on stdout, panics and migration diagnostics on stderr.
+pub struct CliRun {
+    pub command: String,
+    pub exit_code: Option,
+    pub stdout: String,
+    pub stderr: String,
+    pub timed_out: bool,
+}
+
+impl CliRun {
+    pub fn succeeded(&self) -> bool {
+        !self.timed_out && self.exit_code == Some(0)
+    }
+
+    /// The tool's JSON output. `det-cli` prints the MCP text content verbatim,
+    /// so the whole of stdout is the document.
+    pub fn json(&self) -> Result {
+        serde_json::from_str(self.stdout.trim()).map_err(|e| {
+            format!(
+                "`{}` did not print JSON: {e}\n{}",
+                self.command,
+                self.report()
+            )
+        })
+    }
+
+    /// Multi-line dump for assertion failures — the command, how it ended, and
+    /// both streams.
+    pub fn report(&self) -> String {
+        let outcome = if self.timed_out {
+            "timed out".to_string()
+        } else {
+            match self.exit_code {
+                Some(code) => format!("exit code {code}"),
+                None => "killed by a signal".to_string(),
+            }
+        };
+        format!(
+            "command: {}\noutcome: {outcome}\n--- stdout ---\n{}\n--- stderr ---\n{}",
+            self.command,
+            self.stdout.trim_end(),
+            self.stderr.trim_end()
+        )
+    }
+}
+
+/// A `det-cli` bound to one staged data directory.
+pub struct DetCli {
+    binary: PathBuf,
+    data_dir: PathBuf,
+    home: PathBuf,
+    xdg: PathBuf,
+}
+
+impl DetCli {
+    pub fn new(staged: &StagedFixture) -> Result {
+        let binary = locate_binary()?;
+        let home = staged.sandbox().join("home");
+        let xdg = staged.sandbox().join("xdg");
+        for dir in [&home, &xdg] {
+            std::fs::create_dir_all(dir)
+                .map_err(|e| format!("could not create {}: {e}", dir.display()))?;
+        }
+        Ok(Self {
+            binary,
+            data_dir: staged.data_dir().to_path_buf(),
+            home,
+            xdg,
+        })
+    }
+
+    /// Runs one subcommand, killing the child if it outlives `timeout`.
+    pub fn run(&self, args: &[&str], timeout: Duration) -> Result {
+        self.run_with_log(args, timeout, &log_filter())
+    }
+
+    /// [`Self::run`] under an explicit `RUST_LOG` filter.
+    pub fn run_with_log(
+        &self,
+        args: &[&str],
+        timeout: Duration,
+        log_filter: &str,
+    ) -> Result {
+        let command = format!("det-cli --standalone {}", args.join(" "));
+        let mut child = Command::new(&self.binary)
+            .arg("--standalone")
+            .args(args)
+            .env("DASH_EVO_DATA_DIR", &self.data_dir)
+            // Keep every incidental write inside the sandbox: `det-cli` caches
+            // the tool list under the user's cache dir and installs a bash
+            // completion script under the user's data dir.
+            .env("HOME", &self.home)
+            .env("XDG_CACHE_HOME", self.xdg.join("cache"))
+            .env("XDG_DATA_HOME", self.xdg.join("data"))
+            .env("XDG_CONFIG_HOME", self.xdg.join("config"))
+            .env("XDG_STATE_HOME", self.xdg.join("state"))
+            // An inherited key would flip the binary into HTTP mode and talk to
+            // whatever DET instance happens to be running on this machine.
+            .env_remove("MCP_API_KEY")
+            .env_remove("MCP_LISTEN")
+            .env("RUST_LOG", log_filter)
+            .stdin(Stdio::null())
+            .stdout(Stdio::piped())
+            .stderr(Stdio::piped())
+            .spawn()
+            .map_err(|e| format!("could not spawn {}: {e}", self.binary.display()))?;
+
+        let mut stdout = child.stdout.take().expect("stdout is piped");
+        let mut stderr = child.stderr.take().expect("stderr is piped");
+        // Drained on threads: a child that fills a pipe buffer would deadlock
+        // against a parent that only polls for exit.
+        let stdout_reader = std::thread::spawn(move || read_stream(&mut stdout));
+        let stderr_reader = std::thread::spawn(move || read_stream(&mut stderr));
+
+        let deadline = Instant::now() + timeout;
+        let mut timed_out = false;
+        let status = loop {
+            match child.try_wait() {
+                Ok(Some(status)) => break Some(status),
+                Ok(None) => {}
+                Err(e) => return Err(format!("could not wait for `{command}`: {e}")),
+            }
+            if Instant::now() >= deadline {
+                timed_out = true;
+                let _ = child.kill();
+                break child.wait().ok();
+            }
+            std::thread::sleep(Duration::from_millis(50));
+        };
+
+        let stdout = stdout_reader.join().unwrap_or_else(|_| String::new());
+        let stderr = stderr_reader.join().unwrap_or_else(|_| String::new());
+
+        Ok(CliRun {
+            command,
+            exit_code: status.and_then(|s| s.code()),
+            stdout,
+            stderr,
+            timed_out,
+        })
+    }
+
+    /// Cold boot of record: hydrates storage, runs the legacy drain, waits for
+    /// the migration to reach a terminal state, then lists the wallets.
+    pub fn wallets_list(&self, timeout: Duration) -> Result {
+        self.run(&["core-wallets-list"], timeout)
+    }
+
+    /// Finishes the storage update with the wallet password read from an
+    /// owner-only file, as an operator automating an upgrade would.
+    ///
+    /// Logs at `trace` for DET and rmcp, so the harness's leak check covers
+    /// every line det-cli can print — rmcp's raw request logging included.
+    pub fn storage_update(
+        &self,
+        password_file: &Path,
+        timeout: Duration,
+    ) -> Result {
+        let path = password_file.to_str().ok_or_else(|| {
+            format!(
+                "password file path {} is not UTF-8",
+                password_file.display()
+            )
+        })?;
+        self.run_with_log(
+            &["app-storage-update", "--password-file", path],
+            timeout,
+            STORAGE_UPDATE_LOG_FILTER,
+        )
+    }
+
+    /// Active network and configured networks. Network-exempt — no SPV gate.
+    pub fn network_info(&self, timeout: Duration) -> Result {
+        self.run(&["network-info"], timeout)
+    }
+
+    /// Derives a fresh receive address. Waits on the SPV gate, so it needs a
+    /// reachable chain.
+    pub fn address_create(&self, wallet_id: &str, timeout: Duration) -> Result {
+        self.run(
+            &["core-address-create", &format!("wallet-id={wallet_id}")],
+            timeout,
+        )
+    }
+}
+
+fn read_stream(stream: &mut impl Read) -> String {
+    let mut buffer = Vec::new();
+    let _ = stream.read_to_end(&mut buffer);
+    String::from_utf8_lossy(&buffer).into_owned()
+}
+
+/// `info` keeps the migration's own progress logging in the captured stderr,
+/// which is where a failure report gets its evidence from.
+fn log_filter() -> String {
+    std::env::var("MIGRATION_MATRIX_RUST_LOG").unwrap_or_else(|_| "info".to_string())
+}
+
+/// Resolves the binary under test, preferring an explicit override.
+pub fn locate_binary() -> Result {
+    resolve_binary(std::env::var(BINARY_ENV).ok().as_deref(), CARGO_BIN)
+}
+
+fn resolve_binary(
+    override_path: Option<&str>,
+    cargo_path: Option<&str>,
+) -> Result {
+    if let Some(path) = override_path
+        && !path.trim().is_empty()
+    {
+        let path = PathBuf::from(path);
+        return match path.is_file() {
+            true => Ok(path),
+            false => Err(format!(
+                "{BINARY_ENV} points at {}, which is not a file",
+                path.display()
+            )),
+        };
+    }
+
+    let cargo_bin = cargo_path.map(Path::new).filter(|path| path.is_file());
+    match cargo_bin {
+        Some(path) => Ok(path.to_path_buf()),
+        None => Err(format!(
+            "det-cli was not built alongside this test. Build the matrix with the `cli` feature \
+             (`cargo test --test migration-matrix --features testing,cli,headless`) or point \
+             {BINARY_ENV} at a det-cli binary."
+        )),
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn a_bogus_binary_override_is_reported() {
+        let error = resolve_binary(Some("/nonexistent/det-cli"), None)
+            .expect_err("a missing override must fail");
+
+        assert!(error.contains("/nonexistent/det-cli"), "{error}");
+    }
+
+    #[test]
+    fn binary_override_takes_precedence_over_cargo_binary() {
+        let override_file = tempfile::NamedTempFile::new().expect("override binary");
+        let cargo_file = tempfile::NamedTempFile::new().expect("cargo binary");
+        let cargo = cargo_file.path().to_str();
+        assert_eq!(
+            resolve_binary(override_file.path().to_str(), cargo).expect("override exists"),
+            override_file.path()
+        );
+        assert_eq!(
+            resolve_binary(Some(" "), cargo).expect("blank override falls back"),
+            cargo_file.path()
+        );
+    }
+
+    #[test]
+    fn a_failed_run_reports_both_streams() {
+        let run = CliRun {
+            command: "det-cli --standalone core-wallets-list".to_string(),
+            exit_code: Some(1),
+            stdout: "partial".to_string(),
+            stderr: "Error: boom".to_string(),
+            timed_out: false,
+        };
+
+        assert!(!run.succeeded());
+        let report = run.report();
+        assert!(
+            report.contains("exit code 1") && report.contains("boom") && report.contains("partial")
+        );
+    }
+
+    #[test]
+    fn a_timeout_is_named_in_the_report() {
+        let run = CliRun {
+            command: "det-cli --standalone core-address-create".to_string(),
+            exit_code: None,
+            stdout: String::new(),
+            stderr: String::new(),
+            timed_out: true,
+        };
+
+        assert!(!run.succeeded());
+        assert!(run.report().contains("timed out"), "{}", run.report());
+    }
+}
diff --git a/tests/migration-matrix/main.rs b/tests/migration-matrix/main.rs
new file mode 100644
index 000000000..171ecdf73
--- /dev/null
+++ b/tests/migration-matrix/main.rs
@@ -0,0 +1,568 @@
+//! Cross-version data-migration matrix.
+//!
+//! Boots profiles captured by older DET releases with the binary built from
+//! this tree, and asserts the upgrade lands them intact. The fixtures are
+//! multi-megabyte captures of real profiles, stored as CI build artifacts
+//! rather than in the repository, so the matrix only runs when a workflow
+//! points `MIGRATION_FIXTURES_DIR` at an unpacked fixture set. Unset — the
+//! normal `cargo test --all-features --workspace` case — it reports the skip
+//! and passes, while the module-level unit tests below still exercise the
+//! harness's own logic. The bundled public-only v0.9.3 profile also runs
+//! without downloaded archives whenever a CLI binary is available.
+//!
+//! What is deliberately *not* done here: booting `AppState` in-process. Under
+//! the `testing` feature `AppState::boot_inputs` substitutes an in-memory
+//! database, which would leave every migration assertion below testing
+//! nothing. The harness spawns the real `det-cli` binary instead; see
+//! [`cli`] for the boot path it drives.
+//!
+//! Each fixture boots once without a password and once per `password_runs`
+//! manifest entry, every time from a freshly staged copy.
+//!
+//! Environment:
+//!
+//! | Variable | Effect |
+//! |---|---|
+//! | `MIGRATION_FIXTURES_DIR` | Unpacked fixtures + `manifest.json`. Unset ⇒ skip. |
+//! | `MIGRATION_FIXTURES_MANIFEST` | Manifest path, when it lives elsewhere. |
+//! | `MIGRATION_MATRIX_ONLY` | Comma-separated fixture ids to run. |
+//! | `MIGRATION_MATRIX_SKIP_NETWORK` | Skip the checks needing a synced chain. |
+//! | `MIGRATION_MATRIX_SKIP_PASSWORDS` | Explicitly skip secret-dependent scenarios (fork CI). |
+//! | `MIGRATION_MATRIX_BOOT_TIMEOUT_SECS` | Per-boot wall clock (default 300). |
+//! | `MIGRATION_MATRIX_NETWORK_TIMEOUT_SECS` | Chain-gated calls (default 900). |
+//! | `DET_CLI_BIN` | Binary under test, instead of the one Cargo just built. |
+
+mod assertions;
+mod cli;
+mod manifest;
+mod public_identities;
+mod stage;
+
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use assertions::{APP_DB, DATA_DB};
+use dash_evo_tool::database::DEFAULT_DB_VERSION;
+use manifest::{ExpectedWallet, Fixture, Scenario};
+
+const FIXTURES_DIR_ENV: &str = "MIGRATION_FIXTURES_DIR";
+const ONLY_ENV: &str = "MIGRATION_MATRIX_ONLY";
+const SKIP_NETWORK_ENV: &str = "MIGRATION_MATRIX_SKIP_NETWORK";
+const SKIP_PASSWORDS_ENV: &str = "MIGRATION_MATRIX_SKIP_PASSWORDS";
+const BOOT_TIMEOUT_ENV: &str = "MIGRATION_MATRIX_BOOT_TIMEOUT_SECS";
+const NETWORK_TIMEOUT_ENV: &str = "MIGRATION_MATRIX_NETWORK_TIMEOUT_SECS";
+
+/// Generous next to the 60s the MCP layer waits for a cold-start migration,
+/// tight enough that a wedged boot fails instead of hanging the job.
+const DEFAULT_BOOT_TIMEOUT: Duration = Duration::from_secs(300);
+
+/// Covers the 600s SPV gate plus the work that follows it.
+const DEFAULT_NETWORK_TIMEOUT: Duration = Duration::from_secs(900);
+
+/// Knobs resolved once per run.
+struct Options {
+    boot_timeout: Duration,
+    network_timeout: Duration,
+    skip_network: bool,
+    skip_passwords: bool,
+}
+
+impl Options {
+    fn from_env() -> Self {
+        Self {
+            boot_timeout: duration_from_env(BOOT_TIMEOUT_ENV, DEFAULT_BOOT_TIMEOUT),
+            network_timeout: duration_from_env(NETWORK_TIMEOUT_ENV, DEFAULT_NETWORK_TIMEOUT),
+            skip_network: flag(SKIP_NETWORK_ENV),
+            skip_passwords: flag(SKIP_PASSWORDS_ENV),
+        }
+    }
+}
+
+fn duration_from_env(name: &str, fallback: Duration) -> Duration {
+    match std::env::var(name).ok().and_then(|v| v.trim().parse().ok()) {
+        Some(seconds) => Duration::from_secs(seconds),
+        None => fallback,
+    }
+}
+
+fn flag(name: &str) -> bool {
+    matches!(
+        std::env::var(name).unwrap_or_default().trim(),
+        "1" | "true" | "yes"
+    )
+}
+
+/// Runs every fixture in the manifest, reporting all failures at once rather
+/// than stopping at the first — one broken fixture should not hide the state
+/// of the rest of the matrix.
+#[test]
+fn migration_matrix() {
+    let Some(fixtures_dir) = fixtures_dir() else {
+        println!(
+            "{FIXTURES_DIR_ENV} is not set — skipping the cross-version migration matrix. \
+             Set it to a directory holding {} plus the unpacked fixtures to run it.",
+            manifest::MANIFEST_FILE
+        );
+        return;
+    };
+
+    let manifest = manifest::load(&fixtures_dir).unwrap_or_else(|error| panic!("{error}"));
+    let selected = select(&manifest.fixtures);
+    assert!(
+        !selected.is_empty(),
+        "no fixtures to run: {} lists {} fixture(s) and {ONLY_ENV} selects {:?}",
+        manifest::manifest_path(&fixtures_dir).display(),
+        manifest.fixtures.len(),
+        std::env::var(ONLY_ENV).unwrap_or_default(),
+    );
+
+    let options = Options::from_env();
+    println!(
+        "Running {} migration fixture(s) from {} (manifest schema {}) against DEFAULT_DB_VERSION \
+         {DEFAULT_DB_VERSION}",
+        selected.len(),
+        fixtures_dir.display(),
+        manifest.schema_version,
+    );
+
+    let mut failures = Vec::new();
+    for fixture in selected {
+        println!("--- fixture {} ---", fixture.describe());
+        match run_fixture(&fixtures_dir, fixture, &options) {
+            Ok(()) => println!("--- fixture {} ok ---", fixture.id),
+            Err(error) => {
+                println!("--- fixture {} FAILED ---", fixture.id);
+                failures.push(format!("[{}] {error}", fixture.id));
+            }
+        }
+    }
+
+    assert!(
+        failures.is_empty(),
+        "{} of the migration fixtures failed:\n\n{}",
+        failures.len(),
+        failures.join("\n\n")
+    );
+}
+
+fn fixtures_dir() -> Option {
+    let dir = std::env::var(FIXTURES_DIR_ENV).ok()?;
+    match dir.trim().is_empty() {
+        true => None,
+        false => Some(PathBuf::from(dir.trim())),
+    }
+}
+
+fn bundled_public_fixture(root: &Path) -> Fixture {
+    let expected: serde_json::Value = serde_json::from_str(include_str!(
+        "../migration-fixtures/v0.9.3-public-identities/expected.json"
+    ))
+    .expect("public fixture expectations");
+    let fixture: Fixture = serde_json::from_value(serde_json::json!({
+        "id": "v0.9.3-public-identities", "network": "testnet",
+        "git_tag": "v0.9.3", "det_version": "0.9.3",
+        "capture_method": "historical-writer+explorer", "profile": "public-identities-dpns",
+        "expect": {"derive_address": false, "starting_db_version": 11,
+            "public_identities": expected["identities"]}
+    }))
+    .expect("public fixture manifest");
+    let source = root.join(&fixture.id);
+    std::fs::create_dir_all(&source).unwrap();
+    let conn = rusqlite::Connection::open(source.join(DATA_DB)).unwrap();
+    // SQLite dumps can insert child rows before the referenced table exists.
+    conn.pragma_update(None, "foreign_keys", false).unwrap();
+    conn.execute_batch(include_str!(
+        "../migration-fixtures/v0.9.3-public-identities/data.sql"
+    ))
+    .unwrap();
+    conn.pragma_update(None, "foreign_keys", true).unwrap();
+    assert!(
+        conn.prepare("PRAGMA foreign_key_check")
+            .unwrap()
+            .query([])
+            .unwrap()
+            .next()
+            .unwrap()
+            .is_none()
+    );
+    fixture
+}
+
+#[test]
+fn public_identity_fixture_contains_user_dpns_and_evonode_without_wallets() {
+    let root = tempfile::tempdir().unwrap();
+    let fixture = bundled_public_fixture(root.path());
+    let db = root.path().join(&fixture.id).join(DATA_DB);
+    let expected = &fixture.expect.public_identities;
+    assert_eq!(expected.len(), 2);
+    assert!(
+        expected
+            .iter()
+            .any(|id| id.identity_type == "User" && !id.dpns_names.is_empty())
+    );
+    assert!(expected.iter().any(|id| id.identity_type == "Evonode"
+        && id.public_keys.iter().any(|key| key.purpose == "OWNER")));
+    let conn = rusqlite::Connection::open(&db).unwrap();
+    assert_eq!(
+        conn.query_row("SELECT count(*) FROM wallet", [], |row| row
+            .get::<_, u64>(0))
+            .unwrap(),
+        0
+    );
+    assert_eq!(
+        conn.query_row("SELECT count(*) FROM identity", [], |row| row
+            .get::<_, u64>(0))
+            .unwrap(),
+        2
+    );
+    public_identities::check_source(expected, &db, &root.path().join("scratch")).unwrap();
+}
+
+#[test]
+fn public_identity_fixture_migrates() {
+    if !cfg!(feature = "cli")
+        && std::env::var_os(cli::BINARY_ENV).is_none()
+        && fixtures_dir().is_none()
+    {
+        println!("Skipping public identity CLI migration: enable cli or set DET_CLI_BIN");
+        return;
+    }
+    let root = tempfile::tempdir().unwrap();
+    let fixture = bundled_public_fixture(root.path());
+    let options = Options {
+        skip_network: true,
+        ..Options::from_env()
+    };
+    run_fixture(root.path(), &fixture, &options).unwrap_or_else(|error| panic!("{error}"));
+}
+
+/// Applies the `MIGRATION_MATRIX_ONLY` filter, if any.
+fn select(fixtures: &[Fixture]) -> Vec<&Fixture> {
+    let only = std::env::var(ONLY_ENV).unwrap_or_default();
+    let wanted: Vec<&str> = only
+        .split(',')
+        .map(str::trim)
+        .filter(|id| !id.is_empty())
+        .collect();
+    fixtures
+        .iter()
+        .filter(|fixture| wanted.is_empty() || wanted.contains(&fixture.id.as_str()))
+        .collect()
+}
+
+/// Runs every scenario of one fixture — always the boot without a password,
+/// then one per password run — each on a freshly staged copy, and reports
+/// every failing scenario rather than stopping at the first.
+fn run_fixture(fixtures_dir: &Path, fixture: &Fixture, options: &Options) -> Result<(), String> {
+    if options.skip_passwords && !fixture.password_runs.is_empty() {
+        println!(
+            "  SKIPPED {} password scenario(s): explicitly disabled by {SKIP_PASSWORDS_ENV}",
+            fixture.password_runs.len()
+        );
+    }
+    let failures: Vec = scenarios_for_run(fixture, options.skip_passwords)?
+        .iter()
+        .filter_map(|scenario| {
+            println!("  scenario: {}", scenario.label);
+            run_scenario(fixtures_dir, fixture, scenario, options)
+                .err()
+                .map(|error| format!("scenario `{}`: {error}", scenario.label))
+        })
+        .collect();
+    match failures.is_empty() {
+        true => Ok(()),
+        false => Err(failures.join("\n\n")),
+    }
+}
+
+fn scenarios_for_run(fixture: &Fixture, skip_passwords: bool) -> Result, String> {
+    Ok(fixture
+        .scenarios()?
+        .into_iter()
+        .filter(|scenario| !skip_passwords || scenario.password_env.is_none())
+        .collect())
+}
+
+/// Stages one fixture, boots it twice, and checks what the upgrade produced.
+/// A scenario with a password first finishes the storage update through
+/// `app-storage-update --password-file`, as an operator automating an upgrade
+/// would.
+fn run_scenario(
+    fixtures_dir: &Path,
+    fixture: &Fixture,
+    scenario: &Scenario,
+    options: &Options,
+) -> Result<(), String> {
+    let password = scenario.resolve_password_with(|name| std::env::var(name).ok())?;
+    let network = fixture.network()?;
+    let staged = stage::stage(fixtures_dir, fixture)?;
+    let scratch = staged.scratch()?;
+    let data_dir = staged.data_dir().to_path_buf();
+    let data_db = data_dir.join(DATA_DB);
+    let app_db = data_dir.join(APP_DB);
+    let network_db = data_dir.join(assertions::network_db_name(network));
+
+    let before = assertions::schema_snapshot(&data_db, &scratch, "before")?;
+    let starting_version = before.as_ref().and_then(|snapshot| snapshot.version);
+    if let (Some(declared), Some(found)) = (fixture.expect.starting_db_version, starting_version)
+        && declared != found
+    {
+        return Err(format!(
+            "manifest records a starting {DATA_DB} version of {declared}, the staged file is at {found}"
+        ));
+    }
+    // Every boot path opens a pre-update data.db read-only, so its bytes are
+    // part of the contract for every fixture that has one, not an opt-in.
+    let before_bytes = assertions::file_bytes(&data_db)?;
+    let before_sentinels = assertions::migration_sentinels(&app_db, &scratch, "before")?;
+    public_identities::check_source(&fixture.expect.public_identities, &data_db, &scratch)?;
+
+    let cli = cli::DetCli::new(&staged)?;
+
+    // Without its password, a fixture holding a password-protected wallet
+    // cannot finish its storage update headless — det-cli never prompts — so
+    // every wallet-gated boot must stop at exactly that error, not merely fail.
+    let needs_desktop = scenario.needs_desktop();
+    let check_wallet_boot = |run: &cli::CliRun, label: &str| match needs_desktop {
+        true => assertions::check_needs_desktop(run, label),
+        false => assertions::check_boot(run, label),
+    };
+    // Every run of a password scenario is checked for the password first, so
+    // a leak is reported even when the run also fails for another reason.
+    let check_not_echoed = |run: &cli::CliRun| match &password {
+        Some(password) => assertions::check_password_not_echoed(run, password),
+        None => Ok(()),
+    };
+
+    if let Some(password) = &password {
+        let password_file = staged.write_password_file(password)?;
+        let update = cli.storage_update(&password_file, options.boot_timeout)?;
+        check_not_echoed(&update)?;
+        assertions::check_boot(&update, "app-storage-update")?;
+    }
+
+    let first = cli.wallets_list(options.boot_timeout)?;
+    check_not_echoed(&first)?;
+    check_wallet_boot(&first, "the first boot")?;
+
+    let after = assertions::schema_snapshot(&data_db, &scratch, "after")?;
+    assertions::check_schema_outcome(before.as_ref(), after.as_ref())?;
+    if before_bytes.is_some() {
+        let after_bytes = assertions::file_bytes(&data_db)?;
+        assertions::check_bytes_unchanged(before_bytes.as_ref(), after_bytes.as_ref(), DATA_DB)?;
+    }
+
+    let info = cli.network_info(options.boot_timeout)?;
+    check_not_echoed(&info)?;
+    assertions::check_boot(&info, "network-info")?;
+    assertions::check_network(network, &info)?;
+
+    let wallet_ids = match needs_desktop {
+        // Wallet tools stay gated until the desktop app finishes the update,
+        // so nothing is listed; the per-wallet check below reads storage.
+        true => Vec::new(),
+        false => assertions::check_wallets(&scenario.listed_aliases, &first)?,
+    };
+    check_wallet_outcomes(&scenario.wallets, &data_db, &network_db, &scratch, "after")?;
+    public_identities::check_migrated(
+        &fixture.expect.public_identities,
+        &network_db,
+        &scratch,
+        "after",
+        &cli,
+        options.boot_timeout,
+    )?;
+    assertions::check_identities(
+        &fixture.expect.identity_ids,
+        &assertions::identity_ids(&network_db, &scratch, "after")?,
+    )?;
+
+    let sentinels = assertions::migration_sentinels(&app_db, &scratch, "after")?;
+    assertions::check_existing_sentinels(&before_sentinels, &sentinels)?;
+    if needs_desktop {
+        // An unfinished storage update must not claim completion.
+        assertions::check_sentinel_absent(&sentinels, network)?;
+    } else if fixture.expect.finish_unwire_sentinel {
+        assertions::check_sentinel_recorded(&sentinels, network)?;
+    }
+    let backups = assertions::backup_files(&data_dir)?;
+
+    // The second boot never gets the password: once the update finished, a
+    // plain boot must need nothing more.
+    let second = cli.wallets_list(options.boot_timeout)?;
+    check_not_echoed(&second)?;
+    check_wallet_boot(&second, "the second boot")?;
+    if !needs_desktop {
+        assertions::check_wallets(&scenario.listed_aliases, &second)?;
+    }
+    check_wallet_outcomes(
+        &scenario.wallets,
+        &data_db,
+        &network_db,
+        &scratch,
+        "idempotent",
+    )?;
+    let second_schema = assertions::schema_snapshot(&data_db, &scratch, "idempotent")?;
+    public_identities::check_migrated(
+        &fixture.expect.public_identities,
+        &network_db,
+        &scratch,
+        "idempotent",
+        &cli,
+        options.boot_timeout,
+    )?;
+    assertions::check_schema_outcome(before.as_ref(), second_schema.as_ref())?;
+    if before_bytes.is_some() {
+        assertions::check_bytes_unchanged(
+            before_bytes.as_ref(),
+            assertions::file_bytes(&data_db)?.as_ref(),
+            DATA_DB,
+        )?;
+    }
+    assertions::check_identities(
+        &fixture.expect.identity_ids,
+        &assertions::identity_ids(&network_db, &scratch, "idempotent")?,
+    )?;
+    assertions::check_idempotent(
+        (&backups, &sentinels),
+        (
+            &assertions::backup_files(&data_dir)?,
+            &assertions::migration_sentinels(&app_db, &scratch, "idempotent")?,
+        ),
+    )?;
+
+    // Last, because it is the only step that needs a reachable chain: a
+    // failure here should not mask the offline evidence collected above.
+    //
+    // TODO(doctor-module): a wallet the legacy drain registers gets birth
+    // height 0 (`WalletOrigin::Imported`) and no committed sync height, so its
+    // first SPV-gated call waits for a compact-filter scan from genesis. On a
+    // GitHub runner that outlasts the product's 10-minute SPV gate (CI run
+    // 34592733217: ~590k of 1.55M testnet filters). Such fixtures opt out with
+    // `expect.derive_address: false` until the doctor module can bound or
+    // resume that scan; a captured current-era profile carries its committed
+    // height and scans only the blocks since capture.
+    if needs_desktop {
+        println!(
+            "    address derivation skipped (wallet tools wait for the desktop app to finish the storage update)"
+        );
+    } else if fixture.expect.derive_address && !options.skip_network {
+        for wallet_id in &wallet_ids {
+            let label = format!("core-address-create for `{wallet_id}`");
+            let run = cli.address_create(wallet_id, options.network_timeout)?;
+            assertions::check_boot(&run, &label)?;
+            let address = assertions::check_address(&run)?;
+            println!("    {wallet_id}: derived {address}");
+        }
+    } else {
+        println!("    address derivation skipped (needs a synced chain)");
+    }
+
+    Ok(())
+}
+
+/// Checks every wallet the manifest lists against the per-network store. Only
+/// possible for a v0.9.3-era fixture, where `data.db` names each wallet's
+/// account xpub; a fixture without one relies on the boot-level checks.
+fn check_wallet_outcomes(
+    wallets: &[ExpectedWallet],
+    data_db: &Path,
+    network_db: &Path,
+    scratch: &Path,
+    label: &str,
+) -> Result<(), String> {
+    match assertions::legacy_wallet_registrations(data_db, network_db, scratch, label)? {
+        Some(registered) => assertions::check_wallet_outcomes(wallets, ®istered),
+        None => {
+            println!("    per-wallet storage check skipped (no legacy wallet table)");
+            Ok(())
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn review_regression_empty_manifest_cannot_hide_captured_wallets() {
+        let dir = tempfile::tempdir().unwrap();
+        let db = dir.path().join(DATA_DB);
+        let conn = rusqlite::Connection::open(&db).unwrap();
+        conn.execute_batch("CREATE TABLE wallet(alias TEXT, master_ecdsa_bip44_account_0_epk BLOB); INSERT INTO wallet VALUES ('omitted', x'01');").unwrap();
+        assert!(
+            check_wallet_outcomes(
+                &[],
+                &db,
+                &dir.path().join("missing.sqlite"),
+                &dir.path().join("scratch"),
+                "before"
+            )
+            .is_err()
+        );
+    }
+
+    #[test]
+    fn modern_profile_without_legacy_wallet_table_is_allowed() {
+        let dir = tempfile::tempdir().unwrap();
+        let db = dir.path().join(DATA_DB);
+        rusqlite::Connection::open(&db)
+            .unwrap()
+            .execute_batch("CREATE TABLE settings(id INTEGER, database_version INTEGER);")
+            .unwrap();
+        check_wallet_outcomes(
+            &[],
+            &db,
+            &dir.path().join("missing.sqlite"),
+            &dir.path().join("scratch"),
+            "before",
+        )
+        .unwrap();
+    }
+
+    fn fixture(id: &str) -> Fixture {
+        serde_json::from_str(&format!(r#"{{ "id": "{id}", "network": "testnet" }}"#))
+            .expect("fixture json")
+    }
+
+    #[test]
+    fn an_unset_filter_selects_every_fixture() {
+        let fixtures = vec![fixture("v0.9.3-testnet"), fixture("v1.0.0-weekly")];
+        assert_eq!(select(&fixtures).len(), 2);
+    }
+
+    #[test]
+    fn timeouts_fall_back_to_the_defaults_on_junk_input() {
+        assert_eq!(
+            duration_from_env(
+                "MIGRATION_MATRIX_TIMEOUT_THAT_IS_UNSET",
+                DEFAULT_BOOT_TIMEOUT
+            ),
+            DEFAULT_BOOT_TIMEOUT
+        );
+    }
+
+    #[test]
+    fn an_absent_flag_is_off() {
+        assert!(!flag("MIGRATION_MATRIX_FLAG_THAT_IS_UNSET"));
+    }
+
+    #[test]
+    fn password_scenarios_require_an_explicit_opt_out() {
+        let manifest: manifest::Manifest =
+            serde_json::from_str(include_str!("../migration-fixtures/manifest.json"))
+                .expect("manifest");
+        let fixture = manifest
+            .fixtures
+            .iter()
+            .find(|fixture| !fixture.password_runs.is_empty())
+            .expect("protected fixture");
+        let all = scenarios_for_run(fixture, false).expect("all scenarios");
+        assert!(all.iter().any(|scenario| scenario.password_env.is_some()));
+        let public = scenarios_for_run(fixture, true).expect("password-free scenarios");
+        assert_eq!(public.len(), 1);
+        assert!(public[0].password_env.is_none());
+        assert!(public[0].needs_desktop());
+        assert_eq!(public[0].listed_aliases, all[0].listed_aliases);
+    }
+}
diff --git a/tests/migration-matrix/manifest.rs b/tests/migration-matrix/manifest.rs
new file mode 100644
index 000000000..bb9f3f9ec
--- /dev/null
+++ b/tests/migration-matrix/manifest.rs
@@ -0,0 +1,729 @@
+//! Serde model for `tests/migration-fixtures/manifest.json`.
+//!
+//! The manifest is the only permanent pointer to a fixture: the archives
+//! themselves live as GitHub Actions build artifacts with a finite retention,
+//! so the committed manifest records which run produced which fixture.
+//!
+//! Every field except `id` and `network` is optional and defaulted. The
+//! capture tooling and this harness ship in separate changes, so an unknown
+//! field must never fail the parse — `deny_unknown_fields` is deliberately
+//! absent and new keys are additive.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::path::{Path, PathBuf};
+
+use dash_sdk::dpp::dashcore::Network;
+use serde::Deserialize;
+
+/// Manifest file name inside the fixtures directory.
+pub const MANIFEST_FILE: &str = "manifest.json";
+
+/// Overrides the manifest path when the file lives outside the fixtures dir.
+pub const MANIFEST_PATH_ENV: &str = "MIGRATION_FIXTURES_MANIFEST";
+
+#[derive(Debug, Deserialize)]
+pub struct Manifest {
+    /// Manifest schema revision. Informational — the parse is
+    /// version-tolerant by construction.
+    #[serde(default)]
+    pub schema_version: u32,
+    pub fixtures: Vec,
+}
+
+/// One captured data directory: which DET build wrote it, on which network,
+/// and what the harness should be able to observe after booting it.
+#[derive(Debug, Deserialize)]
+pub struct Fixture {
+    /// Stable identifier, also the default archive/directory name.
+    pub id: String,
+    /// Network the profile was captured on (`mainnet` / `testnet` / `devnet`
+    /// / `local`). Drives the sentinel key and the `network-info` assertion.
+    pub network: String,
+    #[serde(default)]
+    pub git_tag: String,
+    #[serde(default)]
+    pub det_version: String,
+    /// How the profile was produced (`gui`, `det-cli`, …). Informational.
+    #[serde(default)]
+    pub capture_method: String,
+    /// Profile flavour (`basic`, `password-protected`, …). Informational.
+    #[serde(default)]
+    pub profile: String,
+    #[serde(default)]
+    pub captured_at: String,
+    #[serde(default, alias = "artifacts")]
+    pub artifact: Artifact,
+    #[serde(default, alias = "expectations")]
+    pub expect: Expectations,
+    #[serde(default)]
+    pub contents: Contents,
+    /// Extra boots of the same fixture with the wallet password supplied
+    /// non-interactively, each on a freshly staged copy.
+    #[serde(default)]
+    pub password_runs: Vec,
+}
+
+/// What the capture put into the data dir, as far as the harness asserts on
+/// it.
+#[derive(Debug, Default, Deserialize)]
+pub struct Contents {
+    #[serde(default)]
+    pub wallets: Vec,
+}
+
+/// One wallet in the captured `data.db`, found there by its alias.
+#[derive(Debug, Deserialize)]
+pub struct FixtureWallet {
+    pub alias: String,
+    /// What a boot without a supplied password must do with the wallet.
+    #[serde(default)]
+    pub expected_outcome: WalletOutcome,
+    /// Environment variable supplying the wallet password at scenario execution.
+    #[serde(default)]
+    pub password_env: Option,
+}
+
+/// What a headless boot must do with one wallet. An unrecognised value fails
+/// the parse: guessing an outcome would make the matrix assert the wrong thing.
+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum WalletOutcome {
+    /// Registered in the per-network wallet store by the boot.
+    #[default]
+    Migrated,
+    /// Password-protected, and no password is supplied. det-cli never prompts,
+    /// so the boot fails with `StorageUpdateNeedsDesktop` and the wallet stays
+    /// unregistered until its password is supplied or the desktop app finishes
+    /// the storage update.
+    NeedsDesktop,
+}
+
+/// A boot of the fixture with the wallet password supplied non-interactively.
+#[derive(Debug, Deserialize)]
+pub struct PasswordRun {
+    /// How det-cli receives the password.
+    pub source: PasswordSource,
+    /// Per-alias outcomes that differ from the wallet's `expected_outcome`.
+    #[serde(default)]
+    pub expected_outcomes: BTreeMap,
+}
+
+/// How a [`PasswordRun`] hands det-cli the password. An unrecognised value
+/// fails the parse.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PasswordSource {
+    /// `app-storage-update --password-file `.
+    File,
+}
+
+/// What one wallet must end up as in one scenario.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExpectedWallet {
+    pub alias: String,
+    pub outcome: WalletOutcome,
+}
+
+/// One staged boot sequence of a fixture; passwords are resolved at execution.
+pub struct Scenario {
+    pub label: String,
+    /// Environment variable resolved for `--password-file`; absent on a plain boot.
+    pub password_env: Option,
+    pub wallets: Vec,
+    /// Aliases a completed boot must list.
+    pub listed_aliases: Vec,
+}
+
+impl Scenario {
+    /// Resolves the password only when executing this scenario.
+    pub fn resolve_password_with(
+        &self,
+        lookup: impl FnOnce(&str) -> Option,
+    ) -> Result, String> {
+        self.password_env
+            .as_deref()
+            .map(|name| {
+                lookup(name)
+                    .filter(|value| !value.is_empty())
+                    .ok_or_else(|| format!("the {} scenario requires non-empty {name}", self.label))
+            })
+            .transpose()
+    }
+
+    /// Whether this boot must stop at `StorageUpdateNeedsDesktop` rather than
+    /// complete.
+    pub fn needs_desktop(&self) -> bool {
+        self.wallets
+            .iter()
+            .any(|wallet| wallet.outcome == WalletOutcome::NeedsDesktop)
+    }
+}
+
+/// Where the fixture bytes came from. `archive` is the only field the harness
+/// reads; the rest exist so a human (or a re-fetch script) can find the
+/// artifact again after the local copy is gone.
+#[derive(Debug, Default, Deserialize)]
+pub struct Artifact {
+    /// Archive (or directory) name inside the fixtures directory.
+    /// `archive_filename` is the key tests/migration-fixtures/README.md
+    /// documents and the capture tooling writes.
+    #[serde(default, alias = "archive_filename", alias = "file", alias = "path")]
+    pub archive: Option,
+    #[serde(default)]
+    pub sha256: Option,
+    #[serde(default)]
+    pub artifact_name: Option,
+    #[serde(default)]
+    pub workflow_run_id: Option,
+    #[serde(default)]
+    pub retention_days: Option,
+}
+
+/// What the harness must observe after booting this fixture.
+#[derive(Debug, Deserialize)]
+#[serde(default)]
+pub struct Expectations {
+    /// Wallet aliases that must appear in `core-wallets-list`.
+    pub wallet_aliases: Vec,
+    /// Lowercase hex identity ids that must survive the migration.
+    pub identity_ids: Vec,
+    /// Exact public metadata for a fixture containing only watch-only identities.
+    pub public_identities: Vec,
+    /// `data.db` schema version at capture time. Cross-checked against the
+    /// staged file; the file itself is authoritative when the two disagree
+    /// only in that the manifest is silent.
+    pub starting_db_version: Option,
+    /// Whether the boot must record the `finish_unwire` completion sentinel.
+    pub finish_unwire_sentinel: bool,
+    /// Whether to derive a receive address. Needs a synced SPV chain, so a
+    /// fixture captured for an offline-only check can opt out.
+    pub derive_address: bool,
+}
+
+impl Default for Expectations {
+    fn default() -> Self {
+        Self {
+            wallet_aliases: Vec::new(),
+            identity_ids: Vec::new(),
+            public_identities: Vec::new(),
+            starting_db_version: None,
+            finish_unwire_sentinel: true,
+            derive_address: true,
+        }
+    }
+}
+
+impl Artifact {
+    /// Where the bytes came from, for a failure report: a local archive name
+    /// is useless once the CI artifact has expired, the run id is not.
+    pub fn describe(&self) -> String {
+        let mut parts = Vec::new();
+        if let Some(name) = &self.artifact_name {
+            parts.push(format!("artifact {name}"));
+        }
+        if let Some(run) = self.workflow_run_id {
+            parts.push(format!("run {run}"));
+        }
+        if let Some(days) = self.retention_days {
+            parts.push(format!("retention {days}d"));
+        }
+        match parts.is_empty() {
+            true => "no artifact pointer".to_string(),
+            false => parts.join(", "),
+        }
+    }
+}
+
+impl Fixture {
+    /// One-line provenance, printed before each fixture runs so a failing CI
+    /// log says which capture it was looking at.
+    pub fn describe(&self) -> String {
+        let field = |label: &str, value: &str| match value.is_empty() {
+            true => String::new(),
+            false => format!(" {label}={value}"),
+        };
+        format!(
+            "{} network={}{}{}{}{}{} [{}]",
+            self.id,
+            self.network,
+            field("tag", &self.git_tag),
+            field("version", &self.det_version),
+            field("capture", &self.capture_method),
+            field("profile", &self.profile),
+            field("captured", &self.captured_at),
+            self.artifact.describe(),
+        )
+    }
+
+    /// The boots the harness runs for this fixture: always one without a
+    /// password, then one per [`PasswordRun`].
+    ///
+    /// # Errors
+    ///
+    /// A password run the fixture cannot honour: no wallet declares a
+    /// password, the wallets declare different ones (one supplied password
+    /// cannot open them all), an override names an unknown alias, or an
+    /// override expects `needs_desktop` — with the password supplied, the
+    /// update either opens every protected wallet or fails.
+    pub fn scenarios(&self) -> Result, String> {
+        let wallets = &self.contents.wallets;
+        let mut scenarios = vec![
+            self.scenario(
+                "no password",
+                None,
+                wallets
+                    .iter()
+                    .map(|wallet| ExpectedWallet {
+                        alias: wallet.alias.clone(),
+                        outcome: wallet.expected_outcome,
+                    })
+                    .collect(),
+            ),
+        ];
+
+        for run in &self.password_runs {
+            let label = match run.source {
+                PasswordSource::File => "password file",
+            };
+            let password_env = self.shared_password_env(label)?;
+            if let Some(alias) = run
+                .expected_outcomes
+                .keys()
+                .find(|alias| !wallets.iter().any(|wallet| &wallet.alias == *alias))
+            {
+                return Err(format!(
+                    "fixture '{}': the {label} run names `{alias}`, which is not in contents.wallets",
+                    self.id
+                ));
+            }
+            let expected: Vec = wallets
+                .iter()
+                .map(|wallet| ExpectedWallet {
+                    alias: wallet.alias.clone(),
+                    outcome: run
+                        .expected_outcomes
+                        .get(&wallet.alias)
+                        .copied()
+                        .unwrap_or(wallet.expected_outcome),
+                })
+                .collect();
+            if let Some(wallet) = expected
+                .iter()
+                .find(|wallet| wallet.outcome == WalletOutcome::NeedsDesktop)
+            {
+                return Err(format!(
+                    "fixture '{}': the {label} run expects `{}` to need the desktop app, but with \
+                     the password supplied the update either opens every protected wallet or fails",
+                    self.id, wallet.alias
+                ));
+            }
+            scenarios.push(self.scenario(label, Some(password_env), expected));
+        }
+        Ok(scenarios)
+    }
+
+    fn scenario(
+        &self,
+        label: &str,
+        password_env: Option,
+        wallets: Vec,
+    ) -> Scenario {
+        let mut listed_aliases = self.expect.wallet_aliases.clone();
+        for wallet in &wallets {
+            if wallet.outcome == WalletOutcome::Migrated && !listed_aliases.contains(&wallet.alias)
+            {
+                listed_aliases.push(wallet.alias.clone());
+            }
+        }
+        Scenario {
+            label: label.to_owned(),
+            password_env,
+            wallets,
+            listed_aliases,
+        }
+    }
+
+    /// The environment variable shared by the protected wallets.
+    fn shared_password_env(&self, label: &str) -> Result {
+        let variables: BTreeSet<&str> = self
+            .contents
+            .wallets
+            .iter()
+            .filter_map(|wallet| wallet.password_env.as_deref())
+            .collect();
+        let mut distinct = variables.into_iter();
+        match (distinct.next(), distinct.next()) {
+            (Some(name), None) if !name.trim().is_empty() => Ok(name.to_owned()),
+            (Some(_), None) => Err(format!(
+                "fixture '{}': the {label} run needs a non-empty wallet `password_env`",
+                self.id
+            )),
+            (None, _) => Err(format!(
+                "fixture '{}': the {label} run needs a wallet `password_env` in contents.wallets",
+                self.id
+            )),
+            (Some(_), Some(_)) => Err(format!(
+                "fixture '{}': the {label} run supplies one password, but the wallets declare different environment variables",
+                self.id
+            )),
+        }
+    }
+
+    /// Parsed network, matching the spelling `network_info` reports
+    /// (`local` for regtest).
+    pub fn network(&self) -> Result {
+        match self.network.to_ascii_lowercase().as_str() {
+            "mainnet" | "dash" => Ok(Network::Mainnet),
+            "testnet" => Ok(Network::Testnet),
+            "devnet" => Ok(Network::Devnet),
+            "local" | "regtest" => Ok(Network::Regtest),
+            other => Err(format!(
+                "fixture '{}' declares unknown network '{other}' (expected mainnet, testnet, devnet or local)",
+                self.id
+            )),
+        }
+    }
+}
+
+/// Resolves the manifest path for `fixtures_dir`, honoring
+/// [`MANIFEST_PATH_ENV`].
+pub fn manifest_path(fixtures_dir: &Path) -> PathBuf {
+    match std::env::var(MANIFEST_PATH_ENV) {
+        Ok(path) if !path.trim().is_empty() => PathBuf::from(path),
+        _ => fixtures_dir.join(MANIFEST_FILE),
+    }
+}
+
+/// Reads and parses the fixture manifest. A missing or malformed manifest is
+/// a hard error: the matrix only runs when a workflow explicitly points it at
+/// fixtures, and silently testing nothing is exactly the failure mode this
+/// harness exists to prevent.
+pub fn load(fixtures_dir: &Path) -> Result {
+    let path = manifest_path(fixtures_dir);
+    let raw = std::fs::read_to_string(&path)
+        .map_err(|e| format!("could not read fixture manifest {}: {e}", path.display()))?;
+    serde_json::from_str(&raw)
+        .map_err(|e| format!("could not parse fixture manifest {}: {e}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn unknown_fields_and_absent_blocks_stay_parseable() {
+        let manifest: Manifest = serde_json::from_str(
+            r#"{
+                "schema_version": 1,
+                "generated_by": "a field this harness has never heard of",
+                "fixtures": [
+                    { "id": "v0.9.3-testnet", "network": "testnet", "future_key": [1, 2] }
+                ]
+            }"#,
+        )
+        .expect("a forward-compatible manifest must parse");
+
+        let fixture = &manifest.fixtures[0];
+        assert_eq!(fixture.network().expect("known network"), Network::Testnet);
+        assert!(fixture.expect.wallet_aliases.is_empty());
+        assert!(
+            fixture.expect.finish_unwire_sentinel && fixture.expect.derive_address,
+            "the sentinel and address checks default to on"
+        );
+        assert!(fixture.artifact.archive.is_none());
+    }
+
+    #[test]
+    fn expectations_and_artifact_pointers_are_read() {
+        let manifest: Manifest = serde_json::from_str(
+            r#"{
+                "fixtures": [{
+                    "id": "v0.9.3-testnet",
+                    "network": "testnet",
+                    "git_tag": "v0.9.3",
+                    "det_version": "0.9.3",
+                    "capture_method": "gui",
+                    "profile": "basic",
+                    "captured_at": "2026-09-10T00:00:00Z",
+                    "artifacts": { "file": "v0.9.3-testnet.tar.zst", "workflow_run_id": 42 },
+                    "expectations": {
+                        "wallet_aliases": ["public-test-wallet"],
+                        "starting_db_version": 11,
+                        "derive_address": false
+                    }
+                }]
+            }"#,
+        )
+        .expect("manifest with aliases must parse");
+
+        let fixture = &manifest.fixtures[0];
+        assert_eq!(
+            fixture.artifact.archive.as_deref(),
+            Some("v0.9.3-testnet.tar.zst")
+        );
+        assert_eq!(fixture.artifact.workflow_run_id, Some(42));
+        assert_eq!(fixture.expect.starting_db_version, Some(11));
+        assert_eq!(fixture.expect.wallet_aliases, ["public-test-wallet"]);
+        assert!(!fixture.expect.derive_address);
+        assert!(
+            fixture.expect.finish_unwire_sentinel,
+            "an unlisted expectation keeps its default"
+        );
+    }
+
+    /// Reads the committed manifest rather than a hand-written sample, so the
+    /// key names the capture tooling writes and the ones this reader expects
+    /// cannot drift apart unnoticed. A pointer that fails to deserialize is
+    /// silently `None` (every field is defaulted), which would send the
+    /// stager hunting for `.tar.zst` instead of the archive CI downloaded.
+    #[test]
+    fn the_committed_manifest_resolves_every_artifact_pointer() {
+        let manifest: Manifest =
+            serde_json::from_str(include_str!("../migration-fixtures/manifest.json"))
+                .expect("the committed manifest must parse");
+        assert!(
+            !manifest.fixtures.is_empty(),
+            "the committed manifest lists no fixtures"
+        );
+        for fixture in &manifest.fixtures {
+            let artifact = &fixture.artifact;
+            assert!(
+                artifact.archive.is_some(),
+                "fixture '{}' has no archive file name the stager can resolve",
+                fixture.id
+            );
+            assert!(
+                artifact.sha256.is_some(),
+                "fixture '{}' has no sha256 to verify the download against",
+                fixture.id
+            );
+            assert!(
+                artifact.artifact_name.is_some(),
+                "fixture '{}' has no artifact name",
+                fixture.id
+            );
+        }
+    }
+
+    #[test]
+    fn wallet_outcomes_default_to_migrated_and_reject_unknown_values() {
+        let fixture: Fixture = serde_json::from_str(
+            r#"{ "id": "f", "network": "testnet", "contents": { "wallets": [
+                { "alias": "plain" },
+                { "alias": "locked", "expected_outcome": "needs_desktop" }
+            ] } }"#,
+        )
+        .expect("parse");
+        assert_eq!(
+            fixture.contents.wallets[0].expected_outcome,
+            WalletOutcome::Migrated
+        );
+        let scenarios = fixture.scenarios().expect("no password runs to validate");
+        assert_eq!(scenarios.len(), 1, "only the boot without a password");
+        assert!(scenarios[0].needs_desktop());
+        assert!(scenarios[0].password_env.is_none());
+        assert_eq!(scenarios[0].listed_aliases, ["plain"]);
+
+        let unknown = serde_json::from_str::(
+            r#"{ "id": "f", "network": "testnet", "contents": { "wallets": [
+                { "alias": "x", "expected_outcome": "maybe" }
+            ] } }"#,
+        );
+        assert!(unknown.is_err(), "an unknown outcome must not parse");
+    }
+
+    fn outcomes(scenario: &Scenario) -> Vec<(&str, WalletOutcome)> {
+        scenario
+            .wallets
+            .iter()
+            .map(|wallet| (wallet.alias.as_str(), wallet.outcome))
+            .collect()
+    }
+
+    /// The committed v0.9.3 entry runs twice. Without a password the plain
+    /// wallet migrates and the protected one needs the desktop app; with the
+    /// password supplied through `--password-file`, both migrate.
+    #[test]
+    fn the_committed_v093_fixture_runs_without_and_with_the_password() {
+        let manifest: Manifest =
+            serde_json::from_str(include_str!("../migration-fixtures/manifest.json"))
+                .expect("the committed manifest must parse");
+        let fixture = manifest
+            .fixtures
+            .iter()
+            .find(|fixture| fixture.id == "v0.9.3-wallet-only")
+            .expect("the v0.9.3 baseline entry");
+        // The legacy drain registers both wallets at birth height 0, so the
+        // SPV-gated address derivation would need a compact-filter scan from
+        // genesis, longer than the 10-minute SPV gate on a CI runner. Key
+        // integrity is still asserted offline: each wallet's registration is
+        // matched by its account xpub.
+        assert!(!fixture.expect.derive_address);
+        let scenarios = fixture.scenarios().expect("the committed runs are valid");
+        assert_eq!(scenarios.len(), 2);
+
+        let [without, with] = &scenarios[..] else {
+            unreachable!("length checked above");
+        };
+        assert!(without.password_env.is_none() && without.needs_desktop());
+        assert_eq!(
+            outcomes(without),
+            [
+                ("migration-fixture-v093", WalletOutcome::Migrated),
+                (
+                    "migration-fixture-v093-protected",
+                    WalletOutcome::NeedsDesktop
+                ),
+            ]
+        );
+
+        assert!(with.password_env.is_some() && !with.needs_desktop());
+        assert_eq!(
+            outcomes(with),
+            [
+                ("migration-fixture-v093", WalletOutcome::Migrated),
+                ("migration-fixture-v093-protected", WalletOutcome::Migrated),
+            ]
+        );
+        assert_eq!(
+            with.listed_aliases,
+            ["migration-fixture-v093", "migration-fixture-v093-protected"]
+        );
+    }
+
+    /// The committed weekly entry is a current-era profile. Its wallet lives
+    /// in the per-network store, not in `data.db`, so the boot asserts it by
+    /// alias through `core-wallets-list`; there is no password run.
+    #[test]
+    fn the_committed_weekly_fixture_is_asserted_by_alias_without_a_password() {
+        let manifest: Manifest =
+            serde_json::from_str(include_str!("../migration-fixtures/manifest.json"))
+                .expect("the committed manifest must parse");
+        let fixture = manifest
+            .fixtures
+            .iter()
+            .find(|fixture| fixture.id == "v1.0.0-weekly.20260908-wallet-only")
+            .expect("the weekly entry");
+        assert_eq!(fixture.network().expect("known network"), Network::Testnet);
+        assert_eq!(fixture.expect.starting_db_version, Some(38));
+        assert!(
+            fixture.contents.wallets.is_empty(),
+            "this era's data.db has no wallet table to find a wallet in"
+        );
+        assert!(
+            fixture.expect.derive_address,
+            "the captured store carries its committed sync height, so derivation scans only \
+             the blocks since capture and stays within the SPV gate"
+        );
+
+        let scenarios = fixture.scenarios().expect("no password runs to validate");
+        let [scenario] = &scenarios[..] else {
+            panic!("expected only the boot without a password");
+        };
+        assert!(scenario.password_env.is_none() && !scenario.needs_desktop());
+        assert_eq!(scenario.listed_aliases, ["weekly-fixture"]);
+    }
+
+    fn fixture_with_runs(wallets: &str, runs: &str) -> Fixture {
+        serde_json::from_str(&format!(
+            r#"{{ "id": "f", "network": "testnet",
+                  "contents": {{ "wallets": [{wallets}] }},
+                  "password_runs": [{runs}] }}"#
+        ))
+        .expect("parse")
+    }
+
+    #[test]
+    fn a_password_run_the_fixture_cannot_honour_is_rejected() {
+        let file_run = r#"{ "source": "file", "expected_outcomes": { "locked": "migrated" } }"#;
+
+        let no_password = fixture_with_runs(
+            r#"{ "alias": "locked", "expected_outcome": "needs_desktop" }"#,
+            file_run,
+        );
+        let error = no_password.scenarios().err().expect("no password declared");
+        assert!(error.contains("needs a wallet `password_env`"), "{error}");
+
+        let different = fixture_with_runs(
+            r#"{ "alias": "locked", "password_env": "TEST_PASSWORD" },
+               { "alias": "other", "password_env": "OTHER_PASSWORD" }"#,
+            file_run,
+        );
+        let error = different.scenarios().err().expect("different passwords");
+        assert!(
+            error.contains("declare different environment variables"),
+            "{error}"
+        );
+        assert!(
+            !error.contains("TEST_PASSWORD") && !error.contains("OTHER_PASSWORD"),
+            "an error must never quote a password: {error}"
+        );
+
+        let unknown_alias = fixture_with_runs(
+            r#"{ "alias": "other", "password_env": "TEST_PASSWORD" }"#,
+            file_run,
+        );
+        let error = unknown_alias.scenarios().err().expect("unknown alias");
+        assert!(error.contains("`locked`"), "{error}");
+
+        let still_locked = fixture_with_runs(
+            r#"{ "alias": "locked", "expected_outcome": "needs_desktop", "password_env": "TEST_PASSWORD" }"#,
+            r#"{ "source": "file" }"#,
+        );
+        let error = still_locked
+            .scenarios()
+            .err()
+            .expect("needs_desktop with a password");
+        assert!(
+            error.contains("either opens every protected wallet"),
+            "{error}"
+        );
+
+        let unknown_source = serde_json::from_str::(
+            r#"{ "id": "f", "network": "testnet", "password_runs": [{ "source": "env" }] }"#,
+        );
+        assert!(unknown_source.is_err(), "an unknown source must not parse");
+    }
+
+    #[test]
+    fn a_scenario_resolves_its_password_only_at_execution() {
+        let fixture = fixture_with_runs(
+            r#"{ "alias": "locked", "password_env": "TEST_PASSWORD" }"#,
+            "",
+        );
+        let scenario = fixture.scenario("password file", Some("TEST_PASSWORD".into()), vec![]);
+        assert!(scenario.resolve_password_with(|_| None).is_err());
+        assert!(
+            scenario
+                .resolve_password_with(|_| Some(String::new()))
+                .is_err()
+        );
+        let password = scenario
+            .resolve_password_with(|name| {
+                assert_eq!(name, "TEST_PASSWORD");
+                Some("runtime-canary".into())
+            })
+            .expect("runtime value");
+        assert_eq!(password.as_deref(), Some("runtime-canary"));
+        let plain = fixture.scenario("no password", None, vec![]);
+        assert!(
+            plain
+                .resolve_password_with(|_| panic!("plain boot must not read secrets"))
+                .expect("no password needed")
+                .is_none()
+        );
+    }
+
+    #[test]
+    fn an_unknown_network_names_the_fixture() {
+        let fixture: Fixture =
+            serde_json::from_str(r#"{ "id": "odd", "network": "mainnnet" }"#).expect("parse");
+        let error = fixture
+            .network()
+            .expect_err("unknown network must be rejected");
+        assert!(
+            error.contains("odd") && error.contains("mainnnet"),
+            "{error}"
+        );
+    }
+}
diff --git a/tests/migration-matrix/public_identities.rs b/tests/migration-matrix/public_identities.rs
new file mode 100644
index 000000000..27d491810
--- /dev/null
+++ b/tests/migration-matrix/public_identities.rs
@@ -0,0 +1,386 @@
+//! Public-only identity metadata checked before import and after each real CLI boot.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+use std::time::Duration;
+
+use dash_evo_tool::model::qualified_identity::{IdentityStatus, QualifiedIdentity};
+use dash_evo_tool::wallet_backend::KV_SCHEMA_VERSION;
+use dash_sdk::dpp::identity::accessors::IdentityGettersV0;
+use dash_sdk::dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0;
+use dash_sdk::dpp::identity::identity_public_key::contract_bounds::ContractBounds;
+use dash_sdk::dpp::platform_value::string_encoding::Encoding;
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+use crate::{assertions, cli};
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
+pub struct ExpectedIdentity {
+    pub id: String,
+    pub alias: Option,
+    pub identity_type: String,
+    pub status: String,
+    pub balance_credits: u64,
+    pub revision: u64,
+    pub dpns_names: Vec,
+    pub public_keys: Vec,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
+pub struct ExpectedName {
+    pub name: String,
+    pub acquired_at: u64,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
+pub struct ExpectedKey {
+    pub id: u32,
+    pub key_type: String,
+    pub purpose: String,
+    pub security_level: String,
+    pub data: String,
+    pub read_only: bool,
+    pub disabled_at: Option,
+    pub contract_bounds: Option,
+}
+
+fn check_records(expected: &[ExpectedIdentity], found: &[ExpectedIdentity]) -> Result<(), String> {
+    let index = |records: &[ExpectedIdentity]| {
+        records
+            .iter()
+            .map(|record| (record.id.clone(), record.clone()))
+            .collect::>()
+    };
+    let expected_by_id = index(expected);
+    let found_by_id = index(found);
+    if expected_by_id.len() != expected.len() || found_by_id.len() != found.len() {
+        return Err("duplicate identity in public metadata".into());
+    }
+    if expected_by_id != found_by_id {
+        return Err(format!(
+            "identity metadata changed: expected {expected_by_id:?}, found {found_by_id:?}"
+        ));
+    }
+    Ok(())
+}
+
+// Mirrors context::identity_db::StoredQualifiedIdentity, including its bincode field order.
+#[derive(Deserialize)]
+struct StoredIdentity {
+    qi_bytes: Vec,
+    status: u8,
+    identity_type: String,
+    wallet_hash: Option<[u8; 32]>,
+    wallet_index: Option,
+}
+
+fn snapshot(bytes: &[u8], status: u8, identity_type: &str) -> Result {
+    let qi = QualifiedIdentity::from_bytes(bytes)?;
+    if !qi.private_keys.is_empty() || !qi.associated_wallets.is_empty() || qi.wallet_index.is_some()
+    {
+        return Err(
+            "public-only identity unexpectedly contains private keys or wallet bindings".into(),
+        );
+    }
+    if qi.associated_voter_identity.is_some()
+        || qi.associated_operator_identity.is_some()
+        || qi.associated_owner_key_id.is_some()
+    {
+        return Err(
+            "public-only identity unexpectedly contains associated identities or owner binding"
+                .into(),
+        );
+    }
+    if qi.identity_type.to_string() != identity_type {
+        return Err("identity type differs between stored metadata and blob".into());
+    }
+    let public_keys = qi
+        .identity
+        .public_keys()
+        .values()
+        .map(|key| {
+            Ok(ExpectedKey {
+                id: key.id(),
+                key_type: format!("{:?}", key.key_type()),
+                purpose: format!("{:?}", key.purpose()),
+                security_level: format!("{:?}", key.security_level()),
+                data: hex::encode(key.data().as_slice()),
+                read_only: key.read_only(),
+                disabled_at: key.disabled_at(),
+                // Compare semantic bounds in the historical expectation format: the
+                // SDK changed JSON field names without changing the stored meaning.
+                contract_bounds: key.contract_bounds().map(|bounds| match bounds {
+                    ContractBounds::SingleContract { id } => serde_json::json!({
+                        "type": "singleContract", "id": id.to_string(Encoding::Base58)
+                    }),
+                    ContractBounds::SingleContractDocumentType {
+                        id,
+                        document_type_name,
+                    } => serde_json::json!({
+                        "type": "documentType", "id": id.to_string(Encoding::Base58),
+                        "document_type_name": document_type_name
+                    }),
+                }),
+            })
+        })
+        .collect::, String>>()?;
+    Ok(ExpectedIdentity {
+        id: qi.identity.id().to_string(Encoding::Base58),
+        alias: qi.alias,
+        identity_type: identity_type.into(),
+        status: IdentityStatus::from(status).to_string(),
+        balance_credits: qi.identity.balance(),
+        revision: qi.identity.revision(),
+        dpns_names: qi
+            .dpns_names
+            .into_iter()
+            .map(|name| ExpectedName {
+                name: name.name,
+                acquired_at: name.acquired_at,
+            })
+            .collect(),
+        public_keys,
+    })
+}
+
+pub fn check_source(
+    expected: &[ExpectedIdentity],
+    data_db: &Path,
+    scratch: &Path,
+) -> Result<(), String> {
+    if expected.is_empty() {
+        return Ok(());
+    }
+    let conn = assertions::open_copy(data_db, scratch, "identity-source")?
+        .ok_or("public identity fixture has no data.db")?;
+    let mut statement = conn.prepare("SELECT id, data, status, identity_type, alias FROM identity WHERE is_local = 1 AND network = 'testnet' ORDER BY id")
+        .map_err(|e| e.to_string())?;
+    let rows = statement
+        .query_map([], |row| {
+            Ok((
+                row.get::<_, Vec>(0)?,
+                row.get::<_, Vec>(1)?,
+                row.get::<_, u8>(2)?,
+                row.get::<_, String>(3)?,
+                row.get::<_, Option>(4)?,
+            ))
+        })
+        .map_err(|e| e.to_string())?;
+    let mut found = Vec::new();
+    for row in rows {
+        let (id, bytes, status, identity_type, alias) = row.map_err(|e| e.to_string())?;
+        let record = snapshot(&bytes, status, &identity_type)?;
+        if record.id != dash_sdk::dpp::dashcore::base58::encode_slice(&id) || record.alias != alias
+        {
+            return Err("legacy identity columns disagree with the serialized identity".into());
+        }
+        found.push(record);
+    }
+    check_records(expected, &found)
+}
+
+pub fn check_migrated(
+    expected: &[ExpectedIdentity],
+    network_db: &Path,
+    scratch: &Path,
+    label: &str,
+    cli: &cli::DetCli,
+    timeout: Duration,
+) -> Result<(), String> {
+    if expected.is_empty() {
+        return Ok(());
+    }
+    let conn = assertions::open_copy(network_db, scratch, &format!("identities-{label}"))?
+        .ok_or("migrated identity database is missing")?;
+    let mut statement = conn.prepare("SELECT identity_id, value FROM meta_identity WHERE key = 'det:identity:v1' ORDER BY identity_id")
+        .map_err(|e| e.to_string())?;
+    let rows = statement
+        .query_map([], |row| {
+            Ok((row.get::<_, Vec>(0)?, row.get::<_, Vec>(1)?))
+        })
+        .map_err(|e| e.to_string())?;
+    let mut found = Vec::new();
+    for row in rows {
+        let (id, bytes) = row.map_err(|e| e.to_string())?;
+        let Some((&KV_SCHEMA_VERSION, body)) = bytes.split_first() else {
+            return Err("unexpected identity k/v schema version".into());
+        };
+        let (stored, consumed): (StoredIdentity, _) =
+            bincode::serde::decode_from_slice(body, bincode::config::standard())
+                .map_err(|e| e.to_string())?;
+        if consumed != body.len() || stored.wallet_hash.is_some() || stored.wallet_index.is_some() {
+            return Err("unexpected data or wallet binding in public identity record".into());
+        }
+        let record = snapshot(&stored.qi_bytes, stored.status, &stored.identity_type)?;
+        if record.id != dash_sdk::dpp::dashcore::base58::encode_slice(&id) {
+            return Err("identity storage key differs from its serialized identity".into());
+        }
+        found.push(record);
+    }
+    check_records(expected, &found)?;
+    let run = cli.run(&["identity-list"], timeout)?;
+    assertions::check_boot(&run, "identity-list")?;
+    check_listing(expected, &run.json()?)?;
+    println!(
+        "    {label}: {} identities retain aliases, DPNS, balances, revisions and every public key; identity-list agrees",
+        found.len()
+    );
+    Ok(())
+}
+
+fn check_listing(expected: &[ExpectedIdentity], output: &Value) -> Result<(), String> {
+    let listed = output["identities"]
+        .as_array()
+        .ok_or("identity-list has no identities array")?;
+    let found: BTreeMap<_, _> = listed
+        .iter()
+        .map(|identity| (identity["id"].as_str(), identity))
+        .collect();
+    if listed.len() != expected.len() || found.len() != listed.len() {
+        return Err("identity-list contains missing, extra or duplicate identities".into());
+    }
+    for identity in expected {
+        let actual = found
+            .get(&Some(identity.id.as_str()))
+            .ok_or_else(|| format!("identity-list omitted {}", identity.id))?;
+        let wanted = serde_json::json!({"id":identity.id,"alias":identity.alias,"identity_type":identity.identity_type,
+            "status":identity.status,"balance_credits":identity.balance_credits,
+            "dpns_names":identity.dpns_names.iter().map(|name| &name.name).collect::>(),
+            "wallet_index":null,"wallet_seed_hashes":[]});
+        if **actual != wanted {
+            return Err(format!(
+                "identity-list metadata mismatch: expected {wanted}, found {actual}"
+            ));
+        }
+    }
+    Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn identity() -> ExpectedIdentity {
+        serde_json::from_value(serde_json::json!({
+            "id": "public-identity", "alias": "Saved alias", "identity_type": "Masternode",
+            "status": "Active", "balance_credits": 123, "revision": 2,
+            "dpns_names": [{"name": "saved-name", "acquired_at": 456}],
+            "public_keys": [{"id": 1, "key_type": "ECDSA_HASH160", "purpose": "OWNER",
+                "security_level": "CRITICAL", "data": "aabb", "read_only": true,
+                "disabled_at": null, "contract_bounds": null}]
+        }))
+        .unwrap()
+    }
+
+    #[test]
+    fn identical_public_metadata_passes() {
+        assert!(check_records(&[identity()], &[identity()]).is_ok());
+    }
+
+    #[test]
+    fn missing_extra_or_duplicate_identities_fail() {
+        let expected = vec![identity()];
+        assert!(check_records(&expected, &[]).is_err());
+        assert!(check_records(&expected, &[identity(), identity()]).is_err());
+        let mut other = identity();
+        other.id = "unexpected-identity".into();
+        assert!(check_records(&expected, &[identity(), other]).is_err());
+    }
+
+    #[test]
+    fn lost_or_changed_public_metadata_fails() {
+        let original = identity();
+        let changes: Vec<(&str, Value)> = vec![
+            ("alias", Value::Null),
+            ("identity_type", "User".into()),
+            ("status", "Unknown".into()),
+            ("balance_credits", 0.into()),
+            ("revision", 0.into()),
+            ("dpns_names", serde_json::json!([])),
+            ("public_keys", serde_json::json!([])),
+        ];
+        for (field, value) in changes {
+            let mut changed = serde_json::to_value(&original).unwrap();
+            changed[field] = value;
+            assert!(
+                check_records(
+                    std::slice::from_ref(&original),
+                    &[serde_json::from_value(changed).unwrap()]
+                )
+                .is_err(),
+                "{field}"
+            );
+        }
+        let mut changed = original.clone();
+        changed.dpns_names[0].acquired_at += 1;
+        assert!(check_records(std::slice::from_ref(&original), &[changed]).is_err());
+        for field in [
+            "id",
+            "key_type",
+            "purpose",
+            "security_level",
+            "data",
+            "read_only",
+            "disabled_at",
+            "contract_bounds",
+        ] {
+            let mut changed = serde_json::to_value(&original).unwrap();
+            changed["public_keys"][0][field] = match field {
+                "id" | "disabled_at" => 7.into(),
+                "read_only" => false.into(),
+                "contract_bounds" => serde_json::json!({"SingleContract": [1]}),
+                _ => "changed".into(),
+            };
+            assert!(
+                check_records(
+                    std::slice::from_ref(&original),
+                    &[serde_json::from_value(changed).unwrap()]
+                )
+                .is_err(),
+                "{field}"
+            );
+        }
+    }
+
+    #[test]
+    fn cli_listing_must_preserve_metadata_and_remain_wallet_free() {
+        let expected = vec![identity()];
+        let entry = serde_json::json!({
+            "id":"public-identity", "alias":"Saved alias", "identity_type":"Masternode",
+            "status":"Active", "balance_credits":123, "dpns_names":["saved-name"],
+            "wallet_index":null, "wallet_seed_hashes":[]
+        });
+        assert!(
+            check_listing(
+                &expected,
+                &serde_json::json!({"identities":[entry.clone()]})
+            )
+            .is_ok()
+        );
+        assert!(check_listing(&expected, &serde_json::json!({"identities":[]})).is_err());
+        assert!(
+            check_listing(
+                &expected,
+                &serde_json::json!({"identities":[entry.clone(),entry.clone()]})
+            )
+            .is_err()
+        );
+        for (field, value) in [
+            ("dpns_names", serde_json::json!([])),
+            ("wallet_index", 0.into()),
+            (
+                "wallet_seed_hashes",
+                serde_json::json!(["unexpected-wallet"]),
+            ),
+            ("id", "other".into()),
+        ] {
+            let mut changed = entry.clone();
+            changed[field] = value;
+            assert!(
+                check_listing(&expected, &serde_json::json!({"identities":[changed]})).is_err(),
+                "{field}"
+            );
+        }
+    }
+}
diff --git a/tests/migration-matrix/stage.rs b/tests/migration-matrix/stage.rs
new file mode 100644
index 000000000..bb8f333f4
--- /dev/null
+++ b/tests/migration-matrix/stage.rs
@@ -0,0 +1,510 @@
+//! Unpacks a fixture into a throwaway data directory the harness may mutate.
+//!
+//! A fixture is either an already-unpacked directory or an archive; both are
+//! copied into a temp dir so the source stays pristine across the two boots.
+//! The staged tree is then held to the same rules `app_dir::ensure_data_dir_exists`
+//! enforces on a real data directory — `0700`, no symlinks — so a fixture that
+//! smuggles in a symlink fails loudly here instead of silently redirecting a
+//! boot write outside the sandbox.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use sha2::{Digest, Sha256};
+use tempfile::TempDir;
+
+use crate::manifest::Fixture;
+
+/// Archive extensions tried when the manifest carries no explicit pointer.
+const ARCHIVE_SUFFIXES: &[&str] = &[".tar.zst", ".tar.gz", ".tgz", ".tar.xz", ".tar"];
+
+/// Files that identify an unpacked tree as a DET data directory. `data.db` is
+/// the v0.9.3-era marker, `det-app.sqlite` the modern one, `.env` common to both.
+const DATA_DIR_MARKERS: &[&str] = &["data.db", "det-app.sqlite", ".env"];
+
+/// A fixture unpacked into a temp sandbox.
+///
+/// The sandbox holds the data directory plus the XDG dirs the spawned
+/// `det-cli` is pointed at, so nothing the subprocess writes escapes into the
+/// real user home. Dropping it deletes the whole tree.
+#[derive(Debug)]
+pub struct StagedFixture {
+    sandbox: TempDir,
+    data_dir: PathBuf,
+}
+
+impl StagedFixture {
+    /// The staged data directory, i.e. what `DASH_EVO_DATA_DIR` points at.
+    pub fn data_dir(&self) -> &Path {
+        &self.data_dir
+    }
+
+    /// Root of the sandbox — parent of the data dir and of the redirected
+    /// XDG dirs.
+    pub fn sandbox(&self) -> &Path {
+        self.sandbox.path()
+    }
+
+    /// Writes `password` as a one-line, owner-only (`0600`) file in the
+    /// sandbox — the only kind of file det-cli's `--password-file` accepts.
+    pub fn write_password_file(&self, password: &str) -> Result {
+        use std::io::Write as _;
+
+        let path = self.sandbox.path().join("wallet-password");
+        let mut options = fs::OpenOptions::new();
+        options.write(true).create_new(true);
+        #[cfg(unix)]
+        {
+            use std::os::unix::fs::OpenOptionsExt as _;
+            options.mode(0o600);
+        }
+        let mut file = options
+            .open(&path)
+            .map_err(|e| format!("could not create {}: {e}", path.display()))?;
+        writeln!(file, "{password}")
+            .map_err(|e| format!("could not write {}: {e}", path.display()))?;
+        Ok(path)
+    }
+
+    /// A scratch directory for harness-side copies (SQLite snapshots), kept
+    /// outside the data dir so reading never perturbs what is under test.
+    pub fn scratch(&self) -> Result {
+        let scratch = self.sandbox.path().join("scratch");
+        fs::create_dir_all(&scratch)
+            .map_err(|e| format!("could not create scratch dir {}: {e}", scratch.display()))?;
+        Ok(scratch)
+    }
+}
+
+/// Stages `fixture` from `fixtures_dir` into a fresh sandbox.
+pub fn stage(fixtures_dir: &Path, fixture: &Fixture) -> Result {
+    let source = resolve_source(fixtures_dir, fixture)?;
+    let sandbox = tempfile::Builder::new()
+        .prefix("det-migration-matrix-")
+        .tempdir()
+        .map_err(|e| format!("could not create sandbox for fixture '{}': {e}", fixture.id))?;
+    let unpacked = sandbox.path().join("unpacked");
+    fs::create_dir_all(&unpacked)
+        .map_err(|e| format!("could not create {}: {e}", unpacked.display()))?;
+
+    match source {
+        Source::Directory(dir) => copy_tree(&dir, &unpacked)?,
+        Source::Archive(archive) => {
+            verify_checksum(&archive, fixture)?;
+            extract(&archive, &unpacked)?;
+        }
+    }
+
+    let data_dir = locate_data_dir(&unpacked, &fixture.id)?;
+    harden(&data_dir)?;
+    restrict_ancestors(sandbox.path(), &data_dir)?;
+
+    Ok(StagedFixture { sandbox, data_dir })
+}
+
+/// Makes every directory from the sandbox root down to (excluding) the data
+/// dir owner-only. [`harden`] owns the data dir and below; the directories
+/// above it were created with the process umask or an archive's modes, and
+/// the wallet store refuses a data dir under a group- or other-writable
+/// ancestor (`insecure_parent_dir`).
+fn restrict_ancestors(sandbox: &Path, data_dir: &Path) -> Result<(), String> {
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+
+        for dir in data_dir
+            .ancestors()
+            .skip(1)
+            .take_while(|dir| dir.starts_with(sandbox))
+        {
+            fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
+                .map_err(|e| format!("could not restrict {}: {e}", dir.display()))?;
+        }
+    }
+    #[cfg(not(unix))]
+    {
+        let _ = (sandbox, data_dir);
+    }
+    Ok(())
+}
+
+enum Source {
+    Directory(PathBuf),
+    Archive(PathBuf),
+}
+
+/// Resolves the fixture bytes: the manifest pointer if present, otherwise a
+/// directory or archive named after the fixture id.
+fn resolve_source(fixtures_dir: &Path, fixture: &Fixture) -> Result {
+    if let Some(name) = fixture.artifact.archive.as_deref() {
+        let path = fixtures_dir.join(name);
+        return match path.metadata() {
+            Ok(meta) if meta.is_dir() => Ok(Source::Directory(path)),
+            Ok(_) => Ok(Source::Archive(path)),
+            Err(e) => Err(format!(
+                "fixture '{}' points at {} which cannot be read: {e}{}",
+                fixture.id,
+                path.display(),
+                describe_dir(fixtures_dir)
+            )),
+        };
+    }
+
+    let unpacked = fixtures_dir.join(&fixture.id);
+    if unpacked.is_dir() {
+        return Ok(Source::Directory(unpacked));
+    }
+    for suffix in ARCHIVE_SUFFIXES {
+        let candidate = fixtures_dir.join(format!("{}{suffix}", fixture.id));
+        if candidate.is_file() {
+            return Ok(Source::Archive(candidate));
+        }
+    }
+    Err(format!(
+        "fixture '{}' has no archive pointer and neither {}/ nor {}[{}] exists{}",
+        fixture.id,
+        fixture.id,
+        fixture.id,
+        ARCHIVE_SUFFIXES.join("|"),
+        describe_dir(fixtures_dir)
+    ))
+}
+
+/// Lists what the fixtures directory actually holds, so a pointer typo or an
+/// expired artifact download names the mismatch instead of just "not found".
+fn describe_dir(dir: &Path) -> String {
+    match fs::read_dir(dir) {
+        Ok(entries) => {
+            let mut names: Vec = entries
+                .flatten()
+                .map(|e| e.file_name().to_string_lossy().into_owned())
+                .collect();
+            names.sort();
+            format!(" — {} contains: {}", dir.display(), names.join(", "))
+        }
+        Err(e) => format!(" — {} is unreadable: {e}", dir.display()),
+    }
+}
+
+fn verify_checksum(archive: &Path, fixture: &Fixture) -> Result<(), String> {
+    let Some(expected) = fixture.artifact.sha256.as_deref() else {
+        return Ok(());
+    };
+    let bytes = fs::read(archive)
+        .map_err(|e| format!("could not read fixture archive {}: {e}", archive.display()))?;
+    let actual = hex::encode(Sha256::digest(&bytes));
+    if !actual.eq_ignore_ascii_case(expected.trim()) {
+        return Err(format!(
+            "fixture '{}' archive {} has sha256 {actual}, manifest expects {expected}",
+            fixture.id,
+            archive.display()
+        ));
+    }
+    Ok(())
+}
+
+/// Extracts with the system `tar`, which auto-detects the compression. Keeps
+/// the harness free of archive crates — adding them is a dependency decision
+/// the fixture-capture workstream owns, not this test target.
+fn extract(archive: &Path, dest: &Path) -> Result<(), String> {
+    let output = Command::new("tar")
+        .arg("-xf")
+        .arg(archive)
+        .arg("-C")
+        .arg(dest)
+        .output()
+        .map_err(|e| format!("could not run tar to unpack {}: {e}", archive.display()))?;
+    if !output.status.success() {
+        return Err(format!(
+            "tar failed to unpack {} ({}): {}",
+            archive.display(),
+            output.status,
+            String::from_utf8_lossy(&output.stderr).trim()
+        ));
+    }
+    Ok(())
+}
+
+/// Copies an unpacked fixture, rejecting symlinks at the source so a staged
+/// tree can never contain one.
+fn copy_tree(source: &Path, dest: &Path) -> Result<(), String> {
+    fs::create_dir_all(dest).map_err(|e| format!("could not create {}: {e}", dest.display()))?;
+    let entries = fs::read_dir(source)
+        .map_err(|e| format!("could not read fixture dir {}: {e}", source.display()))?;
+    for entry in entries {
+        let entry = entry.map_err(|e| format!("could not walk {}: {e}", source.display()))?;
+        let from = entry.path();
+        let to = dest.join(entry.file_name());
+        let meta = fs::symlink_metadata(&from)
+            .map_err(|e| format!("could not stat {}: {e}", from.display()))?;
+        if meta.file_type().is_symlink() {
+            return Err(symlink_rejection(&from));
+        }
+        if meta.is_dir() {
+            copy_tree(&from, &to)?;
+        } else {
+            fs::copy(&from, &to).map_err(|e| {
+                format!("could not copy {} to {}: {e}", from.display(), to.display())
+            })?;
+        }
+    }
+    Ok(())
+}
+
+/// Finds the data directory inside an unpacked tree, descending through
+/// single-child wrapper directories the archive may have kept.
+fn locate_data_dir(root: &Path, fixture_id: &str) -> Result {
+    let mut candidate = root.to_path_buf();
+    for _ in 0..4 {
+        if DATA_DIR_MARKERS
+            .iter()
+            .any(|marker| candidate.join(marker).exists())
+        {
+            return Ok(candidate);
+        }
+        let mut children: Vec = fs::read_dir(&candidate)
+            .map_err(|e| format!("could not read {}: {e}", candidate.display()))?
+            .flatten()
+            .map(|entry| entry.path())
+            .collect();
+        children.retain(|path| path.is_dir());
+        match children.len() {
+            1 => candidate = children.remove(0),
+            _ => break,
+        }
+    }
+    Err(format!(
+        "fixture '{fixture_id}' does not look like a DET data directory: none of {} found under {}",
+        DATA_DIR_MARKERS.join(", "),
+        root.display()
+    ))
+}
+
+/// Applies the data-directory rules from `app_dir::ensure_data_dir_exists`:
+/// owner-only permissions and no symlinks anywhere in the tree.
+fn harden(data_dir: &Path) -> Result<(), String> {
+    #[cfg(unix)]
+    {
+        use std::os::unix::fs::PermissionsExt;
+
+        let meta = fs::symlink_metadata(data_dir)
+            .map_err(|e| format!("could not stat {}: {e}", data_dir.display()))?;
+        if meta.file_type().is_symlink() {
+            return Err(symlink_rejection(data_dir));
+        }
+        if !meta.is_dir() {
+            return Err(format!("{} is not a directory", data_dir.display()));
+        }
+        fs::set_permissions(data_dir, fs::Permissions::from_mode(0o700))
+            .map_err(|e| format!("could not restrict {}: {e}", data_dir.display()))?;
+
+        let entries = fs::read_dir(data_dir)
+            .map_err(|e| format!("could not read {}: {e}", data_dir.display()))?;
+        for entry in entries {
+            let entry = entry.map_err(|e| format!("could not walk {}: {e}", data_dir.display()))?;
+            let path = entry.path();
+            let meta = fs::symlink_metadata(&path)
+                .map_err(|e| format!("could not stat {}: {e}", path.display()))?;
+            if meta.file_type().is_symlink() {
+                return Err(symlink_rejection(&path));
+            }
+            if meta.is_dir() {
+                harden(&path)?;
+            } else {
+                fs::set_permissions(&path, fs::Permissions::from_mode(0o600))
+                    .map_err(|e| format!("could not restrict {}: {e}", path.display()))?;
+            }
+        }
+    }
+    #[cfg(not(unix))]
+    {
+        let _ = data_dir;
+    }
+    Ok(())
+}
+
+fn symlink_rejection(path: &Path) -> String {
+    format!(
+        "fixture contains a symbolic link at {} — a staged data directory must not contain symlinks",
+        path.display()
+    )
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn fixture(id: &str, archive: Option<&str>) -> Fixture {
+        let archive = match archive {
+            Some(name) => format!(r#", "artifact": {{ "archive": "{name}" }}"#),
+            None => String::new(),
+        };
+        serde_json::from_str(&format!(
+            r#"{{ "id": "{id}", "network": "testnet"{archive} }}"#
+        ))
+        .expect("test fixture json")
+    }
+
+    #[test]
+    fn an_unpacked_directory_is_staged_and_locked_down() {
+        use std::os::unix::fs::PermissionsExt;
+
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        let source = fixtures.path().join("v0.9.3-testnet");
+        fs::create_dir_all(source.join("dash_core_configs")).expect("create fixture");
+        fs::write(source.join("data.db"), b"not really sqlite").expect("write data.db");
+        fs::set_permissions(source.join("data.db"), fs::Permissions::from_mode(0o644))
+            .expect("loosen fixture permissions");
+
+        let staged = stage(fixtures.path(), &fixture("v0.9.3-testnet", None)).expect("stage");
+
+        assert!(staged.data_dir().join("data.db").is_file());
+        assert!(
+            staged.data_dir().starts_with(staged.sandbox()),
+            "the staged copy must live inside the sandbox, not in the fixtures dir"
+        );
+        let dir_mode = fs::metadata(staged.data_dir())
+            .expect("stat staged dir")
+            .permissions()
+            .mode();
+        assert_eq!(dir_mode & 0o077, 0, "staged data dir must be owner-only");
+        let file_mode = fs::metadata(staged.data_dir().join("data.db"))
+            .expect("stat staged file")
+            .permissions()
+            .mode();
+        assert_eq!(file_mode & 0o077, 0, "staged files must be owner-only");
+    }
+
+    /// The wallet store refuses a data dir under a group- or other-writable
+    /// ancestor (`insecure_parent_dir`), so every directory the stager creates
+    /// above the data dir must be owner-only too, whatever the umask.
+    #[test]
+    fn the_password_file_is_owner_only_and_holds_one_line() {
+        let staged = StagedFixture {
+            sandbox: tempfile::tempdir().expect("sandbox"),
+            data_dir: PathBuf::new(),
+        };
+        let path = staged
+            .write_password_file("one line")
+            .expect("password file");
+        assert_eq!(fs::read_to_string(&path).expect("read"), "one line\n");
+        #[cfg(unix)]
+        {
+            use std::os::unix::fs::PermissionsExt as _;
+            let mode = fs::metadata(&path).expect("metadata").permissions().mode();
+            assert_eq!(mode & 0o777, 0o600, "det-cli refuses anything wider");
+        }
+    }
+
+    #[test]
+    fn every_directory_above_the_data_dir_is_owner_only() {
+        use std::os::unix::fs::PermissionsExt;
+
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        let nested = fixtures.path().join("wrapped").join("Dash-Evo-Tool");
+        fs::create_dir_all(&nested).expect("create fixture");
+        fs::write(nested.join("det-app.sqlite"), b"x").expect("write marker");
+
+        let staged = stage(fixtures.path(), &fixture("wrapped", None)).expect("stage");
+
+        let ancestors: Vec<&Path> = staged
+            .data_dir()
+            .ancestors()
+            .skip(1)
+            .take_while(|dir| dir.starts_with(staged.sandbox()))
+            .collect();
+        assert!(
+            ancestors.len() >= 2,
+            "expected the sandbox root and at least one staging dir above the data dir, got {ancestors:?}"
+        );
+        for dir in ancestors {
+            let mode = fs::metadata(dir)
+                .expect("stat ancestor")
+                .permissions()
+                .mode();
+            assert_eq!(
+                mode & 0o077,
+                0,
+                "{} is mode {:o}; the data dir's ancestors must be owner-only",
+                dir.display(),
+                mode & 0o777
+            );
+        }
+    }
+
+    #[test]
+    fn a_wrapper_directory_is_descended_into() {
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        let nested = fixtures.path().join("wrapped").join("Dash-Evo-Tool");
+        fs::create_dir_all(&nested).expect("create fixture");
+        fs::write(nested.join("det-app.sqlite"), b"x").expect("write marker");
+
+        let staged = stage(fixtures.path(), &fixture("wrapped", None)).expect("stage");
+
+        assert!(staged.data_dir().join("det-app.sqlite").is_file());
+        assert_eq!(
+            staged.data_dir().file_name().and_then(|n| n.to_str()),
+            Some("Dash-Evo-Tool")
+        );
+    }
+
+    #[test]
+    fn a_symlinked_fixture_entry_is_rejected() {
+        use std::os::unix::fs::symlink;
+
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        let source = fixtures.path().join("linky");
+        fs::create_dir_all(&source).expect("create fixture");
+        fs::write(source.join("data.db"), b"x").expect("write marker");
+        symlink("/etc/passwd", source.join("escape")).expect("create symlink");
+
+        let error = stage(fixtures.path(), &fixture("linky", None))
+            .expect_err("a symlinked entry must be rejected");
+
+        assert!(error.contains("symbolic link"), "{error}");
+    }
+
+    #[test]
+    fn a_tree_without_markers_is_rejected() {
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        fs::create_dir_all(fixtures.path().join("empty")).expect("create fixture");
+
+        let error = stage(fixtures.path(), &fixture("empty", None))
+            .expect_err("a non-DET tree must be rejected");
+
+        assert!(
+            error.contains("does not look like a DET data directory"),
+            "{error}"
+        );
+    }
+
+    #[test]
+    fn a_missing_archive_lists_what_the_fixtures_dir_holds() {
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        fs::write(fixtures.path().join("something-else.tar"), b"x").expect("write decoy");
+
+        let error = stage(fixtures.path(), &fixture("gone", Some("gone.tar.zst")))
+            .expect_err("a missing archive must fail loudly");
+
+        assert!(
+            error.contains("gone.tar.zst") && error.contains("something-else.tar"),
+            "{error}"
+        );
+    }
+
+    #[test]
+    fn a_checksum_mismatch_is_rejected() {
+        let fixtures = tempfile::tempdir().expect("fixtures dir");
+        fs::write(fixtures.path().join("tampered.tar"), b"x").expect("write archive");
+        let fixture: Fixture = serde_json::from_str(
+            r#"{ "id": "tampered", "network": "testnet",
+                 "artifact": { "archive": "tampered.tar", "sha256": "00" } }"#,
+        )
+        .expect("fixture json");
+
+        let error = stage(fixtures.path(), &fixture).expect_err("a bad checksum must be rejected");
+
+        assert!(error.contains("sha256"), "{error}");
+    }
+}